You are on page 1of 45

CONTROLSTATEMENTS

1. Calculate interest on bank deposit at 6% if period is less than


12 months, else at 9%.
2. Write a program that prints PASS if a student gets more
than 50% , and prints FAIL otherwise.
3. Calculate salary of employees as follows:
Rs 1000 per hour if category 1
Rs 850 per hour if category 2
Rs 700 per hour if category 3
Rs 500 per hour if category 4.

1. Calculate interest on bank deposit at 6% if period is less than


12 months, else at 9%.
2. Write a program that prints PASS if a student gets more
than 50% , and prints FAIL otherwise.
3. Calculate salary of employees as follows:
Rs 1000 per hour if category 1
Rs 850 per hour if category 2
Rs 700 per hour if category 3
Rs 500 per hour if category 4.
4. Calculate average of 10 numbers entered by the user.
5. Calculate average of whatever numbers are entered by the
user.

For all these example a logical test needs to be carried out at


some particular point within the program.
One or the other possible actions will then be carried out,
depending on the outcome of the logical test (problem 1 and 2).
This is known as branching.
There is also a special kind of branching, called selection, in
which one group of statements is selected from several available
groups.(prob 3)
In addition, the program may require that a group of instructions
be executed repeatedly, until some logical condition has been
satisfied. This is known as looping. (prob 4 and 5)

if elsestatement
switch statement
for statement
while statement

Simple if statement

if (<boolean expression>)
statement1;
statement2;
statement3;

A store gives discount of 5% on purchase of 100 items or more.


Calculate the total price, given ITEMS and PRICE.

scanf(%d%f,&ITEM,&PRICE);
If(ITEMS>=100)
PRICE=0.95*PRICE
TOTAL=ITEMS*PRICE

if else statement
if (<boolean expression>)
statement1;
else
statement2;
statement3;
statement4;

Example:

if(marks>50)/*ItcanbeeitherTRUEorFALSE*/
printf(studenthaspassedtheexam\n);
else
printf(studenthasfailedtheexam\n);
..............;
..............;

Supposewewantedstudentgetting50alsotobeshownaspassing.
if(marks>=50)
printf(studenthaspassedtheexam\n);
else
printf(studenthasfailedtheexam\n);
..............;
..............;

Supposewewantedstudentgetting50alsotobeshownaspassing.
if(marks>=50)
printf(studenthaspassedtheexam\n);
else
printf(studenthasfailedtheexam\n);
..............;
..............;
Alternatively,
if(marks<50)
printf(studenthasfailedtheexam\n);
else
printf(studenthaspassedtheexam\n);
..............;
..............;

Alternatively,

if(!marks<50)
printf(studenthaspassedtheexam\n);
else
printf(studenthasfailedtheexam\n);
..............;
..............;

Supposeyouneedtoaddmorestatementstoif
orelse parts
if(marks>=50)
printf(marks=%d,marks\n);
printf(studenthaspassedtheexam\n);
else
printf(studenthasfailedtheexam\n);
..............;
..............;

Supposeyouneedtoaddmorestatementstoif
orelse parts
if(marks>=50)
printf(marks=%d,marks\n);
printf(studenthaspassedtheexam\n);
else
printf(studenthasfailedtheexam\n);
..............;
..............;

THISWOULDBEWRONG!!
if(marks>=50){
printf(marks=%d,marks\n);
printf(studenthaspassedtheexam\n);}
else
printf(studenthasfailedtheexam\n);
..............;
..............;

Whataboutequalto?
if(order==50)
printf(yes\n);
else
printf(no\n);
..............;
..............;

b1andb2aretwoBooleanexpressions
(b1)

&&

(b2):TRUEonlyifbothb1andb2aretrue

(b1)

||

(b2):TRUEifanyoneistrue

!(b1)

:FALSEifb1istrue

