Skip to main content

Practical-07

Problem Statement​

Write a program using Foreach loop.

Solution​

To solve this problem, we can use C# and demonstrate the usage of the foreach loop.

  1. Create a new C# Console Application project in Visual Studio.
  2. In the Solution Explorer, right-click on the project name and select "Add" > "Class".
  3. Name the class "ForeachLoopDemo.cs".
  4. Open the "ForeachLoopDemo.cs" file.
  5. Add the following code to demonstrate the usage of the foreach loop:
using System;

namespace ForeachLoopDemo
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };

Console.WriteLine("Printing numbers using foreach loop:");

foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
}
  1. Save the file.

  2. Build and run the project.

  3. The program will print the numbers 1, 2, 3, 4, 5 using the foreach loop.

This completes the solution to the problem.

Summary​

In this practical, we learned how to use the foreach loop in C# to iterate over an array and perform operations on its elements.