You are on page 1of 3

Comput

ingFundament
alsCS1150 _
___
__ LabNO.9:C++
pr
ogr
ammi n

LOOPI
NG:
FORLOOP

Thefor st
atementprov
idesamechani
sm t
orepet
it
ivel
yper
for
m oper
ati
ons.Thegener
al
for
matoftheforst
atementi
s:

f i
or(ni
ti
al_
expr
essi
on;
loop_
condi
ti
on;
loop_
expr
essi
on)
{
st
atement
s
}
Thestatementsthatareenclosedbythecurl
ybracket
sareexecut
edf oranumberofti
mes
speci
fi
edbyt heparameter
soft heforst
atement
.Forexampl
e,theprogram bel
owcomputes
thesquareval
uesusingtheforstat
ement:

#incl
ude<iostr
eam>
usingnamespacest d;
i
ntmai n(
)
{
intcounter1;
for(counter1=1;counter
1<5;counter1++)
{
cout<<"Thesquarev al
ueof"<<counter1<<"
:\
t\t
"<<count
er1*
count
er1<<endl
;
cout<<"\
n"<<endl
;
}
retur
n0;
}

-Impl
ementandr
unt
hepr
ogr
am i
nyourmachi
net
ogett
hemul
ti
pli
cat
iont
abl
e
shownabov
e.

-Modif
ytheprogr
am tocomput
ethesquar
eforal
lint
egernumber
sthatar
egr
eat
er
than0andsmall
erthan10.

-Modi
fytheprogr
am t
ocomputethesquar
efort
heev
eni
ntegernumber
sthatar
e
gr
eat
erthan0andsmal
lert
han10.

-Modi
fytheprogr
am t
ocomputethesquar
efort
heoddi
ntegernumber
sthatar
e
gr
eat
erthan0andsmal
lert
han10.

LOOPI
NG :
WHI
LELOOP

Thewhi
l
est
atementi
susedt
oexecut
eabl
ockofst
atement
swhi
l
esomecondi
ti
oni
str
ue.I
n
Page1of1
Comput
ingFundament
alsCS1150 _
___
__ LabNO.9:C++
pr
ogr
ammi n
t
hisexer
cise,
youwi
l
luset
hewhi
l
est
atementt
orepet
it
ivel
yreadi
nput
sfr
om t
het
ermi
nal
.

TheCpr ogram bel


owdefi
nest woi nt
egervar
iablesnumber
1andnumber2.Thewhil
e
statementisusedtocont
inuouslyreadthevaluesofnumber1andnumber
2from t
he
terminal
,andthencomputetheirsum.

#i
ncl
ude<i
ost
ream>

usi
ngnamespacest
d;

i
ntmai
n()
{

i
ntnumber 1=0; /
/Thef i
rstnumber
i
ntnumber 2=0;/ /Thesecondnumber
i
ntcounter=0;
whi
le(counter<5){
cout<<"
Pleaseenterthev al
uesofnumber
1andnumber2\
n"<<endl
;
ci
n>>number 1>>number 2;
cout<<"
\nThesum i s:"<<number1+number
2<<endl
;
counter+=1;
}
cout
<<"
goodby
e"<<endl
;

r
etur
n0;
}

Compi
l
eandr
unt
heabov
epr
ogr
am.

1.Howmanytimesdoesthepr
ogr
am abov
ereadt
hev
aluesofnumber
1andnumber
2
andt
hencomput
ethei
rsum?

_
___
___
___
___
___
___
___
___
___
___
___
___
___
_

2.Modi
fyt
heabov
epr
ogr
am t
orunt
hewhi
l
eloopf
or10i
nter
act
ions.

3.Modi
fyt
heabov
epr
ogr
am t
ocomput
esubt
ract
ion,
mul
ti
pli
cat
ionanddi
vi
sion.

4.Modi
fytheabovepr
ogr
am t
orunt
hewhi
l
eloopf
ori
nfi
nit
enumberofi
ter
ati
ons
(
endl
essloop)
.

3-Usi
ngf
orl
ooporwhi
l
eloop:

Wr
it
eaC++pr
ogr
am t
ocomput
eandpr
intt
hesum ofal
li
nteger
sbet
ween5and20,
andt
hen
Page2of2
Comput
ingFundament
alsCS1150 _
___
__ LabNO.9:C++
pr
ogr
ammi n
comput
etheav
erageoft
hesenumber
s.

Page3of3

You might also like