Site icon

Loops C++

What are loops?

A loop can execute a set of statements again and again until a certain condition is reached.

Example 1:

If a teacher asked a student to demonstrate the counting from 1 to 10. Then he can ask the student to demonstrate the counting by two different methods.

Method 1:

A teacher can ask the student to demonstrate the counting from 1,2,3,4,5,6,7,8,9 to 10.

The teacher can ask the student to demonstrate the counting from 1 to 10.

Think about it, which one method is best?

Exactly it is better if we used the second method. The concept of the loop is similar to this.

What is a mechanism of the loop?

When we try to run a loop, then we have to care for the followings;

  1. Loop initialization
  2. Loop Condition
  3. Loop Increment/Decrement

What is Loop initialization?

For example: In the example above the beginning of loop is from 1

What is Loop Condition?

Allows the loop to execute only when the condition is true.

For example: In the example above the termination of loop occurred at  10.

What is Loop Increment/Decrement?

For example: In example 6.1, loop increment is the increment from 1 to 2, from 2 to 3, from 3 to 4, from 4 to 5, from 5 to 6, from 6 to 7, from 7 to 8, from 8 to 9 and from 9 to 10.

After reaching to 10 what the student do?

Exactly the student stops at 10 because there is a condition to terminate the loop at 10.

Now let’s begin with a programming example.

Example 2:

If we want to print hello 5 times on the screen without a loop, then we can write the code as follows

Line No Program Code
1 cout<<”loop is working”;
2 cout<<”loop is working”;
3 cout<<”loop is working”;
4 cout<<”loop is working”;
5 cout<<”loop is working”;

Example: Statements without loop

If we take a little attention to this code, we can observe that we need to write the

  cout<<”loop is working”;

five times again and again in the program. It is time-consuming. It also consumes more memory.

So there is a need to introduce a method that that can save a programmer time and can also save the computer memory.

Solution to this problem is by using a loop. Later we will discuss the solution in the example in next tutorial.

There are three common types of loops;

  1. For loop
  2. While loop
  3. Do While loop
Test Your Understandings

1.Loops execute again and again so occupies more space and consumes more time for the programmer?


Answer - Click Here:

2……………Used to stop the loop?

A- Loop initialization

B- Loop condition

C- Loop increment

D- All above

Answer - Click Here:

Exit mobile version