Omitir el primer parámetro en el bucle for

In PHP, Java, C++ (and many other languages), for loops are used like this:

for(int i=0;i<10;i++)

If I already initialized i, how can I omit the initialization statement?

preguntado el 10 de marzo de 12 a las 02:03

Just leave it out.. ; is a valid statement in java and co. -

Or write it as while( i++ < 10 ) -

They aren't parameters. The first and third are statements; the second is a condition. The null statement is legal in Java. -

4 Respuestas

In Java, C++ and PHP it is completely valid to omit the initialization portion of the for loops

int i = 0;
for(; i < 10; i++);

This is true of most languages which have a for estructura de bucle

respondido 10 mar '12, 02:03

@Michael thanks for the clarification. Don't use PHP enough to say for certain off hand and was looking up the syntax. - jaredpar

for(; i < 10; i++) {

You can leave out any of the items in the for loop if they are not needed. You could also put in multiple things to do, or multiple conditions to check such as:

int j = 40;
for(int i = 0; i < 10 || j > 30; i++, j--) {}

respondido 10 mar '12, 02:03

I think for C++, PHP you could just do this. Not sure of the syntax for other languages. You could do the same with a while statement if you want to declare outside the loop.


respondido 10 mar '12, 02:03

Don't forget that, if you have an array to iterate and don't want to use the standard "for", you can always use "foreach ($array as $var)" (on PHP) or the other "for ( X : )" on Java :)

respondido 10 mar '12, 03:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.