CyberArmy Academy | CyberArmy Services & Support | Open Source Institute | CyberArmy Intelligence & Security | CyberArmy Projects

[Library Index]

[View category: C++] [Discuss Article]

Practical C++ Part 5 : Loops

Article is yet to be rated
Author:      Rae
Submitted:      28-Apr-2007 19:41:03
Imported From:      The CyberArmy University (original author: rae)


Practical C++ Part 5 : 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.
 #include<iostream.h></iostream.h> 

void main() {   int i=0;  while(i&lt;3)  {  i++;  cout<<"ABC"<<endl ;="]</endl> } }
The output of the above code will be :-

ABC

ABC

ABC

A point to notice here is that, for making it more easy to understand, we could also write,
 int i=1; while(i<=3)
This would make our code more easy for a newbie, but in actuality it doesn't make a difference either way.

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 :-
 void main()

{   int i=0;  do  {  i++;  cout<<"ABC"<<endl ;="]</endl> }while(i<3); }
The output would once again be same as in the above example.

The 'for' loop :- This is probably the most useful and the most used loop in C/C++. The syntax is slightly more complicated than that of 'while' or the 'do while' loop.

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 :-</increment></condition></initial>
 #include<iostream.h></iostream.h> 

void main() {   for(int i=1;i<=5;i++) cout<<endl ;="]</endl> }
The output for this code would be :-

1

2

3

4

5

Here variable 'i' is given an initial value of 1. The condition applied is till 'i' is less than or equal to 5. And for each iteration, the value of 'i' is also incremented by 1.

Notice here that if we wanted to print,

5

4

3

2

1


We would change our 'for' loop to :-
for(int i=5;i>=1;i--)
References :-

- Computer Science C++ by Sumita Arora

- Object Oriented Programming using C++ By E Balagurusamy

- Using C++ by Rob McGregor

Written by Rae

This article was originally published by CyberArmy.net in the CyberArmy Library.

You must be logged in to vote on an article

About Us | Privacy Policy | Mission Statement | Help