Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views71 pages

Unit III Control Flow

This document covers control flow in C programming, focusing on decision-making and branching using statements like if, if-else, nested if, else-if ladder, switch, and goto. It also discusses looping structures such as while, do-while, and for statements, along with break and continue commands. Examples of each control structure are provided to illustrate their usage in programming.

Uploaded by

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

Unit III Control Flow

This document covers control flow in C programming, focusing on decision-making and branching using statements like if, if-else, nested if, else-if ladder, switch, and goto. It also discusses looping structures such as while, do-while, and for statements, along with break and continue commands. Examples of each control structure are provided to illustrate their usage in programming.

Uploaded by

abolimes4444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 71

UNIT III

Control Flow
Presented by:
Prof.Supriya Jadhav-Deshmukh
Decision Making & Branching

Simple If Statement

If-Else

Else-If

Switch Statement

Goto Statement

2
Decision Making & Looping

While Statement

Do-While

For Statement

Break & Continue

3
Decision Making & Branching
Introduction about Control Structure:

Program by default always execute in a sequential manner.

After every instruction,the processor goes to the next instruction
& continous executing the program in a straight line.

Sometimes we need to take a BRANCH in the program and
change its flow.

This happens during conditional statements like an if-else,or kind
of loop like for loop etc.

4
Cont...

C program is a set of statements which are normally executed
sequentially in the order in which they appear.

This happens when no options or no repetitions of certain
calculations are necessary.

However, in practice, we have a number of situations where we
may have to change the order of execution of statements based
on certain conditions, or repeat a group of statements until
certain specified conditions are met.

5
DECISION MAKING WITH IF STATEMENT

The if statement is a powerful decision making statement & it is used to control
the flow of execution of a statements.

It is basically a two-way decision statement and is used in conjunction with an
expression.
if (test expression)

It allows the computer to evaluate the expression first then,depending on
whether the value of the expression is true or false,it transfer the control to a
particular statement.

This point of program has two paths to follow, one for the true condition and the
other for the false condition.

6
Cont...
Some examples of decision making, using if statements:

If (bank balance is zero)


Borrow money
If (room is dark)
Put on lights
If (age is more than 55)
person is retired

7
SIMPLE IF STATEMENT
-It allows the computer to evaluate the expression/condition first
and them depending on whether the value of the
expression/condition is "true" or "false", it transfer the control
to a particular statements.
-This point of program has two paths to flow, one for the true and
the other for the false condition.
-If condition becomes true than it executes statements written in
true block if condition fails than true block will be skipped.

8
Syntax Flowchart

