Loops in C++

Loops in C++

Loops in C++

In C++, there are three main types of loops: for, while, and do-while. Each of these loops allows you to execute a block of code repeatedly, but they differ in their syntax and behavior.

1.for loop: The for loop is a type of loop that allows you to specify an initialization statement, a loop condition, and an increment statement, all in a single line of code. The general syntax for a for loop is as follows:

				
					for(initialization statement; loop condition; increment statement) {

    // code to be executed repeatedly

}

				
			

For example, the following code uses a for loop to print the values of the variable i from 0 to 4:

				
					for (int i = 0; i < 5; i++) {

    std::cout << i << "";

}
				
			

2. while loop: The while loop is a type of loop that allows you to execute a block of code repeatedly while a certain condition is true. The general syntax for a while loop is as follows:

				
					while(loop condition) {

    // code to be executed repeatedly

}
				
			

For example, the following code uses a while loop to print the values of the variable i from 0 to 4:

				
					int i =0;

while (i< 5) {

    std::cout << i << "";

    i++;

}
​
				
			

3. do-while loop: The do-while loop is a type of loop that is similar to the while loop, but it always executes the block of code at least once, regardless of whether the loop condition is initially true or false. The general syntax for a do-while loop is as follows:

				
					do {

    // code to be executed repeatedly

} while(loop condition);

​
				
			

For example, the following code uses a do-while loop to print the values of the variable i from 0 to 4:

				
					int i =0;

do {

    std::cout << i << "";

    i++;

}while (i < 5);

​
				
			
Join To Get Our Newsletter
Spread the love