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

L4_Control flow

Uploaded by

roukff61736220
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)
3 views

L4_Control flow

Uploaded by

roukff61736220
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
You are on page 1/ 6

if Statement if-else Statement

• Using if statement, you can make your decision based on a condition. • Using if-else statement, you can make your decision based on a condition.
• If the condition is true (i.e. the value of the expression is non-zero or non- • If the condition is true (i.e. the value of the expression is non-zero or non-
null), the if statement will operate. null), the if statement will operate.
• If the condition is false (i.e. the value of the expression is zero or null), the • If the condition is false (i.e. the value of the expression is zero or null), the
compiler will bypass the if statement. else portion will operate.
Examples: Examples:
if(expression) statement 1; • if(expression)
if(expression) { statement 1; statement 2; } statement 1;
else statement 2;
• if (x == 2) x >>= 1; • if(expression)
• if (x == 2) x >>= 1; x <<= 1; statement 1;
• if (x == 2) { x >>= 1; x <<= 1; } else { statement 2; statement 3; }
• if (x == 2) x >>= 1; else x <<= 1;
• if (x == 2) { x >>= 1; x <<= 1; } else x = 0;

Nested if-else Statement else if Statement


• if or if-else statement can be used within another if or if-else statement. • Using else if statement you can add a condition in the else portion.
Examples: • This greatly simplifies the conditional construction.
•if (expression)
• if (expression) statement 1; Examples:
{ if (expression) else if (expression)
statement 1; { statement 2; statement 1;
else if (expression) else if (expression)
statement 3;
statement 2; } statement 2;
else
statement 4; } else statement 3;
if (x == 2)
x >>= 1; if (x == 2)
else { if (x == 2)
if ( y == 3)
{ x >>= 1;
x=y;
if (x!=0) } else if (x!=0)
x <<= 1; else y=x; x <<= 1;
else x = 2; else x = 2;
}
else if Statement Switch Statement
#include <stdio.h> • A switch statement allows a variable to be tested for equality against a list
of values.
void main()
• You can have any number of case statements within a switch. Each case is
{ int a=100;
followed by the value to be compared to and a colon.
if(a>10) printf("ME 171"); Output: ME171
• The constant-expression for a case must be the same data type as the
else if(a>20) printf("\nC programming"); variable in the switch, and it must be a constant.
else if(a>30) printf("\nComputer Programming"); } • The expression in switch must be integer or character type.
Switch (expression)
#include <stdio.h> { case constant-expression :
void main() statement(s);
{ int a=100; break; /* optional */
if(a>10) printf("ME 171"); Output: ME171 case constant-expression :
if(a>20) printf("\nC programming"); C programming statement(s);
else if(a>30) printf("\nComputer Programming"); } break; /* optional */ /* you can have any number of case
statements */
default : /* Optional */ statement(s); }

Switch Statement Switch Statement


