Exercise
Repetitive Structures
Objective
Write a C# program that prompts the user for two numbers and displays the numbers between them (inclusive) three times using "for", "while", and "do while" loops.
Enter the first number: 6
Enter the last number: 12
6 7 8 9 10 11 12
6 7 8 9 10 11 12
6 7 8 9 10 11 12
Write Your C# Exercise
C# Exercise Example
using System; // Importing the System namespace to use Console functionalities
class Program
{
// Main method where the program execution begins
static void Main()
{
// Prompt the user to enter the first number
Console.Write("Enter the first number: ");
int firstNumber = int.Parse(Console.ReadLine()); // Reading the first number entered by the user
// Prompt the user to enter the last number
Console.Write("Enter the last number: ");
int lastNumber = int.Parse(Console.ReadLine()); // Reading the last number entered by the user
// Using a for loop to display numbers from firstNumber to lastNumber
Console.WriteLine("Using for loop:");
for (int i = firstNumber; i <= lastNumber; i++) // Loop runs from firstNumber to lastNumber
{
Console.Write(i + " "); // Display the current number
}
Console.WriteLine(); // Move to the next line after printing the numbers
// Using a while loop to display numbers from firstNumber to lastNumber
Console.WriteLine("Using while loop:");
int j = firstNumber; // Initialize the counter for the while loop
while (j <= lastNumber) // Loop runs while j is less than or equal to lastNumber
{
Console.Write(j + " "); // Display the current number
j++; // Increment the counter
}
Console.WriteLine(); // Move to the next line after printing the numbers
// Using a do-while loop to display numbers from firstNumber to lastNumber
Console.WriteLine("Using do-while loop:");
int k = firstNumber; // Initialize the counter for the do-while loop
do
{
Console.Write(k + " "); // Display the current number
k++; // Increment the counter
}
while (k <= lastNumber); // Loop continues while k is less than or equal to lastNumber
Console.WriteLine(); // Move to the next line after printing the numbers
}
}