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.
- Create a new C# Console Application project in Visual Studio.
- In the Solution Explorer, right-click on the project name and select "Add" > "Class".
- Name the class "ForeachLoopDemo.cs".
- Open the "ForeachLoopDemo.cs" file.
- 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);
}
}
}
}
-
Save the file.
-
Build and run the project.
-
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.