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
11. While Loop in C++
12. C++ Lambda
13. Loop in C++
Now Reading
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
A loop in C++ automates repetition in our code to save us from tedious manual tasks.
Whether we are iterating over data, repeating actions a set number of times, or waiting for a specific condition to occur, loops are our go-to solution. By understanding for, while, and do-while loops, as well as loop control mechanisms, we can unlock the power to write efficient, adaptable, and concise C++ programs.
Let us dive in and learn about the concept of a loop in C++ and how to use the different loops effectively in C++ programming.
Loop in C++ is a control structure designed to execute a block of code multiple times. They provide a streamlined approach to automating repetitive tasks, reducing the need for redundant code, and improving the efficiency and maintainability of programs.
By leveraging loops, we can avoid manually repeating code, thereby minimizing the risk of errors and enhancing the readability and clarity of our programs. Furthermore, loops offer the flexibility to adapt to dynamic conditions, making applications more responsive to user input and environmental changes.
Loops are critical for a variety of programming tasks, including:
C++ offers three primary loop structures, each tailored to different scenarios:
Let us now learn about the more common loops with C++ for loop, C++ while-loop, and C++ do while loop examples.
C++ for loop syntax:
for (initialization; condition; update) {
// Code to be repeated
}
How for loop in C++ Works:
for loop in C++ example 1:
// Counting from 0 to 9
for (int i = 0; i < 10; i++) {
std::cout << i << " ";
}
for loop in C++ example 2:
// Iterating over an array
int arr[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
std::cout << arr[i] << " ";
}
Syntax:
while (condition) {
// Code to be repeated
}
How cpp while loop works:
While loop in C++ example:
// Reading user input until a valid number is entered
int number;
std::cout << "Enter a positive number: ";
std::cin >> number;
while (number <= 0) {
std::cout << "Invalid input. Enter a positive number: ";
std::cin >> number;
}
Syntax:
do {
// Code to be repeated
} while (condition);
How it works:
Cpp do while example:
int choice;
do {
std::cout << "Menu:\n";
std::cout << "1. Option 1\n";
std::cout << "2. Option 2\n";
std::cout << "0. Exit\n";
std::cout << "Enter your choice: ";
std::cin >> choice;
// ... process the choice
} while (choice != 0);
If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.
Introduced in C++11, the range-based for loop streamlines the way you iterate over elements in containers like arrays, vectors, lists, and more. It offers a cleaner and more expressive syntax compared to traditional for loops, making our code easier to read and write.
Syntax:
for (element_declaration : range) {
// Code to be repeated for each element
}
How it works:
Example 1:
// Iterating over an array
int numbers[] = {10, 20, 30, 40};
for (int num : numbers) {
std::cout << num << " ";
}
// Output: 10 20 30 40
Example 2:
// Iterating over a vector
std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
for (const std::string& name : names) { // Use const reference for efficiency
std::cout << name << " ";
}
// Output: Alice Bob Charlie
Here are the key advantages of range-based for loops:
Here's a for each loop in C++ example program that combines both the traditional for loop and the range-based for-each loop:
Code:
#include <iostream>
#include <vector>
int main() {
// Traditional for loop with an array
int numbers[] = {5, 10, 15, 20};
int arraySize = sizeof(numbers) / sizeof(numbers[0]); // Calculate the number of elements in the array
std::cout << "Using for loop (array): ";
for (int i = 0; i < arraySize; ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
// Range-based for-each loop with a vector
std::vector<std::string> fruits = {"apple", "banana", "orange"};
std::cout << "Using for-each loop (vector): ";
for (const std::string& fruit : fruits) {
std::cout << fruit << " ";
}
std::cout << std::endl;
return 0;
}
Loop control statements are essential tools that allow you to fine-tune how our loops behave. They let you alter the usual flow of execution, giving you more flexibility when handling specific conditions within our loops.
The break statement acts like an emergency exit for our loop in C++. When encountered within a loop, it immediately terminates the loop, regardless of the loop condition.
Typical use cases:
Example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Terminate the loop when i reaches 5
}
std::cout << i << " ";
}
// Output: 0 1 2 3 4
The continue statement is like a "skip" button within our loop in C++. When encountered, it immediately jumps to the next iteration of the loop, bypassing any remaining code in the current iteration.
Typical use cases:
Example:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) { // Check if i is even
continue; // Skip even numbers
}
std::cout << i << " ";
}
// Output: 1 3 5 7 9
Let us explore the practical use of loops and how to combine loops.
Example:
int number = 0;
while (number <= 0) {
std::cout << "Enter a positive number: ";
std::cin >> number;
}
std::cout << "You entered: " << number << std::endl;
for (int i = 1; i <= 5; ++i) {
std::cout << i << " ";
}
// Output: 1 2 3 4 5
Explanation: The for loop in C++ initializes a counter i to 1, continues as long as i is less than or equal to 5, and increments i after each iteration. This prints numbers 1 through 5.
Example:
int number = 0;
while (number <= 0) {
std::cout << "Enter a positive number: ";
std::cin >> number;
}
std::cout << "You entered: " << number << std::endl;
Explanation: The while loop in C++ keeps asking the user for input until they enter a positive number. The loop condition checks the input before each iteration.
Note: The C++ for while loop can work together to form a combined loop.
Example:
int choice;
do {
std::cout << "\nMenu:\n";
std::cout << "1. Option 1\n";
std::cout << "2. Option 2\n";
std::cout << "0. Exit\n";
std::cout << "Enter your choice: ";
std::cin >> choice;
// ... handle choice ...
} while (choice != 0);
Explanation: This do-while loop in C++ presents a menu and repeatedly asks for the user's choice until they enter 0 to exit. The code block executes at least once before the condition is checked.
Example:
// Printing a multiplication table
for (int i = 1; i <= 10; ++i) {
std::cout << "Multiplication table for " << i << ":\n";
for (int j = 1; j <= 10; ++j) {
std::cout << i << " x " << j << " = " << (i * j) << std::endl;
}
std::cout << std::endl; // Add space after each table
}
Explanation: The outer for loop iterates through the numbers 1 to 10 (rows of the table).
The inner for loop, nested within the outer loop, also iterates from 1 to 10 (columns of the table). Finally, the multiplication and output are performed inside the inner loop.
Selecting the appropriate loop type depends on our specific requirements:
Infinite loops can cause our program to hang or crash. To prevent them:
Loops can be computationally intensive, especially when dealing with large datasets or complex operations. Here are some tips for improving loop in C++ performance:
Mastering loops is essential for any C++ programmer. With the right loop for the job and a keen eye for optimization, you'll be able to write code that's not only functional but also elegant and efficient.
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.
Loops in C++ are programming constructs that allow you to repeatedly execute a block of code until a specific condition is met.
The main types of loops in C++ are for, while, and do-while.
The syntax is: for (initialization; condition; update) { // code block to be executed }
loop in C++ structure refers to the way a loop is organized, including its initialization, condition, update (for for loops), and the body of code to be repeated.
You can exit a loop in C++ prematurely using the break statement or by making the loop condition false.
The syntax for a for loop in C is the same as in C++: for (initialization; condition; update) { /* code block to be executed */ }
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.