C++ Tutorial

C++ For Loop

for packs init, condition, and step in one line. Use it when you know how many times to repeat.

Three parts in one line

A classic for loop has three slots separated by semicolons: initialize, condition, step. The initialize runs once. Then C++ checks the condition, runs the body, runs the step, and checks again, until the condition is false.

That is the same three jobs a while loop has, written where you can see them together. Usefor when the number of passes is known: 0 to n minus one, 1 to 10, every index in an array.

A complete for program

int i = 0 starts the counter. i < 5 is the test. i = i + 1 is the step. The body prints the current i. The values printed are 0, 1, 2, 3, 4 — five times, not six.

Example

#include <iostream>
using namespace std;

int main() {
  for (int i = 0; i < 5; i = i + 1) {
    cout << i << endl;
  }
  return 0;
}

Run this in /cpp/try. Counting from 0 is the usual C++ habit because array indexes start at 0.

Read the header left to right

SlotThis exampleWhen it runs
Initint i = 0Once, before the first check
Conditioni < 5Before every pass, including the first
Stepi = i + 1After each pass, before the next check

i++ means the same as i = i + 1 here. You will see ++ in other people's code. Either form is fine for a counter.

The variable declared in init exists only inside the loop. After the closing brace, i is gone.

Count the other way

Start high and subtract if you need a countdown. The condition still has to become false. Herei goes 5, 4, 3, 2, 1, then i >= 1 fails.

Example

#include <iostream>
using namespace std;

int main() {
  for (int i = 5; i >= 1; i = i - 1) {
    cout << i << endl;
  }
  cout << "done" << endl;
  return 0;
}

Range-for over a list

When you already have a collection and you want each value, C++17 gives you a range-based for:for (int n : nums). No index. No length. The loop binds n to each element in turn.

This works on a built-in array and on a vector. Include <vector> for the second. Arrays come in a later chapter; this is enough to walk a short list.

Example

#include <iostream>
#include <vector>
using namespace std;

int main() {
  int arr[] = {2, 4, 6};
  for (int n : arr) {
    cout << n << " ";
  }
  cout << endl;

  vector<int> nums = {10, 20, 30};
  for (int n : nums) {
    cout << n << " ";
  }
  cout << endl;
  return 0;
}

Which loop to write

  • Known count or indexes: classic for.
  • Every element in an array or vector, no index needed: range-for.
  • Keep going until a condition changes (input, a flag): while.

A range-for does not give you the index. If you need the position as well as the value, use a classicfor with i.

Off-by-one

i < n runs n times when i starts at 0. i <= n runs n + 1 times. Both are valid; they mean different things. For an array of length n, the last valid index is n minus one, so the test is i < n.

Next: break and continue — leaving a loop early, or skipping one pass.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Physics

A drop, second by second

Ticker-tape and strobe photos show position at equal time steps. From rest, s = ½ g t². At t = 1, 2, 3, 4 s the distances are about 4.9, 19.6, 44.1, 78.5 m. The gaps grow because the object is speeding up.

s(t) = ½ g t²

Example

#include <iostream>
using namespace std;

int main() {
  const double g = 9.81;
  for (int t = 1; t <= 4; t++) {
    double s = 0.5 * g * t * t;
    cout << "t = " << t << " s, s = " << s << " m" << endl;
  }
  return 0;
}

Maths

Sum of squares

1² + 2² + … + 10² is 385. The closed form n(n+1)(2n+1)/6 gives the same 385 for n = 10. The loop is how you check the formula before you trust it on n = 1000.

Σ k² = n(n+1)(2n+1)/6

Example

#include <iostream>
using namespace std;

int main() {
  int sum = 0;
  for (int n = 1; n <= 10; n++) {
    sum += n * n;
  }
  cout << "sum of squares = " << sum << endl;
  return 0;
}

FAQ: C++ For Loop

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ for loop examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ for loop in this C++ C++ lesson (C++ For Loop).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.