WEB DEVELOPER SITE
PYTHONPHP7JAVA
 

C++ LOOPS


In this tutorial you learn about c++ loops


Loops

A loop can define as repeatedly executes a set of statements until a particular condition is satisfied.

A wihle statements define as repeatedly executes a target statement as long as a given condition remains true.

while (condition) {
   statement(s);
}

The while loop

we know that while loop statements {} curly braces. The loop body is the block of statements within curly braces.
The example above declares a variable equal to 2 (int num = 2). The while loop checks the condition (num < 7), and executes the statements in its body, which increment the value of num by one each time the loop runs.

The increment value can be changed. If changed, the number of times the loop is run will change, as well.

int num = 1;
while (num < 6) {
  cout << "Number: " << num << endl;
  num = num + 3;
}

/* Outputs
Number: 1
Number: 4 
*/



The For Loop statements

A for loop define as repetition control structure that allows you to efficiently write a loop that executes a specific number of times.

syntax

for ( init; condition; increment ) {
  statement(s);
}
Note
init step is executed first, and does not repeat.

condition is evaluated, and the body of the loop is executed if the condition is true.

Example
for (int x = 2; x < 8; x++) {
 // some code
 }

The for Loop

Here the simple example of for loop
int main()
{
    for (int a = 2; a < 8; a++) {
        cout << a << endl;
    }

    return 0;
}
//output

2 3 4 5 6 7

The for Loop

The for look example are given below:-

int main()
{
    for (int a = 0; a < 120; a+=12) {
        cout << a << endl;
    }

    return 0;
}
/* Outputs
 

0 12 36 48 60 72 84 96 108
*/

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C++ supports the following control statements.

Sr.No Control Statement & Description
1 break statement

Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

3 goto statement

Transfers control to the labeled statement. Though it is not advised to use goto statement in your program.

The Infinite Loop

A loop becomes infinite loop if a condition never becomes false. You may have an initialization and increment expression, but C++ programmers more commonly use the 'for (;;)' construct to signify an infinite loop.
#include <iostream>
using namespace std;
 
int main () {
   for( ; ; ) {
      printf("This loop will run forever.\n");
   }

   return 0;
}