Chapter 05 - Control Structures
Chapter 05 - Control Structures
Control Structures
In the following sections, we shall discuss each of the control structures (except the
sequence control structure) in detail.
◼ Syntax:
Here,
if(expression)
— expression corresponds to a C expression, that
{
is evaluable to either true (non-zero) or false (zero).
if block statement(s);
— statement(s) corresponds to a set of
}
statements (0, 1, or more no. of statements).
◼ Control Flow:
➢ The expression is evaluated 1st .
➢ If it is true (non-zero), the set of statements within the if block is executed
(sequentially). The control is then transferred to statement immediately
after the if block .
➢ If it is false (zero), the set of statements within the if block are skipped
and the control is directly transferred to the statement immediately after
the if block .
Dr. N. K. Pani, Dept. of CSEA, IGIT Sarang | 5.8
◼ Programming Example:
/* PR5_1.c: Input four integers a, b, c, d and print the value of (a+b)/(c-d) if (c-d) ≠0 */
# include <stdio.h>
# include <conio.h>
void main()
{
int a, b, c, d;
float result;
printf("Enter four integers: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
if((c-d)!=0)
{
result = (float)(a+b)/(c-d);
printf("The value of (a+b)/(c-d) is: %f", result);
} Output
getch(); Run 1:
} Enter four integers: 12 3 8 3
The value of (a+b)/(c-d) is: 3.000000
Run 2:
Enter four integers: 12 3 8 8
if(expression)
{ if(expression)
statement 1; is same as statement 1;
} statement 2;
statement 2;
2. Never put a semicolon (;) after the if clause , because it will be same as
writing no statements within the if block.
if(expression);
if(expression)
{
; /*A blank statement*/
statement 1; is same as statement 1;
}
statement 2;
statement 2;
if(x==0) if(x=0)
{ {
is by mistake
statement 1; statement 1;
written as
statement 2; statement 2;
} }
◼ The simple if statement does nothing when the expression becomes false. If
we want to execute one set of statements when the condition (expression)
becomes true and some other set of statements when the condition
(expression) becomes false , then we should use the if...else statement.
◼ Syntax:
if(expression)
{
if block statement(s);
}
else
{
else block statement(s);
}
else
{ else
statement 1; is same as statement 1;
} statement 2;
statement 2;
/* PR5_2.c: The same program as in PR5_1, but in this case, it will print “(c-d) = 0, The
result is undetermined.”, if (c-d) becomes equal to 0 */ Output
# include <stdio.h> Run 1:
# include <conio.h> Enter four integers: 12 3 8 3
The value of (a+b)/(c-d) is: 3.000000
void main()
{ Run 2:
int a, b, c, d; Enter four integers: 12 3 8 8
float result; (c-d) = 0, The result is undetermined.
getch();
}
◼ Syntaxes:
if(expression1)
if(expression1) {
{ if(expression2)
statement(s); {
if(expression2) statement(s);
{ }
statement(s); }
} else
else {
{ if(expression3)
statement(s); {
} statement(s);
statement(s); }
} else
{
statement(s);
}
statement(s);
}
Dr. N. K. Pani, Dept. of CSEA, IGIT Sarang | 5.16
◼ Programming Example:
# include <stdio.h>
# include <conio.h>
void main()
{
int a, b, c, largest;
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
if(a>b)
{
if (a>c)
largest = a;
else
largest = c;
}
else
{
if (c>b)
largest = c;
else
largest = b;
} [Cont.]
Dr. N. K. Pani, Dept. of CSEA, IGIT Sarang | 5.17
printf("\nThe largest number is: %d", largest); Output
getch();
} Enter three integers: 12 15 2
The largest number is: 15
◼ Notes:
1. Dangling Else Problem: While nesting, care should be exercised to
match every else statement with an if statement. When an else
statement has no matching if, then that else is called dangling else.
if()
if()
if()
else
else
else
else /* The dangling else*/
1 if()
2 if()
3 if()
4 else /*Belongs to the if() in line no. 3*/
5 else /*Belongs to the if() in line no. 2*/
6 else /*Belongs to the if() in line no. 1*/
7 if()
8 else /*Belongs to the if() in line no. 7*/
9 if()
10 else /*Belongs to the if() in line no. 9*/
11 else /*Dangling else*/
We will discuss the else if ladder next. We will see that the program
(PR5_4.c) that we have done by using the if...else construct, can be
done very easily with the else if ladder .
◼ The else if ladder does the same thing as that of the nested if...else
construct (both are meant for multi way decision making), but in a simpler manner.
◼ Syntax:
if(expression1)
{
statement(s);
}
else if(expression2)
{
statement(s); The total structure contains only
}
else if(expression3) one if at the beginning, and only
{ one else at the end.
statement(s);
}
else
{
statement(s);
}
/* PR5_5.c: The same program as that of PR5_4.c (Program to find the highest among
three integers), using else if ladder*/
Output
# include <stdio.h>
# include <conio.h> Enter three integers: 12 15 2
The greatest number is: 15
void main()
{
int a, b, c, greatest;
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
getch();
}
void main()
{
int units, custNo;
float chrges;
is same as
if (expression1)
{
expression2;
}
else
{
expression3;
}
◼ The limitation of the conditional operator is that, after the ? or after the : only
one C statement can be written.
◼ Syntax:
Here,
switch(expression)
{ — expression corresponds to either an
case constant1: integer/character constant like 1, 2, 3, ‘a’,
statement(s); ‘b’, ‘c’ etc., or any C expression that is
break; evaluable to an integer/character value.
case constant2: — constant1, constant2,... are
statement(s); integer/character constants like 1, 2, 3, ‘a’,
break; ‘b’, ‘c’ etc. Each of these constants should be
unique within a switch-case construct.
...
... — The break statements are optional.
— The default level is optional. There can
default: be at most one default level.
statement(s);
— The default level may be placed any
}
where but usually placed at the end.
Sl.
Example Output
No.
1 void main() I am in case 2
{ I am in case 3
int i = 2; I am in default
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");
}
}
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");
break;
default:
printf("I am in default \n");
}
}
switch(i)
{
case 1:
printf("I am in case 1 \n");
case 2:
printf("I am in case 2 \n");
break;
case 3:
printf("I am in case 3 \n");
default:
printf("I am in default \n");
}
}
switch(i)
{
case 1:
printf("I am in case 1 \n");
break;
case 2:
printf("I am in case 2 \n");
break;
case 3:
printf("I am in case 3 \n");
break;
default:
printf("I am in default \n");
}
}
switch(i)
{
case 1:
printf("I am in case 1 \n");
break;
case 2:
printf("I am in case 2 \n");
break;
case 3:
printf("I am in case 3 \n");
break;
default:
printf("I am in default \n");
}
}
switch(i)
{
case 1:
printf("I am in case 1 \n");
break;
default:
printf("I am in default \n");
case 2:
printf("I am in case 2 \n");
break;
case 3:
printf("I am in case 3 \n");
break;
}
}
switch(i)
{
case 1:
printf("I am in case 1 \n");
break;
default:
printf("I am in default \n");
break;
case 2:
printf("I am in case 2 \n");
break;
case 3:
printf("I am in case 3 \n");
break;
}
}
switch(ch)
{
case 'a':
case 'A':
printf("'A' for apple \n");
break;
case 'b':
case 'B':
printf("'B' for ball \n");
break;
case 'c':
case 'C':
printf("'C' for cat \n");
break;
}
}
/* PR5_7.c: Program that reads an alphabet and prints whether it is a vowel or consonant*/
# include <stdio.h>
# include <conio.h>
void main()
{
char ch;
printf("Enter an alphabet: ");
scanf("%c", &ch);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("\nIt is a vowel.\n");
break; [Cont.]
Dr. N. K. Pani, Dept. of CSEA, IGIT Sarang | 5.38
default:
printf("\nIt is a consonant.\n"); Output
}
} Run 1:
Enter an alphabet: p
It is a consonant.
Run 2:
Enter an alphabet: u
It is a vowel.
◼ Programming Example 2:
For a student’s mark within 0-100, the index = (mark/25). The grades are calculated as follows:
Index Grade
0 D
1 C
2 B
3 A
Write a program that reads the mark within 0-100 and prints the appropriate grade.
# include <stdio.h>
# include <conio.h>
void main()
{
int mark, index;
printf("Enter mark (0-100): ");
scanf("%d", &mark);
index = mark/25;
switch(index)
{
case 0:
printf("\nThe grade is: D\n");
break;
case 1:
printf("\nThe grade is: C\n");
break;
case 2:
printf("\nThe grade is: B\n");
break;
case 3:
printf("\nThe grade is: A\n");
break;
[Cont.]
Dr. N. K. Pani, Dept. of CSEA, IGIT Sarang | 5.40
default:
printf("\nYou haven’t entered the mark within 0-100.");
}
}
Output
Run 1:
Enter mark (0-100): 85
The grade is: A
Run 2:
Enter mark (0-100): 145
You haven’t entered the mark within 0-100.
void main()
{
int i = 10;
switch(i)
{
case 78:
printf("I am in case 78 \n");
break;
case 10:
printf("I am in case 10 \n");
break;
case 196:
printf("I am in case 196 \n");
break;
default:
printf("I am in default \n");
}
}
...
switch(i)
{
printf(“Enter a value: ”); /* This statement is never executed*/
case 100:
j = i+50;
printf(“%d \n“, j);
break;
case 200:
j = i-50;
printf(“%d \n“, j);
break;
}
...
◼ Though both are meant for multi way decision making, there are some thing
that simply can’t be done by using the switch-case:
1. switch-case are meant for equality comparisons. One can’t write a case
that looks like: case i<=100.
2. A float value (any value other than integer/character) can’t be tested by
using a switch.
3. A case can’t contain an expression like, a+3.
4. Multiple case can’t use the same expression.
◼ The Overall Looping Process: The looping process, in general, involves the
following four steps
1. Initialization: The control variable is assigned to some initial value.
2. Testing Using a Condition: The control variable is tested (using an
expression). The result is either true (non-zero) or false (zero).
3. Executing the set of statements in the body of the loop.
4. Update: The control variable is updated (incremented, decremented, or
any other operation that changes the value of the control variable).
initialization;
...
while(condition)
{
body of statement(s);
the loop update;
}
➢ When the condition becomes false, the loop is terminated, and the
control goes to the statement immediately after the body of the loop.
Dr. N. K. Pani, Dept. of CSEA, IGIT Sarang | 5.49
◼ Programming Example 1:
/* PR5_9.c: A program to calculate the sum of squares of numbers between 1 to 10. i.e.,
sum = 12+22+32+ ..... +102*/
# include <stdio.h>
# include <conio.h>
void main()
{
int sum = 0;
int i = 1; /*Initialization*/
Output
2. It is not necessary that the control variable must only be an int. It could
also be a float (any numeric value).
Again, the update doesn’t mean only incrementing or
decrementing. It could be any operation, that eventually changes the
control variable, so that the condition becomes false at some time.
void main()
{
float a = 10.0;
while(a <= 1000.0)
{
printf("Hi\n"); /* "Hi" is printed 6 times*/
a = a * 2.5;
}
}
int i; int i;
... ...
while(i <= 10); while(i <= 10)
{ is same as ;
printf(“%d\n“, i); {
i++; printf(“%d\n“, i);
} i++;
}
4. What do you think would be the out put of the following program?
void main()
{
int i = 1;
while(i <= 32767)
{
printf(“%d\n“, i);
i++;
}
}
◼ Syntax:
initialization;
...
do Notice the semicolon (;). It was not
{ present in the syntax of the while loop.
body of statement(s);
the loop update;
} while(condition);
/* PR5_11.c: Program that continues to read a number and displays its square until the use says
“NO”*/
# include <stdio.h>
# include <conio.h>
void main()
{
char status = ‘Y’; /*Initialization*/
int n;
do
{
printf("\n\nEnter an integer: ");
scanf("%d", &n);
printf("\nIts square is: %d", (n*n));
printf("\n\nWould you like to continue (Y/N)?: ");
status = getche(); /*Update*/
}while(status == 'Y' || status == 'y'); /*Condition (Testing)*/
}
Enter an integer: 5
Its square is: 25
Would you like to continue (Y/N)?: Y Output
...
Dr. N. K. Pani, Dept. of CSEA, IGIT Sarang | 5.57
The for Loop / Statement
◼ The for loop is another entry-controlled loop that provides a more concise
loop control structure. It allows initialization, testing using a condition, and
update in a single line.
◼ Syntax:
if the condition
is false
1 2 4
for(initialization; condition; update)
{
if the condition
is true
statement(s) 3
/* PR5_12.c The same program as that of PR5_9.c using the for loop
(A program to calculate sum = 12+22+32+ ..... +102) */
# include <stdio.h>
# include <conio.h>
void main()
{
int sum = 0;
int i;
Output
1. In a for loop, both the initialization and the update sections can contain
more than one expressions. If done so, the expressions should be
separated by commas (,). For example:
...
i=5; /* Initialization is written here */
...
i=5; /* Initialization is written here */
for(; ;) /* No condition and update; Infinite loop (the easiest way to write an
{ infinite loop)*/
printf(“%d\n”, i);
}
◼ Programming Example 1:
# include <stdio.h>
# include <conio.h>
void main()
{
int i, j, n, num;
[Cont.]
Output
Enter a range: 20
The prime numbers within the range 1-20 are: 2 3 5 7 11 13 17 19
1
1 2 /* PR5_15.c A program to display right pyramid */
1 2 3 # include <stdio.h>
1 2 3 4 # include <conio.h>
void main()
{
int row, col;
for(row=1;row<=4;row++)
{
for(col=1;col<=row;col++)
{
printf("%d ", col);
}
printf("\n\n");
}
getch();
}
1
1 2 1 /* PR5_16.c A program to display full pyramid */
1 2 3 2 1 # include <stdio.h>
1 2 3 4 3 2 1 # include <conio.h>
void main()
{
int row, col, space;
for(row=1;row<=4;row++)
{
for(space=1;space<=4-row;space++)
printf(" ");
for(col=1;col<=row;col++)
printf("%d ", col);
for(col=col-2;col>=1;col--)
printf("%d ", col);
printf("\n\n");
}
getch();
}
◼ Syntax: continue;
◼ What It Does?: When executed (within a loop), it takes the control directly to the
next iteration (i.e., to the condition clause) of the current loop, skipping all the
statements after the continue statement within the loop.
# include <stdio.h>
# include <conio.h>
void main()
{
int i;
printf("\nThe odd numbers between 1-10 are: ");
for(i=1;i<=10;i++)
{
if(i%2 == 0)
{
continue;
}
printf("%d ", i);
}
getch(); Output
}
The odd numbers between 1-10 are: 1 3 5 7 9
break
◼ Syntax: break;
◼ What it Does?: The return statement terminates the execution of the current
function and takes the control to the calling function immediately following the
function call. A return statement can also return a value to the calling function.
◼ Syntax: exit([integer_constant]);
◼ What it Does?: The exit() statement (function) takes the control out of the
whole program (i.e., terminates the program).
➢ exit() optionally takes an integer constant as its argument. Normally,
a zero as an argument (exit(0)) is used to indicate normal termination
of the program (to the operating system) and a non-zero value as an
argument is used to indicate termination of program due to some error
or abnormal condition.
➢ An exit() is usually associated with an if.
◼ [NOTE]: The description of exit() is present in the header file “stdlib.h”. So, in order
to use exit() we must include the header file “stdlib.h” in our program through the
preprocessor directive #include<stdlib.h>, otherwise we may get a warning.
/* PR5_18.c A program that tests a number to be prime or not (A prime number is a natural number
greater than 1 that has no positive divisors other than 1 and itself.) */
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
void main()
{
int i, num;
printf("\nEnter an positive integer: ");
scanf("%d", &num);
for(i=2;i<=num-1;i++)
{
if(num%i == 0)
{
printf("\n%d is a NOT a prime number.\n\n", num);
exit(0);
}
} Output
printf("\n%d is a prime number.\n\n", num);
} Enter a number: 56
56 is NOT a prime number.
Few Explanations
... ...
▪ The goto requires a label in
goto label: label:
order to identify the place of
... statement;
jump. The label is nothing but
label: ...
an identifier name.
statement; goto label:
▪ The label must be followed by
... ...
a colon.
(Forward Jump) (Backward Jump)
[NOTE]: In a backward jump (when the “label:” is placed before the “goto label;”
statement), the program will fall in an infinite loop if no condition is specified (though another
goto or an if statement) to take the control after the “goto label;” statement.