I have these little questions about loops
in java
.
- What is the difference between
for
andwhile
? - Is the
while
better for a short loop?
I have these little questions about loops
in java
.
for
and while
? while
better for a short loop? An iteration structure is a structure that groups code sentences, said statements are executed again and again until x condition becomes false.
while
while(condicion){
... // sentencias
}
The while control structure receives a parameter called condicion
that will be evaluated at the start of each iteration. condicion
is a Boolean value, this means that it can only contain two values true
or false
. If at any time condicion
becomes false
the loop ( loop
) will end.
The loop ends the first time that
condicion
becomesfalse
.
int i = 0;
while(i < 11) {
System.out.println(i);
i++;
}
In the previous loop, the condition is i < 11
, initially i = 0
so when evaluating it in condition i < 11
it contains the value true
therefore the structure continues to execute the sentences contained in it , When executing i++
in the first iteration the value of i
changes, now i = 1
, the esctrucutra repeats the previous process for this new value, i
is evaluated within the expression, if i
contains true
then proceed to execute i++
.
i >= 11
, this means that the loop ends when i = 11
since i
increments to a step of 1
, i++
was executed a total of 11
times. Program output:
0
1
2
3
4
5
6
7
8
9
10
for
for(variables ; condicion ; instrucciones){
... // sentencias
}
The for control structure, contrary to while, is segmented into 3 parts, variables
is a designated space for the declaration of local variables that will be accessible only within the structure. condicion
is interpreted the same as in the structure while
, finally instrucciones
is a space designed to place sentences that will be executed after an iteration
The loop ends the first time that
condicion
becomesfalse
.
for(int i = 0, j = 10 ; i < 11 ; i++ , j--){
System.out.println(i + "," + j);
}
In the previous example, two local variables i
and j
are created, both of type int
, with initial values i = 0
, j = 10
, the condition is the same as example # 1. After executing the System.out.println(i + "," + j);
statement, the statements i++
and j--
that increase the value of i
and decrement the value of j
respectively will be executed.
Program output:
0,10
1,9
2,8
3,7
4,6
5,5
6,4
7,3
8,2
9,1
10,0
for
to while
This conversion is undoubtedly the simplest of all (straightforward)
for(variables ; condicion ; instrucciones){
... // sentencias
}
It is equivalent to
variables;
while(condicion){
... // sentencias
instrucciones;
}
The explanation is simple, the variables were declared before, the expression to be evaluated is the same, finally the sentences are added the post-iteration sentences at the end of the structure.
Example: Conversion of example # 2
for(int i = 0, j = 10 ; i < 11 ; i++ , j--){ System.out.println(i + "," + j); }
int i = 0,
j = 10;
while(i < 11){
System.out.println(i + "," + j);
i++;
j--;
}
while
to for
Contrary to the conversion of for - while
, the conversion while - for
is not so obvious, since the transformation
while(condicion){
... // sentencias
}
In
for(; condicion ;){
... // sentencias
}
It is not very useful and results in semantic losses. But not everything is bad, luckily, it was previously discovered that
variables;
while(condicion){
... // sentencias
instrucciones;
}
It is equivalent to
for(variables ; condicion ; instrucciones){
... // sentencias
}
If you have a while
as described above, the conversion to for
is simple. the variables used within the while are located first, then the final transformations to those same variables.
Example: Conversion of example # 1
int i = 0; while(i < 11) { System.out.println(i); i++; }
for(int i = 0; i < 11 ; i++){
System.out.println(i);
}
Is the while better for a short loop?
It will depend mostly on the structure of while
, remembering that while
and for
are totally equivalent, the choice of one will not affect the functionality of the code, however the choice of one over another, will make the code more readable, that is, easier to read.
For example, the while
of example # 1, the equivalent in for
resulted in a better code.
Notwithstanding the following while
while(buffer.nextChar()!= EOF){
...
}
Its equivalent in for
worsens the readability of the code
for(;buffer.nextChar()!= EOF;){
...
}
What is the difference between switch, for and while?
for
and while
are iteration structures.
switch
is a structure of selection, very similar to several if
's nested, I will not go into details since it was already answered by Quidi90
The While
is usually called "condition loop", that is, the programmer does not know how many times the loop is going to be executed and it will simply continue when the condition imposed in the loop ends.
On the other hand the For
is a control loop with which the developer repeats the loop a certain number of times in which the developer knows how many or at least approximately how many times it will run.
I start by explaining the switch. Unlike the other 2 does not make any kind of loop is more like a succession of if.
switch(day) {
case 'lunes':
contador++;
break;
case 'martes':
contador += 2;
case 'miercoles':
contador += 3;
break;
case 'default':
contador = 2;
break;
}
In this case we use the variable day to make the switch. If its value is 'Monday' one will be added to the counter variable. If it is' Wednesday 'it will be added 3. On the other hand, if it is' Tuesday, 5 will be added, because there is no break instruction and once you enter the switch, you go to the end unless you find a break. . On the other hand, if none of the other values is valid, there is a default case (which is not mandatory), it would be like the else of the switch.
On the other side while and for serve to make loops. The difference is that for is specialized (optimized) to make loops of the type I need an index, that a condition is met and I do something with that index. Therefore, whenever the structure of a for is fulfilled (regardless of the size to be traversed) the for. Should be used.
When to use FOR
?
for
is used when you know the end of the iteration
example:
for(int i=0; i<100; i++){
***notese que 'i' no puede ser modificado, si se modifica ocasionara errores de ejecucion***
}
analyzing in code above,
i starts at 0
i will travel up to 100 (we know where the loop will end)
When to use WHILE?
while used when you do not know when the iteration is finished example:
while(n%2==0){
n=((n*100)/3)+5;
}
note that n
is being modified , this is key to understanding and differentiating when using for
or while
analyzing the code above:
The while loop depends on the variable
n
.-- >while(n%2==0){
variable
n
is changing value - >n=n/10;
for that reason not you know when it's over, and that will depend on the value of n .therefore the calculations could be made exponential.
When to use Swith?
swith is used to match the value of a variable with cases and also the cases have to be finite:
example: the months of the year
switch(mes) {
case 'enero':
//hacer algo
break;
case 'febrero':
//hacer algo
break;
case 'marzo':
//hacer algo
break;
.
.
.
//etc hasta diciembre
}
Is the while better for a short loop?
NO, a loop is supposed to be short when you know the end of done , so it's convenient to use for
Extra information:
The execution time of for
(for simple, not nested) is n
the execution time of while is greater than "n" since it is exponential iterations
conclusion: it is not the same to use for and while in any case, because it would be to kill a fly with a bomb:)