Loops and functions

What loops and functions are in C++.

1. What is this?

A loop repeats a block. for (int i = 1; i <= 5; i++) runs with i = 1..5. A function is a reusable block: int doubleIt(int n) takes an int and returns an int. Declare it before main (or prototype it) so main can call it.

2. Why do we use it?

Games loop over frames; engines call the same function millions of times. Write once, run fast.

3. Syntax breakdown

  • int doubleIt(int n) { return n * 2; }

    Function taking int n, returning n*2.

  • for (int i = 1; i <= 3; i++) {

    Loop i from 1 while <= 3.

  •   std::cout << doubleIt(i) << std::endl;

    Calls the function each pass and prints the result.

5. Common mistakes

  • Calling a function before it is declared — define it above main.
  • Forgetting the return type (int) before the function name.
  • Off-by-one loop bounds.

Practice task

Make tripleIt (n * 3) and print tripleIt(i) for i = 1..5.

Hint

Change * 2 to * 3 and loop test to i <= 5.

Try it below — tests run automatically when you press Run.

cpp

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. Where must a function be relative to its use?

  2. 2. What does int before a function name mean?

  3. 3. How many passes for i=1; i<=5?

4. Example — edit and run

cpp

Output

Press Run to see output.

Expected output: 2