0% found this document useful (0 votes)
18 views

Unit 3 Notes

Uploaded by

sanskarkale24
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Unit 3 Notes

Uploaded by

sanskarkale24
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Unit 3 Control Flow

CONTROL FLOW
The conditional statements (also known as decision control
structures) such as if, if else, switch, etc. are used for decision-
making purposes in C programs.
They are also known as Decision-Making Statements and are used to
evaluate one or more conditions and make the decision whether to
execute a set of statements or not. These decision-making
statements in programming languages decide the direction of the
flow of program execution.
Need of Conditional Statements
There come situations in real life when we need to make some
decisions and based on these decisions, we decide what should we
do next. Similar situations arise in programming also where we need
to make some decisions and based on these decisions we will
execute the next block of code. For example, in C if x occurs then
execute y else execute z. There can also be multiple conditions like in
C if x occurs then execute p, else if condition y occurs execute q, else
execute r. This condition of C else-if is one of the many ways of
importing multiple conditions.
1. if in C
The if statement is the most simple decision-making statement. It is
used to decide whether a certain statement or block of statements
will be executed or not i.e if a certain condition is true then a block of
statements is executed otherwise not.
Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
Unit 3 Control Flow

}
Here, the condition after evaluation will be either true or false. C if
statement accepts boolean values – if the value is true then it will
execute the block of statements below it otherwise not. If we do not
provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default
if statement will consider the first immediately below statement to
be inside its block.
Flowchart of if Statement

Flow Diagram of if Statement


Example of if in C
C
// C program to illustrate If statement
#include <stdio.h>
Unit 3 Control Flow

int main()
{
int i = 10;
if (i > 15) {
printf("10 is greater than 15");
}
printf("I am Not in if");
}
Output
I am Not in if

2. if-else in C
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 of if else in C
if (condition)
{
// Executes this block if
// condition is true
}
else
{
Unit 3 Control Flow

// Executes this block if


// condition is false
}
Flowchart of if-else Statement

Example of if-else
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 20;
Unit 3 Control Flow

if (i < 15) {
printf("i is smaller than 15");
}
else {
printf("i is greater than 15");
}
return 0;
}

Output
i is greater than 15
The block of code following the else statement is executed as the
condition present in the if statement is false.

3. Nested if-else 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. Yes, C allow us to nested if statements within if
statements, i.e, we can place an if statement inside another if
statement.
Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{
// statement 1
Unit 3 Control Flow

}
else
{
// Statement 2
}
}
else {
if (condition_3)
{
// statement 3
}
else
{
// Statement 4
}
}
The below flowchart helps in visualize the above syntax.
Flowchart of Nested if-else
Unit 3 Control Flow

Example of Nested if-else


C
// C program to illustrate nested-if statement
#include <stdio.h>

int main()
Unit 3 Control Flow

{
int i = 10;
if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
else {
if (i == 20) {
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 22)
printf("i is smaller than 22 too\n");
else
printf("i is greater than 25");
Unit 3 Control Flow

}
}
return 0;
}

Output
i is smaller than 15
i is smaller than 12 too

4. if-else-if Ladder 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;
else if (condition)
statement;
.
.
else
statement;
Flowchart of if-else-if Ladder
Unit 3 Control Flow

Flow Diagram of if-else-if


Example of if-else-if Ladder
C
// C program to illustrate nested-if statement
#include <stdio.h>
int main()
{
int i = 20;
if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
Unit 3 Control Flow

printf("i is not present");


}

Output
i is 20

Switch Statement in C
C switch-case Statement
The switch-case statement is a decision-making statement in C.
The if-else statement provides two alternative actions to be
performed, whereas the switch-case construct is a multi-way
branching statement. A switch statement in C simplifies multi-way
choices by evaluating a single variable against multiple values,
executing specific code based on the match. It allows a variable to be
tested for equality against a list of values.

Syntax of switch-case Statement


The flow of the program can switch the line execution to a branch
that satisfies a given case. The schematic representation of the usage
of switch-case construct is as follows −
switch (Expression){

// if expr equals Value1


case Value1:
Statement1;
Statement2;
Unit 3 Control Flow

break;
// if expr equals Value2
case Value2:
Statement1;
Statement2;
break;
.
.
// if expr is other than the specific values above
default:
Statement1;
Statement2;
}
How switch-case Statement Work?
The parenthesis in front of the switch keyword holds an expression.
The expression should evaluate to an integer or a character. Inside
the curly brackets after the parenthesis, different possible values of
the expression form the case labels.
One or more statements after a colon(:) in front of the case label
forms a block to be executed when the expression equals the value
of the label.
You can literally translate a switch-case as "in case the expression
equals value1, execute the block1", and so on.
C checks the expression with each label value, and executes the
block in front of the first match. Each case block has a break as the
Unit 3 Control Flow

