0% found this document useful (0 votes)
1 views20 pages

Module 3 - Programming in C

Module 3 of the Programming in C course focuses on conditional branching, covering various statements such as if, if-else, nested if-else, and switch statements. It discusses the advantages and disadvantages of branching, emphasizing improved decision-making and code readability, while also warning against complexity and potential logical errors. Each statement is explained with syntax, examples, and detailed explanations of their functionality.

Uploaded by

nexmindify
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views20 pages

Module 3 - Programming in C

Module 3 of the Programming in C course focuses on conditional branching, covering various statements such as if, if-else, nested if-else, and switch statements. It discusses the advantages and disadvantages of branching, emphasizing improved decision-making and code readability, while also warning against complexity and potential logical errors. Each statement is explained with syntax, examples, and detailed explanations of their functionality.

Uploaded by

nexmindify
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TCET Programming in C Module 3

Module – 3 Conditional Branching

Index:

SR. NO. Topic Name Page No.


1 Introduction 2
2 Advantages and disadvantages 2
3 If Statement 3
4 If –else Statement 5
5 Nested If –else Statement 7
6 Switch case 9
7 Functionality of Break 12
8 If-else & else if statement (Multiway 12
decision)
9 Menu -driven 17

pg. 1
TCET Programming in C Module 3

Branching/Selection
Branching statements in C
The capacity to decide what to do and how to run distinct pieces of code based on specific
circumstances is essential in the realm of programming. This ability to manage the execution flow is
provided by branching statements in the C programming language. We'll examine the different
branching statements in C in this blog article, going through their syntax, giving examples,
and showcasing the results they produce.

Advantages of Branching Statements:


Better Decision Making: Branching statements give programmers the ability to decide
what to do next in their code depending on certain circumstances. It improves the
program's functionality and versatility by allowing it to respond and adapt to various
conditions.

Readability of the code: Branching statements make the logic of the code clearer and
simpler to understand. For other developers to understand and maintain the codebase,
the conditional statements provide distinct signs of the program's decision-making
process.

Code effectiveness: Branching statements optimize program execution by only running


the necessary code blocks in accordance with the predetermined circumstances. It can
make programs run more quickly and effectively, especially when employing the "switch"
statement to process big sets of cases or complex decision trees.

Flexibility: Programming flexibility is provided through branching statements, which


enables several code paths to be performed in response to diverse circumstances. This
adaptability is especially helpful when the program needs to react quickly to altering inputs
or outside influences.

Code Reusability: Branching statements make it easier to reuse code by enabling the
execution of code blocks in response to various situations. Programmers can create
modular code that can be easily reused in various portions of the program by utilizing
branching statements efficiently.

Disadvantages of Branching Statements:


Code Complexity: When branching statements are overused or deeply nested, the code
may become clearer and easier to comprehend. It may result in maintenance problems,
defects, and poorer-quality code. It's crucial to utilize branching statements sparingly
and aim for simplicity.

Readability Issues: Although branching statements can sometimes make code easier to
comprehend, they can also cause issues if used carelessly. The code may become more
difficult to read and understand if there are too many nested levels, complex conditional
expressions, or duplicative sections of code.

pg. 2
TCET Programming in C Module 3

Potential for Logical Mistakes: If the conditions are not adequately established and
validated, branching statements run the danger of logical mistakes.

Code Maintenance: The intricacy of branching statements makes it more difficult to


maintain the code. It can be difficult to comprehend the logic of the code and make the
necessary adjustments without adding problems when there are numerous branching
statements and nested conditions present.

Branching Statements:
In C, conditional branching statements are used to execute particular code blocks
based on a condition (as needed). These branching instructions in C allow programmers
to run the code only when specific conditions are met. The various categories of
conditional branching statements in C are as follows:

o if Statement
o if-else Statement
o nested if-else Statement
o switch Statement

1. ‘if’ Statement

The if statement is used to execute a block of code only if a specified condition is true.

Syntax:
if (condition) {
// Code to execute if the condition is true
}

Example:
#include <stdio.h>
int main() {
int num = 10;

if (num > 0) {
printf("The number is positive.\n");
}

return 0;
}
Output:

The number is positive.

pg. 3
TCET Programming in C Module 3

Explanation:

1. Including the Standard Input Output Header File


#include <stdio.h>

This line includes the stdio.h header file, which is necessary for using input and output
functions in C. Specifically, printf is used to output text to the console.

2. Defining the main function


