Here I will explain you all the loops in C++.
for loop
The for loop is a commonly used loop that allows you to repeat a block of code for a specific number of iterations. It consists of three parts: initialization, condition, and increment/decrement. Here's the general syntax:
for (initialization; condition; increment/decrement) { // code to be repeated }
Example:
for (int i = 0; i < 5; i++) { cout << i << " "; }
Output: 0 1 2 3 4
while loop
The while loop repeatedly executes a block of code as long as a given condition is true. It does not require initialization or increment/decrement statements explicitly. Here's the general syntax:
while (condition) { // code to be repeated }
Example:
int i = 0; while (i < 5) { cout << i << " "; i++; }
Output: 0 1 2 3 4
do-while loop
The do-while loop is similar to the while loop but with one key difference: it executes the code block first and then checks the condition. This guarantees that the loop will be executed at least once. Here's the general syntax:
do { // code to be repeated } while (condition);
Example:
int i = 0; do { cout << i << " "; i++; } while (i < 5);
Output: 0 1 2 3 4
range-based for loop
The range-based for loop is a convenient loop introduced in C++11 that iterates over a range of elements, such as an array or a container. It simplifies the process of iterating through the elements without worrying about indices. Here's the general syntax:
for (element : range) { // code to be repeated }
Example:
int arr[] = {1, 2, 3, 4, 5}; for (int num : arr) { cout << num << " "; }
Output: 1 2 3 4 5
if loop
The if statement is not a loop, but rather a conditional statement used for decision-making. It allows you to execute a block of code only if a certain condition is true. Here's the general syntax:
if (condition) { // code to be executed if condition is true }
Example:
int x = 5; if (x > 0) { cout << "x is positive"; }
Output: "x is positive"
The if statement can also be extended with an else block to specify an alternative block of code to be executed when the condition is false:
if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is false }
Example:
int x = -2; if (x > 0) { cout << "x is positive"; } else { cout << "x is non-positive"; }
Output: "x is non-positive"