Structure in C++
Structure in C++
in C++
(PRACTICAL#05)
Objective: To become familiar with Control Structures
(Iteration statements/ Loops)
The execution of the program is linear.
Control Structures are used to alter/change the flow of program.
Controls which statement(s) should be executed next.
Control Structures
Selection / Iterative/
Conditional/ Branching Loops (Jump Statements)
Loops Definition : cause a section of your code
to repeated a certain number of times,
The repetition continues while a condition
remains true, when the condition becomes
false the loop terminates and the control
transferred to the statements following the
loop.
for Loop
while Loop
do-while Loop
void main() {
Int n;
for(n=1; n<=10; n++)
cout<<“Loop Cyc le: “<< + n;
}
Iteration Statements
loop variations
for(int
z = 100; z>=1; z--);
//loops from 100 to 1 with step of -1.
While :A while statement repeats an action again and again as long as a controlling
Boolean expression is true.
When condition becomes false, control passes to the next line of code immediately
following the loop.
Used when we don’t know the exact number of repetitions to be performed in our program.
It uses “while” (without quotes) as a c++ keyword for looping.
Syntax
while(test expression)
{
// body of loop
}
Iteration Statements
While : Syntax
When condition becomes false, control passes to the next line of code immediately
following the loop.
Used when we don’t know the exact number of repetitions to be performed in our program.
It uses “while” (without quotes) as a c++ keyword for looping.
Syntax
while(test expression)
{
// body of loop
}
While counter-controlled repetition
int main(){
int count =0;
while(count < 50 ){
Cout<<count<<endl;
count++;
}
Cout<<“End of loop”;
}
While Sentinel-controlled repetition
int main(){
int num1, num2; char ch =‘A’;
while(ch != ‘n’ ) {
Cout<Cout<<“Enter first number:”;
cin>>num1
<“Enter second number:”;
cin>>num2;
Cout<<“Sum=”<<num1+num2;
Cout<<“Do you want to continue(y/n)”;
Cin>>ch;
}
Cout<<“End of loop”;
}
Nested while loop
Allow the flow of execution to jump to a different part of the program.
Do . . . While
the body of a do-while loop is always executed at least once, no matter
what the initial state of test expression.
Syntax
do {
First_Statement
Second_Statement
...
Last_Statement
}
while(Boolean_Expression);
do-while loop
Allow the flow of execution to jump to a different part of the program.
void main(){
int count =0;
do {
cout<<count;
count++;
}
while(count<=10);
Cout<<“End of loop”;
}
Nested do-while loop
Allow the flow of execution to jump to a different part of the program.
int num;
cout<<"Enter a number: "; cin>>num;
if (num % 2==0){ goto print; }
else {
cout<<"Odd Number";
}
print: cout <<"Even Number"; return 0; }
int num;
cout<<"Enter a number: "; cin>>num;
if (num % 2==0){ goto print; }
else {
cout<<"Odd Number";
}
print:
cout <<"Even Number"; return 0; }