Sei sulla pagina 1di 54

DECISION MAKING, BRANCHING AND

LOOPING
CONTROL STRUCTURES:
There are 5 control structures. They are
1. if statement
2. switch statement
3. for loop
4. while loop
5. do while loop

LOOPS:
There are 2 types of loops, they are:
1. Counter-controlled loops
2. Sentinel-controlled loops

1. Counter-controlled loops:
In Counter-controlled loops, we know in advance how many times the loop will
be executed. Counter-controlled loops are also called as definite repetition loops.

2. Sentinel-controlled loops:
In Sentinel-controlled loops, a sentinel value is used to change the loop
expression from True to False. For example, when reading data we may indicate the end
of data reading by a special value, like -1 and so on. Sentinel-controlled loops are
also called as indefinite repetition loops, because the number of repetitions is not known,
before the loop begins executing.

CONDITIONAL STATEMENTS:
1

There are 2 conditional statements. They are


1. if statement
2. switch statement

1. if statement:
Syntax 1 (if with else):
if(cond)
{
St1;
St2;
}
else
{
St3;
St4;
}
St5;
Note: If there is more than 1 statement in if loop we must enclose them in braces.
For single statements braces are optional. Condition must be enclosed in brackets.
Semicolan must not be used at the end of the condition. if and else are reserved
words. For every else corresponding if is necessary but not vice versa. There can
be if without else .
Syntax 2 (if without else) :
if(condition)
{
St1;
St2;
}
St3;
2

If the condition is true, statements St1 and St2 are executed. If the condition is
false, statements St1 and St2 are not executed, but St3 is executed.
For every if , else is not compulsory
Syntax 3 (else if ladder) :
if(condition 1)
{
St1;
St2;
}
else
if(condition 2)
{

Condition 1 Condition2 Condition 3 Statements executed

St3;

True

1,2,9

St4;

False

True

3,4,9

False

False

True

5,6,9

False

False

False

7,8,9

}
else
if(condition 3)
{
St5;
St6;
}
else
{
St7;
St8;
}
St9;

Note: If a particular condition is true, remaining conditions are not tested due to else .

Syntax 4 (Nested if statement) :


if statement in if is called nested if statement.
if(condition 1)
{
if(condition 2)
{
St1;
St2;
}
else
{
St3;
St4;
}
}

Condition 1 Condition2 Condition 3 Statements executed


True

True

1,2,9

True

False

3,4,9

False

True

5,6,9

False

False

7,8,9

else
{
if(condition 3)
{
St5;
St6;
}
else
{
St7;
St8;
}

}
St9;
Note: Only 1 condition among condition 2 and condition 3 is tested. It all depends on
condition 1.

PROGRAMS
1. To find largest of 2 numbers
Logic: if(a > b)
else
Eg:

printf(a is largest) ;
printf(b is largest) ;

For a = 10, b = 20, Ans is b is largest


For a = 10, b = 10, Ans is b is largest (since a > b is not true, else is executed)

2. To test a number is even or odd


Logic: if(n % 2 = = 0)
else

printf(Even number) ;
printf(Odd number) ;

Note: We should use only = = , but not = in conditions, as = is assignment


operator.
3. Test whether year is a leap year or not
A leap year is divisible by 4 but not by 100 , or divisible by 400 . */
Logic: if(year % 4 = = 0 && year %100 ! = 0 || year % 400 = = 0)
printf(The year is a leap year) ;
else
printf(The year is not a leap year) ;
4. To find largest of 3 numbers
Logic: if(a > = b && a > = c)
printf(a is largest) ;
else
if(b > = a && b > = c)
printf(b is largest) ;
else
5

printf(c is largest) ;
Note: Dont just use > , < or = , as they are binary operators. We should use
only relational operators.
5. To test whether a point (x,y) lies in the 1st , 2nd ,3rd or 4th quadrant and also whether
in x-axis, y-axis or origin
main( )
{
float x, y ;
printf(Enter values for points x and y \n :)) ;
scanf(%f %f, &x, &y) ;
if(x > 0 && y > 0)
printf(Point lies in 1st quadrant) ;
else
if(x < 0 && y > 0)
printf(Point lies in 2nd quadrant) ;
else
if(if(x < 0 && y < 0)
printf(Point lies in 3rd quadrant) ;
else
if(x > 0 && y < 0)
printf(Point lies in 4th quadrant) ;
else
if(x ! = 0 && y = = 0)
printf(Point lies in x-axis) ;
else
if(x = = 0 && y ! = 0)
printf(Point lies in y-axis) ;
else
printf(Point lies in origin) ;

getch( ) ;
}