Gettingfloatingpointdatafromtheuserandperformifelse
floatpriceA,priceB;
printf(PleaseenterthepricesofAandB:);
scanf(%f%f,&priceA,&priceB);
if(priceA>priceB)
printf(\nitemAcostlier);
else
printf(\nitemANOTcostlier.);

Printingfloatingpointvalues
floatpriceA,priceB,;
printf(PleaseenterthepricesofAandB:);
scanf(%f%f,&priceA,&priceB);
if(priceA>priceB)
{printf(\nitemAcostlier);
printf(AcostsRs.%f.,priceA);
}
else
printf(\nitemANOTcostlier.);

UsingBooleanOperators
Example.
Acompanyconductstwoexamsforselectingcandidatesfor
interview.Togetqualified,thecandidatemustgetatleast60in
paperAandatleast50inpaperB.
int marksA,marksB;
printf(PleaseenterthemarksinpaperAandpaperB:);
scanf(%d%d,&marksA,&marksB );
if(marksA >=60&&marksB >=50)
printf(\nQualified);
else
printf(\nNotqualified);

ImproperuseofBooleanOperators
Example2.
Acompanyconductstwoexamsforselectingcandidatesfor
interview.Togetqualified,thecandidatemustgetatleast50inboth
paperAandpaperB.
int marksA,marksB;
printf(PleaseenterthemarksinpaperAandpaperB:);
scanf(%d%d,&marksA,&marksB );
if(marksA

&&marksB >=50)

printf(\nQualified);
else
printf(\nNotqualified);

ProperuseofBooleanOperators
Example2.
Acompanyconductstwoexamsforselectingcandidatesfor
interview.Togetqualified,thecandidatemustgetatleast50inboth
paperAandpaperB.
int marksA,marksB;
printf(PleaseenterthemarksinpaperAandpaperB:);
scanf(%d%d,&marksA,&marksB );
if(marksA

&&marksB >=50)

if(marksA >=50&&marksB >=50)


printf(\nQualified);
else
printf(\nNotqualified);

MULTIPLEBRANCHING
Letusnowlookatanexamplewhereweneedmultiple
branching.

Basedonmarks,astudentistogetgradeAifhegets80or
more,gradeBifhegetsbetween65and79,gradeCifhegets
between50and64,andgradeFifhegetslessthan50.
if(marks>=80)
printf(GradeA\n);
else
if(marks>=65&&marks<80)
printf(GradeB\n);
else
if(marks>=50&&marks<65)
printf(GradeC\n);
else
if(marks<50)
printf(GradeF\n);

Simplifiedcode!
if(marks>=80)
printf(GradeA\n);
else/*Marksarenowlessthan80,sononeedtocheck*/
if(marks>=65)
printf(GradeB\n);
else
if(marks>=50)
printf(GradeC\n);
else
printf(GradeF\n);

Exercise:
Computeincometaxforapersonasperfollowing
table:
income<1,00,000

:notax

incomebetween1,00,000and
3,00,000

:10%ofincome

incomebetween3,00,000and
8,00,000

:20%ofincome

incomeabove8,00,000

:30%ofincome

TheSWITCHstatementfor
multiplebranching

selectionisdonebasedonexactintegers
(notrange)

Example1forswitch
Acompanygivesbonustoitsemployeesdependingon
thecategoryofemployeesasperfollowingschedule:
Category1:20000
Category2:15000
Category3:10000
Category4:5000
Wecanwriteaswitchstatementtoimplementthis.

intcategory;
scanf(%d,&category);
switch(category)
{
case1: printf(bonus=Rs20,000);
break;
case2: printf(bonus=Rs15,000);
break;
case3: printf(bonus=Rs10,000);
break;
case4: printf(bonus=Rs5,000);
break;
default: printf(NoBonus);
}

Example2forswitch
Atestisconducted.Themaximummarksforthetestis10.
Theteachergivesoutonlyintegermarkstothestudentslike
5,8,7,10,4etc.
Wewanttoprintthegradebasedonfollowing:
marks
10:
9:
8:
7:
6:
5:
4:
3:
2:
1:
0:

