Hello all,

I am working through Beginning Microsoft Visual C# 2008 I was asked to create a console application that multiplies 4 input values. I decided to take all 4 values at once and multiply them. Here is my code:

            string inputNumbers;
            string userName;
            Console.WriteLine("Enter your name:");
            userName = Console.ReadLine();
            Console.WriteLine("Welcome {0}!", userName);
            Console.WriteLine("Now give me 4 numbers seperated by a space:");
            inputNumbers = Console.ReadLine();
            string[] numbers = inputNumbers.Split(' ');


            Console.WriteLine("The product of {0} * {1} * {2} * {3} is {4}.", 
                numbers[0], 
                numbers[1], 
                numbers[2], 
                numbers[3], 
                Convert.ToDouble(numbers[0]) * Convert.ToDouble(numbers[1]) * Convert.ToDouble(numbers[2]) * Convert.ToDouble(numbers[3])
                );

Is there an easier way to do the converts in a loop somehow, or an easier way in general of achieving the same result?

Edited 2 Years Ago by pritaeas: Moved to C#

It's C# so this is the best place for it.

This is the only way I can think to do it using a loop...

double Total = Convert.ToDouble(numbers[0]);

for (int i = 1; i < numbers.Count(); i++)
{
    Total = Total * Convert.ToDouble(numbers[i]);
}

It would be the best way if you have a lot of numbers or the amount of numbers would change but if you only have a constant amount of about 4 or less number the way you have done it is good.

Edited 2 Years Ago by ChrisHunter

I'd go with a loop as well. You could do it using more advanced methods, but since this exercise is at the beginner level, it's better to keep things simple.

You could use the

ConsoleKeyInfo

class and the

ConsoleKey

struct. Put them in a do while loop and you should be able to manage your code with spaces after the number input. Don't forget to combine them with the Console.Read() or .ReadLine() methods...

This article has been dead for over six months. Start a new discussion instead.