6. To test a point (x,y) lies inside the circle, outside the circle or on the circle
Centre is origin, radius is r.
main( )
{
float x, y, r, d ;
printf(Enter values for points x and y :)) ;
scanf(%f %f, &x, &y) ;
printf(Enter the radius :) ;
scanf(%f, &r) ;
d = sqrt(x * x + y * y) ;
if(d > r)
printf(Point lies outside the circle) ;
else
if(d < r)
printf(Point lies inside the circle) ;
else
printf(Point lies at the centre of the circle) ;
getch( ) ;
}
7. To find whether the given sides of a triangle form a equilateral, isosceles or
scalene triangle and to find the area of the same.
main( )
{
float a, b, c, p, s, area ;
printf(enter the 3 sides of the triangle as a, b, c) ;

scanf(%f %f %f, &a, &b, &c) ;


if(a + b > c && b + c > a && c + a > b)
{
if(a = = b && b = = c &&c = = a)
{
printf(equilateral triangle) ;
area = sqrt(3)/4 * a * a ;

printf(the area is %f , area) ;

}
else
if(a = = b || b = = c || c = = a)
{
printf(Isosceles triangle) ;
p = a + b + c;

printf(Perimeter = %f, p) ;

}
else
{
printf(Scalene triangle) ;
p = a + b + c;

s = p / 2;

printf(Perimeter = %f, p) ;

area = sqrt(s * (s a) * (s b) * (s c)) ;


printf(Area = %f, area) ;

}
}
else
printf(Not a triangle) ;
getch( ) ;
}

exit( ):
exit( ) is used to stop the program execution. Rest of the program is not executed
when exit(0) or exit(1) is encountered. 0 indicates successful termination of program
and 1 means abnormal termination. It is predefined in <process.h> .

8. To find the roots of a quadratic equation


main( )
{
float a, b, c, root1, root2, realpart, imaginarypart, discriminant ;
printf(Enetr values of a, b, c:) ;
scanf(%f %f %f, &a, &b, &c) ;
if(a = = c)
{
printf(Value of a cannot be zero ) ;
exit(0) ;
}
discriminant=b * b 4 * a * c;
if(dicriminant > 0)
{
printf(Roots are real and equal) ;
root1=(- b + sqrt(discriminant)) / (2 * a) ;
root2=(- b - sqrt(discriminant)) / (2 * a) ;
printf(Root1 = %.2f,root1) ;
printf(Root2 = %.2f,root2) ;
}
else
if(discriminant= =0)
{
printf(Roots are real and equal ) ;
root1 = root2 = - b / (2 * a) ;
printf(Root1 = %.2f,root1) ;
printf(Root2 = %.2f,root2) ;
}
else

{
printf(Roots are complex) ;
realpart = - b / (2 * a) ;
imaginarypart = sqrt(- discriminant) / (2 * a) ;
printf(Root1 = %.2f + i * %.2f ,realpart,imaginarypart) ;
printf(Root1 = %.2f + i * %.2f ,realpart,imaginarypart) ;
}
getch( ) ;
}
9. To find the largest,smallest and middle number for given 3 numbers
main( )
{
int a, b, c, largest, smallest, middle ;
printf(Enter 3 numbers:) ;
scanf(%d %d %d, &a, &b, &c) ;
maximum = a;

/* Assume that a is largest */

if(b > maximum)


maximum = b;
if(c > maximum)
maximum = c;
minimum = a;
if(b < minimum)
minimum = b;
if(c < minimum)
minimum = c;
middle = (a + b + c) (maximum + minimum) ;
printf(Largest number = %d \n,maximum) ;
printf(Smallest number = %d \n,minimum) ;
printf(Middle number = %d \n,middle) ;

10

getch( ) ;
}
Eg:

If a = 50 , b = 90 , c = 60;
Ans is Largest number = 90
Smallest number = 50
Middle number = 60

ASSIGNING STRING TO POINTER:


char a = g ;

/* Here a is a variable that contains character g .

char * b = Rama Rao ;


/* Here Rama Rao is a string stored somewhere in memory.Address
of first character is stored in b . b is a pointer to first character
Rama Rao. Strings are of type char * */
b
1000

Rama Rao
1000

10. To find the grade of a student based on marks of 3 subjects using if


Condition
Average < 40
Average > = 70
Average > = 60
Average > = 50

Grade
Fail
Distinction
1st class
2nd class

11

Average > = 40

3rd class

