Skip to main content

Going in loops?

The next set of control statements is loop statements. C family has 3 loop statements viz for, while and do .. while

for statement 

for is the most compact loop statement. Often it is used when the loop is to be repeated fixed number of times.

Syntax
for(expr1;expr2;expr3)
   statement;

expr1 is initialization. expr2 is condition and expr3 is increment. 

To start with expr1 is executed and next expr2 is evaluated. If expr2 is true the loop is repeated. If it is false, loop is terminated.

After each iteration, expr3 is executed - which increments or decrements the control variable.   After this, again expr2 is evaluated and loop is repeated as long expr2 is true. 

Now let us understand this with an example 

int a;
cin>>a;
for(int i=1;i<5;i++)
   cout<<a*i<<" ";

The output of the program is
 8 16 24 32
 if input is 8

Here i is defined and initialized with 1. Then is compared with 5. Since condition i<5 is true, the cout statement is executed - which print a*i = 8*1 = 8. Next i++ increments i to 2. i is compared with 5 and as condition i<5 is true, the cout is executed.

This loop is repeated till i becomes 5.

One nice thing about C++ for loop is, the control variable i can be defined within the statement. The life and scope of i is within the loop.

Let us look at another example - this time reading an array
   An array is a group of elements having a common name and identified by an integer index.


#include <iostream>
using namespace std;
int main()
{
  int arr[10];
  for(int i=0;i<10;i++)
  {
     int b = i*i*i;
     arr[i]=b;
   }
   int sum=0;
   for(int i=0;i<10;i++)
     sum+=arr[i];
   cout<<"Sum of array elements is "<<sum;
}
Note the following things
  • arr is an array of integers.
  • In the for loop array elements are initialized with i*i*i. That is arr[0] is 0, arr[1] is 1, arr[2] is 8, arr[3] is 3*3*3 - 27 and so on.
  • In the second for loop, the elements of the array are added together into sum.
  • We also notice that, in the first loop, instead of one statement in the body of the loop, we use a block - which is enclosed in braces. We can use a block of statements with the help of braces in all three types of loops or if -else statement. 

  inifinite loop anyone?

Do you want an infinite loop? Just write

for(;;)
   cout<<"hello";

 OK, now we know that the three expression in the for loop are optional. 

Now why don't you write a simple program using for loop? 

Write a program to read 10 elements of an integer array and print the sum of only positive integers.

Write a program to find the second largest element of an array.

while loop  

A while loop is quite straight forward. It repeatedly executes a statement (or a block of statements) while a condition is true.

Syntax 
while(expression)
   statement;

To start with expression is evaluated. Expression can be relational or even arithmetic. Remember that C and C++ use 0 as false and 1 as true. If the expression is true, statement is executed. Then again expression is evaluated. This is repeated as long as expression is true. Once it is false, loop is terminated. 

Let us see an example. 


int arr[10];
int i=0;
while(i<10)
  {  
    arr[i]=i*i*i;
    i++;
  }
int sum=0;
for(int i=0;i<10;i++)
    sum+=arr[i];
cout<<"Sum of array elements is "<<sum;

We have re-written the same example, using while for the first loop. Now do you agree that for loop is more suited for this example? :)

break or continue ?

There are situations where we want to terminate the loop abruptly. Some times we may want to skip the current iteration. For these, we can  use break and continue.

break
break will terminate the loop. By loop we mean any of the three - for, while or do -while. 

#include <iostream>
using namespace std;
int main()
{ 
int i;
while(true)
  {  
    int m;
    cout<<"Enter a number (-1 to terminate)";
    cin>>m;
    if(m==-1)
      break;
    if(m%2) 
       cout<<"Even"<<endl;
    else
       cout<<"Odd"<<endl; 
    i++;
  }  
}

Here we are reading numbers from console infinitely - we use while(true) . When -1 is entered, we break the loop.

Output of this program will be
Enter a number (-1 to terminate)22 
Even
Enter a number (-1 to terminate)7
Odd
Enter a number (-1 to terminate)678
Even
Enter a number (-1 to terminate)99
Odd
Enter a number (-1 to terminate)-1
 
 

do .. while loop

A do while loop is similar to a while loop, except for the fact that condition is tested at the end of loop.  

A for and while loops are entry controlled, but a do ..while loop is exit controlled. So this loop executes its body at least once.

Syntax
do
   statement;
while(expression);

Here the statement is executed. Then the expression is tested. If the expression is true, the loop is repeated.

Let us write an example.  

#include <iostream>
using namespace std;
int main()
{ 
do
  {  
    int m;
    cout<<"Enter a number (-1 to terminate)";
    cin>>m;     
    if(m!=-1 && m%2) 
       cout<<"Even"<<endl;
    else
       cout<<"Odd"<<endl; 
  } while(m!=-1);
}
Here we read numbers and print if the number is even or odd as long as number entered is -1. As while(expression) is executed after the block, we are sure that the body of the loop gets executed at least once.

do while loop is called repeat until in some languages. 

Comments

Popular posts from this blog

Find the error in C++ program

This C++ program is not compiling. What do you think is the error with the program? #include<iostream> using namespace std; int main() {    int arr[10];    arr={1,2,3,4,5,6,7,8};    cout<<"arr[0]="<<arr[0];    return 0; } Is the error due to Not using printf Initialising the array with only 8 elements instead of 10 Initialising array in the next statement instead of in definition. None of the above  Now if you like this question, there are plenty more questions like this and programs and notes in my app Simplified C++. Download the Simplif ied C++   by Hegdeapps now By the way the correct answer is (3)

Abstract class

 If we can not create any objects of a class, then it is called an abstract class. A class is made abstract by adding at least one pure virtual function to it. Pure virtual function A function is said to be a pure virtual function , if it has no definition but has only declaration. Pure virtual function is defined with the keyword virtual and followed by return type, function name and "=0". class Shape { public: virtual void printarea() =0 ; }; int main () { Shape obj1; //error } Here printarea() function of Shape class is a pure virtual function as it has no body. To make a function as pure virtual function, you should use =0 at the end of virtual function declaration Abstract class When a class has at least one pure virtual function, it is incomplete and no objects can be created from that class. Such a class is called an abstract class . In the earlier example class Shape is an abstract class, and objects can not be created from t...

Friends of C++

Friend function Remember that a member which is not public (Private and protected )  can not be accessed from outside the class.  Three are some situations where you may need to access these. Keyword friend  is used for this. A friend functions and classes can access all members of a class.  This concept is controversial. People say friend concept violates data encapsulation  A friend function is a non-member function but still can access all the members of a class including private members. Such a function is declared within class body with the prefix "friend" class Number { int num; public: Number( int m){ /*code*/ } friend void printNum(Number ob); /*friend function*/ }; void printNum (Number obj) { cout << obj.num << "endl" ; } printNum() is not member of class Number . But it can still access all members including private members, because it is a friend. Friend class An object of a friend c...