Loops and methods

What loops and methods (functions) are.

1. What is this?

A loop repeats a block: for (int i = 1; i <= 5; i++) runs with i = 1..5. A method (Java's word for function) is a reusable block: static int doubleIt(int n) takes an int, returns an int. Parameters are declared with types; return sends the value back.

2. Why do we use it?

Same logic, many inputs: totals, validations, formatting. Methods keep it in one tested place.

3. Syntax breakdown

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

    Counter i from 1 while <= 5, +1 each pass.

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

    Method taking int n, returning n*2. static lets main call it directly.

  • System.out.println(doubleIt(7));

    Calls the method with 7, prints 14.

5. Common mistakes

  • Calling a non-static method from static main without an object.
  • Off-by-one in the loop bounds.
  • Forgetting return in a non-void method.

Practice task

Change doubleIt to tripleIt (n * 3) and loop i from 1 to 5 printing tripleIt(i).

Hint

Rename and change * 2 to * 3; change loop test to i <= 5.

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

java

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. What is a method?

  2. 2. Why is doubleIt static?

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

4. Example — edit and run

java

Output

Press Run to see output.

Expected output: Call 1: 2