You are on page 1of 4

C# LOOPING STATEMENTS ACTIVITY

FOR LOOP
Here's an example of a simple C# program that uses a for loop to calculate the factorial of a number. The factorial of
a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n.

using System;

class Program
{
static void Main()
{
Console.Write("Enter a non-negative integer: ");
int n = Convert.ToInt32(Console.ReadLine());

long factorial = 1;

for (int i = 1; i <= n; i++)


{
factorial *= i;
}

Console.WriteLine("The factorial of " + n + " is: " + factorial);


}
}

Here's how the program works:

1. The program asks the user to enter a non-negative integer.


2. It reads the input using Console.ReadLine() and converts it to an integer using Convert.ToInt32().
3. It initializes a variable factorial to 1, as the factorial of 0 is defined to be 1.
4. The for loop iterates from i = 1 to i <= n. In each iteration, it multiplies factorial by i.
5. Finally, it prints out the factorial of the entered number.

WHILE LOOP
Here's an example of a C# program that uses a while loop to simulate a simple guessing game.

using System;

class Program
{
static void Main()
{
Random random = new Random();
int targetNumber = random.Next(1, 101); // Generates a random number between 1 and 100
int attempts = 0;
int guess = 0;

Console.WriteLine("Welcome to the Guessing Game!");

while (guess != targetNumber)


{
Console.Write("Enter your guess (1-100): ");
guess = Convert.ToInt32(Console.ReadLine());
attempts++;

if (guess < targetNumber)


{
Console.WriteLine("Too low! Try again.");
}
else if (guess > targetNumber)
{
Console.WriteLine("Too high! Try again.");
}
}

Console.WriteLine("Congratulations! You guessed the number in " + attempts + " attempts.");


}
}

Here's how the program works:

1. The program generates a random number between 1 and 100 using Random.Next().
2. It initializes variables attempts (to keep track of the number of attempts) and guess (to store the user's
guess).
3. It enters a while loop that continues as long as the user's guess is not equal to the target number.
4. Inside the loop, it prompts the user to enter a guess and increments the attempts counter.
5. It then checks whether the guess is too low or too high, providing feedback to the user.
6. If the guess is correct, the loop exits, and the program congratulates the user on guessing the number and
displays the number of attempts it took.

DO WHILE LOOP
Here's an example of a C# program that uses a do-while loop to simulate a basic calculator:

using System;

class Program
{
static void Main()
{
char operation;
double num1, num2, result;

do
{
Console.WriteLine("Welcome to the Basic Calculator!");
Console.Write("Enter the first number: ");
num1 = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter the operation (+, -, *, /): ");


operation = Convert.ToChar(Console.ReadLine());
Console.Write("Enter the second number: ");
num2 = Convert.ToDouble(Console.ReadLine());

switch (operation)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0)
{
result = num1 / num2;
}
else
{
Console.WriteLine("Error: Division by zero!");
result = 0;
}
break;
default:
Console.WriteLine("Invalid operation! Please try again.");
result = 0;
break;
}

Console.WriteLine($"Result: {num1} {operation} {num2} = {result}");

Console.Write("Do you want to perform another calculation? (y/n): ");


}
while (Console.ReadLine().ToLower() == "y");
}
}

Here's how the program works:

1. The program provides a simple calculator interface and prompts the user to enter the first number.
2. It then asks for the operation (+, -, *, or /).
3. Next, it prompts the user for the second number.
4. It uses a switch statement to perform the corresponding operation based on the user's choice.
5. If the user attempts to divide by zero, it handles the error and informs the user.
6. The result of the calculation is displayed.
7. Finally, the program asks the user if they want to perform another calculation. If the user enters 'y', the loop
continues; otherwise, it exits.
FOREACH LOOP
Here's an example of a C# program that uses a foreach loop to calculate the average of a list of numbers:
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
int sum = 0;

foreach (int number in numbers)


{
sum += number;
}

double average = (double)sum / numbers.Count;

Console.WriteLine("Numbers: " + string.Join(", ", numbers));


Console.WriteLine("Sum: " + sum);
Console.WriteLine("Average: " + average);
}
}

Here's how the program works:

1. The program creates a List<int> called numbers and initializes it with a set of integers.
2. It initializes a variable sum to 0. This variable will be used to accumulate the sum of the numbers.
3. It uses a foreach loop to iterate over each element in the numbers list.
4. In each iteration, it adds the current number to the sum.
5. After the loop, it calculates the average by dividing the sum by the number of elements in the list.
6. Finally, it prints out the list of numbers, the sum, and the average.

You might also like