Practical-06
Problem Statement
Write a program using a while or for loop to print the sum of the first 100 odd and even numbers.
Solution
To solve this problem, we can use C# and demonstrate the usage of a while or for loop to calculate the sum of the first 100 odd and even numbers.
- 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 "SumOfNumbers.cs".
- Open the "SumOfNumbers.cs" file.
- Add the following code to calculate the sum of the first 100 odd and even numbers:
using System;
namespace SumOfNumbers
{
class Program
{
static void Main(string[] args)
{
int sumOfEvenNumbers = 0;
int sumOfOddNumbers = 0;
// Calculate the sum of the first 100 even numbers
for (int i = 1; i <= 200; i++)
{
if (i % 2 == 0)
{
sumOfEvenNumbers += i;
}
}
// Calculate the sum of the first 100 odd numbers
int j = 1;
while (j <= 200)
{
if (j % 2 != 0)
{
sumOfOddNumbers += j;
}
j++;
}
Console.WriteLine("Sum of the first 100 even numbers: " + sumOfEvenNumbers);
Console.WriteLine("Sum of the first 100 odd numbers: " + sumOfOddNumbers);
}
}
}
-
Save the file.
-
Build and run the project.
-
The console application will display the following output:
Sum of the first 100 even numbers: 10100
Sum of the first 100 odd numbers: 10000
This completes the solution to the problem.
Summary
In this practical, we learned how to use a while or for loop to calculate the sum of the first 100 odd and even numbers using C#.