Lecture 6
Lecture 6
L E C T U R E 6
M A E M O O N A K A Y A N I
Repetition Structure
• Conditional loop
• Enter a number: 7
(for loop) --Class Exercise-3
-Write a program that asks the user to enter two numbers (multiple of 10) : speed1, and
speed2 representing speeds in KPH (KilometersperHour). Then the program should convert
and show table of speeds in MPH(MilesperHour) for all the speed values between speed1
and speed2.
• Speed1 and speed2 variables should be multiple of 10. Each table entry (in KPH) should
be updated by 5 in each iteration.
for loop –Multiple Expressions
(1) for loop –Multiple Expressions
(1) for loop -Variable Visibility
int main()
{
for(int j=0; j<10; j++)
k = j*j;
return 0;
}
(1) for loop –optional expressions
for loop
int i= 10;
--i;
Output?
While Loop
While Loop
• In this case a different kind of loop may be used: the while loop
While loop syntax
Example: tracing a while loop
Example: tracing a while loop
Example: tracing a while loop
Example: tracing a while loop
Example: tracing a while loop
Example: tracing a while loop
Example: tracing a while loop
Example: tracing a while loop
Example: tracing a while loop
While loop
Example
While loop - Example
While loop - Example
do Loop
do Loop
•For that, we use do loop, that guarantees at least on execution of the loop
body
do while loop - Syntax
do while loop - Syntax
int main( )
{
cin>>howmuch; counter = 0;
do {
counter++;
cout<<counter<<endl;
return 0;
}
do Loop – Example 2
int main( )
do {
cin>>num1;
cin>>num2;
cin.get(ch);
} while(ch==‘y’);
break Statement
• break statement
• Common uses:
• continue statement
•In nested loops any loop (for, while, or do loop) can be placed
inside another loop which can be a for, while, or a do loop
(Nested Loops)- Example
(Nested Loops) - Example
(Nested Loops) –Exercise-1
-Write a program to print triangle of stars.
*
**
***
****
*****
******
*******
********
*********
(Nested Loops) –Exercise-2
-Write a program to print triangle of stars.
*********
********
*******
******
*****
****
***
**
*
(Nested Loops) –Exercise-3
-Write a program to print Rectangle based on two triangles (One using + and other using *
symbol).
+********
++*******
+++******
++++*****
+++++****
++++++***
+++++++**
++++++++*
+++++++++
(Nested Loops) –Exercise-4
-Write a program for a company to calculate total sales for 3 regions. Each region’s sales is
entered by user which is then summed in total regional sales. The program keep accepting
regional sales until it is not 0. The program prints the final regional sum for three regions
and exits.
Example Output: