How to multiply all values in an array?
Asked Answered
H

3

10

I have an assignment where I need to find the product of all of the numbers in an array, I'm not sure how to do this.

    int[] numbers = new int[SIZE];

    Console.WriteLine("Type in 10 numbers");
    Console.WriteLine("To stop, type in 0");
    for (int input = 0; input < SIZE; input++)
    {
        userInput = Console.ReadLine();
        numberInputed = int.Parse(userInput);

        if (numberInputed == ZERO)
        {
            numberInputed = ONE;
            break;
        }
        else
        {
            numbers[input] = numberInputed;
        }

    }

This is where I'm trying to find the product of all of the numbers in the array.

    foreach (int value in numbers)
    {
        prod *= value;
    }

    Console.WriteLine("The product of the values you entered is {0}", prod);

What am I doing wrong in the foreach statement? Thanks in advance

Edit, left out my declared values

    const int SIZE = 10;
    const int ZERO = 0;
    string userInput;
    int numberInputed;
    int prod = 1;

It now works when I type in all ten values but if I put a 0 in order to break the loop then everything equals 0. How do I prevent a 0 from being entered into the array?

Hainaut answered 21/11, 2013 at 22:2 Comment(1)
What's going wrong with your code?Cardioid
L
32

It's possible you initialize prod to 0, which means no matter what numbers are in your array, prod will remain 0. Make sure you initialize it to 1 to get the correct result:

int prod = 1;
foreach (int value in numbers)
{
    prod *= value;
}

You could also use Linq's Aggregate extension method to do the same thing:

using System.Linq; // put with other using directives

int prod = numbers.Aggregate(1, (a, b) => a * b);

Update

The real problem (which I failed to notice before) is that your array isn't being fully populated if you break out of your loop early. So any array entries you didn't set are still initialized to 0. To fix this, use a List<int> instead of an int[]:

using System.Collections.Generic; // put with other using directives

List<int> numbers = new List<int>(SIZE); // Capacity == SIZE

...

for (int input = 0; input < SIZE; input++)
{
    ...
    if (numberInputed == ZERO)
    {
        break;
    }
    else
    {
        numbers.Add(numberInputed);
    }
}
Leopoldeen answered 21/11, 2013 at 22:4 Comment(14)
+1. You always manage to provide more than one way of doing things. Kudos :)Interject
Sorry, I updated my post with the declared values. I did have prod equal 1. I tried your method but I get a "Error 1 'System.Array' does not contain a definition for 'Aggregate' and no extension method 'Aggregate' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)" errorHainaut
using System.Linq; <-- You need to add this, OP.Runge
@Hainaut Are you sure that you didn't declare a local variable named prod that hides the class member? Also to use Aggregate, make sure you include using System.Linq at the top of your file.Leopoldeen
Not sure what you mean unfortunately, I just have int prod = 1; Where would I add the System.Linq? Right now I have using System;Hainaut
@Hainaut Just put using System.Linq; immediately after using System;Leopoldeen
Awesome that worked. I found another issue I can't figure out. It seems like it works perfectly unless I have the user enter a 0 to break the loop. I can't seem to prevent that 0 from being added to the loopHainaut
@Hainaut Yes, I just noticed that issue as well. See my updated answerLeopoldeen
So I copy the List<int> numbers = new List<int>(SIZE); over my int[] numbers = new int[SIZE];? It gives me another error, "The type of namespace name 'List' could not be found"Hainaut
@Hainaut Include using System.Collections.Generic; along with the other using statements.Leopoldeen
Awesome that works. Is it recommended to always have those extra using System. at the beginning?Hainaut
@Hainaut Typically you should avoid having any unnecessary using's. If you happen to use Visual Studio, you can right-click > 'Organize Usings' > 'Remove and Sort' to clean them up. That said, I usually keep using System; even if it's not necessary, just out of habit.Leopoldeen
why did u call it prodGrotesque
@Grotesque short for product -- i.e. the result of multiplication. Also this is OP's code was written as well.Leopoldeen
F
1

The problem is that you don't keep track of how many items there are in the array that actually are assigned a value. If you exit from the loop using a zero input, then the rest of the items are unchanged. As they are zero by default, you will be using those zeroes in your second loop, and when you have a zero somewhere in the array, the total product becomes zero.

Keep track of how many items there are by keeping the loop variable outside the loop:

int input = 0;
while (input < SIZE)
{
    userInput = Console.ReadLine();
    numberInputed = int.Parse(userInput);
    if (numberInputed == ZERO) {
      break;
    }
    numbers[input] = numberInputed;
    input++;
}

Now you can use only the items that are actually assigned:

for (int i = 0; i < input; i++) {
    prod *= numbers[i];
}
Fungosity answered 21/11, 2013 at 22:21 Comment(0)
H
0

Multiply all numbers inside an Array

int[] array = { 1, 2, 3, 4, 5 };
int sum = array[0];
for (int i = 1; i != array.Length; i++)
{
    sum *= array[i];
}

If your array is somehow populated with zeroes (0), then use List instead of an array.

Hangbird answered 8/5, 2020 at 22:26 Comment(1)
Your loop is correct, ArrayFormula, but it is not an answer to the question. There is no fixed number of elements.. the number of elements is decided by the user, by inputting a "0" for the last item.Pert

© 2022 - 2024 — McMap. All rights reserved.