Anda di halaman 1dari 32

By:

B.SenthilKumar
Asst.Prof.,CSE
SSNCollegeofEngineering
B.E.FirstYearIntroductiontoC
Programming
DennisRitchie
1.for
2.while
3.dowhile
4.goto
5.continue
Overview
Overview
Loopstatementsanintroduction
Theforloop
Nestedforloops
Thewhileloop
Thedowhileloop
Thegotostatement
Thecontinuestatement
Checkyourprogress
LoopstatementsAnIntroduction
LoopstatementsAnIntroduction

Aloopisdefinedasablockofstatementswhicharerepeatedly
executedforcertainnumberoftimes

Loopvariable:Itisavariableusedintheloop

Initialization:Itisthefirststepinwhichstartingandfinalvalueis
assignedtotheloopvariable

Incrimination/Decrimination:Itisthenumericalvalueaddedtoor
subtractedfromthevariableineachroundoftheloop
Loopcontrolstatements
Loopcontrolstatements

Chasthreekindsofloopcontrolstatements
1. for loop statement
2. while loop statement
3. do-while loop statement
The
The
for
for
loop
loop

Theforloopcomprisesofthreeactions

Theseactionsareplacedintheforloopstatementitself

Thethreeactionsare:initializingaloopcounter,testthecounter,and
updatethevalueofcounter

Theactionsareseparatedbysemicolons(;)
for (initialize counter; test condition; re-evaluation parameter)
{
statement 1;
statement 2;
....
}
The
The
for
for
loop
loop

Initialization
setsalooptoaninitialvalue
thisstatementisexecutedonlyonce

Testcondition
arelationalexpressionthatdetermineswhentoexitfromtheloop/the
numberofiterationsdesired
theloopcontinuestoexecuteaslongasconditionissatisfied

Reevaluationparameter
decideshowtomakechangesintheloop(increase/decrease)
executedeverytimebeforetheloopconditionistested
The
The
for
for
loop
loop
Formatsof
Formatsof
for
for
loop
loop
Syntax o/p Remarks
--------------------------------------------------------------
1.for(;;) infiniteloop Noarguments
2.for(a=0;a<=20;) infiniteloop aisneitherincreasednordecreased
3.for(a=0;a<=10;a++)displaysvalue valueofaisdisplayedfrom0to10.
printf(%d,a); from0to10 scopeonestatementafterforloop
4.for(a=10;a>=0;a--)displaysvalue aisdecreasedfrom10to0
from0to10
Example1usingfor
Example1usingfor
Print first 5 numbers with their squares
#include<stdio.h>
main()
{
int i;
for(i=1;i<=5;i++)
printf(\n Number: %d it's Square: %d,i, i*i);
}
Output:
Number: 1 it's Square: 1
Number: 2 it's Square: 4
Number: 3 it's Square: 9
Number: 4 it's Square: 16
Number: 5 it's Square: 25
Example2usingfor
Example2usingfor
To display numbers from 1 to 15.
#include<stdio.h>
main()
{
int i;
for(i=1;i<=15;)
{
printf(%d ,i);
i++;
}
}
Note:
increment is done inside the body of for..loop statement
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Example3usingfor
Example3usingfor
To display even numbers from 0 to 14.
#include<stdio.h>
main()
{
int i=0;
for(;i<=15;)
{
printf(%d,i);
i+=2;
}
}
Note:
for contains two semicolons(;), eventhough no parameters
are provided
Output:
0 2 4 6 8 10 12 14
Example4usingfor
Example4usingfor
#include<stdio.h>
main()
{
int i=0;
for(;;)
{
printf(%d,i++);
if(i==11)
break;
}
}
Note:
To exit from the infinite inner loop, break statement
is used

Todisplaynumbersupto10usinginfiniteforloop
Output:
0 1 2 3 4 5 6 7 8 9 10
Checkyourprogress
Checkyourprogress

Writeaprogramtodisplaynumbersinascendinganddescending
ordersusingfor..conditionexpressiononly

Writeaprogramtofindsumofthefollowingseries:
1+2+3+...+n
1+2+3+...+n

Perform multiplication of two integers by using repetitive addition


Nested
Nested
for
for
loop
loop

Oneormoreforstatementsareincludedinthebodyoftheloop
#include<stdio.h>
main()
{
int i,j,x,k=1;
printf(Enter the value of x :);
scanf(%d,&x);
for(i=1;i<=x;++i)
{
for(j=1;j<=i;++j)
printf(%d \t,k++);
printf(\n);
}
}
Enter the value of x :4
1
2 3
4 5 6
7 8 9 10
while
while
loop
loop

Thisisapretestloopdeclarationconstruct

Theconditionistestedbeforetheexecutionofbodyoftheloop

Theloopwillbeskipped,iftheconditionfails

Theprocessofexecutionofbodywillcontinuetillthetestcondition
becomestrue

Awhileloopdoesnotnecessarilyiterateaspecifiednumberoftimes
While (test condition)
{
body of the loop;
}
while
while
loop
loop
Example1
Example1
while
while
loop
loop

Toadd5consecutivenumbersstartingfrom1
#include<stdio.h>
main()
{
int a=1,sum=0;
while(a<=5)
{
printf(%d,a);
sum+=a;
a++;
}
printf(\n Sum of 5 numbers :%d,sum);
}
Output:
12345
Sum of 5 numbers :15
Example2
Example2
while
while
loop
loop

Tocalculatefactorialofagivennumber
#include<stdio.h>
main()
{
int a,fact=1;
printf(\n Enter the number :);
scanf(%d,&a);
while(a>=1)
{
printf(%d* ,a);
fact=fact*a
a--;
}
printf= %d,fact);
printf(\nFactorial of given number is %d,fact);
}
Output:
Enter the number :5
5* 4* 3* 2* 1* = 120
Factorial of given number is 120
Example3
Example3
while
while
loop
loop

