How to split elements of an array using the For loop?

Asked

Viewed 1,018 times

3

Program Summary

Good morning, I’m developing a calculator that asks the user for the amount of numbers that will be calculated, the operation and the numbers in question. To store the values, I use a array. The code that calculates the numbers of the array is:

The Code

for (i = 0; i < arrayLength; i++) { result /= num[i]; }

Where arrayLength is the size of the array, and "result" is a variable of type double declared at 0.

Problem

*Assuming we have one array one-dimensional with 2 positions whose values are one[0] = 120 and one[1] = 5*

The problem is that when the division is executed, what is eventually calculated is: (0 / 120) / 5

Completion

I’d like to know how to go through mine array "in a" and divide the values contained in it efficiently. And if possible a way to reduce the code size.

Complete Code

static void Main(string[] args)
    {

        int arrayLength, loopCounter = 0;
        int numCounter = 1;
        int i = 0;

        double result = 0;
        string operation = "";

        Console.WriteLine("Digite a quantidade de números a serem calculados");

        arrayLength = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("\nEscolha a operação:\n\n1: Soma\n2: Subtração\n3: Multiplicação\n4: Divisão (Temp. Desativado)\n");
        operation = Console.ReadLine();

        Console.WriteLine("");

        double[] num = new double[arrayLength];

        while (loopCounter < arrayLength)
        {
            Console.Write("Digite o {0}º valor: ", numCounter);
            num[loopCounter] = Convert.ToDouble(Console.ReadLine());

            numCounter++;
            loopCounter++;

        }

        switch (operation.ToUpper())
        {
            case "1":
                for (i = 0; i < arrayLength; i++)
                {
                    result += num[i];
                }
            break;

            case "2":
                for ( i = 0; i < arrayLength; i++)
                {
                    result -= num[i];
                }
            break;

            case "3":
            result = 1;
                for (i = 0; i < arrayLength; i++)
                {
                    result *= num[i];
                }
            break;

            case "4":
                for (i = 0; i < arrayLength; i++)
                {
                    result /= num[i];
                }
            break;

            default:
            Console.WriteLine("Operação Inválida.");
            break;
        }

        Console.Write("\nO resultado é: ");

        Console.WriteLine(Math.Round(result,2));
    }
  • 1

    The same problem happens for multiplication, which cannot start at 0. It would be better to put the result as the first element of the array and do the calculations forward. Note: Watch the Length Writing Error arrayLenght which is quite common, although it does not affect the program itself.

  • @Isac Thanks for the grammar correction. Could fix my source code for better viewing?

2 answers

4


You can start the result with the first position of the array, and the loop start from the second, just a hint:

 case "4":
 {
     result = num[0];
     for (i = 1; i < arrayLength; i++)
         result /= num[i];
 }
 break;
  • 1

    I believe this should be the answer. But the only thing I would do is simplify the code by looping it directly there instead of several loops inside each switch.

  • 1

    Hello, I edited my code and now it’s working, thank you!

2

Their code has a very common feature in academic code. They are thought of to process mathematical states. Try to see how you, as a human, would do this calculation, and then rewrite.

Example: Calculate the sum of the 3 numbers: 1, 2 and 3. You don’t start like this:

Zero + 1 = 1, 1 + 2 = 3, 3 + 3 = 6

You just do:

1 + 2 = 3, 3 + 3 = 6

Now, pass the way you perform the calculation for codes:

result = num[0]; // começa já no primeiro número.
for (int i = 1; i < num.Length; i++)
     result += num[i];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.