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 is a reusable block: static int DoubleIt(int n) takes an int and returns an int. PascalCase (DoubleIt) is the C# convention for methods.

2. Why do we use it?

One tested method, called everywhere: pricing, validation, formatting.

3. Syntax breakdown

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

    Method declaration: returns int, takes int n.

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

    Loop counter from 1 while <= 3.

  •   System.Console.WriteLine(DoubleIt(i));

    Calls the method each pass.

5. Common mistakes

  • Forgetting return in a non-void method.
  • Calling a non-static method from static Main.
  • Off-by-one bounds.

Practice task

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

Hint

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

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

csharp

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. What is a method?

  2. 2. C# method naming convention?

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

4. Example — edit and run

csharp

Output

Press Run to see output.

Expected output: 2