For Loops

Traditional and range-based for loops

Interview Relevant: Essential for iteration

For Loops

For loops provide controlled iteration over a range of values.

Types of For Loops

  • Traditional: for (init; condition; update)
  • Range-based (C++11): for (auto x : container)

Code Examples

Traditional and range-based for loops.

cpp
1// Traditional for loop
2for (int i = 0; i < 5; i++) {
3    cout << i << " ";  // 0 1 2 3 4
4}
5
6// Decrementing
7for (int i = 5; i > 0; i--) {
8    cout << i << " ";  // 5 4 3 2 1
9}
10
11// Multiple variables
12for (int i = 0, j = 10; i < j; i++, j--) {
13    cout << i << "," << j << " ";
14}
15
16// Range-based for loop (C++11)
17vector<int> nums = {1, 2, 3, 4, 5};
18for (int n : nums) {
19    cout << n << " ";
20}
21
22// By reference (to modify)
23for (int& n : nums) {
24    n *= 2;
25}
26
27// By const reference (read-only, efficient)
28for (const auto& n : nums) {
29    cout << n << " ";
30}
31
32// Iterate over initializer list
33for (int x : {1, 2, 3, 4, 5}) {
34    cout << x << " ";
35}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In