gx15
gx15

Reputation: 79

When input is 0 stop taking values

I need code, that takes inputs from user and then adds them together-simple. But I can't find a way, to take inputs until 0 is pressed and than add the numbers together.. So far, I made it take 10 values, but like I said it needs to be custom.. Thanks for your help.

int[] myarray = new int[10];
for (int i = 0; i < 10; i++)
{
    myarray[i] = Convert.ToInt32(Console.ReadLine());
}

int a = 0;
for (int j = 0; j < 10; j++)
{
    a = a + myarray[j];
}

Console.WriteLine(a);
Console.ReadLine();

Upvotes: 2

Views: 924

Answers (5)

webdevduck
webdevduck

Reputation: 593

As you don't know the length of the array, I'd recommend using a list. I've also added a tryparse to cope with dodgy user input. You can use Sum() on the list to avoid writing out another loop.

        IList<int> myList = new List<int>();
        string userInput = "";
        int myInt = 0;

        while (userInput != "0")
        {
            userInput = Console.ReadLine();
            if(Int32.TryParse(userInput, out myInt) && myInt > 0)
            {
                myList.Add(myInt);
            }
        }

        Console.WriteLine(myList.Sum());
        Console.ReadLine();

Upvotes: 1

R&#233;mi
R&#233;mi

Reputation: 3967

You could use something like this :

while(true)
{
    int input = Convert.ToInt32(Console.ReadLine());
    if(input == 0)
        break;

    //do you math here
}

Upvotes: 0

Matan Shahar
Matan Shahar

Reputation: 3240

When you have an unknown size array you should use a list.

var ls = new List<int>();

    while(true)
    {
        var input = Convert.ToInt32(Console.ReadLine());
        if(input == 0) 
            break;

        ls.Add(input);
    }

Lists by MSDN

Upvotes: 0

Sarwar Erfan
Sarwar Erfan

Reputation: 18068

The code below is not limited to 10 inputs, you can give as many input as you like

int sum=0, input;
do
{
    input = Convert.ToInt32(Console.ReadLine());
    sum += input;
}
while(input != 0);

Console.WriteLine(sum);
Console.ReadLine();

Upvotes: 6

Oded
Oded

Reputation: 499012

Check the input before adding it, and break out of the loop if it is 0:

int input = Convert.ToInt32(Console.ReadLine());
if(input == 0) 
{
  break;
}

myarray[i] = input;

Upvotes: 2

Related Questions