Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Programming
Control Structures
Muhammad Adnan Talib
Lec#06
29th March,2012
while loop
for loop
do while loop
while Repetition Structure
Repetition structure
Action repeated while some condition remains true
Pseudocode
while there are more items on my shopping list
Purchase next item and cross it off my list
while loop repeats until condition becomes false
C++ Language Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
Flow Chart of while loop
Start
Initialize
Test False
Stop
True
Body of Loop
Increment
/*
* C
* Using a while loop to ask the user to input a number
* between 1 and 10 (inclusive).
*
* Variables:
* value : variable to store the input
*/
cout<<"Please Enter a Number between 1 and 10 (1-10): ";
cin>>value;
while ( value < 1 || value > 10)
{
cout<<"Incorrect input, please try again.\n";
cout<<"Enter a Number between 1 and 10 (1-10): ";
cin>>value;
}
Fictorial…
int n ;
int j =1; int i=1; / ∗ initialization ∗ /
while (i <= n) / ∗ condition ∗ /
{
j ∗= i;
i ++; / ∗ increment ∗ /
}
So how to print
******
*****
****
***
**
*
by using while loop?
num=6
>>> while num>0:
print ‘*’ * num
num = num-1
//#include <stdio.h>
#include <conio.h>
#include <iostream.h>
int main()
{
int num = 6;
int i = num;
while (num > 0)
{
while(i!=0)
{
cout<<"*";
i--;
}
cout<<endl;
num--;
i = num;
}
getche();
return 0;
}
Then, how to print
*
**
***
****
*****
******
by using while loop?
Solution…
//#include <stdio.h>
#include <conio.h>
#include <iostream.h>
int main()
{
int num = 1;
int i = 1;
while (num != 7)
{
while(i<=num)
{
cout<<"*";
i++;
}
cout<<endl;
num++;
i = 1;
}
getche();
return 0;
}
Solution…for loop
//#include <stdio.h>
#include <conio.h>
#include <iostream.h>
int main()
{
int num = 1;
int i = 1;
for (int num = 1; num != 7; num++)
{
for(int i = 1;i<=num; i++)
{
cout<<"*";
}
cout<<endl;
}
getche();
return 0;
}
for Loop
Start
Initialize
Test False
Stop
True
Body of Loop
Increment
General form of for loop
Example
Fictorial…
Initialize
Body of Loop
Increment
True
Test
False
Stop
Infinite Loop
This loop will never
terminate
Since you are not
updating value of i
therefore condition will
never become false
Infinite Loops
Sometimes we intentionally use infinite
loops
In this case we terminate by other means
e.g. by exiting the program
Nested Loops
The break Statement
We often come across situations where we
want to jump out of a loop instantly,
without waiting to get back to conditional
test