main( )
{
int rollno,maths,physics,chemistry,total,k;
float average;
char studentname[20];
char *grade;
printf(Enter roll no: ) ;
scanf(%d \n,&rollno) ;
printf(Enter student name: ) ;
fflush(stdin) ;
gets(studentname) ;
printf(Enter marks of 3 subjects ) ;
scanf(%d %d %d ,&maths,&physics,&chemistry) ;
total = maths + physics + chemistry;
average=total / 3.0;
if(maths < 40 || physics < 40 || chemistry < 40)
grade = fail ;
else
if(average > = 70)
grade = Distinction;
else
if(average > = 70)
grade = 1st class;
else
if(average > = 50)
grade = 2nd class;
else
if(average > = 40)
grade = 3rd class;

12

printf(the total marks=%d,total) ;


printf(average=%f,average) ;
printf(grade is =%s,grade) ;
getch( ) ;
}

strcmp( ):
strcmp( ) is used to compare 2 strings and returns a corresponding value. It is
predefined in <string.h> .
Syntax:
strcmp(string1 , string2) ;
Eg:

strcmp( hyd , hyd ) ;

Ans is 0 (False) .

strcmp( vij , hyd ) ;

Ans is non zero (True) .

The strcmp( ) returns 0 when strings are same and non zero when
they are not.
Note: Dont use = = when comparing strings. Use = = to compare integers, float
and characters but not strings.

11. To find Gross pay and net pay of n employee


I/P is Employee number,name,salary,city .
DA = 50% of salary, HRA = 20% of salary
If employee lives in hyd city, CCA = Rs 100 and Rs 80 otherwise .
Gross pay = salary + DA + HRA + CCA
PRINTF = 8% of Gross pay but a max of Rs 400 .
If gross pay is below 10,000, tax is 10% of Gross pay otherwise tax is 15% of
Gross pay.
net pay = Gross pay PRINTF Tax

13

main( )
{
int employeeno ;
char employeename[20], city[20] ;
float salary, da, hra, cca, gp, np, tax ;
printf(Enter employee number :) ;
scanf(%d \n, &employeeno) ;
printf(Enter employee name :) ;
fflush(stdin) ;
gets(employeename) ;
printf(Enter employee salary :) ;
scanf(%f \n, &salary) ;
printf(Enter employee city :) ;
fflush(stdin) ;
gets(city) ;
da = 0.50 * salary;
hra = 0.20 * salary;
if( strcmp(city , HYD) = = 0 || strcmp(city , Hyd) = = 0 )
/* If HYD or Hyd is typed, if statement is true as strcmp
returns 0 if the strings match . */
cca = 100;
else
cca = 80;
gp = salary + da + hra + cca;
pf = 0.08 * gp;
if(pf > 400)
pf = 400;
if(gp < 10000)
tax = 0.10 * gp;
else

14

tax = 0.15 * gp;


np = gp pf tax;
printfGross pay = %.2f \n, gp) ;
printfNet pay = %.2f \n, np) ;
getch( ) ;
}

2. switch statement:
Switch statement can be used as an alternative for if statement.It provides more
clarity and readability.Use if statements only if conditions are involved.Use switch when
selection is involved.Every switch can be replaced by if but not vice versa.
Eg:
switch(a + b* c)
{
case 7:
case -25:
case 0:
{
St1;
break;
}
case 6:

a+b*c

Statements executed

7 , -25 , or 0
6 or 15
None of the above

1 and 4
2 and 4
3 and 4

case 15:
{
St2;
break;
}
default :
{
St3;
break;
15

}
}
St4;

RULES TO BE FOLLOWED:
1.We can use variable or expression in switch.
Eg: switch(a) or switch(a + b* c)
2.The variable in switch can be integer or character but not float.
Eg: float a;
Switch(a)

/* This gives error */

case 7: and case g: are valid but case 10.8: and case hyd are not valid .
3.Value in one case cannot be repeated in another case.
4.There must be atleast one space between case and value .
Eg: case 7 is valid but not case7 .
Note: default is executed when space is missing.
5.default is optional in switch.
If (a + b * c) is 100 default is executed since there is no 100 in any case.
And in this case where we get 100 and if there is no default statement no statements are
executed.However statements outside are executed.
6.default must be the last block of switch .
7.break statement must be at the end of every case.for default , break is optional.

16

8.Braces are optional for cases as break is at the end.However switch braces are
compulsory.
9.If no break statement is used all cases from that particular case are executed.
10.If wrong I/P and default is not present no O/P at all.

break:
When break statement is executed, control comes out of switch statement .

12. To find the grade of a student based on marks of 3 subjects using switch
main( )
{
int rollno, maths, physics, chemistry, total,k;
float average;
char studentname[20];
char *grade;
printf(enter roll no: ) ;
scanf(%d \n, &rollno) ;
printf(enter student name: ) ;
fflush(stdin) ;

/* We have to use this if we give any I/P before gets( ) */

gets(studentname) ;
printf(enter marks of 3 subjects ) ;
scanf(%d %d %d , &maths, &physics, &chemistry) ;
total = maths + physics + chemistry;
average=total / 3.0;
if(maths < 40 || physics < 40 || chemistry < 40)
grade = fail ;
17

else
{
k=avg/10;
switch(k)
{
case 7:
case 8:
case 9:
case 10:
{
grade = distinction ;
break;
}
case 6:
{
grade= 1st class ;
break;
}
case 5:
{
grade= 2nd class ;
break;
}
case 4: or default :
{
grade= 3rd class ;
break;
}
}
}
printf(the total marks=%d,total) ;

18

printf(average=%f,average) ;
printf(grade is =%s,grade) ;
getch( ) ;
}

13. To find the tax for a given income


Income
< 10,000
10,000-19,999
20,000-39,999
40,000-69,999
>= 70,000

Tax
0
10 %
15 %
20 %
25 %

main( )
{
char personname[20];
long income;
float tax;
printf(enter person name: ) ;
gets(personname) ;
printf(enter income: ) ;
scanf(%ld,&income) ;
k=income/10000;
switch(k)
{
case 0:
{
tax=0;
break;
}
case 1:

19

{
tax=0.1 * income;
break;
}
case 2:
case 3:
{
tax==0.15 * income;
break;
}
case 4:
case 5:
case 6:
{
tax=0.2 * income;
break;
}
default:
{
tax=0.25 * income;
break;
}
}
printf(tax= %.2f,tax) ;
getch() ;
}

Nested Switch( ):
Switch in switch is called nested switch.

20

Syntax:
switch(a)
{
case 1:
{
switch(b)
{
case 1:

/* executed when a=1 and b=1 */

{
St1;
break;
}
case 2:

/* executed when a=1 and b=2 */

{
St2;
break;
}
}
break;
}
case 2:

/* executed when a=2 */

{
St3;
break;
}
}

Note: When break is executed in inner switch, control comes out of inner switch only.
When break is executed in outer switch then control comes out of outer switch.

21

case 1 and case 2 appear in inner switch as well as outer switch. They can appear because
they belong to different switches.
14. To generate an electricity bill based on present and previous meter reading with
I/Ps as meter number, customer name, present and previous readings. Add a
surcharge of Rs 10
Units = Present reading Previous reading
Type 1 - Residential
Units
First 100
Next 100
Next 200
Next 300
Above 700

Cost
3.00 / unit
3.50 / unit
4.00 / unit
4.50 / unit
5.00 / unit

Type 2 Commercial
Units
Any number of units

Cost
5.00 / unit

main( )
{
int meternumber,type,units,k;
float cost;
long previous,present;
char customername [20];
printf(enter the meter number) ;
scanf(%d,&meternumber):
printf(enter customer name: ) ;
fflush(stdin) ;
gets(customername) ;
printf(enter previous and present meter reading) ;
scanf(%ld %ld,&previous,&present) ;
22

printf(enter 1 - residential,2 commercial) ;


scanf(%d,&type) ;
units=abs(present previous) ;
switch(type)
{
case 1:
{
k=units / 100;
switch(k)
{
case 0:
{
cost = units * 3.00;
break;
}
case 1:
{
cost = 100 * 3.00 + (units-100) * 3.50;
break;
}
case 2:
case 3:
{
cost = 100 * 3.00 + 100 * 3.50 + (units-200) * 4.00;
break;
}

case 4:
case 5:
case 6:

23

{
cost = 100 * 3.00 + 100 * 3.50 + 200 * 4.00 + (units-400) * 4.50 ;
break;
}
default :
{
cost = 100 * 3.00 + 100 * 3.50 + 200 * 4.00 +
300 * 4.50 + (units - 700) * 5.00;
break;
}
}
break;
}
case 2:
{
cost = units * 5.00;
break;
}
}
printf(bill amount = %.2f,cost) ;
getch( ) ;
}

INVALID EG:
switch(a)
{
switch(b)
{
24

St1;
break;
}
}
Note: Inner switch must exist in a case of the outer switch .
Find the output of the following program:
main( )
{
int a=1,b;
switch(a)
{
case 1:
b=10;
case 2:
b=20;
case 3:
b=30;
}
printf(b = %d,b) ;
getch( ) ;
}
Ans is b = 30 , since all three statements are executed as break is missing .

LOOPS OR ITERATIVE STATEMENTS


There are 3 iterative statements, they are
1. for loop
2. while loop

25

3. do while loop

1. for loop statement:


For loop is used to execute a set of sttements n times .
Syntax:
for(i=initialization;condition;increment or decrement)
{
Statements ;
}
Eg:

