You are on page 1of 32

Programming

DennisRitchie

By:
B.SenthilKumar
Asst.Prof.,CSE
SSNCollegeofEngineering

B.E.FirstYearIntroductiontoC

1.for
2.while
3.dowhile
4.goto
5.continue

Overview
Loopstatementsanintroduction
Theforloop
Nestedforloops
Thewhileloop
Thedowhileloop
Thegotostatement
Thecontinuestatement
Checkyourprogress

LoopstatementsAnIntroduction

Aloopisdefinedasablockofstatementswhicharerepeatedly
executedforcertainnumberoftimes

Loopvariable:Itisavariableusedintheloop

Initialization:Itisthefirststepinwhichstartingandfinalvalueis
assignedtotheloopvariable

Incrimination/Decrimination:Itisthenumericalvalueaddedtoor
subtractedfromthevariableineachroundoftheloop

Loopcontrolstatements

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

Theforloop

Theforloopcomprisesofthreeactions

Theseactionsareplacedintheforloopstatementitself

Thethreeactionsare:initializingaloopcounter,testthecounter,and
updatethevalueofcounter

Theactionsareseparatedbysemicolons(;)

for (initialize counter; test condition; re-evaluation parameter)


{
statement 1;
statement 2;
....
}

Theforloop

Initialization
setsalooptoaninitialvalue
thisstatementisexecutedonlyonce

Testcondition
arelationalexpressionthatdetermineswhentoexitfromtheloop/the
numberofiterationsdesired
theloopcontinuestoexecuteaslongasconditionissatisfied

Reevaluationparameter
decideshowtomakechangesintheloop(increase/decrease)
executedeverytimebeforetheloopconditionistested

Theforloop

Formatsofforloop
Syntax
o/p
Remarks
-------------------------------------------------------------1.for(;;)
infiniteloop
Noarguments
2.for(a=0;a<=20;)

infiniteloop

aisneitherincreasednordecreased

3.for(a=0;a<=10;a++)displaysvalue
printf(%d,a);
from0to10

valueofaisdisplayedfrom0to10.
scopeonestatementafterforloop

4.for(a=10;a>=0;a--)displaysvalue

aisdecreasedfrom10to0

from0to10

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:
Number:
Number:
Number:
Number:

1
2
3
4
5

it's
it's
it's
it's
it's

Square:
Square:
Square:
Square:
Square:

1
4
9
16
25

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
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

Todisplaynumbersupto10usinginfiniteforloop
#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

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

Checkyourprogress

Writeaprogramtodisplaynumbersinascendinganddescending
ordersusingfor..conditionexpressiononly
Writeaprogramtofindsumofthefollowingseries:
1+2+3+...+n
1+2+3+...+n

Nestedforloop

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

whileloop

Thisisapretestloopdeclarationconstruct

Theconditionistestedbeforetheexecutionofbodyoftheloop

Theloopwillbeskipped,iftheconditionfails

Theprocessofexecutionofbodywillcontinuetillthetestcondition
becomestrue
Awhileloopdoesnotnecessarilyiterateaspecifiednumberoftimes
While (test condition)
{
body of the loop;
}

whileloop

Example1whileloop

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

Example2whileloop

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

Example3whileloop

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);
}

Example3whileloop
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

Writeaprogramtoprintthesumofdigitsofanumber

dowhileloop

TheformatofdowhileloopinCisasfollows:
do
{
statement/s;
}
while (test condition);

Thedowhileloopwillexecuteatleastone
timeeveniftheconditionisfalse

Inthewhileloop,thebodygetsexecuted
onlyaftertheconditionistestedtotrue

Example1:dowhileloop

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:dowhileloop

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

gotoStatement

Thegotostatementisanothertypeofcontrolstatement

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

gotoStatement

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);
}

continueStatement

Thecontinuestatementisusedinwhile,for,ordowhileloopsto
terminateaninteration
...
if(cond)
continue;
...

Thecontinueisexactlyoppositetobreakstatement

Whenitoccursintheloop,itskipstheremainingstatementsinthebody
oftheloop,andcontinueswiththenextiterationoftheloop

continueStatement

Afteracontinuestatementis
executedinaforloop,itsincrement/
decrementandconditionalexpressions
areevaluated

Afteracontinuestatementis
executedinawhileordowhileloop,
itsconditionalexpressionisevaluated

for(init;cond;incr)
{

if()
continue;

}
while(condition)
{

if()
continue;

}
do{

if()
continue;

}
while(condition)

continueStatement

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
3 is an
5 is an
7 is an
9 is an

odd
odd
odd
odd
odd

number.
number.
number.
number.
number.

References

ComputerProgramming,AshokN.Kamthane
FundamentalsofComputingandProgramminginC
PradipDey,ManasGhosh

Whatisthedifferencebetweenbreakandcontinue?

Isitpossibletocreateaforloopthatis
neverexecuted?

Writeaprogramtoprintthequotientofan
integernumberwithoutusing'
/'

Writeaprogramtoprintthefollowing:
1
22
333

4444

55555...uptonthline

You might also like