C++ Programming

FOR Loop C++, Nested FOR Loop, While loop, do-while loop flow control

Introduction:

flow control for loop c++, nested for loop While loop, do-while loop– In this article two main features of computer programming will be discussed counter and looping. A loop is an essential programming technique that permits the repetitive execution of a statement or a group of statements whereas the counter is a technique for controlling a looping process. C/C++ has three looping statements the flow control for a statement flow control while statement and flow control do/while statement. After this article, you will be able to know how to construct or design a program with a looping structure.


Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Counters:

The counter is a very important feature of computer programming. It is a technique for controlling a looping process (i.e_) it is a systematic method of counting the number of repetitions.there are three types of counters which are given below:

  1. Standard counter
  2. Accumulator counter
  3. Multiplicative counter.

Standard counter:

the standard counter is normally used for counting process. With the help of this counter it is possible to count and control the number of execution of a statement or group of statements. A few examples of standard counter are given below :

C= C+1;

C++;

Z=z+5;

N+=10;

Notice that each time a standard counter is executed a constant value is added to the counter.

Accumulator Counter:

Accumulator counter is normally used to accumulate the subtotals. It differs from a standard counter, which is indexed by a fixed value, whereas accumulator counter is indexed by the different values each time the program executes it. The accumulator counter often looks like this:

I=I+J;

K+=L;

A=B+C;

Notice that the value of accumulator counter is not indexed by a fixed value. But by the value of a variable.


Multiplicative counter:

Unlike standard and accumulator counter multiplicative counters are used for multiplication purposes. In case of standard and accumulator counters we always initialize these counters with zero but while using multiplicative counter the starting value of the counter must be one if we initialize this counter with zero the result will be zero because we know that zero multiplied by anything will be zero multiplicative counter often look like these:

A=A*2;

W * =3;

X *=Z;

Looping in C/C++:

One of the main features of computer programming Is Looping in many situations some operations are performed over and over again most programs involve repetition or looping. A loop is instruction or group of instruction that the computer executes repeatedly to specified number of times or until some terminating condition is satisfied.

The looping process can be achieved with an if and goto statements but like many other programming languages, C++ provides special statements that makes the loop easy to write and easy to understand. It is therefore recommended to use these control statements instead of goto statements.

There are two types of loops that may be encountered in computer programming

  1. Counter or determined loop.
  2. Controlled or undetermined loop.

Counter or determined loop is used in that case when the precise number of repetitions is known in advance and it executes statement or group of statements a specific number of time-such as 30 time or 200 times. It is an extremely powerful loop. This type of loop might be used in a problem such as display the word ‘Programming digest’ 5 times on screen in C++ . for statement is used to implement this type of loop structure.

A loop whose execution depends on a condition being true or false is called a controlled loop. Controlled loop is also known as undetermined loop because in this loop structure the number of execution of a loop is not known in advance. This type of loop is used in a problem such as ‘compute the sum and average of the number until -999 is encountered’. It is not known that how many times a loop will be executed in C++ language, while and do/while loops are used for this kind of problem.


For loop c++ flow control:

Flow control for loop allows a statement or grout of statements to be performed in an loop a given number of time. It is most widely used loop structure in C++. It is a timesaving loop. Although the if and goto statements can also be used to build a such type of loop structure but for lool is a convenient easier and more efficient way to build a loop structure. It is a determined loop because it specifies how many times a loop will be executed. The for loop has the following syntax:

for(initialize the variable; condition, expression )

{

Body of the loop;

}

The initialize is an assignment statement that is used to initialize the control variable(used as a counter) that controls the looping process. It evaluates only once, at the top of the loop and never evaluates again in the looping process.

The condition evaluates the condition i.e it compares the value of the control variable with some limit value (B<= 20). For continuation of the looping process this condition must be satisfied.

The expression is an assignment statement or unary statement that is used to alter the value (increment or decrement ) of the counter, initially assigned by the initialize.

The body of the loop (consists of either simple or compound statement ) is executed repeatedly, as long as the condition remains true.

Example: how to print number from 1 through 10 using for loop c++ flow control:

#include <iostream.h>
#include <conio.h>
Void main() 
{
int a;
for(a=1; a<=10; a++)
{
cout<<a<<”\t”;
}
getch();
}

Output:
1   2   3   4   5   6   7   8   9   10