for(i=0;i<=3;i++)

/* i++ or ++i has the same effect */

{
Statements ;
}

STEPS IN FOR LOOP:


1.Execute initialization.
2.Test the condition . If true, statements in for loop are executed .
3.Execute increment or decrement .
4.Test the condition again, if true repeat step 2 and step 3.If false ,control
comes out of the loop and statements outside the loop are executed .

Syntax 2:
initialization;
for( ; condition ; )
{

26

St1;
St2;
increment or decrement;
}
Note: 1. There are supposed to be 2 semicolons in for loop even though initialization
and increment or decrement are not in the for loop parenthesis .
2. Statements in for loop are executed repeatedly as long as condition is true.
Control comes out of loop the moment condition is false .For loop is Pre tested
or Entry tested loop ,that is condition is tested at the beginning of the loop.
For loop is never executed when the condition is false for the first time itself.

Find the O/P of the following


main( )
{
for( ; ; )
printf(Hello \n) ;
}
Note: When no condition is specified in for loop default condition is true .
Here Hello is executed infinite times .

2. While loop:
Syntax:
initialization;
while(condition)
{
St1;
St2;
27

increment or decrement;
}
Note: Statements in while loop are executed repeatedly as long as condition is true .
Control comes out of loop the moment condition is false. while loop is Pre tested or
Entry tested loop ,that is condition is tested at the beginning of the loop. For loop
is never executed when the condition is false for the first time itself.
Eg:

i=1;
while(i<=3)
{
st1;
st2;
i++;
}

3. do while loop:
Syntax:
initialization;
do
{
St1;
St2;
increment or decrement;
}
while(condition) ;
Note: 1. Statements in do while loop are executed repeatedly as long as condition is
true. Control comes out of loop the moment condition is false. do while loop is Post
tested or Exit tested loop ,that is condition is tested at the end of the loop. do

28

while loop is executed atleast once even since the condition is tested at the end. first
time itself. ; after while statement in do while is used to end do while loop .
Eg:

i=1
do
{
St1;
St2;
i++;
}
while(i<=3) ;

PROGRAMS:
1. To display natural numbers 1 to n
main( )
{
int i,n;
printf(Enter a value for n :) ;
scanf(%d,&n) ;
printf(Natural numbers are :) ;
for(i=1;i<=n;i++)
printf(%d \t,i) ;
getch( ) ;
}
2. To display first 20 even numbers
main( )
{
int i;

29

printf(First 20 even numbers are :) ;


for(i = 1; i < = 20 ; i++)
printf(%d \t,( 2 * i )) ;
( or)
for(i = 2 ; i < = 40 ; i = i + 2)
printf(%d \t,i) ;

*/

getch( ) ;
}
3. To display first 20 odd numbers
main( )
{
int i ;
printf(First 20 odd numbers are :) ;
for(i = 1 ; i < = 40 ; i = i + 2)
printf(%d \t,i) ;
getch( ) ;
}
4. To displat upper case and lower case alphabets
main( )
{
char ch ;
for(ch = A ; ch < = Z ; ch++)
printf(%c \t,ch) ;
printf(\n) ;
for(ch = a ; ch < = z ; ch++)
printf(%c \t,ch) ;
getch( ) ;
}

30

5. To display 10 9 8 7 . 2 1
main( )
{
int i;
for(i = 10 ; i > = 1 ; i - -)
printf(%d \t,i) ;
getch( ) ;
}
6. To find the sum of first n numbers
main( )
{
int i, n, sum = 0 ;
printf(Enter a value for n) ;
scanf(%d, &n) ;
for(i = 1 ; i < = n ; i++)
sum = sum + i;
printf(The sum of first %d numbers is %d,n,sum) ;
getch( ) ;
}
7. To find the sum of first 20 even numbers
main( )
{
int i, sum = 0 ;
for(i = 1 ; i < = 20 ; i++)
sum = sum + ( 2 * i ) ;
printf(The sum of first 20 even numbers is %d, sum) ;
getch( ) ;
}

31

8. To find the sum of first 20 odd numbers


