Monday, August 8, 2011

C++ Loops

Loops are basically means to do a task multiple times, without actually coding all statements over and over again.
For example, loops can be used for displaying a string many times, for counting numbers and of course for displaying menus.
Loops in C++ are mainly of three types :-

1. 'while' loop
2. 'do while' loop
3. 'for' loop

The 'while' loop :-
Let me show you a small example of a program which writes ABC three(3) times.
01#include<iostream>
02
03int main()
04{
05  int i=0;
06  while(i<3)
07  {
08    i++;
09    cout<<"ABC"<<endl;
10  }
11}The output of the above code will be :-
ABC
ABC
ABC
The 'do while' loop :-
It is very similar to the 'while' loop shown above. The only difference being, in a 'while' loop, the condition is checked beforehand, but in a 'do while' loop, the condition is checked after one execution of the loop.

Example code for the same problem using a 'do while' loop would be :-
01#include <iostream>
02int main()
03{
04  int i=0;
05  do
06  {
07    i++;
08    cout<<"ABC"<<endl;
09  }while(i<3);} // main end






The 'for' loop :-
This is probably the most useful and the most used loop in C++.

The general syntax can be defined as :-
for(<initial value>;<condition>;<increment>)

To further explain the above code, we will take an example. Suppose we had to print the numbers 1 to 5, using a 'for' loop. The code for this would be :-
1#include<iostream>
2
3int main()
4{
5  for(inti=1;i<=5;i++)
6  cout<<i<<endl;
7}



    



















 

No comments:

Post a Comment