Loops in C++ are used to execute a block of code repeatedly. Here are some of the most common loop types in C++:
1. while loop: The while loop is used to execute a block of code repeatedly as long as a condition is true. The basic syntax of the while loop is as follows:
while (condition) { // code to be executed repeatedly as long as condition is true }
For example:
int i = 0; while (i < 10) { cout << i << endl; i++; }
2. do-while loop: The do-while loop is used to execute a block of code repeatedly as long as a condition is true. The difference between the do-while loop and the while loop is that the do-while loop executes the code block at least once, even if the condition is false. The basic syntax of the do-while loop is as follows:
do { // code to be executed at least once } while (condition);
For example:
int i = 0; do { cout << i << endl; i++; } while (i < 10);
3. for loop: The for loop is used to execute a block of code repeatedly a specific number of times. The basic syntax of the for loop is as follows:
for (initialization; condition; update) { // code tobe executed repeatedly as long as condition is true }
The initialization step is executed only once, at the beginning of the loop. The condition is checked at the beginning of each iteration, and if it is true, the code block is executed. The update step is executed at the end of each iteration, before checking the condition for the next iteration. For example:
for (int i = 0; i < 10; i++) { cout << i << endl; }
In this example, the loop will execute 10 times, with the value of `i` ranging from 0 to 9.
4. range-based for loop: The range-based for loop is a specialized form of the for loop used to iterate over the elements of a container (e.g. an array, a vector, a map, etc.). The basic syntax of the range-based for loop is as follows:
for (type var : container) { // code to be executed repeatedly for each element in the container }
For example:
int arr[] = {1, 2, 3, 4, 5}; for (int x : arr) { cout << x << endl; }
In this example, the loop will iterate over each element in the `arr` array and print its value.
These are some of the most common loop types in C++. Understanding how to use these loops is an important partof learning C++.