← Back

Activity 2.9 For Loops


Introduction

C# offers several loop constructs to facilitate iteration. While the while loop is versatile enough to handle most iterative tasks, other loops can sometimes achieve the same results with more efficient code.

One such loop is the for loop. Although it shares similarities with the while loop, its structure is distinct. A for loop consists of three main components, aside from the for keyword and the code block:

Example: Count up from 1 to 10 with a for loop

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

Example: Count down from 10 to 1 with a for loop

for (int i = 10; i >= 1; i--)
{
  Console.WriteLine(i);
}

Example Video

While loop vs For loop

Skills to Practice


Instructions

Setup

  1. Create a new C# console application. Name the project 2.9 For Loops.
  2. Click Create.

Code

Console.WriteLine("--- Demo 1 - Counting Multiples ---");

Console.Write("Choose a number: ");
int number = Convert.ToInt32(Console.ReadLine());
int sum = number; // Sum keeps track of current multiple

Console.Write($"How many multiples of {number} would you like listed? ");
int length = Convert.ToInt32(Console.ReadLine());

for (int i = 0; i < length; i++)
{
    Console.Write(sum + " "); // Count horizontally
    sum = sum + number;
}

Console.WriteLine("\nPress Enter to continue.\n");
Console.ReadLine();

Console.WriteLine("--- Demo 2 - Square Tables ---");

Console.Write("How many numbers would you like displayed? ");
int num = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("\nNumber\tSquare");
Console.WriteLine("----------------");

// Use a for loop to print numbers 1 to 10 and their squares
for (int i = 1; i <= num; i++)
{
    Console.WriteLine($"{i}\t{i * i}");
}

Debug

--- Demo 1 - Counting Multiples ---
Choose a number: 3
How many multiples of 3 would you like listed? 5
3 6 9 12 15
Press Enter to continue.


--- Demo 2 - Square Tables ---
How many numbers would you like displayed? 7

Number  Square
----------------
1       1
2       4
3       9
4       16
5       25
6       36
7       49

Tips, Tricks, and Reflection