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

While

Embed Size (px)

Citation preview

Page 1: While

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

Page 2: While

Print numbers from 0 to 1000

Page 3: While

int count_down=3;

while (count_down > 0)

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

}

Page 4: While

int count_down=3;

while (count_down > 0)

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

}

What happens now?

Page 5: While

int x = 10;

while ( x > 0)

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

}

Page 6: While

int x = 10;

while (x > 0)

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

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

Page 7: While

What happens here?

int x = 1;

while (x != 12)

{ cout << x << endl;

x = x + 2;

}

Page 8: While

Print the odd numbers less than 12

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

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

Page 9: While

While loopsWhat's wrong with this?

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

Page 10: While

While-loop and for-loop

Page 11: While

int x = 1;

while (x < 12)

{

cout<<x<<endl;

x = x + 2;

}

Page 12: While

The for loopfor (initialization; expression; increment){

//statements here}

Example: flowchart

Page 13: While

int x = 1;

while (x < 12)

{

cout<<x<<endl;

x = x + 2;

}

Page 14: While

int x = 1;

while (x < 12)

{

cout<<x<<endl;

x = x + 2;

}

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

{

cout<<x<<endl;

}

Page 15: While

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

cout << i << " ";}

Page 16: While

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

cout << i << " ";}

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

cout <<i << " ";}

Page 17: While

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

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

Page 18: While

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

Page 19: While

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;

Page 20: While

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;

Page 21: While

The For Loop

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

cout << i << " ";}

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

cout <<i <<" ";}

Page 22: While

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;

}

Page 23: While

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 …