Explanation for the error in the following code

1

I began to solve the problems of the Euler project as a way of training in learning.

  

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

     

Find the sum of all of the multiples of 3 or 5 below 1000.

This is the statement. I decided to personify my answer by adding some more details in the code.

The code is:

using System;
using System.Collections.Generic;
using System.Linq;

int[] x= new int[10];
int Tot=0;

for (int i=0; i<10; i++)
{  
    if ((i%3==0)||(i%5==0)) 
    {    
        x[i] = i;
        Console.WriteLine(x[i]);         
    }

    Console.WriteLine(Tot+=x[i]);

Executing the code, it will show only the multiples of 3 and 5 in the range 0 to 10: 3,5,6,9

When I add the sum of the array, instead of giving the total number, 23, it presents this list: 0 0 0 0 3 3 3 5 8 6 14 14 14 9 23.

Why? Why does not it only return the number 23?

    
asked by anonymous 27.05.2016 / 07:01

1 answer

1

I've turned your code into a Fiddle .

Note that this:

Console.WriteLine(Tot+=x[i]);

It is inside for , so it will be printed with each new iteration.

Another thing is that you are not assigning Tot to this line. You are only writing the result of the sum of Tot with x[i] . As you are not assigning, the result is lost.

I've modified your code for:

    int[] x= new int[10];
    int Tot=0;

    for (int i=0; i<10; i++)
    {  
        if ((i%3==0)||(i%5==0)) 
        {    
            x[i] = i;
            // Console.WriteLine(x[i]);    
            Tot += x[i]; // Aqui temos uma atribuição correta
        }
    }

    Console.WriteLine(Tot); // Fiz imprimir o resultado fora do for

Notice that the answer in the bottom corner of the screen is 23.

    
27.05.2016 / 07:12