Compare the while loops with for loops - C++ Statement

C++ examples for Statement:while

Introduction

while loop syntax

<initialize-loop-variables>; 
while  (<test  loop variables>)   { 
   <perform  main  steps  of code> 
   <update  loop  variables> 
} 

for loop takes the general form:

for  (<initialize   loop  variables>; <test  loop variables>; <update  loop  variables>)   { 
   <perform  main  steps  of code> 
} 

For example, our code to launch a rocket becomes:

Demo Code

#include <iostream> 
using namespace std ; 

int main(){/*from   www. j  a  v  a  2s .co  m*/
    for (int i = 10; i > 0; i--) { 
       cout << i; 
       cout << "\n"; 
    } 
    cout << " Blast off !\n"; 
}

Result

Here is the code to count up from 0 to 9 (inclusive). You should commit this code to memory:

Demo Code

#include <iostream> 
using namespace std ; 

int main(){/* w  w  w  .  j  a  v a  2  s. co  m*/

    for (int i = 0; i <10; i ++) { 
       cout << i; 
       cout << "\n"; 
    } 
}

Result

Here is the code to count up from 0 to 90 (inclusive) in steps of 10.

Demo Code

#include <iostream> 
using namespace std ; 

int main(){// w  ww.  j  av a  2 s  .  c o m

    for (int i = 0; i < 100; i += 10) { 
       cout << i; 
       cout << "\n"; 
    } 
}

Result


Related Tutorials