last statement. The break statement takes the control out of the
scope of the switch construct.
You can also define a default case as the last option in the switch
construct. The default case block is executed when the expression
doesn’t match with any of the earlier case values.

Flowchart of switch-case Statement


The flowchart that represents the switch-case construct in C is as
follows −

Rules for Using the switch-case Statement


The following rules apply to a switch statement −
 You can have any number of case statements within a switch.
Each case is followed by the value to be compared to and a
colon.
Unit 3 Control Flow

 The constant-expression for a case must be the same data type


as the variable in the switch, and it must be a constant or
a literal.
 When the variable being switched on is equal to a case, the
statements following that case will execute until a break
statement is reached.
 When a break statement is reached, the switch terminates, and
the flow of control jumps to the next line following the switch
statement.
 Not every case needs to contain a break. If no break appears,
the flow of control will fall through to subsequent cases until a
break is reached.
 A switch statement can have an optional default case, which
must appear at the end of the switch. The default case can be
used for performing a task when none of the cases is true. No
break is needed in the default case.
C switch-case Statement Examples

Practice the following examples to learn the switch case statements in


C programming language –

Example 1

In the following code, a series print three different greeting messages


based on the value of a "ch" variable ("m", "a" or "e" for morning,
afternoon or evening).

#include <stdio.h>
int main (){
// local variable definition
char ch = 'm';
Unit 3 Control Flow

printf("Time code: %c\n\n", ch);


switch (ch){
case 'a':
printf("Good Afternoon\n");
break;
case 'e':
printf("Good Evening\n");
break;
case 'm':
printf("Good Morning\n");
}
return 0;
}

Example 2
#include <stdio.h>
int main (){
// local variable definition
int a = 10, b = 5;
// Run the program with other values 2, 3, 4, 5
int op = 1;
float result;
printf("1: addition\n");
printf("2: subtraction\n");
Unit 3 Control Flow

printf("3: multiplication\n");
printf("4: division\n");
printf("\na: %d b: %d : op: %d\n", a, b, op);
switch (op){
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
printf("Invalid operation\n");
}
printf("Result: %f", result);
return 0;
}
Unit 3 Control Flow

C - While Loop
The while loop is often called the entry verified loop
Syntax of C while Loop
The syntax of constructing a while loop is as follows −
while(expression){
statement(s);
}
The while keyword is followed by a parenthesis, in which there
should be a Boolean expression. Followed by the parenthesis, there
is a block of statements inside the curly brackets.

Flowchart of C while Loop


The following flowchart represents how the while loop works −
Unit 3 Control Flow

How while Loop Works in C?


The C compiler evaluates the expression. If the expression is true, the
code block that follows, will be executed. If the expression is false,
the compiler ignores the block next to the while keyword, and
proceeds to the immediately next statement after the block.
Since the expression that controls the loop is tested before the
program enters the loop, the while loop is called the entry verified
loop. The while keyword implies that the compiler continues to
execute the ensuing block as long as the expression is true. The
condition sits at the top of the looping construct. After each
iteration, the condition is tested. If found to be true, the compiler
performs the next iteration. As soon as the expression is found to be
false, the loop body will be skipped and the first statement after the
while loop will be executed.

Example of while Loop in C


