While

Preview:

Citation preview

Loops of various sorts are used to repeat a set of statements some number of times.

Print numbers from 0 to 1000

int count_down=3;

while (count_down > 0)

{ cout << "Hello "; count_down -= 1;

}

int count_down=3;

while (count_down > 0)

{ cout << "Hello "; //count_down -= 1;

}

What happens now?

int x = 10;

while ( x > 0)

{ cout << x << endl; x = x – 3;

}

int x = 10;

while (x > 0)

{ cout << x << endl; x = x – 3;

}Output using the comparison x < 0 instead of x > 0?

What happens here?

int x = 1;

while (x != 12)

{ cout << x << endl;

x = x + 2;

}

Print the odd numbers less than 12

int x = 1;while (x != 12){ cout << x << endl;

x = x + 2;}How to fix it?

While loopsWhat's wrong with this?

int x = 10; while ( x > 0 ); { cout << x << endl; x--; }

While-loop and for-loop

int x = 1;

while (x < 12)

{

cout<<x<<endl;

x = x + 2;

}

The for loopfor (initialization; expression; increment){

//statements here}

Example: flowchart

int x = 1;

while (x < 12)

{

cout<<x<<endl;

x = x + 2;

}

int x = 1;

while (x < 12)

{

cout<<x<<endl;

x = x + 2;

}

for (x=1; x<12; x=x+2)

{

cout<<x<<endl;

}

int i ;for( i=0; i<10; ++i ){

cout << i << " ";}

int i;for( i=0; i<10; ++i ){

cout << i << " ";}

int i;for (i=0; i<10; i++){

cout <<i << " ";}

int x, n=100;for (x=0; x<n; x++){

x=x+1;}cout<<"x after end of loop is "<<x<<endl;

int x, n=100;for (x=0; x<n; x++){

x=x+1;}cout<<"x after end of loop is "<<x<<endl;

x is the smallest even number >= n

SELF TEST

int x, n=100;

for (x=0; x<n; x++){

cout<<x<<endl;

x=x+1;

}cout<<"x after end of loop is "<<x<<endl;

SELF TEST

int x, n=100;

for (x=0; x<n; x++){

x=x+1;

cout<<x<<endl;

}cout<<"x after end of loop is "<<x<<endl;

The For Loop

int i ;for( i=23; i>=30; ++i ){

cout << i << " ";}

for (i=13; i>=10; --i){

cout <<i <<" ";}

The For Loop

What is wrong here?int i, j, k ;for( i=0; i<10; i-- ){

cout<<i;}

for (i=0; i<10; ){

j=i+30;k=j+30;

}

Fibonacci numbers

F1=1

F2=2

Fn=Fn-1 + Fn-2

1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 …

Recommended