In the above program notice that initialize (a=1) condition (a<=10) and expression (a++) are enclosed in parentheses. The first tie the is loop is executed the initializer  initializes the initial value of 1 to control variable a . after the initialization process the condition is tested. Since a is 1 the condition is satisfied and the body of the loop is executed for the first time (in the above program body of the is consisted of only one statement i.e cout<<a<<”\t”). after execution of the statement within the body of the loop control is sent back to the for loop statement again where the value of a gets incremented by 1 i.e a become 2 now. Again the condition is tested to check whether the new value of a is < 10. Since it is true the statement within the body of the loop is executed again. Each time the loop is executed the value of a is incremented and the condition is tested. The looping process will be executed as long as the current value of a does not exceed 10. Once the value of a exceeds 10(in the above case) the control is transferred to the statement immediately following the body of the loop.


Example: how to write a program which print number in reversed order from 10 to 1 using for loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main() 
{
int a;
for (a=10; a>=1; --a)
{
cout<<a<<”\t”;
}
getch();
}

Example: how to write a program which prints even number from 1 to 100 using for loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main() 
{
int even;
for (even =2; even <=100; even + =2)
{
cout<< even <<”\t”;
}
getch();
}

Example: how to write a program which print table of any number using for loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main() 
{
int n,m;
cout<<”Enter any number for table:”;
cin>>n;
for (m =1; m <=12; m++)
{
cout<< m <<”*”<<m<<”*”<<n*m<<endl;
}
getch();
}


Example: how to write a program which find the Fibonacci sequence using for loop c++ flow control:

In this example I want to show you how to find the Fibonacci sequence in C++. so as you might know if it the Fibonacci sequence all it means is just the first term added to the maximum for example that we start with zero and one so we have to add 0 plus 1 we get 1 then we add 1 plus 1 we get 2 and we add 2 plus 1 we get a 3 and so on it’s just like a bunch of series of numbers added one after the other one like term 1 plus term 2 so in this example I’m going to show you how to find those sequences whatever term you want using.

#include <iostream.h>
#include <conio.h>
void main() 
{
int first=0, second=1,third;
int n,c;
clrscr()
cout<<”Order of  Fibonacci Series:  ”;
cin>>n;
cout<<”\n Fibonacci Series is: ”<<endl;
cout<<first<<”\t”<<second<<”\t”;
for(c=0;c<n-2;c++)
{
third= first+second;
cout<<third<<”\t”;
first=second;
second=third;
}
getch();
}

Example: how to write a program which find the factorial  of a Number using for loop c++ flow control:

In this example we are going to make a program to find out the factorial of a number so before proceeding I am going to let you know how to calculate factorial of a number suppose I want to calculate factorial of 5 then the process is like factorial 5 is equal to 5 x 4 x 3 x 2 x 1 which is 120 and if we want to calculate the factorial of n which is the generalized formula of factorial then we have to follow this approach factorial n is equal to n multiplied by n minus 1 multiplied by n minus 2 x dot dot dot till 1 we have to multiply it and and decreasing the value of n and we have to multiply the value till 1 now coming to the programming part

#include <iostream.h>
#include <conio.h>
void main() 
{
int n,f=1;
cout<<”Enter A Number: ”;
cin>>n;
for(int c=1;  c <= n; c++)
{
f*=c;
cout<<n<<”Factorial is ”<<f;
}
getch();
}



Nested for loop c++ flow control:

In C++ language it is possible to nest for loops. When a for loop is placed within another for loop it is called a nested for loop. In other words we can say that loops that occur within other loops are called nested loops. In such type of loop structure. It is important to note that flow control variable of nested loop must always be different i.e an outer loop and inner loop should not have the same flow control variable.

Example: how to write a program which print the pattern using nested for loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main() 
{
int i,j;
clrscr();
for(i=1; i<= 5; i++)
{
    for(j=1; j<= i; j++)
{
cout<<i<<”\t”;
cout<<endl;
}
}
getch();
}

Output:
1
2   2   
3   3   3
4   4   4   4
5   5   5   5   5

While loop c++ flow control:

There are many programming problems in which it is not known in advance that how many times a loop is to be executed. In such cases the looping process is controlled by a condition. For this purpose, while or do/while loops are used these loops are called undetermined loops.

A looping statement while  is used to execute a series of statement in a loop over and over as long as a given condition is true. The general format is :

While(condition)

{

Body of the loop;

}

The while loop structure illustrated with the following flowchart

for loop c++

Notice that as long as the condition expression in the while statement is true the statements in the body of the loop will be repeated and this process continues until the condition becomes false and then the control skips down to the statement immediately following the while loop structure.

Structure1

int no = 1;

while (no < = 10)

{

cout<<no<<endl;

no++;

}

 

Structure2

int No = 1;

while(No < = 10)

cout<<No++<<endl;

Structure3:

int No = 0;

while (++No < 10)

cout<<No<<endl;

in the first glance you might think that if and while are alike but there is a difference if the condition is initially false the while will act much like an if statement. But if the condition is true the while may behave very differently. The if statement conditionally executes the statements once whereas the while loop conditionally executes the statements more than once. A few examples of while loop are given below.

