For working professionals
For fresh graduates
More
Explore C++ Tutorials: Explori…
1. The Ultimate C++ Guide: C++ Tutorial for Beginners
2. Application of C++
3. C++ Hello World Program
4. C++ Variable
5. Reference Variable in C++
6. Function Overloading in C++
7. Functions in C++
8. Pointer in C++
9. Data Types in C++
10. C++ for Loop
Now Reading
11. While Loop in C++
12. C++ Lambda
13. Loop in C++
14. Switch Case in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
18. Class and Object in C++
19. Constructor in C++
20. Copy Constructor in C++
21. Destructor in C++
22. Multiple Inheritance in C++
23. Encapsulation in C++
24. Single Inheritance in C++
25. Friend Class in C++
26. Hierarchical Inheritance in C++
27. Virtual Base Class in C++
28. Abstract Class in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
32. Initialize Vector in C++
33. Iterators in C++
34. Queue in C++
35. Priority Queue in C++
36. Stack in C++
37. ifstream in C++
38. Exception Handling in C++
39. Memory Management in C++
40. Templates in C++
41. Type Conversion in C++
42. Enumeration in C++
43. Namespace in C++
44. Set Precision in C++
45. Stringstream in C++
46. Recursion in C++
47. Random Number Generator in C++
48. C++ Shell
49. Setw in C++
50. Multithreading in C++
51. Atoi in C++
52. Call by Value and Call by Reference in C++
53. Difference Between C and C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
59. Power Function in C++
60. Data Hiding in C++
61. Inline Function in C++
62. Getline Function in C++
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
67. static_cast in C++
68. C++ Comments
69. Structures in C++
70. C++ Standard Template Library (STL)
71. Virtual Function in C++
72. Sorting in C++
73. Polymorphism in C++
74. Oops Concepts in C++
75. Converting Integers to Strings in C++
76. Differences Between Break and Continue
Repetition is a fundamental concept in programming that allows us to automate tasks and perform actions multiple times. This repetitive execution of code is achieved through loops, and in the world of C++, the for loop is well-known as a versatile and efficient tool for controlling these iterations.
Whether we are traversing arrays, vectors, or other data structures, the C++ for loop provides a powerful and intuitive way to iterate through our data. The for loop also lets us unlock new possibilities for data manipulation and processing in our C++ programs.
Let us learn how to use the C++ for loop effectively and explore its various applications.
A loop is a sequence of instructions in programming that is repeated until a specific condition is met. Loops are essential for tasks that require repeated actions, such as processing a list of items, performing calculations multiple times, or iterating through user input.
Loops are indispensable in programming for several reasons:
The for loop is an essential tool in C++, renowned for its ability to iterate over sequences of data with precision and clarity. The C++ for loop can be used to solve a wide range of problems and handle diverse data structures with ease. It consists of three essential components that control the loop's execution:
The combination of these three components allows the for loop to execute its code block repeatedly, with the loop counter variable evolving on each iteration until the condition is no longer met.
To effectively wield the power of the for loop, let us dissect its structure and understand the role of its constituent parts.
The C++ for loop adheres to a specific syntax:
for (initialization; condition; update) {
// Code to be executed repeatedly (loop body)
}
Let us break down this syntax:
Here is a simple example to illustrate the basic usage of the for loop:
for (int i = 1; i <= 10; ++i) {
std::cout << i << " ";
}
// Output: 1 2 3 4 5 6 7 8 9 10
In this example:
The for loop is a versatile tool that can be applied in a variety of scenarios. Let us explore some common use cases to illustrate its power and flexibility.
Arrays and vectors are fundamental data structures in C++, used to store collections of elements of the same type. The for loop is the perfect companion for traversing these sequential containers.
Example:
int numbers[] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; ++i) { // i is the index variable
std::cout << numbers[i] << " ";
}
// Output: 10 20 30 40 50
In this example, the for loop iterates through each element of the numbers array. The index variable i starts at 0 and increments with each iteration, providing access to each element in sequence until i reaches the end of the array.
C++ offers a rich collection of containers beyond arrays and vectors, such as lists, sets, and maps. To traverse these containers, we use iterators which are special objects that act as pointers to elements within the container.
Example:
std::list<std::string> names = {"Alice", "Bob", "Charlie"};
for (std::list<std::string>::iterator it = names.begin(); it != names.end(); ++it) {
std::cout << *it << " "; // Dereference iterator to get the element
}
// Output: Alice Bob Charlie
In this snippet, it is an iterator that starts at the beginning (begin()) of the names list and advances to the next element with each iteration until it reaches the end (end()). The * operator is used to dereference the iterator and access the value of the element it points to.
Nested for loops are powerful when dealing with multi-dimensional data or performing repetitive tasks within loops. Each inner loop completes all its iterations for every single iteration of the outer loop.
Example:
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
In this case, the nested loops traverse a 3x3 matrix, printing each element in a row-by-row fashion.
An infinite loop is a loop that never terminates, continuing to execute its code block indefinitely. This can happen due to a flawed loop condition that never becomes false.
Example:
for (int i = 1; i > 0; ++i) { // Incorrect condition: i will always be greater than 0
// This loop will run forever
}
To avoid infinite loops:
If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.
As you become more familiar with the for loop, you will discover that it offers even more flexibility and expressiveness than its basic syntax suggests. Let us delve into some advanced techniques that can elevate our loop usage to the next level.
C++11 introduced the range-based for loop, a concise and elegant way to iterate over elements in containers (like vectors, lists, and sets) and arrays. It eliminates the need for explicit iterators or index variables, making our code more readable and less prone to errors.
Example:
std::vector<int> numbers = {10, 20, 30, 40, 50};
for (int num : numbers) { // Range-based for loop
std::cout << num << " ";
}
// Output: 10 20 30 40 50
In this example, num automatically takes on the value of each element in the numbers vector during each iteration. Range-based for loops are also known as C++ for each loop.
While the for loop traditionally has three expressions (initialization, condition, update), we can actually omit any or all of them in certain situations.
Here's an example with an omitted condition, creating an infinite loop that breaks based on a condition inside the loop body:
std::string input;
for ( ; ; ) { // Infinite loop
std::getline(std::cin, input);
if (input == "quit") {
break;
}
// ... process input ...
}
The comma operator (,) allows us to evaluate multiple expressions sequentially within a single statement. We can use this in the initialization or update parts of the for loop to perform multiple actions at once.
Example:
for (int i = 0, j = 10; i < 5; ++i, --j) {
std::cout << "i: " << i << ", j: " << j << std::endl;
}
In this case, the initialization step sets i to 0 and j to 10. The update step increments i and decrements j in each iteration.
The C++ for while loop is ideal when we want to repeat a block of code as long as a condition remains true. We can combine the for loop and the while loop in a nested fashion in order to use these two together. For example, a for loop within a while loop or vice versa. It is ideal for our programming use when the number of iterations is unknown and depends on a condition.
Example:
int outerCounter = 0;
while (outerCounter < 3) {
std::cout << "Outer loop iteration: " << outerCounter << std::endl;
for (int innerCounter = 0; innerCounter < 2; ++innerCounter) {
std::cout << " Inner loop iteration: " << innerCounter << std::endl;
}
outerCounter++;
}
In the above C++ for loop example, the outer while loop iterates 3 times based on the outerCounter. For each iteration of the outer loop, the inner for loop iterates 2 times based on the innerCounter.
Here is a C++ for loop program for calculating factorials that you can try out yourself:
Code:
#include <iostream>
int main() {
int num;
std::cout << "Enter a positive integer: ";
std::cin >> num;
long long factorial = 1; // Use long long for potentially large factorials
for (int i = 1; i <= num; ++i) {
factorial *= i;
}
std::cout << "Factorial of " << num << " is " << factorial << std::endl;
return 0;
}
This C++ for loop example prompts the user to enter a positive integer. The program then initializes factorial to 1 (the factorial of 0 is 1). It iterates from i = 1 up to the input number (num). In each iteration, it multiplies the factorial by the current value of i. Finally, it prints the calculated factorial.
While the for loop is a straightforward concept, mastering its usage involves understanding best practices and avoiding common pitfalls. Let us delve into some tips and tricks to elevate our for loop game.
Optimizing our for loops can significantly improve our program's performance, especially when dealing with large datasets or computationally intensive tasks. Consider these tips:
Avoid these common C++ for loop mistakes:
The for loop enables precise control over repetitive code execution, making it ideal for tasks with a known number of iterations or when access to the loop counter (index) is essential. Choosing the right loop type, minimizing loop overhead, and avoiding common pitfalls like off-by-one errors are crucial for writing efficient and reliable code.
By mastering the common use cases and understanding potential pitfalls like infinite loops, you'll be well-equipped to leverage the for loop's capabilities for efficient and error-free code execution. If you wish to learn programming languages such as C++, you can check out upGrad’s computer science programs such as the Master’s in Computer Science Program.
A for loop is a repeatedly executing control flow statement for executing a block of code as long as a given condition is true.
The syntax is for (initialization; condition; update) { /* loop body */ }.
It initializes or declares and initializes the loop counter variable(s) used to control the loop's iterations.
Yes, you can have multiple initialization statements separated by commas.
Yes, you can combine multiple conditions using logical operators (&& for AND, || for OR) in the condition part.
Yes, if the loop counter variable is already declared and initialized before the loop, you can omit the initialization part.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.