Let's start from the basis that there is always more than one way of doing things.
Well then having this clear you can iterate using for
or while
as you like and better apply in your code, but remember that sometimes it is more verbose to use a certain instruction.
For example, when you iterate a known number of values, the for defines a scope for the variances avoiding that by mistake it is modified outside of this
for(int i=0; i<10; i++){
Console.Write(i);
}
in this case the variable i
will only be accessible within the scope of the for
once it leaves this will not be accessible
int i=0;
while(i<10){
Console.Write(i);
i++;
}
is the same, of course, but I change the scope of the variable, which can be accessed once the while
ends
By rule when you iterate a known number of values you use the for
you need to define a more complex condition you use the while
, for example
string salir = "";
do{
//codigo
Console.WriteLine("Desea salir? yes/no :")
salir = Console.ReadLine();
}while(salir != "yes")
there if it is clear that you should use the while
, since under that condition the for
does not apply
In c # you can also iterate items from string
with foreach
string cadena = "texto de prueba";
foreach(char letra in cadena){
//codigo
}
but actually it is used more with lists and collections