Skip to main content

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.

  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 "SumOfNumbers.cs".
  4. Open the "SumOfNumbers.cs" file.
  5. 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);
}
}
}
  1. Save the file.

  2. Build and run the project.

  3. 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#.