UNIT III
Decision Making & Branching
C has decision-making statements to support conditional logic. C conditional
statements allow you to make a decision based upon the result of a condition.
These statements are called Decision Making Statements or Conditional
Statements. C has a number of alternatives to add decision-making in the code.
In programming, we come across situations when we need to make some decisions.
Based on these decisions, we decide what should we do next. Similar situations
arise in algorithms too where we need to make some decisions and based on these
decisions, we will execute the next block of code.
This type of structure requires that the programmers indicate several conditions for
evaluation within a program. The statements will be executedif the condition
becomes true, and optionally, if the condition becomes false, an alternative statement
or set of statements will be executed.
The flowchart of the Decision-making technique in C can be expressed as:
Decision making is about deciding the order of execution of statements based on
certain conditions or repeat a group of statements until certain specified
conditions are met. C language handles decision-making by supporting the
following statements,
• if Statement
• if-else Statement
• Nested if Statement
• if-else-if Ladder
• switch Statement
• Conditional Operator
• Jump Statements:
➢ break
➢ continue
➢ goto
➢ return
Decision Making with If Statement:
In C programming, the if statement is a fundamental control structure used for
decision making. It allows you to execute a block of code if a specified condition
evaluates to true.
Syntax:
if (condition)
{
// block of code to be executed if the condition is true;
}
Flowchart of If Statement:
If the condition is fails the control goes outside the if statement. The if
statement in C allows you to control the flow of your program based on
conditions. For example write a program in C to find if the entered number is
positive or negative:
#include <stdio.h>
void main( )
{
int num;
printf ( “ Enter a number”);
scanf ( “%d”, &num);
if (num > 0)
{
printf("%d is a positive number.\n", num); }
if (num < 0)
{
printf("%d is a negative number.\n", num); }
if (num = = 0)
{
printf (“Entered number is Zero”); }
}
In this example:
- If `num` is greater than 0, it prints that `num` is a positive number. - If
`num` is less than 0, it prints that `num` is a negative number. - If `num` is
exactly 0, it prints that `num` is zero.
Decision Making with if else statement:
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do
something else when the condition is false? Here comes the C else statement. We
can use the else statement with the if statement to execute a block of code when
the condition is false. The if-else statement consists of two blocks, one for false
expression and one for true expression.
Syntax :
if(condition)
{
}
else
{
}
Flowchart of if-else Statement
For example write a program in C to check if a number is even or odd.
#include <stdio.h>
int main()
{
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num % 2 == 0)
printf("%d is an even number.\n", num);
}
else
{
printf("%d is an odd number.\n", num);
}
In this program:
➢ We prompt the user to enter an integer.
➢ We use scanf to read the input integer from the user and store it in the
variable num.
➢ We check if the number stored in num is even or odd using the modulo
operator %. If the remainder of num divided by 2 is 0, it means num is even;
otherwise, it's odd.
➢ We use an if-else statement to print the appropriate message depending on
whether the number is even or odd.
Nested if statement in C:
A nested if in C is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. C allows us to nested
if statements within if statements, i.e, we can place an if statement inside another
if statement.
Nested if-else statements in C are used when you need to test multiple conditions
within each other. This allows for more complex decision-making logic.
Syntax of Nested if-else
if(condition1)
{
if(condition2)
{
}
else
{
}
Flowchart of Nested if-else
For example write a program in C to enter age and check if they are eligible to vote
and classify them as a youth voter, middle-age voter, or senior citizenbased on their
age using nested if-else statements
#include <stdio.h>
void main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18)
printf("You are eligible to vote.\n");
if (age >= 18 && age <= 35)
{
printf("You are a youth voter.\n");
}
if (age >= 36 && age <= 60)
{
printf("You are a middle-age voter.\n");
}
If (age > 60)
{
printf("You are a senior citizen.\n");
}
else
{
printf("You are not eligible to vote.\n");
}
In this program:
➢ We prompt the user to enter their age.
➢ We use scanf to read the age input from the user and store it in the variable
age.
➢ We first check if the age is greater than or equal to 18 to determine if the
person is eligible to vote.
➢ If the person is eligible to vote, we then further check their age to classify
them into one of the three categories: youth voter (ages 18-35), middle age
voter (ages 36-60), or senior citizen (ages 61 and above).
➢ If the person is not eligible to vote (age less than 18), we print a message
indicating so.
Compile and run this program, and it will prompt you to enter your age. Based on
the age entered, it will determine if you are eligible to vote and classify you into one
of the three categories.
else if Ladder statement in C:
The if else if statements are used when the user has to decide among multiple
options. The C if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is executed,
and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed. if-else-if ladder is similar to the switch
statement.
Syntax of if-else-if Ladder
if(condition)
statement;
elseif(condition)
statement;
elseif(condition)
statement;
.
.
else
statement;
Flowchart of if-else-if Ladder
An "else-if ladder" in C refers to a series of `if-else if-else` statements chained
together to check multiple conditions. It's used when you have multiple
conditions to check and want to execute different blocks of code based on
these conditions.
For example:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0)
{
printf("Number is positive.\n");
}
else if (num < 0)
{
printf("Number is negative.\n");
}
else
{
printf("Number is zero.\n");
}
return 0;
}
In this example:
- We prompt the user to enter a number.
- We use an `else-if ladder` to check the number:
- If the number is greater than 0, it prints "Number is positive." - If
the number is less than 0, it prints "Number is negative."
- If the number is neither greater nor less than 0 (i.e., it's 0), it prints
"Number is zero."
You can extend the else-if ladder to handle more conditions as needed. Each `else
if` statement is evaluated only if the preceding conditions are false. If none of the
conditions are true, the code inside the `else` block is executed.
Example 2: C program that takes input as the percentage of a student and displays
the corresponding grade according to the given criteria:
#include <stdio.h>
void main()
{
float percentage;
printf("Enter the percentage: ");
scanf("%f", &percentage);
if (percentage >= 90 && percentage <= 100)
{
printf("Grade: A\n");
}
else if (percentage >= 80 && percentage < 90)
{
printf("Grade: B\n");
}
else if (percentage >= 70 && percentage < 80)
{
printf("Grade: C\n");
}
else if (percentage >= 60 && percentage < 70)
{
printf("Grade: D\n");
}
else if (percentage >= 50 && percentage < 60)
{
printf("Grade: E\n");
}
else
{
printf("Invalid percentage entered!\n");
}
This program first prompts the user to enter the percentage. Then, based on the
entered percentage, it evaluates which grade range the percentage falls
into and prints the corresponding grade. If the entered percentage is not within the
valid range (0 to 100), it displays an error message.
Switch Case statement in C:
In C programming, the switch statement is used as a control flow mechanism to
execute different blocks of code based on the value of an expression. It is
particularly useful when you have multiple conditions to check against a single
variable. The switch case statement is an alternative to the if else if ladder that can
be used to execute the conditional code based on the value of the variable specified
in the switch statement. The switch block consists of cases to be executed based on
the value of the switch variable.
Syntax:
The switch expression should evaluate to either integer or character. It cannot
evaluate any other data type.
Flowchart of switch
For example,WAP of a simple calculator in C that uses a `switch` statement to
perform different arithmetic operations:
In this program:
- The user is prompted to enter an operator (`+`, `-`, `*`, `/`). -
Then, the user is prompted to enter two numbers.
- Based on the operator entered, the program performs the corresponding
arithmetic operation using a `switch` statement.
- If the user enters an invalid operator or tries to divide by zero, appropriate error
messages are displayed.
Example1: C program that takes a number representing a month and
displays the corresponding month name:
#include <stdio.h>
int main() {
int monthNumber;
printf("Enter the month number (1-12): ");
scanf("%d", &monthNumber);
switch(monthNumber)
{
case 1:
printf("January\n");
break;
case 2:
printf("February\n");
break;
case 3:
printf("March\n");
break;
case 4:
printf("April\n");
break;
case 5:
printf("May\n");
break;
case 6:
printf("June\n");
break;
case 7:
printf("July\n");
break;
case 8:
printf("August\n");
break;
This program prompts the user to enter a number representing a month. Then,
based on the entered number, it uses a switch-case statement to determine the
corresponding month name and displays it. If the entered number is not within the
range of 1 to 12, it displays an error message.
Conditional and Unconditional branching in C
goto statement:
The C goto statement is a jump statement which is sometimes also referred to as
an unconditional jump statement. The goto statement can be used to jump from
anywhere to anywhere within a function.
Syntax:
Syntax1 | Syntax2
goto label; | label:
.|.
.|.
.|.
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the
statement marked as a label. Here, the label is a user-defined identifier that
indicates the target statement. The statement immediately followed after ‘label:’ is
the destination statement. The ‘label:’ can also appear before the ‘goto label;’
statement in the above syntax.
For example, WAP check if a number is even or odd.
#include <stdio.h>
void main()
{
int i = 0;
start: printf("i = %d\n", i);
i++;
if (i < 5)
goto start;
}
Loops in C:
Loops in programming are used to repeat a block of code until the specified
condition is met. A loop statement allows programmers to execute a statement or
group of statements multiple times without repetition of code.
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Loops are required to avoid writing statements unnecessarily and repeatedly. There
are mainly two types of loops in C Programming:
Entry Controlled loops: In Entry controlled loops the test condition ischecked
before entering the main body of the loop. For Loop and While Loop is Entry
controlled loops.
Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the
end of the loop body. The loop body will execute at least once, irrespective of
whether the condition is true or false. do-while Loop is Exit Controlled loop.
Loop Type Description
for loop first Initializes, then condition check, then executes the body
and at last, the update is done.
while first Initializes, then condition checks, and then executes the
loop body, and updating can be inside the body.
do-while do-while first executes the body and then the condition check is
loop done.
1. for Loop
for loop in C programming is a repetition control structure that allows programmers
to write a loop that will be executed a specific number of times. for loop enables
programmers to perform n number of steps together in a single line.
The for loop is used when you know how many times you want to execute a block of
code.
Syntax:
for (initialization; condition; increment)
{
// Code to be repeated
}
In for loop, a loop variable is used to control the loop. Firstly we initialize the loop
variable with some value, then check its test condition. If the statementis true then
control will move to the body and the body of for loop will be executed. Steps will be
repeated till the exit condition becomes true. If the test condition will be false then it
will stop.
• Initialization Expression: In this expression, we assign a loop variable or
loop counter to some value. for example: int i=1;
• Test Expression: In this expression, test conditions are performed. Ifthe
condition evaluates to true then the loop body will be executed and then an
update of the loop variable is done. If the test expression becomes false then
the control will exit from the loop. for example, i<=9;
• Increment Expression: After execution of the loop body loop variable is
updated by some value it could be incremented
{
int i;
for (i=1; i<=100; i++) {
For example
#include <stdio.h> void
main()
printf( "Hello World\n");
}
}
This program will give the same output.
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Example:
#include <stdio.h>
void main() {
int number;
int i;
printf ("Enter any number whose table is to be printed”);
scanf (“%d”, &number);
for (i = 1; i <= 10; i++)
printf("%d x %d = %d\n", number, i, number * i);
}
This program iterates through numbers from 1 to 10 and multiplies each number
with the entered number to display its corresponding product, effectively showing
the table of a number.
2. While Loop
While loop does not depend upon the number of iterations. In for loop the number
of iterations was previously known to us but in the While loop, the execution is
terminated on the basis of the test condition. If the test condition will become false
then it will break from the while loop else body will be executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
increment_expression;
}
Flow Diagram for while loop:
For example:
#include <stdio.h>
int main()
{
int i = 2;
while(i < 10)
printf( "Hello World\n");
i++;
}
return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Example:
#include <stdio.h>
int main() {
int number = 1275;
int i = 1;
printf("Table of %d:\n", number);
while(i <= 10)
printf("%d x %d = %d\n", number, i, number * i);
i++;
}
return 0;
}
This program uses a while loop to iterate through numbers from 1 to 10 and
multiplies each number with 1275 to display its corresponding product, effectively
showing the table of 1275. The loop condition i <= 10 ensures that the loop runs
until the value of i reaches 10.
3. do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do
while loop test condition which is tested at the end of the body. In the do- while loop,
the loop body will execute at least once irrespective of the test condition.
Syntax:
do
{
--------;
} while (test_expression);
For Example:
Output
Hello World
Above program will evaluate (i<1) as false since i = 2. But still, as it is a do while
loop the body will be executed once.
Loop Control Statements
Loop control statements in C programming are used to change execution from its
normal sequence.
Name Description
break the break statement is used to terminate the switch andloop
statement statement. It transfers the execution to the statement
immediately following the loop or switch.
continue continue statement skips the remainder body and
statement immediately resets its condition before reiterating it.
goto goto statement transfers the control to the labeled
statement statement.
Infinite Loop
An infinite loop is executed when the test expression never becomes false and the
body of the loop is executed repeatedly. A program is stuck in an Infinite loop when
the condition is always true. Mostly this is an error that can be resolved by using
Loop Control statements.
Using for loop:
C
for ( ; ; )
Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...
Using While loop:
Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...
Using the do-while loop:
} while (1);
Output
This loop will run forever.
This loop will run forever.
This loop will run forever. ...