Toentersomenumbersandthenfindtheiraverage
#include<stdio.h>
main()
{
int n=0,a,sum=0;
float avg;
char ans='y';
while(ans=='y' || ans=='Y')
{
printf(\n Enter the number :);
scanf(%d,&a);
sum += a;
n++;
printf(\n Will you add more(Y/N)? );
scanf(%c,&ans);
}
avg=(float)sum/n;
printf(\n Average is %f,avg);
}
Example3
Example3
while
while
loop
loop
Output:
Enter the number :5
Will you add more(Y/N)? y
Enter the number :10
Will you add more(Y/N)? Y
Enter the number :6
Will you add more(Y/N)? n
Average is 7
Checkyourprogress
Checkyourprogress

Writeaprogramtoprintthesumofdigitsofanumber
dowhile
dowhile
loop
loop

TheformatofdowhileloopinCisasfollows:

Thedowhileloopwillexecuteatleastone
timeeveniftheconditionisfalse

Inthewhileloop,thebodygetsexecuted
onlyaftertheconditionistestedtotrue
do
{
statement/s;
}
while (test condition);
Example1:
Example1:
dowhile
dowhile
loop
loop

Usedowhileanddisplayamessageusingfalsecondition
#include<stdio.h>
main()
{
int i=5;
do
{
printf(\n This is a do-while loop.);
i++;
}
while(i<=3); < theconditionisfalse
}
Output:
This is a do-while loop.
Example2:
Example2:
dowhile
dowhile
loop
loop

Evaluateaseries1+2+3+...n
#include<stdio.h>
main()
{
int i,a=1,s=0;
printf(\n Enter a number: );
scanf(%d,&i);
do
{
printf(%d + ,a);
s=s+a;
a++;
}
while(a<=i);
printf( =%d,s);
}
Output:
Enter a number: 5
1 + 2 + 3 + 4 + 5 + =15
Comparingloopconstructs
Comparingloopconstructs
goto
goto
Statement
Statement

Thegotostatementisanothertypeofcontrolstatement

Thecontrolisunconditionallytransferredtothestatementassociated
withthelabelspecifiedinthegoto
...
goto label_name;
...
...
label_name:
statement1;
...
goto
goto
Statement
Statement

Tofindthefactorialofagivennumber
#include<stdio.h>
main()
{
int n,c;
long int f=1;
printf(\n Enter the number: );
scanf(%d,&n);
if(n<0)
goto end;
for(c=1;c<=n;c++)
f*=c;
printf(\n Factorial is %ld,f);
end:
printf(\n Invalid number);
}
continue
continue
Statement
Statement

Thecontinuestatementisusedinwhile,for,ordowhileloopsto
terminateaninteration

Thecontinueisexactlyoppositetobreakstatement

Whenitoccursintheloop,itskipstheremainingstatementsinthebody
oftheloop,andcontinueswiththenextiterationoftheloop
...
if(cond)
continue;
...
continue
continue
Statement
Statement

Afteracontinuestatementis
executedinaforloop,itsincrement/
decrementandconditionalexpressions
areevaluated

Afteracontinuestatementis
executedinawhileordowhileloop,
itsconditionalexpressionisevaluated
while(condition)
{

if()
continue;

}
do{

if()
continue;

}
while(condition)
for(init;cond;incr)
{

if()
continue;

}
continue
continue
Statement
Statement

Toprinttheoddnumbersfrom1to10
#include <stdio.h>
#include <stdlib.h>
int main () {
unsigned x;
x = 0;
while (x < 10)
{
++x;
if (x % 2 == 0)
continue;
printf ("%i is an odd number.\n", x);
}
return 0;
}
Output:
1 is an odd number.
3 is an odd number.
5 is an odd number.
7 is an odd number.
9 is an odd number.
References
References

ComputerProgramming,AshokN.Kamthane

FundamentalsofComputingandProgramminginC
PradipDey,ManasGhosh

Whatisthedifferencebetweenbreakandcontinue?

Isitpossibletocreateaforloopthatis
neverexecuted?

Writeaprogramtoprintthequotientofan
integernumberwithoutusing'/'

Writeaprogramtoprintthefollowing:
1
22
333
4444
55555...uptonthline

Anda mungkin juga menyukai