main( )
{
int i, sum = 0 ;
for(i = 1 ; i < = 40 ; i = i + 2)
sum = sum + i ;
printf(The sum of first 20 odd numbers is %d, sum) ;
getch( ) ;
}
9. To find the factorial of a given number
main( )
{
int i,n;
long double product = 1 ;
printf(Enter any +ve integer or 0) ;
scanf(%d, &n) ;
for(i = 1 ; i < = n ; i++)
product = product * i ;
printf(The factorial of %d is %Lf, n, product) ;
getch( ) ;
}
Note: Approximately only 30! can be found in system even using long double .
10. To display Fibonacci series with n terms
main( )
{
int a, b, c, n, i ;
printf(Enter the number of terms) ;
scanf(%d,&n) ;
a = 0;

b = 1;

printf(Fibonacci series is :) ;

32

printf(%d \t %d \t,a,b) ;
for(i = 1 ; i < = n 2 ; i++)
{
c = a + b;
printf(%d \t,c) ;
a = b;

b = c;

}
getch( ) ;
}
11. To display Fibonacci series upto n
main( )
{
int a,b,c,n;
printf(Enter the value of n :) ;
scanf(%d,&n) ;
a = 0;
b = 1;
printf(Fibonacci series is :) ;
printf(%d \t %d \t,a,b) ;
c = a + b;
while(c < = n)
{
printf(%d \t,c) ;
a = b;
b = c;
c = a + b;
}
getch( ) ;
}

33

