Java Basics - Loops 1
While Loops
While loops are continuous loops that repeat as long as a condition stays true.
For Example:
while(x<5){
//execute some code here
x++:
}
_______________________________
For Loops
for(int i=1; i<5; i++)
{
//write code here
}
Section 1: Intialize loop counter at value;
Section 2: The condition to continue looping
Section 3: What to to the loop counter every cycle
Now.
Lets run through the following for loop below
for(int i=1; i<=5; i++)
{
//run code here
}
Note we only increment at the end of the loop.
for(int i=1; i<=5; i++)
{
//run code here
//increment i by 1 here at the end of the loop here.
}
__________________________________
Short notes on incrementing etc.
i=i-1 is the same as i--;
i=i+1 is the same as i++;
i=i+5 is the same as i +=5
i=i-6 is the same as i -=6
i=i*3 is the same as i*=3
i= i/2 is the same as i/=2
__________________________________
Ending the loop before it reaches its conditions
To do this we can use the word break;
__________________________________
While loops are continuous loops that repeat as long as a condition stays true.
For Example:
while(x<5){
//execute some code here
x++:
}
_______________________________
For Loops
for(int i=1; i<5; i++)
{
//write code here
}
Section 1: Intialize loop counter at value;
Section 2: The condition to continue looping
Section 3: What to to the loop counter every cycle
Now.
Lets run through the following for loop below
for(int i=1; i<=5; i++)
{
//run code here
}
i
|
Is i<=5?
|
Step into loop again?
|
1
|
1<=5 (true)
|
Yes
|
2
|
2<=5 (true)
|
Yes
|
3
|
3<=5 (true)
|
Yes
|
4
|
4<=5 (true)
|
Yes
|
5
|
5<=5 (true)
|
Yes
|
6
|
6<=5 (false)
|
No
|
Note we only increment at the end of the loop.
for(int i=1; i<=5; i++)
{
//run code here
//increment i by 1 here at the end of the loop here.
}
__________________________________
Short notes on incrementing etc.
i=i-1 is the same as i--;
i=i+1 is the same as i++;
i=i+5 is the same as i +=5
i=i-6 is the same as i -=6
i=i*3 is the same as i*=3
i= i/2 is the same as i/=2
__________________________________
Ending the loop before it reaches its conditions
To do this we can use the word break;
__________________________________
Comments
Post a Comment