Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Loops

Loops

Loops are fundamental constructs in programming that allow you to execute a block of code repeatedly based on a specified condition. In C++, there are several types of loops:

1. While Loop:

Executes a block of code repeatedly as long as a specified condition is true.

while (condition) {
    // Code to be executed
}

Example:

#include <iostream>
using namespace std;

int main() {
  int i = 0;
  while (i < 4) {
    cout << i << "\n";
    i++;
  }
  return 0;
}

Output:

0
1
2
3

2. Do-While Loop:

Similar to the while loop, but it guarantees that the block of code is executed at least once before checking the condition.

do {
    // Code to be executed
} while (condition);

Example:

#include <iostream>
using namespace std;

int main() {
  int i = 0;
  do {
    cout << i << "\n";
    i++;
  }
  while (i < 4);
  return 0;
}

Output:

0
1
2
3

3. for Loop:

Executes a block of code a specified number of times, typically based on an initialization, condition, and update statement.

for (initialization; condition; update) {
    // Code to be executed
}

Example:

#include <iostream>
using namespace std;

int main() {
  for (int i = 0; i < 4; i++) {
    cout << i << "\n";
  }
  return 0;
}

Output:

0
1
2
3

4.Nested Loop:

A nested loop in programming refers to placing one loop inside another loop. This enables you to iterate over elements in a multidimensional data structure, such as a two-dimensional array, or to perform repetitive tasks with multiple levels of iteration.

Example:

#include <iostream>
using namespace std;

int main() {
  // Outer loop
  for (int i = 1; i <= 3; ++i) {
    cout << "Outer: " << i << "\n";  // Executes 2 times
    
    // Inner loop
    for (int j = 1; j <= 2; ++j) {
      cout << " Inner: " << j << "\n";  // Executes 6 times (2 * 3)
    }
  }
  return 0;
}

Output:

Outer: 1
 Inner: 1
 Inner: 2
Outer: 2
 Inner: 1
 Inner: 2
Outer: 3
 Inner: 1
 Inner: 2

5. Foreach Loop:

In C++, the range-based for loop, also known as the “for each” loop, provides a concise way to iterate over elements in a container or a range. It’s particularly useful for iterating over the elements of an array, a standard library container such as a vector, list, or set, or any other data structure that supports iteration.

for (type variableName : arrayName) {
  // code block to be executed
}

Example:

#include <iostream>
using namespace std;

int main() {
  int myNumbers[5] = {1, 2, 3, 4, 5};
  for (int i : myNumbers) {
    cout << i << "\n";
  }
  return 0;
}

Ouput:

1
2
3
4
5

    Leave a Reply

    Your email address will not be published.

    Need Help?