12. There are 21 match sticks. User can pick 1,2,3 or 4 match sticks and computer
picks after user. Who ever picks the last matchstick, they lose the program. Write a
program so hat computer always wins.
Logic:If the user picks 1,2,3 or 4 computer should pick 4,3,2 and 1 respectively
inorder to get 5 everytime so that user will be left with 1 at the end. The following
program will work for match sticks of number 21,26,31,36 etc.
main( )
{
int n = 21;
int pick;
while(n > 1)
{
printf(Enter your number of match sticks)
scanf( %d \n,&pick) ;
while(pick < 1 || pick >4)
{
printf(Invalid, renter) ;
scanf(%d \n,&pick) ;
}
printf(Computer picks %d match sticks \n,(5 pick)) ;
n = n - 5;
}
printf(You have lost the game as there is only one match stick left \n) ;
getch( ) ;
}
13. To display each character and its ascii value with 20 values per page
main( )
{

34

int i;
for(i = 0 ; i < = 255 ; i++)
{
printf(%d - %c \n,i,i) ;
if((i + 1) % 20 = = 0)
{
printf(Press any key to continue : \n) ;
getch( ) ;
clrscr( ) ;
}
}
getch( ) ;
}
14. To evaluate an expression like calculator say 3 + 4 * 5 6 / 2 = 14.5.
ie first (3 + 4),then (result * 5),then (result 6),then (result / 2).
main( )
{
float a,b;
char op;
printf(Enter any expression terminated by = ) ;
scanf((%f,&a) ;
scanf(%c,&op) ;
while(op ! = = )
{
scanf(%f,&b) ;
switch(op)
{
case +:
{

35

a = a + b;
break;
}
case -:
{
a = a - b;
break;
}
case *:
{
a = a * b;
break;
}
case /:
{
a = a / b;
break;
}
}
scanf(%c,&op)
}
printf(Result is %f : ,a) ;
getch( ) ;
}
Note: Dont press spacebar in expression. It must be continous expression without any
spaces in it.

NESTED LOOPS:
Loop in loop is a called nested loop. Inner loop can be for, while, or do
while loop. Outer loop can be for, while, or do while loop. Inner loop execution is

36

fast, whereas outer loop execution is slow. Outer loop and inner loop cannot have the
same index.
Eg:

main( )
{
int i,j;
for(i = 1 ; i < = 3 ; i++)
{
for(j = 1 ; j < = 2 ; j++)
printf(%d \t %d \n, i, j) ;
printf(Hello \n) ;
}
printf(Bye \n) ;
getch( ) ;
}

O/P:
1

Hello
2

Hello
3

Hello
Bye
Note: Here inner loop index is i and outer loop index is j . When i = 1 j
varies from 1 to 4. For each value of i, j varies from 1 to 4. If outer loop is executed m
times and inner loop is executed n times, then statements
in inner loop is executed (m * n) times.

37

Eg:

for(h = 0 ; h < = 23 ; h++) /* Executed 24 times */


{
for(m = 0 ; m < = 59 ; m++) /* Executed (24 * 60) times */
{
for(s = 0 ; s < = 59 ; s++) /* Executed (24 * 60 * 60) times */
{
statements;
}
}
}

Find the O/P of the following program


main( )
{
int i,j;
for(i = 1 , j = 1 ; i < = 3 && j < = 4 ; i++ , j++)
printf(%d \t %d \n,i,j) ;
getch( ) ;
}
O/P:
1

Note: If we use || instead of && O/P is


1

38

Note: If we say a = 2 , 3 ;

O/P is a = 3 .

If we say a[i , j] ;

O/P is a[ j ] .

If we say a[i , j , k] ;

O/P is a[ k ] .

PROGRAMS
1. To display mathematical tables 1 to n each table containing variable number
of rows.
main( )
{
int i, j, n, k;
printf(Enter the number of tables :) ;
scanf(%d \n, &n) ;
for(i = 1 ; i < = n ; i++)

/* Display n tables */

{
printf(Enter the number of rows in table :) ;
scanf(%d \n,&k) ;
for(j = 1 ; j < = k ; j++)

/* Display k rows in each table */

printf(%d * %d = %d \n, i, j, (i * j)) ;


printf(Press any key to continue :\n) ;

/* Display next table only after user


presses any key */

getch( ) ;
clrscr( ) ;

/* Clear current table */

}
getch( ) ;
}
2. To display the following output
ABCDEFGFE DCBA
39

ABCDEF
ABCDE
ABCD

FEDCBA
EDCBA
DCBA

ABC

CBA

AB

BA

main( )
{
int i,j,s;
char lc, ch;
lc = F;
s = 2;
for(i = 1 ; i < = 7 ; i++)
{
if(i = = 1)
{
for(ch = A ; ch < = G ; ch++)
printf(%c ,ch) ;
for(ch = F ; ch > = A ; ch--)
printf(%c ,ch) ;
printf(\n) ;
}
else
{
for(ch = A ; ch < = lc ; ch++)
printf(%c ,ch) ;
for(j = 1 ; j < = s ; j+)
printf( ) ;
for(ch = lc ; ch > = A ; ch--)
printf(%c ,ch) ;
printf(\n) ;

40

lc-- ;
s = s + 4;
}
}
getch( ) ;
}
3. To display the following output
1
2

10

main( )
{
int i, j, n, value ;
printf(Enter the number of lines :) ;
scanf(%d \n,&n) ;
value = 1;
for(i = 1 ; i < = n ; i++)
{
for(j = 1 ; j < = i ; j++)
{
printf(%d \t,value) ;
value++;
}
printf(\n) ;
}
getch( ) ;
}

41

4. To display the following output


1
1

main( )
{
int i,j,n,value;
printf(Enter the number of lines :) ;
scanf(%d \n,&n) ;
for(i = 1 ; i < = n ; i++)
{
value = 1;
for(j = 1 ; j < = i ; j++)
{
printf(%d \t,value) ;
value++;
}
printf(\n) ;
}
getch( ) ;
}
5. To display the following output
1
1

42

main( )
{
int i,j,n,value;
printf(Enter the number of lines :) ;
scanf(%d \n,&n) ;
value = 1;
for(i = 1 ; i < = n ; i++)
{
for(j = 1 ; j < = i ; j++)
printf(%d \t,value) ;
printf(\n) ;
}
getch( ) ;
}
6. To display the following O/P
r
r

main( )
{
char a[40];
int i,j;
printf(Enter any string) ;
gets(a) ;
for(i = 0 ; a[i] ! = \0 ; i++) /* Display n lines where n is string length. */
{

43

for(j = 0 ; j < = i ; j++)

/* Display the characters in the line. */

putchar(a[j]) ;
putchar(\n) ;
}
getch( ) ;
}

7. To display the following O/P


1
3

main( )
{
int i,j,n,col,row;
printf(Enter the number of lines :) ;
scanf(%d,&n) ;
col = 40;
row = 5;
clrscr( ) ;
for(i = 1 ; i < = n ; i++)

/* Display n lines. */

{
gotoxy(col,row) ;
for(j = 1 ; j < = (2 * i - 1) ; j++) /* Display (2 * i 1) values in each row. */
printf(%d,i) ;
col = col - 2;
row++;
}
getch( ) ;

44

8. To display Pascal triangle


0C0
1C0
2C0
3C0

1C1
2C1

3C1

ie

2C2
3C2

3C3

1
1
1

1
2

1
3

main( )
{
int i,j,n,col,row;
int ner(int,int) ;
printf(Enter number of lines :) ;
scanf(%d \n,&n) ;
col = 40;
row = 5;
clrscr( ) ;
for(i = 0 ; i < = n 1 ; i++)
{
gotoxy(col,row) ;
for(j = 0 ; j < = i ; i++)
printf(%d ,ner(i , j)) ;
col = col 2;
row++;

45

}
getch( ) ;
}
9. To generate a random number and ask user to guess that value. If user enteres
number matches with random number, display message congrats , otherwise
display too low or too high and try again. Give user 10 chances to guess
main( )
{
int i,n,guess;
char ch;
do
{
randomize( ) ;
n = rand( ) ;
printf(I have a random number, guess it) ;
for(i = 1 ; i < = 10 ; i++)
{
printf(Enter your guess :) ;
scanf(%d \n,&guess) ;
if(guess = =n)
{
printf(Congrats, you have guessed it right in %d attempts,i) ;
break;

/* Come out of loop if user guessed right */

}
else
if(guess < n)
printf(Too low, try again \n) ;
else
printf(Too low, try again \n) ;
}

46

if(i = 11)
{
printf(10 attempts are over,correct value is : %d \n, n) ;
printf(Do you want to play another game,if yes press y otherwise n :) ;
fflush(stdin) ;
scanf(%c,&ch) ;
}
}
while(ch = = y || ch = = Y) ;
getch( ) ;
}
Note: randomize( ) ;
a = rand( ) ;
This randomize( ) ensures that rand( ) generates a different random
number each time it is called between 1 and 32767 .
Eg 1: int a,b,c;
randomize( ) ;
a = rand( ) ;
randomize( ) ;
b = rand( ) ;
randomize( ) ;
c = rand( ) ;
Here when execution a,b,c contain different random numbers,as randomize( ) is called 3
times.
Eg 2: int a,b,c;
a = rand( ) ;

47

b = rand( ) ;
c = rand( ) ;
Here when execution a,b,c contain same random number as randomize( ) is no called.
Eg 3: int a;
randomize( ) ;
a = rand(100) ;
Here when execution a conatins a random number between 1 and 100 .
Eg 4: long a;
randomize( ) ;
a = rand( ) * 100;
Here when execution a conatins a random number between 100 and 3276700 .

break Statement:
break statement is also used to come out of a for, while, do-while loop and
switch statement.
Eg 1: while(condition 1)
{
St1;
if(condition 2)
break;
St2;
St3;

/* Skipped */

}
St4;
Note: If the condition 2 is true, next statement executed is St4; ie control comes out of
loop. Statements following break statement are skipped along with the remaining
iterations.
Eg 2: if(condition)
48

{
St1;
break;
St2;
}
Note: We cant use break in if statement, but when if statement is enclosed in a
loop, break statement can be used in if.

Eg 3: while(condition 1)
{
while(condition 2)
{
St1;
if(condition 2)
break;
St2;
St3;

/* Skipped */

}
St4;
}
Note: When break statement is used in inner loop, control comes out of inner loop
only, but not from outer loop. In the above example control comes to St4;.

continue Statement:

49

continue statement is used to skip the current iteration and go to the next iteration.
It can be used in for, while and do-while loop, but not in switch.
Eg 1: while(condition 1)
{
St1;
if(condition 2)
continue;
St2;
St3;

/* Skipped */

}
St4;

Note: If the condition 2 is true, control goes to next iteration of loop. Remaining
statements following continue statement in the current iteration are skipped.

Find the O/P of the following program.


main( )
{
void f1( ) ;
f1( ) ;
printf(Back to the main \n) ;
getch( ) ;
}
Continued.
void f1( )

50

{
int i;
for(i = 1 ; i < = 7 ; i++)
{
printf(%d \n, i) ;
if(i % 3 = = 0)
break; (or) continue; (or) return; (or) exit(0) ;
printf(Hello \n) ;
}
printf(Outside loop \n) ;
}
O/P:

break;

continue;

return

exit(0)

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Outside loop

Back to main

Back to main

Hello
5
Hello
6
7
Hello
Outside loop
Back to main

Note: When void is used, we can use return;, but not return(value) ;.
When using exit(0) ;, use getch( ) ; before exit(0) ;.

51

10. To search for a value in Fibonacci series and display message found or not
found. If found, then its position. Dont generate Fibonacci series.
void search(int x)
{
int a, b, c, position ;
if(x = = 0)
printf(Found at position 1 \n) ;
else
if(x = = 1)
printf(Found at position 2 and 3 \n) ;
else
{
position = 4;
a = 1;

b = 1;

c = a + b;

while(c < = x)
{
if(c = =x)
{
printf(Found at position %d \n, position) ;
return;
}
else
{
a = b;

b = c;

c = a + b;

position + + ;
}
}
printf(Not found \n) ;
}
}

52

11. To find the prime divisors of a number


void prime_div(int n)
{
int i = 2;
while(n > 1)
{
if(n % i = = 0)
{
printf(%d \n, i ) ;
n=n/i;
}
else
i + +;
}
}
main( )
{
void prime_div(int) ;
int n;
printf(Enter a value :;
scanf(%d, &n) ;
prime_div(n) ;
getch( ) ;
}

goto statement:
2 forms of goto and label statements are:
1. Forward jump
2. Backward jump

53

Forward jump:

goto label ;
..
..
label :
Statements ;

Backward jump:
label :
Statements ;
..
..
goto label ;

54

Potrebbero piacerti anche