An iteration structure is a structure that groups code statements, these statements are executed over and over again until x condition becomes false.
1.while
1.1 Syntax
while(condicion){
... // sentencias
}
1.2 Description
The while control structure receives a parameter called condicionthat will be evaluated at the start of each iteration. condicionis a boolean value , this means that it can only contain two values trueor false. If at any time the condicionloop falsereturns ( loop) it will end.
The loop ends the first time condicionit becomes false.
1.3 Example #1
int i = 0;
while(i < 11) {
System.out.println(i);
i++;
}
In the previous loop, the condition is i < 11, initially i = 0so when it is evaluated in the condition i < 11it contains the value true, therefore the structure continues to execute the statements contained in it, When executing i++in the first iteration the value of ichanges, now i = 1, the structure repeats the previous process for this new value, it is evaluated iwithin the expression , if it icontains truethen it proceeds to execute i++.
Q: Until when does the loop end?
A : Until i >= 11, this means that the loop ends when i = 11since it i
increments to a step of 1, i++it has been executed a total of 11times.
The control structure for, contrary to while, is segmented into 3 parts, variablesit is a space designated for the declaration of local variables that will be accessible only within the structure. condicionit is interpreted the same as in the structure while, finally it instruccionesis a space designated to place statements that will be executed after an iteration
The loop ends the first time condicionit becomes false.
In the above example, two local variables are created iand j, both of type int, with initial values i = 0, j = 10, the condition is the same as example #1 . After executing the statement , the and statements that increase the value of and decrease the value of respectively System.out.println(i + "," + j);will be executed .i++j--ij
Program output:
0,10
1,9
2,8
3,7
4,6
5,5
6,4
7,3
8,2
9,1
10,0
3. Conversion between iteration structures
3.1 fortowhile
This conversion is undoubtedly the simplest of all (straightforward)
The explanation is simple, the variables will be declared before, the expression to be evaluated is the same, finally the post-iteration statements are added to the statements at the end of the structure.
if you have a whileof the form described above, the conversion to foris easy. the variables used within the while are first located, 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);
}
answering
Is while better for a short loop?
It will depend mainly on the structure of the while, remembering that whileand forare totally equivalent, the choice of one will not affect the functionality of the code, however the choice of one over the other will make the code more readable, that is, easier to read.
For example the whileone in example #1 , the equivalent in forresulted in better code.
However the followingwhile
while(buffer.nextChar()!= EOF){
...
}
Its equivalent in forworsens code readability
for(;buffer.nextChar()!= EOF;){
...
}
What is the difference between switch, for and while?
forand whileare iteration structures.
switchis a selection structure, very similar to several ifnested 's , I won't go into details since it was already answered by Quidi90
This Whileis often called a "condition loop", that is, the programmer does not know how many times the loop is going to execute and it will simply continue when the condition imposed on the loop ends.
On the other hand, Forit 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 be executed.
I start by explaining the switch. Unlike the other 2, it does not perform any type of loop, it 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 day variable to perform the switch. If its value is 'Monday', one will be added to the counter variable. If it is 'Wednesday', 3 will be added. 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 through it until the end unless you find a break . On the other hand, if none of the other values are valid, there is the default case (which is not mandatory), it would be like the else of the switch.
On the other hand, while and for are used to make loops. The difference is that for is specialized (optimized) to perform loops of the type I need an index, that a condition is met, and do something with that index. Therefore, whenever the structure of a for is fulfilled (regardless of the length to go through) the for should be used.
Iteration Structure
An iteration structure is a structure that groups code statements, these statements are executed over and over again until x condition becomes false.
1.
while
1.1 Syntax
1.2 Description
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 valuestrue
orfalse
. If at any time thecondicion
loopfalse
returns (loop
) it will end.1.3 Example #1
In the previous loop, the condition is
i < 11
, initiallyi = 0
so when it is evaluated in the conditioni < 11
it contains the valuetrue
, therefore the structure continues to execute the statements contained in it, When executingi++
in the first iteration the value ofi
changes, nowi = 1
, the structure repeats the previous process for this new value, it is evaluatedi
within the expression , if iti
containstrue
then it proceeds to executei++
.i >= 11
, this means that the loop ends wheni = 11
since iti
increments to a step of1
,i++
it has been executed a total of11
times.Program output:
two.
for
2.1 Syntax
2.2 Description
The control structure for, contrary to while, is segmented into 3 parts,
variables
it is a space designated for the declaration of local variables that will be accessible only within the structure.condicion
it is interpreted the same as in the structurewhile
, finally itinstrucciones
is a space designated to place statements that will be executed after an iteration2.3 Example #2
In the above example, two local variables are created
i
andj
, both of typeint
, with initial valuesi = 0
,j = 10
, the condition is the same as example #1 . After executing the statement , the and statements that increase the value of and decrease the value of respectivelySystem.out.println(i + "," + j);
will be executed .i++
j--
i
j
Program output:
3. Conversion between iteration structures
3.1
for
towhile
This conversion is undoubtedly the simplest of all (straightforward)
It is equivalent to
The explanation is simple, the variables will be declared before, the expression to be evaluated is the same, finally the post-iteration statements are added to the statements at the end of the structure.
Example : Conversion of example #2
3.2
while
tofor
Contrary to the conversion of
for - while
, the conversionwhile - for
is not so obvious, since the transformationIn
It is not very useful and results in semantic losses. But not everything is bad, luckily, it was previously discovered that
It is equivalent to
if you have a
while
of the form described above, the conversion tofor
is easy. the variables used within the while are first located, then the final transformations to those same variables.Example : Conversion of example #1
answering
It will depend mainly on the structure of the
while
, remembering thatwhile
andfor
are totally equivalent, the choice of one will not affect the functionality of the code, however the choice of one over the other will make the code more readable, that is, easier to read.For example the
while
one in example #1 , the equivalent infor
resulted in better code.However the following
while
Its equivalent in
for
worsens code readabilityfor
andwhile
are iteration structures.switch
is a selection structure, very similar to severalif
nested 's , I won't go into details since it was already answered by Quidi90This
While
is often called a "condition loop", that is, the programmer does not know how many times the loop is going to execute and it will simply continue when the condition imposed on the loop ends.On the other hand,
For
it 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 be executed.I start by explaining the switch. Unlike the other 2, it does not perform any type of loop, it is more like a succession of if.
In this case we use the day variable to perform the switch. If its value is 'Monday', one will be added to the counter variable. If it is 'Wednesday', 3 will be added. 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 through it until the end unless you find a break . On the other hand, if none of the other values are valid, there is the default case (which is not mandatory), it would be like the else of the switch.
On the other hand, while and for are used to make loops. The difference is that for is specialized (optimized) to perform loops of the type I need an index, that a condition is met, and do something with that index. Therefore, whenever the structure of a for is fulfilled (regardless of the length to go through) the for should be used.
When to use
FOR
?for
is used when the end of the iteration is known example:When to use WHILE?
while is used when it is not known when the iteration has finished, example:
note that
n
it is being modified , this is key to understand and differentiate when to usefor
orwhile
Analyzing the code above:
When to use Switch?
swith is used to match the value of a variable with cases and also that the cases have to be finite:
example: the months of the year
Is while better for a short loop?
NO, a loop is supposed to be short when the end is actually known , so it is 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 deals with exponential iterationsconclusion: it is not the same to use for and while in any case, because it would be killing a fly with a bomb :)