Example: how to write a program which computes the total sum from 1 to 50 using while loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main()
{
int c=1;
int sum=0;
while(c<=50)
{
sum + = c;
c++;
}
cout<<”Sum from 1 to 50 = ”<<sum;
getch();
}

Example: how to write a program, which computes the factorial of, any number using while loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main()
{
int n ,c = 1;
int fact=1;
cout<<”Enter the number: ”;
cin>>n;
while (c <= n)
{
fact  *= c++;
}
cout<<”Factorial of  the number is :”<<n<<”=”<<fact;

getch();
}


Example: how to write a program, which finds the characters in a text using while loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main()
{
int count=0;
clrscr();
cout<<”Enter Text, and Press Enter key to stop”<<endl;
while(getch() != ‘\r’)
{
count++;
cout<<”\nTotal character is =”<<count;
}
getch();
}


OutPut:
Enter Text, and Press Enter key to stop
Programming digest
Total character is = 18

Note:As you know that space is also a character. Programming digest have 17 character but in this program It shows 18 because space is also counted in this program

Example: how to write a program, which prints a given number in reverse using, while loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main()
{
long int n;
int r;
clrscr();
cout<<”Enter the number : ”;
cin>>n;
while(n>0)
{
r=n% 10;
n=n/10;
cout<<r;
}
getch();
}

Example: how to write a program, which compute the prime number, using while loop c++ flow control:

#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
int n, c=2,r;
cout<<”Enter the number :”;
cin>>n;
while(c < n)
{
r=n % c;
if(r==0)
{
cout<<n<<”is composite number ”;
exit(0);
}
else
{
c++;
continue;
}
}
cout<<n<<”is prime number”;
}

As you know that 1 is used for true and 0 is used for false. You can create a loop that will never end by using the 1 (while(1) ) for the condition to be tested. In this case the break statement is used to terminate the looping process as shown in the following example


Example: how to write a program, which display number from `1 to 10 using, break and continue in  while loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main()
{
int n = 0;
while(1)
{
n++;
cout<<n<<endl;
if(n== 10)
break;
else
continue;
}
}

Do-while loop c++ flow control:

The do-while is a looping statement unlike the while and for loop, (which are pre tested loops) the do-while is the post-tested loop i.e the condition is tested after the execution of the body of the loop. Thus in this loop either the condition is true or false the body of the loop executes at least once. It has the following general format

Do

{

Body of the loop;

}

While(condition);

The do-while loop structure is illustrated with the following flowchart

for loop c++

Notice that the condition appears after the body of the loop which means that it is tested at the end of the loop. So the body of the loop is always executed at least once even if the condition fails for the first itself. After executing the statement(s) in the body of the loop once condition is then tested of the condition is true the body of the loop is excuted again and as long as the conditional expression in the do-while statement is true the statement(s) in the body of the loop will be repeated and this process continues until the condition becomes false and then the control skips down to the statement immediately following the do-while loop structure.

Unlike while loop the loop condition of a do-while loop must be followed by a semicolon. Otherwise, a syntax error will result. And unlike for loop do-while loop must contain some feature that alters the value of expression so that the looping action can terminate. A few examples of programs with do-while loops are given below:



Example: how to write a program, which display number from `1 to 10 using, do while loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main()
{
int c = 1;
do
{
cout<<c++<<endl;
}
while(c <= 10);
}

Example: how to write a program, which displays all the ASCII value of their equivalent character using, do-while loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main()
{
int c = 1;
clrscr();
do
{
printf(“\n %d\t%c”,c,c);
c++;
}
while(c < = 255);
getch();
}

Example: how to write a program, which displays the sum up the series 1/1! + 2/2! + 3/3! +….. using, do-while loop c++ flow control:

#include <iostream.h>
#include <conio.h>
void main()
{
int n;
float i=1.0, f=1.0,sum=0.0,s;
cout<<”which term the series is to be sum up: ”;
cin>>n;
do
{
f=f*i; s=i/f; sum =  sum + s;
i++;
}
while(i< = n)
cout<<”sum of the series up to ”<<n<<”=”<<sum;
getch();
}


Break continue and exit() statements:

The break statement immediately ends the looping process. It transfers control to the closing brace of the most current loop. If the break statement is used in the inner loop of a nested loop the break exits only the inner loop. Whereas the continue statement performs the opposite function of break statement. It transfers the control at the top of the loop for next iteration while exit() statement. Which is declared in the stdlib.h header file enables you to exit the program i.e it terminates the program and returns the user to the operation system. The break, continue and exit() may be used in any construct.

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button