CONTROL STRUCTURES
1
• Branching: if-else
• Looping: while-do while-for
• Nested control structures
• Switch
• Break
• Continue
• Comma
• goto
Three kinds of execution flow
◦ Sequence:
 The execution of the program is sequential.
◦ Selection / Branching
 A control structure which chooses alternative to execute/program chooses to
follow one branch or another
 Example: if, if/else, switch, Conditional operator
◦ Repetition / Looping
 A control structure which repeats a group of statements.
 Example: while, do/while, for, nested loops, break ,
continue.
2
BRANCHING :IF-ELSE STATEMENT
 Simple if
 Multiple if
 if-else
 if-else if ladder
 Nested if-else
 Switch-Case
3
The simple if Statement
 The if statement has the following syntax:
4
if ( condition )
statement;
if is a C
reserved word
Condition is an expression that is
either false (represented by 0) or
true (represented by 1/non-zero).
If the condition is true, the statement is executed.
If the condition is false, the statement is not executed ,control
comes out
Branching/ Decision
Flow chart for if statement
5
The if-else Statement
 An if statement can be followed by an optional else statement,
which executes when the boolean expression is false.
 Syntax:
if(boolean_expression) // eg: A>0
{
True statements; // A is positive
else
{
False statements; //B is negative
}
6
The if-else Statement- flow
void main()
{
int age;
scanf(“age=%d “,&age);
if (age>= 18)
{
printf(“Eligible");
}
else
printf(“Not eligible”);
}
7
OUTPUT 1
Age=30
Eligible
OUTPUT 2
Age=12
Not Eligible
The if-else Statement-Program to find the given number is odd or even
#include <stdio.h>
void main( )
{
int num;
printf("Enter a number you want to check.n");
scanf("%d",&num);
if((num%2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
}
8
OUTPUT
Enter a number you want to check.
25
25 is odd.
Enter a number you want to check.
2
2 is even.
Sample programs
 In a company an employee is paid as under:
 If his basic salary is less than Rs. 1500,
then HRA = 10% of basic salary and
DA = 90% of basic salary.
 If his salary is either equal to or above Rs. 1500,
then HRA = Rs. 500 and DA = 98% of basic salary.
 If the employee's salary is input through the keyboard
write a program to find his gross salary.
9
/* Calculation of gross salary */
void main( )
{
float bs, gs, da, hra ;
printf ( "Enter basic salary " ) ;
scanf ( "%f", &bs ) ;
if ( bs < 1500 )
{
hra = bs * 10 / 100 ;
da = bs * 90 / 100 ;
}
else
{
hra = 500 ;
da = bs * 98 / 100 ;
}
gs = bs + hra + da ;
printf ( "gross salary = Rs. %f", gs ) ;
}
10
(if...elseif....else / else-if ladder Statement)
 The if...else if statement is used when program requires more than one test expression
if (test expression1)
{
statement/s to be executed if test expression1 is true;
}
else if(test expression2)
{
statement/s to be executed if test expression1 is false and 2 is true;
}
.
.
.
.
else
{
statements to be executed if all test expressions are false;
}
11
To print given number is positive or negative or
zero-using elseif ladder
#include <stdio.h>
int main()
{
int num;
printf("Enter a number n");
scanf("%d",&num);
if (num > 0)
{
printf(“number %d is
positiven“,num);
}
12
else if (num < 0)
{
printf(“number %d is
negativen“,num);
}
else if (num = = 0)
{
printf(“number is zero “);
}
printf(“Thank you”);
}
Nested if else Statement
 It is always legal in C programming to nest if-else statements, which means you can
use one if or else if statement inside another if or else
Syntax:
if(cond 1)
{
/* Executes when the boolean expression 1 is true */
if(cond 2)
{
/* Executes when the boolean expression 2 is true */
}
else
{ /* Executes when the boolean expression 2 is false */
}
}
else
{ if(cond3)
{
/* Executes when the boolean expression 3 is true */
}
else
{ /* Executes when the boolean expression 3 is false */
} 13
Largest of three numbers-Nested if else Statement
#include <stdio.h>
void main ()
{
int a, b,c ;
printf(“enter values a,b and cn”);
scanf(“%d%d%d”,a&a,&b,&c);
if( a >b )
{
if( a>c)
{
printf("a is largestn" );
}
else
{
printf(“c is largestn" );
}
}
14
else
{
if( b> c )
{
printf(“b is largestn" );
}
else
{
printf(“c is largestn" );
}
}
}
Nested if else Statement
#include <stdio.h>
int main ()
{
int a = 100;
int b = 200;
if( a == 100 )
{
if( b == 200 )
{
printf("Value of a is 100 and b is 200n" );
}
}
printf("Exact value of a is : %dn", a );
printf("Exact value of b is : %dn", b );
return 0;
}
15
OUTPUT
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
Sample programs
The marks obtained by a student in 5 different subjects
are input through the keyboard. The student gets a
division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
Write a program to calculate the division obtained by the
student.
16
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division ") ;
else
{
if ( per >= 50 )
printf ( "Second division" ) ;
else
{
if ( per >= 40 )
printf ( "Third division" ) ;
else
printf ( "Fail" ) ;
}
}
}
17
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division" ) ;
if ( ( per >= 50 ) && ( per < 60 ) )
printf ( "Second division" ) ;
if ( ( per >= 40 ) && ( per < 50 ) )
printf ( "Third division" ) ;
if ( per < 40 )
printf ( "Fail" ) ;
}
18
main( )
{
int m1, m2, m3, m4, m5, per ;
per = ( m1+ m2 + m3 + m4+ m5 ) / per ;
if ( per >= 60 )
printf ( "First division" ) ;
else if ( per >= 50 )
printf ( "Second division" ) ;
else if ( per >= 40 )
printf ( "Third division" ) ;
else
printf ( "fail" ) ;
}
19
A certain grade of steel is graded according to the following conditions:
(i) Hardness must be greater than 50
(ii) Carbon content must be less than 0.7
(iii) Tensile strength must be greater than 5600
The grades are as follows: Grade is 10 if all three conditions are met
Grade is 9 if conditions (i) and (ii) are met
Grade is 8 if conditions (ii) and (iii) are met
Grade is 7 if conditions (i) and (iii) are met
Grade is 6 if only one condition is met
Grade is 5 if none of the conditions are met
Write a program, which will require the user to give values of hardness, carbon
content and tensile strength of the steel under consideration and output the grade
of the steel.
20
Calculate the EB bill using if-else-if ladder
Get the no. of units (n)
Units 1 to 100 Amount: Rs. 3.00 per unit
Units 101 to 250 Amount: Rs. 4.50 per unit
Units 251 to 350 Amount: Rs. 5.00 per unit
More than 350 Amount: Rs. 7.00 per unit
21
To print ASCIIvalues(ifelseif)
 Any character is entered through the keyboard, write a
program to determine whether the character entered is
a capital letter, a small case letter, a digit or a special
symbol. The following table shows the range of ASCII
values for various characters.
22
Characters
A – Z
a – z
0 – 9
special symbols
ASCII Values
65 – 90
97 – 122
48 – 57
0 - 47, 58 - 64,
91 - 96, 123 - 127
23
Switch Statement Syntax
switch(expr/var)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
}
24
Flow of execution-switch
25
26
main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 n" ) ;
case 2 :
printf ( "I am in case 2 n" ) ;
case 3 :
printf ( "I am in case 3 n" ) ;
default :
printf ( "I am in default n" ) ;
}
}
The output of this program would be:
I am in case 2
I am in case 3
I am in default
27
main( )
{
int i = 22 ;
switch ( i )
{
case 121 :
printf ( "I am in case 121 n" ) ;
break ;
case 7 :
printf ( "I am in case 7 n" ) ;
break ;
case 22 :
printf ( "I am in case 22 n" ) ;
break ;
default :
printf ( "I am in default n" ) ;
}
}
The output of this program would be:
I am in case 22
28
void main()
{
char c = 'x' ;
switch ( c )
{
case 'v' :
printf ( "I am in case v n" ) ;
break ;
case 'a' :
printf ( "I am in case a n" ) ;
break ;
case 'x' :
printf ( "I am in case x n" ) ;
break ;
default :
printf ( "I am in default n" ) ;
}
}
The output of this program would be:
I am in case x
Example 1
scanf(“%d”, &day);
switch ( day )
{
case 0:
printf (“Sundayn”) ;
break ;
case 1:
printf (“Mondayn”) ;
break ;
case 2:
printf (“Tuesdayn”) ;
break ;
case 3:
printf (“Wednesdayn”);
break ;
case 4:
printf (“Thursdayn”) ;
break ;
case 5:
printf (“Fridayn”) ;
break ;
case 6:
printf (“Saturdayn”) ;
break ;
default:
printf (“Error -- invalid
day.n”) ;
break ;
}
29
Example 2
#include<stdio.h>
void main()
{
char a;
printf("Enter any Alphabet : ");
scanf("%c",&a);
switch (a)
{
case'A':
case'a':
case'E':
case'e':
case‘I':
case'i':
case'O':
case'o':
case'U':
case'u': printf("It is a Vowel");
break;
default: printf("It is a Consonent");
}
}
30
Example 3
#include <stdio.h>
int main ()
{
char grade;
scanf(“%c”, &grade);
switch(grade)
{
case 'A' :
printf("Excellent!n" );
break;
case 'B' :
case 'C' :
printf("Well donen" );
break;
case 'D' :
printf("You passedn" );
break;
case 'F' :
printf("Better try againn" );
break;
default :
printf("Invalid graden" );
}
printf("Your grade is %cn",
grade ); }
31
Example 4
#include <stdio.h>
int main ()
{
int a,b,c,choice;
scanf(“%d %d”, &a,&b);
printf(“Menu 1.Add 2.Sub
3.Mul 4.Div 5.Modn”);
scanf(“%d”,&choice);
switch(choice)
{
case 1 :c=a+b;
printf(“Sum is %dn“,c );
break;
case 2:c=a-b;
printf(“Difference is %dn“,c );
break;
case 3:c=a*b;
printf(“Multiply is %dn“,c );
break;
case 4:c=a/b;
printf(“Division is %dn“,c );
break;
case 5:c=a%b;
printf(“Remainder is %dn“,c );
break;
default :
printf("Invalid Choicen" );
} } 32
 Cannot do with switch:
1. A float expression cannot be tested .
2. Cases cannot have variable expressions(eg: case a+3)
3. Multiple cases cannot use same expressions
Eg: case 3: case 1+2:
 Switch is faster than if-else ladder when more conditions
to be tested (because switch matches the value but in if-
else all conditions are evaluated)
33
Switch vs if-else ladder
Switch vs if-else ladder
 A nested if-else structure is just as efficient as a switch
statement.
 However, a switch statement may be easier to read.
 Also, it is easier to add new cases to a switch
statement than to a nested if-else structure.
34

CONTROLSTRUCTURES.ppt

  • 1.
    CONTROL STRUCTURES 1 • Branching:if-else • Looping: while-do while-for • Nested control structures • Switch • Break • Continue • Comma • goto
  • 2.
    Three kinds ofexecution flow ◦ Sequence:  The execution of the program is sequential. ◦ Selection / Branching  A control structure which chooses alternative to execute/program chooses to follow one branch or another  Example: if, if/else, switch, Conditional operator ◦ Repetition / Looping  A control structure which repeats a group of statements.  Example: while, do/while, for, nested loops, break , continue. 2
  • 3.
    BRANCHING :IF-ELSE STATEMENT Simple if  Multiple if  if-else  if-else if ladder  Nested if-else  Switch-Case 3
  • 4.
    The simple ifStatement  The if statement has the following syntax: 4 if ( condition ) statement; if is a C reserved word Condition is an expression that is either false (represented by 0) or true (represented by 1/non-zero). If the condition is true, the statement is executed. If the condition is false, the statement is not executed ,control comes out
  • 5.
  • 6.
    The if-else Statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false.  Syntax: if(boolean_expression) // eg: A>0 { True statements; // A is positive else { False statements; //B is negative } 6
  • 7.
    The if-else Statement-flow void main() { int age; scanf(“age=%d “,&age); if (age>= 18) { printf(“Eligible"); } else printf(“Not eligible”); } 7 OUTPUT 1 Age=30 Eligible OUTPUT 2 Age=12 Not Eligible
  • 8.
    The if-else Statement-Programto find the given number is odd or even #include <stdio.h> void main( ) { int num; printf("Enter a number you want to check.n"); scanf("%d",&num); if((num%2)==0) //checking whether remainder is 0 or not. printf("%d is even.",num); else printf("%d is odd.",num); } 8 OUTPUT Enter a number you want to check. 25 25 is odd. Enter a number you want to check. 2 2 is even.
  • 9.
    Sample programs  Ina company an employee is paid as under:  If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of basic salary.  If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary.  If the employee's salary is input through the keyboard write a program to find his gross salary. 9
  • 10.
    /* Calculation ofgross salary */ void main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) { hra = bs * 10 / 100 ; da = bs * 90 / 100 ; } else { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; } 10
  • 11.
    (if...elseif....else / else-ifladder Statement)  The if...else if statement is used when program requires more than one test expression if (test expression1) { statement/s to be executed if test expression1 is true; } else if(test expression2) { statement/s to be executed if test expression1 is false and 2 is true; } . . . . else { statements to be executed if all test expressions are false; } 11
  • 12.
    To print givennumber is positive or negative or zero-using elseif ladder #include <stdio.h> int main() { int num; printf("Enter a number n"); scanf("%d",&num); if (num > 0) { printf(“number %d is positiven“,num); } 12 else if (num < 0) { printf(“number %d is negativen“,num); } else if (num = = 0) { printf(“number is zero “); } printf(“Thank you”); }
  • 13.
    Nested if elseStatement  It is always legal in C programming to nest if-else statements, which means you can use one if or else if statement inside another if or else Syntax: if(cond 1) { /* Executes when the boolean expression 1 is true */ if(cond 2) { /* Executes when the boolean expression 2 is true */ } else { /* Executes when the boolean expression 2 is false */ } } else { if(cond3) { /* Executes when the boolean expression 3 is true */ } else { /* Executes when the boolean expression 3 is false */ } 13
  • 14.
    Largest of threenumbers-Nested if else Statement #include <stdio.h> void main () { int a, b,c ; printf(“enter values a,b and cn”); scanf(“%d%d%d”,a&a,&b,&c); if( a >b ) { if( a>c) { printf("a is largestn" ); } else { printf(“c is largestn" ); } } 14 else { if( b> c ) { printf(“b is largestn" ); } else { printf(“c is largestn" ); } } }
  • 15.
    Nested if elseStatement #include <stdio.h> int main () { int a = 100; int b = 200; if( a == 100 ) { if( b == 200 ) { printf("Value of a is 100 and b is 200n" ); } } printf("Exact value of a is : %dn", a ); printf("Exact value of b is : %dn", b ); return 0; } 15 OUTPUT Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200
  • 16.
    Sample programs The marksobtained by a student in 5 different subjects are input through the keyboard. The student gets a division as per the following rules: Percentage above or equal to 60 - First division Percentage between 50 and 59 - Second division Percentage between 40 and 49 - Third division Percentage less than 40 - Fail Write a program to calculate the division obtained by the student. 16
  • 17.
    main( ) { int m1,m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First division ") ; else { if ( per >= 50 ) printf ( "Second division" ) ; else { if ( per >= 40 ) printf ( "Third division" ) ; else printf ( "Fail" ) ; } } } 17
  • 18.
    main( ) { int m1,m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First division" ) ; if ( ( per >= 50 ) && ( per < 60 ) ) printf ( "Second division" ) ; if ( ( per >= 40 ) && ( per < 50 ) ) printf ( "Third division" ) ; if ( per < 40 ) printf ( "Fail" ) ; } 18
  • 19.
    main( ) { int m1,m2, m3, m4, m5, per ; per = ( m1+ m2 + m3 + m4+ m5 ) / per ; if ( per >= 60 ) printf ( "First division" ) ; else if ( per >= 50 ) printf ( "Second division" ) ; else if ( per >= 40 ) printf ( "Third division" ) ; else printf ( "fail" ) ; } 19
  • 20.
    A certain gradeof steel is graded according to the following conditions: (i) Hardness must be greater than 50 (ii) Carbon content must be less than 0.7 (iii) Tensile strength must be greater than 5600 The grades are as follows: Grade is 10 if all three conditions are met Grade is 9 if conditions (i) and (ii) are met Grade is 8 if conditions (ii) and (iii) are met Grade is 7 if conditions (i) and (iii) are met Grade is 6 if only one condition is met Grade is 5 if none of the conditions are met Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and output the grade of the steel. 20
  • 21.
    Calculate the EBbill using if-else-if ladder Get the no. of units (n) Units 1 to 100 Amount: Rs. 3.00 per unit Units 101 to 250 Amount: Rs. 4.50 per unit Units 251 to 350 Amount: Rs. 5.00 per unit More than 350 Amount: Rs. 7.00 per unit 21
  • 22.
    To print ASCIIvalues(ifelseif) Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol. The following table shows the range of ASCII values for various characters. 22 Characters A – Z a – z 0 – 9 special symbols ASCII Values 65 – 90 97 – 122 48 – 57 0 - 47, 58 - 64, 91 - 96, 123 - 127
  • 23.
  • 24.
    Switch Statement Syntax switch(expr/var) { caseconstant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ } 24
  • 25.
  • 26.
    26 main( ) { int i= 2 ; switch ( i ) { case 1 : printf ( "I am in case 1 n" ) ; case 2 : printf ( "I am in case 2 n" ) ; case 3 : printf ( "I am in case 3 n" ) ; default : printf ( "I am in default n" ) ; } } The output of this program would be: I am in case 2 I am in case 3 I am in default
  • 27.
    27 main( ) { int i= 22 ; switch ( i ) { case 121 : printf ( "I am in case 121 n" ) ; break ; case 7 : printf ( "I am in case 7 n" ) ; break ; case 22 : printf ( "I am in case 22 n" ) ; break ; default : printf ( "I am in default n" ) ; } } The output of this program would be: I am in case 22
  • 28.
    28 void main() { char c= 'x' ; switch ( c ) { case 'v' : printf ( "I am in case v n" ) ; break ; case 'a' : printf ( "I am in case a n" ) ; break ; case 'x' : printf ( "I am in case x n" ) ; break ; default : printf ( "I am in default n" ) ; } } The output of this program would be: I am in case x
  • 29.
    Example 1 scanf(“%d”, &day); switch( day ) { case 0: printf (“Sundayn”) ; break ; case 1: printf (“Mondayn”) ; break ; case 2: printf (“Tuesdayn”) ; break ; case 3: printf (“Wednesdayn”); break ; case 4: printf (“Thursdayn”) ; break ; case 5: printf (“Fridayn”) ; break ; case 6: printf (“Saturdayn”) ; break ; default: printf (“Error -- invalid day.n”) ; break ; } 29
  • 30.
    Example 2 #include<stdio.h> void main() { chara; printf("Enter any Alphabet : "); scanf("%c",&a); switch (a) { case'A': case'a': case'E': case'e': case‘I': case'i': case'O': case'o': case'U': case'u': printf("It is a Vowel"); break; default: printf("It is a Consonent"); } } 30
  • 31.
    Example 3 #include <stdio.h> intmain () { char grade; scanf(“%c”, &grade); switch(grade) { case 'A' : printf("Excellent!n" ); break; case 'B' : case 'C' : printf("Well donen" ); break; case 'D' : printf("You passedn" ); break; case 'F' : printf("Better try againn" ); break; default : printf("Invalid graden" ); } printf("Your grade is %cn", grade ); } 31
  • 32.
    Example 4 #include <stdio.h> intmain () { int a,b,c,choice; scanf(“%d %d”, &a,&b); printf(“Menu 1.Add 2.Sub 3.Mul 4.Div 5.Modn”); scanf(“%d”,&choice); switch(choice) { case 1 :c=a+b; printf(“Sum is %dn“,c ); break; case 2:c=a-b; printf(“Difference is %dn“,c ); break; case 3:c=a*b; printf(“Multiply is %dn“,c ); break; case 4:c=a/b; printf(“Division is %dn“,c ); break; case 5:c=a%b; printf(“Remainder is %dn“,c ); break; default : printf("Invalid Choicen" ); } } 32
  • 33.
     Cannot dowith switch: 1. A float expression cannot be tested . 2. Cases cannot have variable expressions(eg: case a+3) 3. Multiple cases cannot use same expressions Eg: case 3: case 1+2:  Switch is faster than if-else ladder when more conditions to be tested (because switch matches the value but in if- else all conditions are evaluated) 33 Switch vs if-else ladder
  • 34.
    Switch vs if-elseladder  A nested if-else structure is just as efficient as a switch statement.  However, a switch statement may be easier to read.  Also, it is easier to add new cases to a switch statement than to a nested if-else structure. 34