grade
A
A
B
C
D
F
F
F
F
F
F

intmarks;
scanf(%d,&marks);
switch (marks)

{
case10:
case9: printf(grade
break;
case8: printf(grade
break;
case7: printf(grade
break;
case6: printf(grade
break;
default: printf(grade

=A);
=B);
=C);
=D);
=F);

Example2Bforswitch
Supposewehaveasmallchangeinthegradingprocess
marks
10:
9:
8:
7:
6:
5:
4:
3:
2:
1:
0:

grade
A
B
B
C
D
F
F
F
F
F
F

intmarks;
scanf(%d,&marks);
switch (marks)

{
case10:printf(grade
break;
case9:
case8: printf(grade
break;
case7: printf(grade
break;
case6: printf(grade
break;
default: printf(grade

=A);

=B);
=C);
=D);
=F);

REPITITION

Therealpowerofcomputersisintheirabilityto
repeatanoperationoraseriesofoperations
manytimes.
Thisrepetition,calledlooping,isoneofthebasic
structuredprogrammingconcepts.
Theloopingcanbedoneforafixednumberof
times,
for loop
ordependentonsatisfactionofsomecondition
while loop.

For Loop
Here is the general syntax:

for ( initialization ;
test condition ;
increment )
{
stmts;
}
stmt..;
stmt;
Steps:
Loopvariableisinitialized.
Conditionistested.
IfitisTRUE,statementsinloopbodyareexecuted.
loopvariableisincremented.
Stepsrepeatedtilltestconditionfails.

Example: Find the sum of all numbers between 1


and 100.
#include <stdio.h>
int main(void) {
int val ;
int sum = 0;
for (val = 1;
val < =100;
val = val+1)
{
sum = sum + val;
}
printf("1+2 +3+...+100= %d .\n",sum);
return 0;
}

Hereisavariationofthatexample.
Findthesumofallodd numbersbetween1and100.
#include <stdio.h>
int main() {
int val, sum = 0;
for (val = 1;
val < 100; val = val+2)
{
sum = sum + val;
}
printf( 1+3+5+...+99= %d\n",sum);
return 0;
}

Example:
Printthemultiplicationtablefor8,asshownbelow:
8x1=8
8x2=16
8x3=24
8x4=32
8x5=40
8x6=48
8x7=56
8x8=64
8x9=72
8x10=80

#include <stdio.h>
int main(void) {
int val , product;
for (val = 1; val < =10; val = val++)
{
product = 8 * val;
}
printf("8 * %d = %d\n, val, product);
return 0;
}

CalculatingFactorialofanumber
6!=1x2x3x4x5x6

printf(enternumber\n");
scanf(n=%d",&n);
answer=1;
for(index=1;index<=n;index++)
answer=answer*index;
printf("%d!=%d\n",n,answer);

Example: Reverse order


Print all numbers between 1 and 100 in the reverse
order.
#include <stdio.h>
int main(void) {
int val ;
for (val = 100;
val < =1;
{
printf( %d , val);
}
return 0;
}

val = val--)

Nesting of Loops
You can have another loop inside a loop. Let us see an
application first.

Sayyouwanttoprintthepattern
*******
*******
*******
*******

int rows=4;
int numstars =7;
for(row=1;row<=rows;row++)
{
//Printouttherightnumberofstars.
for(col=1;col<=numstars;col++)
printf("*");
//Gotothenewline.
printf("\n");
}

Second Pattern:
*
**
***
****
*****
******
Noticethatwhenweprintoutith line,
wealsowanttoprinti starsonthatline.
int TOTAL_ROWS=6;
for(row=1;row<=TOTAL_ROWS;row++)
{
for(col=1;col<=row;col++)
printf("*");
printf("\n");
}

Calsopermitsomittingtheinitializationandincrementstatements
fromtheforloop.

m=5;
for(
{

;m!=100;
printf(m=%d\n,m);
m=m+5;

}
.
.

You might also like