int main() {

This is the entry point of the program. Every C program starts execution from the main
function.

3. Declaring an Integer Variable


int num = 10;

Here, a variable num of type int (integer) is declared and initialized to 10.

4. Conditional if Statement
if (num > 0) {
printf("The number is positive.\n");
}

 The if statement checks if the value of num is greater than 0.


 Since num is initialized to 10, the condition num > 0 is true.
 Because the condition is true, the code inside the {} (curly braces) of the if statement
is executed.
 The printf function outputs the string "The number is positive.\n" to the
console.

5. Return Statement
return 0;

The return 0; statement indicates that the main function has finished executing and returns
an exit status of 0, which traditionally signifies successful program completion.

Output:

Since the value of num is positive (10), the program will output:

The number is positive.

Summary:

pg. 4
TCET Programming in C Module 3

This program simply checks if the number 10 is greater than zero and prints "The number is
positive." to the console. Since num is initialized to 10 (a positive number), the message is
printed when the program runs.

2. if-else Statement

By offering a different block of code to run when the condition is false, the "if-else"
statement builds on the "if" statement. The "if-else" expression has the following
syntax:

if (condition) {
// Code to execute if condition is true
}
else {
// Code to execute if condition is false
}

Example:

#include <stdio.h>

int main() {
int num = -5;

if (num > 0) {
printf("The number is positive.\n");
}
else {
printf("The number is non-positive.\n");
}

return 0;
}
Output:

The number is non-positive

Explanation:

1. Including the Standard Input Output Header File

pg. 5
TCET Programming in C Module 3

#include <stdio.h>

This line includes the standard library header file stdio.h, which is required to use
input/output functions like printf in C. It allows the program to output text to the console.

2. Defining the main Function


int main() {

The main() function is the entry point of any C program. This is where the program starts
executing.

3. Declaring an Integer Variable


int num = -5;

Here, an integer variable num is declared and initialized with the value -5. This value will be
used in the if statement to check whether it is positive or non-positive.

4. The if Statement
if (num > 0) {

This if statement checks whether the value of num is greater than 0. Since num is -5, the
condition num > 0 evaluates to false because -5 is not greater than zero.

5. The Code Block for the if Statement


printf("The number is positive.\n");

This line of code would be executed if the condition num > 0 was true (i.e., if num were a
positive number). However, since num is -5, the condition is false, so this line is skipped.

6. The else Statement


else {

The else block is executed when the if condition is false. Since num is not greater than 0, the
program enters this block.

7. The Code Block for the else Statement


printf("The number is non-positive.\n");

This line of code is executed because the else block is entered. It prints the message "The
number is non-positive." to the console, indicating that num is either zero or a negative
number.

8. Return Statement

pg. 6
TCET Programming in C Module 3

return 0;

The return 0; statement indicates that the main function has finished executing. Returning
0 signifies that the program has executed successfully without errors.

Summary:

The program declares a variable num with the value -5 and uses an if-else statement to
check if the number is positive. Since num is negative, the else block is executed, and the
message "The number is non-positive." is printed to the console.

[Link] nested if-else Statement:


You can have an "if-else" statement within another "if" or "else" block in C since it
supports the nesting of "if-else" statements. It allows for adaptability when managing
various environments. The nested "if-else" statement has the following syntax:

if (condition1) {
// Code to execute if condition1 is true

if (condition2) {
// Code to execute if condition2 is true
}
else {
// Code to execute if condition2 is false
}
}
else {
// Code to execute if condition1 is false
}
Example:

#include <stdio.h>

int main() {
int num = 0;

if (num > 0) {
printf("The number is positive.\n");
}
else if (num < 0) {
printf("The number is negative.\n");
}
else {
printf("The number is zero.\n");

pg. 7
TCET Programming in C Module 3

return 0;
}
Output:

The number is zero.

Explaination:

1. Including the Standard Input Output Header File


#include <stdio.h>

This line includes the stdio.h header file, which is necessary for using input and output
functions like printf. The printf function is used in the program to print messages to the
console.

2. Defining the main Function


int main() {

This is the entry point of the program. Every C program starts its execution from the main
function.

3. Declaring an Integer Variable


int num = 0;

Here, an integer variable num is declared and initialized to 0. This variable will be checked in
the following if-else statements to determine whether it's positive, negative, or zero.

4. The First if Statement


if (num > 0) {
printf("The number is positive.\n");
}

The program checks if the value of num is greater than 0. Since num is 0, the condition num >
0 is false, so the code inside this block (printing "The number is positive.") will not be
executed.

5. The else if Statement


else if (num < 0) {
printf("The number is negative.\n");
}

pg. 8
TCET Programming in C Module 3

Since the first condition was false, the program now checks if num is less than 0. The
condition num < 0 is also false because num is 0. So, this block is skipped as well, and the
code inside (printing "The number is negative.") is not executed.

6. The else Block


else {
printf("The number is zero.\n");
}

Since neither of the previous conditions (num > 0 or num < 0) were true, the program enters
this else block. It prints the message "The number is zero." because num is exactly 0.

7. Return Statement
return 0;

The return 0; statement marks the end of the main function and indicates that the program
executed successfully.

Output:

Since num is 0, the program will output:

The number is zero.

Summary:

This program checks whether a given number (in this case, 0) is positive, negative, or zero
using if-else statements. It prints the appropriate message based on the value of num. Since
num is zero, the program prints "The number is zero." to the console.

[Link] switch Statement:


Multiple actions can be taken using the "switch" statement based on the value of a
variable or expression. When managing several instances, it is especially helpful.
The "switch" statement has the following syntax:

switch (expression) {
case constant1:
// Code to execute if expression matches constant1
break;
case constant2:
// Code to execute if expression matches constant2
break;
// More cases...

pg. 9
TCET Programming in C Module 3

default:
// Code to execute if expression doesn't match any constant
}

Example:

#include <stdio.h>

int main() {
int day = 3;

switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Invalid day\n");
}

return 0;
}

Explanation:

Certainly! Let’s explain the code line-by-line, focusing on the flow of execution for one case
in the switch statement.

1. int day = 3;

int day = 3;

 Line 1: This line declares an integer variable day and assigns it the value 3. This value will be
used in the switch statement to determine which case to execute.

2. switch (day) {

switch (day) {

pg. 10
TCET Programming in C Module 3

 Line 2: The switch statement begins. It evaluates the value of day (which is 3 in this case).
It will compare this value with each case label defined inside the switch block.

3. case 1:

case 1:

 Line 3: This defines the first case in the switch. It checks if day equals 1. Since day is 3,
this case does not execute. The program will continue to the next case until a match is
found or the default is reached.

4. printf("Monday\n");
printf("Monday\n");

 Line 4: This would print "Monday" followed by a newline if day were 1. However, since day
is 3, this line is skipped.

5. break;
break;

 Line 5: The break statement prevents the program from continuing to the next case after it
has found a match. It stops the execution of the switch block. However, this break is not
reached since the day is not 1.

5. same we will do for all cases

6. default:
default:

 Line 18: The default block is executed if no case matches the value of day. However,
since day is 3 and we already matched case 3, this block is not executed.

7. printf("Invalid day\n");

printf("Invalid day\n");

 Line 19: This would print "Invalid day" if none of the cases matched. Since we have a match
with case 3, this line is not executed.

8. return 0;

return 0;

 Line 20: This line marks the end of the main function and returns 0 to the operating system,
indicating that the program ran successfully.

pg. 11
TCET Programming in C Module 3

Summary of Execution:

1. The value of day is 3.


2. The switch statement starts and matches case 3.
3. It executes the code in case 3, printing "Wednesday".
4. The break statement exits the switch block.
5. The program ends with a return 0, indicating successful execution.

Functionality of the break Statement in C

In C programming, the break statement is used to terminate the execution of a loop (for,
while, do-while) or a switch block immediately, causing the program to jump to the
statement after the loop or switch block. This can be particularly useful in scenarios where a
condition is met, and there's no need to continue executing the rest of the loop or switch
statements.

In a Loop:

When the break statement is encountered inside a loop, it exits the loop immediately,
regardless of whether the loop has completed its iterations or not. This is often used when a
certain condition is met, and continuing with the loop would be unnecessary or inefficient.

In a switch Block:

In a switch statement, the break statement is used to terminate the execution of a


particular case block. Without a break statement, the program will execute the following
cases (a behavior known as "fall-through"). The break prevents this fall-through and ensures
only the matched case block is executed.

5. if-else else-if Statement (Multiway Decision)


In C programming, an if-else if-else statement is used when you have multiple
conditions to evaluate and execute different blocks of code depending on which condition is
true. This structure allows you to handle multiple choices in a clear and organized manner.

Syntax:

pg. 12
TCET Programming in C Module 3

if (condition1) {
// Block of code if condition1 is true
}
else if (condition2) {
// Block of code if condition2 is true
}
else if (condition3) {
// Block of code if condition3 is true
}
else {
// Block of code if none of the above conditions are true
}
Example:
#include <stdio.h>
int main() {
int score;
// Input score from user
printf("Enter your score: ");
scanf("%d", &score);

// Check the grade using if-else if-else structure


if (score >= 90) {
printf("You received an A grade.\n");
} else if (score >= 80) {
printf("You received a B grade.\n");
} else if (score >= 70) {
printf("You received a C grade.\n");
} else if (score >= 60) {
printf("You received a D grade.\n");
} else {
printf("You received an F grade.\n");
} return 0;
}

Explanation:

pg. 13
TCET Programming in C Module 3

1. #include <stdio.h>

#include <stdio.h>

 Purpose: This line includes the Standard Input/Output library (stdio.h), which provides
the functions for input (scanf) and output (printf). It is necessary for working with user
input and printing results.

2. int main() {

int main() {

 Purpose: This defines the main function where the execution of the program starts. The int
before main means the function will return an integer value (typically 0 to indicate that the
program ran successfully).

3. int score;

int score;

 Purpose: This line declares an integer variable score that will store the user's score input. It
is used to determine the grade based on the score.

4. printf("Enter your score: ");

printf("Enter your score: ");

 Purpose: This line uses the printf function to display the message "Enter your score: " on
the screen, prompting the user to input their score.

5. scanf("%d", &score);

scanf("%d", &score);

 Purpose: This line uses the scanf function to take the user's input.
o %d is the format specifier for reading an integer.
o &score is the address of the score variable where the input value will be stored.
 The user is expected to enter a numerical score (e.g., 85), and that value will be stored in the
score variable.

6. if (score >= 90) {

if (score >= 90) {

 Purpose: This begins the if-else if-else structure, which checks multiple conditions.
o The if statement checks whether the score is greater than or equal to 90.
o If the condition is true (i.e., the score is 90 or higher), the code inside this if block
will execute.

7. printf("You received an A grade.\n");

pg. 14
TCET Programming in C Module 3

printf("You received an A grade.\n");

 Purpose: If the score is greater than or equal to 90, this line will print "You received an A
grade." followed by a newline.
 The \n is used to print a newline character, ensuring that the output appears on a new line.

8. } else if (score >= 80) {

} else if (score >= 80) {

 Purpose: This line checks the else if condition, which is only evaluated if the previous if
condition was false.
o It checks if the score is greater than or equal to 80 but less than 90.
o If this condition is true, the code inside this block will execute.

9. printf("You received a B grade.\n");

printf("You received a B grade.\n");

 Purpose: If the score is between 80 and 89 (inclusive), this line will print "You received a B
grade." followed by a newline.

10. } else if (score >= 70) {

} else if (score >= 70) {

 Purpose: This line checks the else if condition after the previous else if condition fails
(if the score is less than 80).
o It checks if the score is greater than or equal to 70 but less than 80.
o If true, the code inside this block will execute.

11. printf("You received a C grade.\n");

printf("You received a C grade.\n");

 Purpose: If the score is between 70 and 79, this line will print "You received a C grade."
followed by a newline.

12. } else if (score >= 60) {

} else if (score >= 60) {

 Purpose: This line checks the else if condition, which is evaluated if all previous
conditions are false.
o It checks if the score is greater than or equal to 60 but less than 70.
o If true, the code inside this block will execute.

13. printf("You received a D grade.\n");

printf("You received a D grade.\n");

pg. 15
TCET Programming in C Module 3

 Purpose: If the score is between 60 and 69, this line will print "You received a D grade."
followed by a newline.

14. } else {

} else {

 Purpose: This line starts the else block, which is executed if all the previous conditions (if,
else if) are false.
o This means the score is less than 60.

15. printf("You received an F grade.\n");

printf("You received an F grade.\n");

 Purpose: If none of the previous conditions were true (meaning the score is less than 60),
this line will print "You received an F grade." followed by a newline.

16. return 0;

return 0;

 Purpose: This line marks the end of the main function and returns an integer value of 0 to
the operating system, which indicates that the program has executed successfully without
errors.

Summary of Execution:

1. The user is prompted to enter a score.


2. The if-else if-else structure checks the value of the score:
o If the score is 90 or higher, it prints "A grade."
o If the score is between 80 and 89, it prints "B grade."
o If the score is between 70 and 79, it prints "C grade."
o If the score is between 60 and 69, it prints "D grade."
o If the score is below 60, it prints "F grade."
3. The program ends after printing the grade.

Example Outputs:

 For input 95, the output will be:


 You received an A grade.
 For input 75, the output will be:
 You received a C grade.
 For input 50, the output will be:
 You received an F grade.

This structure allows the program to check multiple conditions in sequence and respond
accordingly based on the user's input.

pg. 16
TCET Programming in C Module 3

Menu-Driven Program Example in C


A menu-driven program allows the user to choose an option, and based on that input, a
corresponding action is taken. This is commonly used in calculators, games, or other
interactive programs.

Example: Simple Calculator (Menu-Driven)


include <stdio.h>

int main() {
int choice;
double num1, num2;

printf("Menu: \n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Multiply\n");
printf("4. Divide\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
printf("Sum: %.2f\n", num1 + num2);
break;

case 2:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
printf("Difference: %.2f\n", num1 - num2);
break;

case 3:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
printf("Product: %.2f\n", num1 num2);
break;

case 4:
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
if (num2 != 0) {
printf("Quotient: %.2f\n", num1 / num2);
} else {
printf("Error: Division by zero!\n");
}
break;

pg. 17
TCET Programming in C Module 3

case 5:
printf("Exiting the program.\n");
break;

default:
printf("Invalid choice. Please try again.\n");
}

return 0;
}

Explanation of the Program:

1. Menu: The program presents a simple menu with 5 options: Add, Subtract, Multiply, Divide,
and Exit.
2. User Input: The user is asked to enter their choice (1-5).
3. Switch Case: Based on the user's choice, the program:
o Prompts the user to enter two numbers.
o Performs the corresponding mathematical operation.
o If division is selected, it checks if the divisor is zero to avoid division by zero.
4. Exiting the Program: If the user selects the "Exit" option (choice 5), the program ends.

Summary of Branching Statements in C

 if Statement: Used for a simple decision-making scenario (one condition).


 if-else Statement: Used when there are two possible outcomes (true or false).
 if-else if-else Statement: Used when there are multiple conditions to check.
 switch Statement: More efficient for checking multiple possible values of a single variable.

Best Practices

1. switch Statements:
o Always use the break statement to exit the switch case after executing a block.
o Include a default case to handle unexpected or invalid inputs.
2. Avoid Deep Nesting: Try to avoid deeply nested if statements as they can make your
code harder to read. Instead, use switch or refactor into separate functions.
3. Clear and Readable Code: Write clear and easy-to-follow conditions in if-else
and switch statements to enhance readability.

pg. 18
TCET Programming in C Module 3

SR. No. Questions Refer pg. no.


2 Marks
1 What is the purpose of the if statement in C? 3
What is the difference between if and if-else statements
2 in C?
3-7
3 Explain the role of the else statement in C. 5
4 What does the switch statement do in C? 9
What is the purpose of the break statement in a switch
5 12
block?
6 What does the default case in a switch statement do? 13
7 What is the syntax of the if-else statement in C? 5
Explain how an if-else structure works in decision-
8 making.
5
What is the difference between switch and if-else else-
9 if statements in C?
5&9
10 Explain what is the need of if-else statement? 5
5 Marks
Explain how the switch statement works in C. Provide an
1 example of using a switch statement to find the grade 9
based on a score.
Write a program using an if-else statement to check if a
2 number is divisible by 2.
5
What is switch blocks explain in detail with one simple
3 example ?
9
Write a program using an if-else statement to check if a
4 number is positive, negative, or zero.
12
Write a program using a switch statement to print the
5 corresponding name of the day based on a number (1 for 9
Monday, 7 for Sunday).
What is the difference between if-else and else-if
6 statements in C?
12
Write a program using an if-else & else if structure to
7 determine the largest of three numbers.
12
What is the role of the else if statement in decision-
8 making? Provide an example.
12
Write a program that uses a nested if-else statement to
9 check if a given year is a leap year.
7
Write a program to determine whether a number is
10 divisible by both 2 and 5.
5
10 Marks
Write a menu-driven program that allows the user to
choose between three operations:
1 5, 9, 17
Option 1: Check if a number is even or odd.
Option 2: Check if a number is prime.

pg. 19
TCET Programming in C Module 3

Option 3: Calculate the factorial of a number.


The program should use either if-else or switch
statements.
Explain the differences between switch and if-else
2 statements in terms of performance, readability, and use 5&9
cases. Provide an example for each.
Write a program using an if-else else-if structure to
classify a student’s grade based on the score:11
3 12
A (90 and above), B (80-89), C (70-79), D (60-69), F (below 60).
Create a program that uses a switch statement to display
4 the corresponding season based on the month number (1- 9
3: Winter, 4-6: Spring, etc.).
Write a program using an if-else statement to determine
5 the largest of three numbers entered by the user.
5
write a program that takes a year as input and uses a
6 nested if-else statement to determine if it’s a leap year or 7
not.
Describe the functionality of the break statement in a loop
7 or switch block and provide an example.
12

pg. 20

You might also like