Pop Module2
Pop Module2
This allows the computer to evaluate the expression first and then, depending on whether the
value of expression is true(or non zero) or false(zero), it transfers the control to a particular
statement.
Example: Program to check the eligibility for pension after retirement from service
#include<stdio.h>
#include<conio.h>
void main()
{
int age;
printf(“Enter age of person:\n”);
scanf(“%d”,&age);
if(age>60)
printf(“Eligible for pension”);
if(age<60)
printf(“Not eligible for pension”);
getch();
}
Output:
1> Enter age of person: 56
Not eligible for pension
if(test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
Statement-x
If the test expression is true, then the true block statement(s), immediately following the if
statements are executed, otherwise, the false block statement(s) are executed. In earlier case,
either true or false block will be executed, not both. This is illustrated in below flowchart.
Example: Program to check the eligibility for pension after retirement from
service.(using if…else condition)
#include<stdio.h>
#include<conio.h>
void main()
{
int age;
printf(“Enter age of person:\n”);
scanf(“%d”,&age);
if(age>60)
printf(“Eligible for pension”);
else
printf(“Not eligible for pension”);
getch();
}
Output:
1> Enter age of person: 59
Not eligible for pension
The logic (syntax) of execution is illustrated in figure 4. If the test expression is false,
it enters to nested test expression otherwise it continues to perform body of if. If the nested
test expression is true body of nested if is executed, otherwise body of nested else will
perform and then control will transfer to the statement below to if.
Fig. 4: Flowchart of nested if…else statements.
Example: C program to find maximum between three numbers using nested if..else
#include <stdio.h>
int main()
{
/* Declare three integer variables */
int num1, num2, num3;
/* Input three numbers from user */
printf("Enter three numbers: ");
scanf("%d%d%d", &num1, &num2, &num3);
if(num1 > num2)
{
if(num1 > num3)
{
/* If num1>num2 and num1>num3 */
printf("%d is max.", num1);
}
else
{
/* If num1>num2 but num1<num3 */
printf("%d is max.",num3);
}
}
else
{
if(num2 > num3)
{
/* If num1<num2 and num2>num3 */
printf("%d is max.",num2);
}
else
{
/* If num1<num2 and num2<num3 */
printf("%d is max.",num3);
}
}
return 0;
}
Output:
Enter three numbers: 25
58
47
58 is max
10.2.3 if-else-if statement (else if ladder/cascaded if-else)
When we have multiple options available or we need to take multiple decisions based
on available condition, we can use another form of if statement called else…if ladder.
In else…if ladder each else is associated with another if statement. Evaluation of condition
starts from top to down. If condition becomes true then the associated block with if statement
is executed and rest of conditions are skipped. If the condition becomes false then it will
check for next condition in a sequential manner. It repeats until all conditions are cheeked or
a true condition is found. If all condition available in else…if ladder evaluated to false then
default else block will be executed. This construct is known as the else if ladder. The
conditions are evaluated from the top, downwards. This can be shown in the flowchart shown
in figure 5.
Syntax:
if (condition 1)
{
// block 1
}
else if (codition 2)
{
// block 2
}
else if(codition 3)
{
// block 3
}
else
{
// default block }
Fig.5: Flowchart of else..if ladder.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int x, y, z, ch;
clrscr();
printf("\n1.Addition\n2.Subtraction\n3.Multiplication\4.Division\n");
printf("\nEnter your choice :");
scanf("%d", &ch);
printf("\nEnter X and Y :");
scanf("%d %d", &x, &y);
if (ch == 1)
{
z = x + y;
}
else if (ch == 2)
{
z = x - y;
}
else if(ch == 3)
{
z = x * y;
}
else if(c == 4)
{
z = x/y ;
}
else
{
printf("\n Invalid choice! Please try again!");
}
printf("\n Answer is %f", z);
getch();
}
Output:
1> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
2
Enter X and Y :37 12
Answer is 25.000000
2> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
3
Enter X and Y :37 12
Answer is 444.000000
3> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
9
Invalid choice! Please try again!
10.2.4 Switch case
When multiple decisions involved in the program at that time we can use else…if
ladder but some time it is difficult to read and understand. In addition to this when the
numbers of alternative are more than the complexity of the program will also get increase. In
such situation C-Language provides another multi-way decision making statement called
switch statement. Switch statement tests a value against the different value. If the value is
matched, then the corresponding group of statements are executed. Switch statement begins
with switch keyword.
The structure of switch statement is more standard and readable then the else if
ladder. Switch statement uses different cases to be matched. It will match the expression
value with different cases available in switch statement from the top to down ward. Each case
has its associated block of statement. Matching of the case value will perform from the first
case. As soon as it founds the matching case, statements associated with that case block is
executed and remaining cases are skipped. If no matching case is found then the default block
will be executed if present. The default is optional if present then it will be executed
otherwise no action will be taken.
Rules for Switch statement:
o Switch expression must be of type integer or character.
o Each case value must be unique that means no two case value should be same.
o Default is optional it can be place anywhere in switch statement but normally it is
place at the end.
o Break statement is also optional if not present then similar cases will be executed.
Matching of case expression will be start from top to the down when it found
matching case the block associated with that case expression executes then after control
transfers to the statement-x. If case expression doesn’t match next case expression will be
tested in sequential manner up to the last case and if no matching case is found, default block
will be executed if present.
Example: Program to demonstrate the use of switch statement for basic calculation
#include<stdio.h>
#include<conio.h>
void main()
{
float x, y, ans;
int ch;
clrscr();
printf("\n1.Addition\n2.Subtraction\n3.Multiplication\4.Division\n");
printf("\nEnter your choice :");
scanf("%d", &ch);
printf("\nEnter X and Y :");
scanf("%f %f", &x, &y);
switch(ch)
{
case 1:
ans = x + y;
break;
case 2:
ans = x - y;
break;
case 3:
ans = x * y;
break;
case 4:
ans = x / y;
break;
default:
printf("\n Invalid choice! Please try again!");
}
printf("\n Answer is %.2f", ans);
getch();
}
Output:
1> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
2
Enter X and Y :37 12
Answer is 25.00
2> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
3
Enter X and Y :37 12
Answer is 444.00
3> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
9
Invalid choice! Please try again!
Table 10.1: Comparison between the switch and if-else construct
Output:
1
2
3
4
5
6
7
8
9
10
The above program illustrates the use of while loop. In the above program, we have
printed series of numbers from 1 to 10 using a while loop.
(1) We have initialized a variable called num with value 1. We are going to print from
1 to 10 hence the variable is initialized with value 1. If you want to print from 0, then assign
the value 0 during initialization.
(2) In a while loop, we have provided a condition (num<=10), which means the loop
will execute the body until the value of num becomes 10. After that, the loop will be
terminated, and control will fall outside the loop.
(3) In the body of a loop, we have a print function to print our number and an
increment operation to increment the value per execution of a loop. An initial value of num is
1, after the execution, it will become 2, and during the next execution, it will become 3. This
process will continue until the value becomes 10 and then it will print the series on console
and terminate the loop.
Note: - \n is used for formatting purposes which means the value will be printed on a
new line
do
{
Statements; /* body of loop
} while (expression);
As we saw in a while loop, the body is executed if and only if the condition is true. In
some cases, we have to execute a body of the loop at least once even if the condition is false.
This type of operation can be achieved by using a do-while loop.
In the do-while loop, the body of a loop is always executed at least once. After the
body is executed, then it checks the condition. If the condition is true, then it will again
execute the body of a loop otherwise control is transferred out of the loop.
Similar to the while loop, once the control goes out of the loop the statements which
are immediately after the loop is executed.
The critical difference between the while and do-while loop is that in while loop the
while is written at the beginning. In do-while loop, the while condition is written at the end
and terminates with a semi-colon (;)
(1) We have initialized a variable 'num' with value 1. Then we have written a do-
while loop.
(2) In a loop, we have a print function that will print the series by multiplying the
value of num with 2.
(3) After each increment, the value of num will increase by 1, and it will be printed on
the screen.
(4) Initially, the value of num is 1. In a body of a loop, the print function will be
executed in this way: 2*num where num=1, then 2*1=2 hence the value two will be printed.
Then the num will be incremented by 1 (num++=num+1), now 2*num where num value is 2,
then 2*2=4, hence value 4 is printed. This will go on until the value of num becomes 10.
After that loop will be terminated and a statement which is immediately after the loop will be
executed.
2.3.3 for loop
A for loop is a more efficient loop structure in 'C' programming. It is also most used
and preferred looping statement. for loop consists of three parts. The general structure of for
loop is as follows:
Syntax:
for(initial value; test-condition; incrementation or decrementation )
{
statements;
}
(2) In for loop, in the initialization part, we have assigned value 1 to the variable
number. And remember that the initial value of the for loop is performed only once. In the
condition part, we have specified our condition and then the increment part.
(3) In the body of a loop, we have a print function to print the numbers on a new line
in the console. We have the value one stored in number, after the first iteration the value will
be incremented, and it will become 2. Now the variable number has the value 2. The
condition will be rechecked and since the condition is true loop will be executed, and it will
print two on the screen. This loop will keep on executing until the value of the variable
becomes 10. After that, the loop will be terminated, and a series of 1-10 will be printed on the
screen.
In C, the for loop can have multiple expressions separated by commas in each part.
For example:
for (x = 0, y = num; x < y; i++, y--)
{
statements;
}
We can skip the initial value expression, condition and/or increment by adding a
semicolon.
For example:
int i=0;
int max = 10;
for (; i < max; i++)
{
printf("%d\n", i);
}
Notice that loops can also be nested where there is an outer loop and an inner loop.
For each iteration of the outer loop, the inner loop repeats its entire cycle.
10.4 NESTED LOOPS
A nested loop means a loop statement inside another loop statement. That is why
nested loops are also called “loop inside loops“. Any number of loops can be defined inside
another loop, i.e., there is no restriction for defining any number of loops. The nesting level
can be defined at n times.
Syntax:
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{
// statement of inside loop
}
// statement of outer loop
}
Fig. 10: nested for loop construct
Consider the following example, that uses nested for loops output a multiplication table:
#include <stdio.h>
int main()
{
int i, j;
int table = 2;
int max = 5;
for (i = 1; i <= table; i++) // outer loop
{
for (j = 0; j <= max; j++)
{
printf("%d x %d = %d\n", i, j, i*j); // inner loop
}
printf("\n"); /* blank line between tables */
}
}
Output:
1x0=0
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
2x0=0
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
The nesting of for loops can be done up-to any level. The nested loops should be
adequately indented to make code readable. In some versions of 'C,' the nesting is limited up
to 15 loops, but some provide more.
The nested loops are mostly used in array applications which we will see in further
tutorials.
10.5 BREAK AND CONTINUE STATEMENTS (Unconditional Control Transfer
Statements)
Unconditional Control Transfer Statements is used to transfers the control to some
other place/block in the program. In C Programming Language, There are three types of
unconditional control transfer statements.
break statement
continue statement
goto statement
10.5.1 break statement
A break statement can be used to terminate or to come out from the loop or
conditional statement unconditionally. It can be used in switch statement to break and come
out from the switch statement after each case expression. Whenever, break statement is
encounter within the program then it will break the current loop or block. A break statement
is normally used with if statement. When certain condition becomes true to terminate the loop
then break statement can be used.
In the following program demonstrates the use of break statement. Loop will be
terminated as soon as the counter value becomes greater than 5.
Example: Program to demonstrate the use of continue
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for( i = 1; i <= 10 ; i++ )
{
if (i > 5)
break; // terminate loop
printf("\n %d ", i);
}
getch();
}
goto statement requires a label to determine where to transfer the control. A label
must end with colon (:). We can use any valid name as a label similar to variable name. When
compiler encounters goto statement with a label name then, it transfers the control to the
location where label has been defined in the program
When we use goto statement either some statement are execute repeatedly or skipped.
When goto statement is placed after the label, control jumps backward direction and some
statement are repeated. Such type of go to jump is called backward jump. When goto
statement is placed before the label in the program, control transfers to the label and some
statements are skipped. Such type of jump is called forward jump. In highly structure
programming language such as c, it is not advisable to use go to statement. We should avoid
using go to statement as far as possible because it affects performance of the program.
The following program demonstrates the use of goto statement.
Example: /* without goto and label */ /* without goto and label */
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
printf(“Davangere \t”); printf(“Davangere \t”);
printf(“is a \t”); goto label;
printf(“smart city”); printf(“is a \t”);
} lable: printf(“smart city”);
Output: }
Davangere is a smart city Output:
Davangere smart city