I get an error when accumulating the sum, I get "Local variable not assigned"

public static void BucleFor() {
    int i,numero, dato, repuesta;

    Console.WriteLine("Cantidad de numeros a sumar");
    dato = Convert.ToInt32(Console.ReadLine());

    for (i=1; i<=dato; i++)
         Console.WriteLine("introdusca el dato " + i +"a Sumar");
         numero = Convert.ToInt32(Console.ReadLine());
         repuesta = repuesta + numero;
         Console.WriteLine("la suma es :" +repuesta);

asked by Wicho Reyes 26.03.2018 в 05:30

2 answers


Although the answer of @DMG solves the problem and is totally correct, it does not explain it, that's why my answer tries to expand the information on the subject a bit.

It is necessary to differentiate between local and instance variable. An instance variable is the one that is defined at the class level. The local variable is defined at the method level.

In the question that concerns us, this difference is important, since in the case of int for example, if it is an instance variable, it is initialized to its default value, which in the case of int is 0, however if it is a local variable, its value is undefined. For example, let's see this code:

class prueba
     int i;
     public void metodo()
          int j;

This will not compile, since it will complain that the local variable j is not assigned. However, if we put int j = 0; , it will compile correctly and Console.WriteLine(i); will write a 0 , showing that the instance variable has been initialized automatically.

answered by 26.03.2018 / 09:33

only initializes the response variable

int i,numero, dato, repuesta=0;


answered by 26.03.2018 в 05:39