Question

I've got the base code done, and it is generating 20 random numbers, but now I am trying to add all the odd numbers and display the sum at the bottom. My problem is I don't know how to accomplish this.

Please keep your code simple and explain it in a way so I can understand it.

Random rnd = new Random();
Console.WriteLine("\n20 random integers from 1 to 10:");
for (int X = 1; X <= 20; X++)
{
    int y = rnd.Next(1, 10);
    if (y % 2 == 1)
    {
        // Add all the odd # and display sum.
        // No clue, LOL.
    }
    else
    {
    }
    Console.WriteLine("{0}", y);
}
Console.ReadLine();
Was it helpful?

Solution

Create a variable to store the sum and add to it whenever you find an odd number:

int sum = 0;
for (int X = 1; X <= 20; X++)
{
    int y = rnd.Next(1, 10);
    if (y % 2 == 1)
    {
        sum += y; // sum = sum + y;
    }

    Console.WriteLine("{0}", y);
}

Console.WriteLine("sum: {0}", sum);

OTHER TIPS

Random rnd = new Random();
int sumOdd = 0;
Console.WriteLine("\n20 random integers from 1 to 10:");
for (int X = 1; X <= 20; X++)
{
    int y = rnd.Next(1, 10);
    if (y % 2 == 1)
    {
    sumOdd += y;
    //add all the odd # and display sum
    // no clue lol
    }
    else
    {
    }
    Console.WriteLine("{0}", y);
}
Console.WriteLine("Sum is {0}", sumOdd);
Console.ReadLine();

You are almost done just you need to create sum variable and add the odd numbers into sum variable inside if block

Try This:

        Random rnd = new Random();
        int sum=0;
        Console.WriteLine("\n20 random integers from 1 to 10:");
        for (int X = 1; X <= 20; X++)
        {
            int y = rnd.Next(1, 10);
            if (y % 2 == 1)
            sum+=y;                

            Console.WriteLine("{0}", y);
        }
        Console.ReadLine("sum is ="+sum);
        Console.ReadLine();

Here is the LINQ approach if you like to prefer:

int[] numbers = new int[20];
Random rnd = new Random();
var sum = numbers.Select(x => rnd.Next(1, 10))
          .Where(number => number % 2 != 0)
          .Sum();

To be simplest than possible, i would do some like this. See:

    for (int i = 1; i <= 20 / 2; i++)
    {
        System.Console.WriteLine(i * 2);
    }

I am not doing any test, just taking the even numbers from 1 to 20. To get the odd, you could do -1 at that list.

for (int i = 1; i <= 20 / 2; i++)
{
    System.Console.WriteLine((i * 2) - 1);
}

So to generate the Random for 20 times of odd numbers you could do this:

int sum = 0;
for (int X = 1; X <= 20; X++)
{
    int y = (rnd.Next(1, 10 / 2) * 2) - 1; // the number allways will be generated and odd.
    sum += y;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top