if(test-expression/condition)
{
True statement-block;
{
Statement-x;

9
Syntax Example

------------------------
if(test-expression/condition) ------------------------
{ if(balance>5000)
True statement-block; {
} bonus=0.5*balance;
Statement-x; }
balance=balance+bonus;
---------------------------------
-------------------------------

10
C program to check equivalence of two
numbers using if statement.
#include<stdio.h>
int main()
{
int m,n;

printf(" \n enter two numbers:");


scanf(" %d %d", &m, &n);
if(m-n==0)
printf(“\n two numbers are equal");
return 0;
}

11
C program calculate the absolute value of an
integer using if statement.
#include<stdio.h>
int main()
{
int no;
printf("enter a no");
scanf("%d",&no);
if(no<0)
{
no=- no;
}
printf("The absolute value is %d\n",no);
return 0;
}

12
NOTE:
If statement will execute one statement bellow to it by default,
if we want to execute more than one statement, then those all
statements we have to group in open and close Curly brackets { and }.

13
THE IF.....ELSE STATEMENT
-The if-else statement is an extension of the simple if statement.
-If the test- expression/condition is true, then true-block
statements immediately following if statement are executed
otherwise the false block statements executed.
-In other case, either true-block or false-block will be executed,
not both.

14
Syntax

if(test-expression/condition)
{
True statement-block;
{
else
{
false statement-block;
}
Statement-x;

15
Syntax Example

------------------------
if(test-expression/condition) ------------------------
{ if(balance>5000)
True statement-block; {
{
else bonus=0.5*balance;
{ }
false statement-block; else
} {
Statement-x; bonus =0.04*balance;
}
balance=balance+bonus;
---------------------------------
-------------------------------
16
C program to read any number as input through the
keyboard and find out whether it is Odd Number or Even
Number.
#include<stdio.h>
int main()
{
int n;
printf("Enter the Number");
scanf("%d",&n);
if(n%2==0)
{
printf("This is Even Number");
}
else
{
printf("This is Odd Number");
}
return 0;
}

17
C program to find biggest among two numbers
using if else.
#include<stdio.h>
int main()
{
int a,b;

printf("Enter the two Number");


scanf("%d%d",&a,&b);
if(a>b)
{
printf("The number a %d is bigger", a);
}
else
{
printf("The number b %d is bigger",b);

}
return 0;
}

18
Nested if….else statement:
-C language supports if-else statements to test additional
conditions apart from the initial test expression.
-The if-else construct works in the same way as normal if
statement nested if construct is also know as if-else-if construct.
-When an if statement occurs within another if statement, then
such type of is called nested if statement.

19
Cont...
-when a series of decisions are
involved, we may have to use more
than one if...else statement in
nested form.
-if the condition-1 is false, the
statement-3 will be executed;
otherwise it continues to perform
the second test. if the condition-2 is
true,the statement-1 will be
evaluated; otherwise the statement-
2 will be evaluated and then the
control is transferred to the
20
statemet-x.
21
Syntax Example

------------------------
if(test-expression/condition) if(A>B)
{ {
if(test condition) if(A>C)
{ printf(“largest no%f\n”,A);
Statement 1;
} Else
Else printf(“largest no%f\n”,C);
{ }
Statement 2; else
} {if(C>B)
} printf(“largest no%f\n”,C);
Else Else
{ printf(“largest no%fn”,B);
Statement 3; }
} -------------------------------
Statement x; 22
Example
C program if the ages of Ram, sham and Ajay are input
through the keyboard, write a program to determine the
youngest of the three.

23
#include< stdio.h > Else
void main() {
{ if(sham < ajay)
int ram,sham,ajay; {
printf("Enter the Three Ages of printf("Sham is Youngest");
Ram,Sham and Ajay\n"); }
scanf("%d%d%d",&ram,&sham,&ajay); else
if(ram < sham) {
{ printf("Ajay is Youngest");
if(ram < ajay)
{ }
printf("Ram is Youngest"); }
} return 0;
else }
{
printf("Ajay is Youngest");
}
} 24
Cont...
C program to check whether person is eligible for work or
not.

25
{
#include <stdio.h>
printf("You are Eligible to Work \n");
int main()
printf("Please fill in your details and apply\n")
{
}
int age; else
printf("Please Enter Your Age Here:\n"); {
scanf("%d",&age); printf("You are too old to work as per the
if ( age < 18 ) Government rules\n");
{ printf("Please Collect your pension! \n");
printf("You are Minor.\n"); }
printf("Not Eligible to Work"); }
return 0;
}
}
else
{
if (age >= 18 && age <= 60 )

26
THE ELSE IF LADDER

-if else if ladder in C programming is used to test a series of conditions


sequentially.
-Furthermore, if a condition is tested only when all previous if conditions in the if-
else ladder are false. If any of the conditional expressions evaluate to be true,
the appropriate code block will be executed, and the entire if-else ladder will be
terminated.
-The conditions are evaluated from the top to bottom. As soon as true condition is
found the statement associated with it is executed and the control is transferred
to statement-x (skipping the restof ladder) when all the conditions become
false, then the final else containing the default statement will be executed.

27
Syntax

28
29
Synrax Example
if(condition 1)
Statement 1; ---------------------------
Else if(condition 2) if(marks>79)
Statement 2;
Else if (condition 3) grade=”Honour”;
Statement 3;
Else if(marks>59)
Else if (condition n)
Statement n; grade=”first division”;
Else Else if(marks>44)
Default statement; grade =”second division”;
Statement x; Else if (marks>29)
Grade =”thidr division”
30
Else
C Program to print grade of a student using If
Else Ladder Statement.
#include<stdio.h>
void main() }
{ else if (marks >= 50 && marks < 70)
int marks; {
printf("Enter your marks between 0-100\n"); printf("YOUR GRADE : C\n");
scanf("%d", &marks); }
if(marks >= 90) Else
{ {
printf("YOUR GRADE : A\n"); printf("YOUR GRADE : Failed\n")
} }
else if (marks >= 70 && marks < 90) return 0;
{ }
printf("YOUR GRADE : B\n");

31
THE SWITCH STATEMENT

-A switch statement allows a variable to be tested for equality against


a list of values.
-Each value is called a case, and the variable being switched on is
checked for each switch case.
-C has a built-in multiway decision statement known as a switch.
The switch statement tests the value of a given variable (or
expression) against a list of case values and when a match is
found, a block of statements associated with that case is executed.
-The general form of the switch statement is as shown below:

32
Cont...
-Switch case statements follow a selection-control mechanism and
allow a value to change control of execution.
-They are a substitute for long if statements that compare a variable
to several integral values.
-The switch statement is a multiway branch statement. It provides
an easy way to dispatch execution to different parts of code
based on the value of the expression.
-In C, the switch case statement is used for executing one condition
from multiple conditions. It is similar to an if-else-if ladder.

33
The following rules apply to a switch statement −
1.The expression used in a switch statement must have an integral or
character type, or be of a class type in which the class has a single
conversion function to an integral or enumerated type.
2.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 (:).
3.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.
4.When the variable being switched on is equal to a case, the
statements following that case will execute until a break statement is
reached.

34
Cont...
5.When a break statement is reached, the switch terminates, and the
flow of control jumps to the next line following the switch statement.
6.Not every case needs to contain a break.If no break appears, the
flow of control will follow through to subsequent cases until a break
is reached.
7.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.

35
Syntax
switch(expression)
{
case value1: statement_1;
Break;
case value2: statement_2;
Break;
.
.
. case value_n: statement_n;
Break;
default: default_statement;
}

36
Flowchart

37
Example
C Program to create a simple calculator performs addition,
subtraction, multiplication or division depending the input from
user.

38
# include <stdio.h>
int main() break;
{ case '*': mul=a*b;
char operator; printf("multiplication is%d",mul);
int a,b,sum,sub,div,mul; break;
printf("Enter an operator (+, -, *, /): "); case '/': div=a/b;
scanf("%c", &operator); Printf(“division is%d”,div);
printf("Enter two operands: ");
scanf("%d%d",&a, &b);
switch(operator) break;
{ default: printf("Error! operator is not
correct");
case '+': sum=a+b; }
printf("sum is %d",sum); return 0;
break; }
case '-': sub=a-b;
printf(" substraction is %d", sub); 39
C program to Check Character is Vowel or not using Switch Case
if it is vowel which

40
#include <stdio.h> case 'I': printf(" %c is a vowel", ch);
void main() Break;
{ case 'o':
char ch; case 'O': printf(" %c is a vowel", ch);
printf(" Enter any character: "); Break;
scanf("%c", &ch); case 'u':
switch (ch) case 'U': printf(" %c is a vowel", ch);
{ Break;
case 'a': default:printf(" %c is not a vowel", ch);
case 'A': printf(" %c is a vowel", ch); }
Break; Return 0;
case 'e': }
case 'E': printf(" %c is a vowel", ch);
Break;
case 'i':

41
Goto
-A goto statement in C programming provides an unconditional
jump from the 'goto' to a labeled statement in the same function.

NOTE − Use of goto statement is highly discouraged in any


programming language because it makes difficult to trace the
control flow of a program, making the program hard to
understand and hard to modify. Any program that uses a goto
can be rewritten to avoid them.

42
Syntax

BACKWARD goto
FORWARD goto
label: statement;
goto label; -----------------
------------ -----------------
------------ Goto label;
label: statement;

43
44
#include<stdio.h> #include<stdio.h>
int main() #include<math.h>
{ int main()
printf (“Hello Worldn”); {
goto Label; int num;
printf(“How are you?”);
printf(“Are you Okey?”);
int answer;
Label: Label:
printf(“Hope you are fine”); printf (“Enter a number:”);
Return 0; scanf(“%d”,&num);
} if(num>0)
answer = sqrt(num);
printf(“Square root of %d is
%dn”,num,answer);
goto Label;
Return 0; 45
}
Decision Making and Looping

While Statement

Do-While

For Statement

Break & Continue

46
THE WHILE STATEMENT
The simplest of all the looping structures in C is the while statement.
We have used while in many of our earlier programs. The basic
format of the while statement is:

Syntax :
while (test condition)
{
body of the loop
}

47
Cont...
-The while is an entry-controlled loop statement. The test-condition
is evaluated and if the condition is true,then the body of loop is
executed.
After execution of body ,the test condition is once again evaluated
and if it is true, the body is executed once again. This process of
repeated execution of the body contineous until the test
condition finally become false and the control is transfer out of
the loop.

48
Flowchart

49
Working:
step1: The loop variable is initialized with some value and then it
has been tested for the condition.
step2: If the condition returns true then the statements inside the
body of while loop are executed else control comes out of the
loop.
step3: The value of loop variable is incremented/decremented then
it has been tested again for the loop condition.

50
C program to Calculate sum of digits using while
loop.
#include<stdio.h>
Main()
{
int a, s;
printf("Enter value of a: ");
scanf("%d",&a);
S = 0;
while(a > 0)
{
s = s + (a%10);
a = a / 10;
}
printf("Sum of digits: %d",s);
Retuen 0;
}

51
Do while statement
do-while loop: is an exit controlled loop i.e. the condition is
checked at the end of loop.
-It means the statements inside do-while loop are executed at least
once even if the condition is false.
-Do-while loop is an variant of while loop.

52
Syntax:
Initialization of loop variable;
Do
{
Statement 1;
Statement 2;
---------------
statement n;
updation of loop variable;
}while (condition);

NOTE: We have to place semi-colon after the While condition.

53
Flowchart

54
Working
1. First we initialize our variables, next it will enter into the Do
While loop.
2. It will execute the group of statements inside the loop.
3. Next we have to use Increment and Decrement Operator inside
the loop to increment or decrements the value.
4. Now it will check for the condition. If the condition is True, then
the statements inside the do while loop will be executed again. It
will continue the process as long as the condition is True.
5. If the condition is False then it will exit from the loop.

55
Example: Write a C program to print the sum of
all even and odd numbers up to n.
#include<stdio.h>
Main()
{ s2=s2+i;
int n,s1=0,s2=0,i; i++;
printf("Enter Number : "); }while(i<=n);
scanf("%d",&n); printf("\nSum of Even Numbers : %d\n",s1);
i=1; printf("\nSum of Odd Numbers : %d\n",s2);
Do return 0;
{ }
if(i%2==0)
s1=s1+i;
Else

56
57
FOR STATEMENT
: This is one of the most frequently used loop in C programming.
This is an entry control loop.
The for loop is another entry-controlled loop that provides a more
concise loop control structure.
The general form of the for loop is
for (initialization; condition test; increment or decrement)
{
//Statements to be executed repeatedly
}

58
59
Working:
Step 1: First initialization happens and the counter variable gets
initialized.
Step 2: In the second step the condition is checked, where the
counter variable is tested for the given condition.if the condition
returns true then the C statements inside the body of for loop gets
executed, if the condition returns false then the for loop gets
terminated and the control comes out of the loop.
Step 3: After successful execution of statements inside the body of
loop, the counter variable is incremented or decremented,
depending on the operation (++ or –).

60
C Program to calculate the sum of n natural
numbers.
#include <stdio.h>
Main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when num is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
Return 0;
}

61
Various forms of for loop in C:
1) Initialization part can be skipped from loop as shown below, the
counter variable is declared before the loop.
int num=10;
for (;num<20;num++)
Note: Even though we can skip initialization part but
semicolon (;) before condition is must, without which you
will get compilation error.

62
Cont...
2) Like initialization, you can also skip the increment part as we did
below. In this case semicolon (;) is must after condition logic. In
this case the increment or decrement part is done inside the
loop.
for (num=10; num<20; )
{
//Statements
Num++;
}

63
Cont...
3) This is also possible. The counter variable is initialized before
the loop and incremented inside the loop.
int num=10;
for (;num<20;)
{
//Statements;
Num++;
}

64
Cont...
4) As mentioned above, the counter variable can be decremented
as well. In the below example the variable gets decremented
each time the loop runs until the condition num>10 returns false.
for(num=20; num>10; num--)

65
66
Nested For Loop in C:
#include <stdio.h>
Main()
{
for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
printf("%d, %d\n",i ,j);
}
}
Return 0;
}
In the above example we have a for loop inside another for loop, this is called nesting of loops. One
of the example where we use nested for loop is Two dimensional array.

67
Break
Break: It is used to terminate a switch statement.
BREAK is a keyword that allows us to jump out of a loop instantly,
without waiting to get back to the conditional test.
The break statement terminates the loop (for, while and do...while
loop) immediately when it is encountered. The break statement
is used with decision making statement such as if...else.

Syntax of break statement


Break;

68
69
Continue
The continue statement skips some statements inside the loop.
The continue statement is used with decision making statement
such as if...else.
Syntax of continue Statement
continue;

70
71

You might also like