Start learning free

LESSON 153 OF 674 · WHILE LOOPS & FOR LOOPS

For Loops: Printing Numbers II in C#

Lesson

Let's see an example where we change the iteration statement.

We can print all even numbers from 2 through 10:

for (int i = 2; i <= 10; i += 2) {
	Console.WriteLine(i);
}

The output of this code is:

2
4
6
8
10

Let's break down this code:

  • The initialization statement is int i = 2, so we start iterating from number 2.

  • The condition statement is i <= 10 so we end at number 10. We could've written i < 11 and it would still be correct.

  • The iteration statement is i += 2, so we increase our number by 2 every time.


Assignment

Let's print all odd numbers from 7 through 23 using a for loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check