• When the variable in switch expression is #include <stdio.h> #include <stdio.h>
equal to a case, the statements following int main () int main ()
that case will execute until a break { char grade; grade=getchar(); { float grade_point;
statement is reached. switch(grade) scanf("%f",&grade_point);
• When a break statement is reached, the { case 'A' : printf("Excellent!\n" ); switch(grade_point)
whole switch terminates, and the flow of
break; { case 4.0 : printf("Excellent!\n" );
control jumps to the next operation
following the switch statement. case 'B' : break;
• Not every case needs to contain a break. If case 'C' : printf("Well done\n" ); case 3.75 :
no break appears, the flow of control will fall break; case 3.5 : printf("Well done\n" );
through to subsequent cases until a break is case 'D' : break;
reached. case ‘E‘ : printf("You passed\n" ); case 3.25 : printf("You passed\n" );
• A switch statement can have an optional break;
default case, which must appear at the end break;
case 'F' : printf("Better try again\n" ); default : printf("Invalid grade\n" ); }
of the switch. The default case can be used
for performing a task when none of the break; return 0; }
cases is true like else portion in if-else default : printf("Invalid grade\n" ); }
statement. No break is needed in the printf("Your grade is %c\n", grade );
error: switch quantity not an integer/
default case. return 0;} character
Nested Switch Statement Loops
#include <stdio.h> • S = 1+3+5+7+9+……………….+4999
int main () • To find the value of S, a novice programmer may take attempt to write:
{ char Book, Category; main ()
printf("Which authors or books do you want to read, Tagore[T] or Brown[B]?\n");
{ int s;
Book=getch();
s = 1+3+5+7+9+11+13+15+………………………
switch(Book)
{ case 'T': { printf("Novel[N] or Poem[P]?\n");
• In such cases, while a particular task is needed to perform several times
looping can be done to ease the difficulty.
Category=getch();
switch(Category) • A loop statement allows us to execute a statement or group of statements
multiple times.
{ case 'N' : printf("I also like your choice\n"); break;
case 'P' : printf("What do they mean actually?\n"); break; } } • So a real programmer will write the following to sum up the integer numbers
case 'B' : { printf("Novel[N] or Poem[P]?\n");
up to 4999
Category=getch(); int main ()
switch(Category) { int s=0,i;
{ case 'N' : printf("I also like your choice"); break; for(i=1;i<=4999;i+=2)
case 'P' : printf("You have no idea about Dan Brown.\n"); break; } } } s+=i;
return 0; } printf("%d\t%d",s,i); }

for Loop for Loop


for (initialization; condition; increment/decrement) • Initialization of the loop can be done before the for loop.
{ statement(s); } • Increment can be done in the body of the for loop.
• The initialization step is executed first, and only • If the condition portion is eliminated the loop will run forever. This is known
once. This step allows you to declare and
as an infinity loop.
initialize any loop control variables.
• Next, the condition is evaluated. If it is true, the
body of the loop is executed. If it is false, the int main ()
int main ()
body of the loop does not execute and the flow { int s=0;
of control jumps to the next statement just after { int s=0;
int i=1;
the 'for' loop. int i=1; for( ; ; )
for(;i<=4999;)
• After the body of the 'for' loop executes, the flow { s+=i; i+=2; }
of control jumps back up to the increment { s+=i; i+=2; }
printf("%d\t%d",s,i);
statement. This statement allows you to update printf("%d\t%d",s,i);
any loop control variables. return 0;} return 0;}
• The condition is now evaluated again. If it is
true, the loop executes and the process repeats Infinite loop
6250000 5001
itself (body of loop, then increment step, and
then again condition). After the condition
becomes false, the 'for' loop terminates.
for Loop while Loop
• Initialization, condition, increment/decrement can be done with more than while (condition)
one variable.
{ statement(s); }
#include <stdio.h> #include <stdio.h> • A while loop in C programming repeatedly
int main() executes a target statement as long as a given
int main()
{ int i,j,k; condition is true (the value of the condition/
{ int i; expression is 1 or any non-zero value).
for(i=0,j=2,k=1;i<=4;i++,--j)
for( ; i=0,i<=3 ; i++) • Here, statement(s) may be a single statement or
{ printf("%d ",i+j+k); } a block of statements. The condition may be any
{ printf("%d ",i); }
return 0; } expression, and true is any nonzero value. The
return 0; } loop iterates while the condition is true.
Output: 3 3 3 3 3
Output: Infinte loop • When the condition becomes false, the program
control passes to the line immediately following
• Loop without body is possible. the loop.
int main() • A while loop might not execute at all. When the
{ int i; condition is tested and the result is false, the
loop body will be skipped and the first statement
for(i=0;i<=10;i++); Output: 11 after the while loop will be executed. (Use do
printf("%d",i); while loop to guarantee at least one execution)
return 0; }

while Loop while Loop


• In while loop condition expression is compulsory. #include <stdio.h> #include <stdio.h>
• While loop without any body is possible. int main( ) int main()
• In while loop there can be more than one conditional expression. { while( )
{ int x=2,y=2;
{ printf("Hello world"); }
#include <stdio.h> #include <stdio.h> return 0; } while(y<=3, x<=5)
int main(){ int main(){ Output: Error printf("%d %d ",++x, ++y);
int x=4,y=2; float a=1.5; return 0; }
while(x-y+2){ #include <stdio.h>
while(a) Output: 3 3 4 4 5 5 6 6
printf("%d ",x--+y); int main(){
} { printf("%.0f ",a); int x=2,y=2;
return 0; a-=0.5; } while(x<=5, y<=3)
} return 0;} printf("%d %d ",++x, ++y);
return 0;
}
Output: 6 5 4 3 Output: 2 1 0 Output: 3 3 4 4
// %.0f - print the value of a floating point
number with 0 places after the decimal point
do while Loop Nested Loop
do { statement(s); }
#include <stdio.h> Find the prime numbers up to
while (expression); 1000.
•It is also called as post tested loop.
int x = 9;
( homework-using all loops)
•Unlike for and while loops, which test the loop int main()
condition at the top of the loop, the do...while loop { do #include <stdio.h>
in C programming checks its condition at the bottom { do int main ()
of the loop. {
•A do...while loop is similar to a while loop, except { printf("%o", x ); }
int i, j,flag;
the fact that it is guaranteed to execute at least one while(!-2); }
for(i = 2; i<1000; i++)
time. while(0); {flag=0;
•The statement(s) in the loop executes once before
return 0; for(j = 2; j <i; j++)
the condition is tested.
•If the condition is true (the value of the expression is } if((i%j)==0)
int main() Output: 11 {flag=1; break;}
1 or any nonzero value), the flow of control jumps
back up to do, and the statement(s) in the loop { int i=11; if(flag==0)
executes again. This process repeats until the given do printf("I am fortunate printf("%d \t", i); }
%o – denotes octal return 0;
condition becomes false. using a do while loop.\n");
•If there is only one statement in the loop body then while(i<10);
Decimal = 9 Octal = 11 }
braces is optional. return 0;}

break statement break statement


• It is keyword of c programming. • Another task of break keyword is to switch the control from one case to
• Task of this keyword is to bring the control from out of the loop in the case another case in case of switch case control statement.
of looping. • break statement can not be used in any other purpose.

#include <stdio.h> #include <stdio.h> #include <stdio.h>


int main() int main() int main()
{ int i; { int i; { float a=5.5;
for(i=0;i<=4;i++) if(a==5.5) //Compilation error : break statement not within
for(i=0;i<=4;i++)
{ printf("%d\n",i); // break; { loop or switch
{ printf("%d\n",i); break;
printf("Inner printf"); printf("equal");
printf("Inner printf");
} }
printf("\nOuter printf"); } else
return 0; } printf("\nOuter printf"); { break; }
return 0; } return 0; }
Output: 0
Outer printf
continue statement Example
• It is keyword of c and task of this keyword is to transfer the control of Draw a Pascal’s triangle like the following one using C programming (for/while
program at the beginning of loop. loop).

#include <stdio.h>
int main()
{ int i=5;
do To find nth term of a pascal triangle we use following formula.

{ printf("%d",i);
• Where n is row number and k is term of that row.
continue; //compiler will get stuck here
Step by step descriptive logic to print pascal triangle.
i++; }
• Input number of rows to print from user. Store it in a variable say num.
while(i<=10);
• To iterate through rows, run a loop from 0 to num, increment 1 in each iteration.
return 0; } The loop structure should look like for(n=0; n<num; n++).
• Inside the outer loop run another loop to print terms of a row. Initialize the loop
• Except looping, we cannot use continue keyword. from 0 that goes to n, increment 1 in each iteration.
• Inside the inner loop use formula term = fact(n) / (fact(k) * fact(n-k)); to print
current term of pascal triangle.

Example Example
Draw a Pascal’s triangle like the following one using C programming (for/while Draw a Pascal’s triangle like the following one using C programming (for/while
loop). loop).

#include <stdio.h> /* Function definition */ for(k=0; k<=n; k++)


long long fact(int n); { term = fact(n) / (fact(k) * fact(n-k)); /* Generate term for current row */
int main() printf("%6lld", term); }
{ int n, k, num, i; long long term; /* Input number of rows */ printf("\n"); }
printf("Enter number of rows : "); return 0; } / * Function to calculate factorial */
scanf("%d", &num); long long fact(int n)
for(n=0; n<num; n++) { long long factorial = 1; while(n>=1)
{ { factorial *= n; n--; }
for(i=n; i<=num; i++) printf("%3c", ' '); /* Prints 3 spaces */ return factorial; }

You might also like