Explanation for the error in the following code

Asked

Viewed 33 times

1

I started to solve the problems of the Euler project as a form 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 the multiples of 3 or 5 Below 1000.

This is the statement. I decided to personify my answer by adding a few more details to 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]);

Running the code will show only 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 9 23.

Why? Why don’t you just return the number 23?

1 answer

1

I turned your code into a Fiddle.

Notice that this:

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

Is inside the for, then it will be printed every new iteration.

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

I modified your code to:

    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

See that the answer, at the bottom corner of the screen, is 23.

Browser other questions tagged

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