Explain Loops – While loop, Do-while loop, for loop

          
Interview questions

Explain Loops – While loop, Do-while loop, for loop.


<<Previous  Next>>

C++  - Explain Loops – While loop, Do-while loop, for loop - Dec 29, 2008 at 18:10 PM by Anuja Changede

Explain Loops – While loop, Do-while loop, for loop.  

Loops are used to carry out certain instruction(s) in continuation for a fixed no of times.

Syntax of while loop:

//initialization stmt(s)

while (condition)
{
           //stmt1;
           //stmt2;
           ….
           ….
}

e.g.
x = 0; // initialization stmt
while (x < 10)
{
          cout << x<<”\n”;
          x ++;
}

This prints nos 0 to 9 on the screen.

Do- while loop:

This is similar to while loop; the only difference is unlike while loop, in do-while loop condition is checked after the loop statements are executed. This means the statements in the do while loop are executed at least once; even if the condition fails for the first time itself.

//initialization stmt(s)

do
{
        Stmt1;
        Stmt2;
} while (condition)

e.g.
x = 0;         // initialization stmt
do
{
        cout << x<<”\n”;
        x ++;
}while (x < 10);

This prints numbers 0 through 9 on the screen.

The for loop:

It does exactly the same thing as while loop; only difference is the initialization, the condition stmt is written on the same line.

for loop:

This is used when we want to execute certain statements for a fixed no of times. This is achieved by initializing a loop counter to a value and increasing or decreasing the value for certain no of times until a condition is satisfied. The loop statements are executed once for every iteration of the for loop.

for (initialize loop counter; condition checking; increasing/decreasing loop counter)
{
            //stmt1;
            //stmt2;
}

for (x = 0; x < 10; x++)
{
            cout <<x <<”\n”;
}

This code snippet will print nos 0 to 9.

Also read

What is private inheritance? Provide an example using c++.

When a class is being derived from another class, we can make use of access specifiers. This is essentially useful to control the access the derived class members have to the base class. When inheritance is private..................

Explain why and when do we use protected instead of private.

Private data members cannot be accessed outside the class. When a class inherits a base class, all the data members except the private get inherited into it. So if we want data members to be accessible...................

<<Previous  Next>> 

Write your comment - Share Knowledge and Experience


 

 
Latest placement tests
Latest links
 
 
Home | Want a Job? Submit Key Skills | Employer login | My key skills | About us | Sitemap | Contact us