The following program prints the "Hello World" message five times.
Open Compiler
#include <stdio.h>
int main(){
// local variable definition
int a = 1;
// while loop execution
while(a <= 5){
printf("Hello World \n");
a++;
}
Unit 3 Control Flow

printf("End of loop");
return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
End of loop

Do-While Loop in C
The do and while keywords are used together to form a loop. The do-
while is an exit-verified loop where the test condition is checked
after executing the loop's body. Whereas the while loop is an entry-
verified. The for loop, on the other hand, is an automatic loop.
Syntax of do while Loop
The syntax of do-while loop in C is −
do {
statement(s);
} while(condition);

How do while Loop Works?


The loop construct starts with the keword do. It is then followed by a
block of statements inside the curly brackets. The while keyword
Unit 3 Control Flow

follows the right curly bracket. There is a parenthesis in front


of while, in which there should be a Boolean expression.
Now let's understand how the while loop works. As the C
compiler encounters the do keyword, the program control enters
and executes the code block marked by the curly brackets. As the
end of the code block is reached, the expression in front of
the while keyword is evaluated.
If the expression is true, the program control returns back to the top
of loop. If the expression is false, the compiler stops going back to
the top of loop block, and proceeds to the immediately next
statement after the block. Note that there is a semicolon at the end
of while statement.
Flowchart of do while Loop
The following flowchart represents how the do-while loop works −
Unit 3 Control Flow

Example of do while Loop


The following program prints the Hello world message five times.
Open Compiler
#include <stdio.h>
int main(){
// local variable definition
int a = 1;
// while loop execution
do{
printf("Hello World\n");
a++;
} while(a <= 5);
printf("End of loop");
return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
End of loop
Unit 3 Control Flow

Difference Between while and do while Loops


The loops constructed with while and do-while appear similar. You
can easily convert a while loop into a do-while loop and vice versa.
However, there are certain key differences between the two.
The obvious syntactic difference is that the do-while construct starts
with the do keyword and ends with the while keyword.
The while loop doesn't need the do keyword. Secondly, you find a
semicolon in front of while in case of a do-while loop. There is no
semicolon in while loops.

For Loop in C
The for loop is an entry-controlled loop that executes the statements
till the given condition. All the elements (initialization, test condition,
and increment) are placed together to form a for loop inside the
parenthesis with the for keyword.
The for loop in C Language provides a functionality/feature to repeat
a set of statements a defined number of times.
Syntax of for Loop
for(initialization; check/test expression; updation)
{
// body consisting of multiple statements
}
1. Initialization: This step initializes a loop control variable with an
initial value that helps to progress the loop or helps in checking
the condition. It acts as the index value when iterating.
2. Check/Test Condition: This step of the for loop defines the
condition that determines whether the loop should continue
executing or not. The condition is checked before each iteration
Unit 3 Control Flow

and if it is true then the iteration of the loop continues


otherwise the loop is terminated.
3. Body: It is the set of statements i.e. variables, functions, etc
that is executed repeatedly till the condition is true. It is
enclosed within curly braces { }.
4. Updation: This specifies how the loop control variable should
be updated after each iteration of the loop. Generally, it is the
incrementation (variable++) or decrementation (variable–) of
the loop control variable.

Control Flow of a For Loop


Here is how the control flows in a "for" loop −
The init step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required
to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and the
control jumps to the next statement just after the "for" loop.
After the body of the "for" loop executes, the control flow jumps
back up to the increment statement. This statement allows you to
update any loop control variables. This statement can be left blank,
as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes
and the process repeats itself (body of loop, then increment step,
and then again the condition). After the condition becomes false, the
"for" loop terminates.

Flowchart of for Loop


The following flowchart represents how the for loop works −
Unit 3 Control Flow

Example: Basic for Loop


This is the most basic form of the for loop. Note that all the three
clauses inside the parenthesis (in front of the for keyword) are
optional.
Open Compiler
#include <stdio.h>

int main(){
int a;
Unit 3 Control Flow

// for loop execution


for(a = 1; a <= 5; a++){
printf("a: %d\n", a);
}

return 0;
}
Output
Run the code and check its output −
a: 1
a: 2
a: 3
a: 4
a: 5

Jumps in loop
Jump statements are used to jump from one part of the code to
another altering the normal flow of the program.They are used to
transfer the program control to somewhere else in the program.
Types of Jump Statements in C
There are 4 types of jump statements in C:
1. break
1. continue
2. goto
Unit 3 Control Flow

1. break in C
The break statement exits or terminates the loop or switch
statement based on a certain condition, without executing the
remaining code.
Syntax of break in C
break;

Uses of break in C
The break statement is used in C for the following purposes:
1. To come out of the loop.
1. To come out from the nested loops.
1. To come out of the switch case.
Unit 3 Control Flow

#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
printf("%d ", i);
}
printf("Loop exited.\n");
return 0;
}

2.continue
The continue statement in C is used to skip the remaining code after
the continue statement within a loop and jump to the next iteration
of the loop. When the continue statement is encountered, the loop
control immediately jumps to the next iteration, by skipping the lines
of code written after it within the loop body.
Syntax of continue in C
continue;
Unit 3 Control Flow

#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 5; i++) {
if (i == 2) {
printf("Skipping iteration %d\n", i);
continue;
}
printf("Executing iteration %d\n", i);
}
return 0;
}
Unit 3 Control Flow

3. goto
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.
The goto keyword is followed by a label. When executed, the
program control is redirected to the statement following the label. If
the label points to any of the earlier statements in a code, it
constitutes a loop. On the other hand, if the label refers to a further
step, it is equivalent to a Jump.
The label is any valid identifier in C. A label must contain
alphanumeric characters along with the underscore symbol (_). As in
case of any identifier, the same label cannot be specified more than
once in a program. It is always followed by a colon (:) symbol. The
statement after this colon is executed when goto redirects the
program here.
Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
Unit 3 Control Flow

#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}
Unit 3 Control Flow

You might also like