In the next 2 cases I find it hard to understand the execution flow. Look at the Line marked with %%%%%%%%%%%%%%
is the line where my question is presented,
Initially I put that line out of for
but I got a output
in which only the last element of the vector repeated twice was returned. Now, although this is resolved, I could not understand why ...
This is my logic, correct me where I got lost or I was wrong, when line %%%%
is out of for
, I start entering the number 2 to generate a vector of 2, well once this is done, the for
starts % requesting me the data A.id
I continue with A.nom
ends the first round with lista[cont]=A
, OKey, starts the second, repeats everything again, only this time, the values of A
are reassigned, so when it reaches the end lista[cont]=A
the second element ( lista[1]
) has new values, and then, why does lista[0]
disappear taking the same value as lista[1]
?
Code:
int public main()
{
Console.WriteLine("ingrese cantidad de objetos");
int i =int.Parse( Console.ReadLine());
servivo[] lista = new servivo[i] ;
for (int cont = 0; cont < i; cont++)
{
servivo A = new servivo(); %%%%%%%%%%%%%%%%%%%%%%
Console.WriteLine("ing id");
A.id = Console.ReadLine();
Console.WriteLine("ing nom");
A.nom = Console.ReadLine();
lista[cont] = A;
}
Console.WriteLine("Lista de objetos");
for (int cont = 0; cont < i; cont++)
{
Console.WriteLine(lista[cont].id);
Console.WriteLine(lista[cont].nom);
}
Console.ReadKey();
}
class servivo
{
public string id;
public string nom;
public void respiro()
{ Console.WriteLine("puedo respirar"); }
}
EXAMPLE 2
int[] lista = new int[2];
int var;
for (int cont = 0; cont < 2; cont++)
{
Console.WriteLine("ingrese valor para var");
var=int.Parse(Console.ReadLine());
lista[cont] = var;
}
for (int cont = 0; cont < 2; cont++)
{
Console.WriteLine(lista[cont]);
}
Console.ReadKey();