Question on the Odd-Even Numbers 1 to 10 program in c#
- 1. Print all even numbers from 1 to 10
- 2. Print the sum of all odd numbers from 1 to 10
- 3. Print all numbers from 1 to 10 that are divisible by 3
Explanation:
- Even Numbers: The program uses a
for
loop to iterate through numbers from 1 to 10. It checks if a number is even usingi % 2 == 0
and prints it if true. - Sum of Odd Numbers: The program calculates the sum of odd numbers by checking if a number is odd using
i % 2 != 0
and adding it to thesumOfOdds
variable. - Numbers Divisible by 3: The program checks each number from 1 to 10 to see if it's divisible by 3 using
i % 3 == 0
and prints it if true.
Example,
class EvenOddNumber
{
static void Main()
{
// 1. Print all even numbers from 1 to 10
Console.WriteLine("Even numbers from 1 to 10:");
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
Console.WriteLine(i);
}
}
// 2. Print the sum of all odd numbers from 1 to 10
int sumOfOdds = 0;
for (int i = 1; i <= 10; i++)
{
if (i % 2 != 0)
{
sumOfOdds += i;
}
}
Console.WriteLine($"\nSum of all odd numbers from 1 to 10: " + sumOfOdds);
// 3. Print all numbers from 1 to 10 that are divisible by 3
Console.WriteLine("\nNumbers from 1 to 10 divisible by 3:");
for (int i = 1; i <= 10; i++)
{
if (i % 3 == 0)
{
Console.WriteLine(i);
}
}
}
}
Oput put look like:
Even numbers from 1 to 10:
2
4
6
8
10
Sum of all odd numbers from 1 to 10: 25
Numbers from 1 to 10 divisible by 3:
3
6
9