Tutorial Task 3rd Aprli 2024
Tutorial Task 3rd Aprli 2024
Q1. What is the difference between for loop and the for-each
loop?
For Loop:
- This is the usual type of loop used when you want to run a block of code several times.
- It uses an index, which is a way to count through each cycle of the loop. This is helpful when
you need to perform complex patterns of iteration or change the elements you are
looping through.
- Here’s how it looks (Syntax):
for (initialization; condition; update) { // code to be executed }
- Use this loop when you need to know exactly how many times the loop should run, or if you
need to adjust the counting index directly.
For-Each Loop:
- This was added to Java in version 5 to make looping simpler.
- It makes it easy to loop through items in collections or arrays without worrying about
managing the index yourself.
- For-Each Loop doesn’t allow you to change the elements of the collection or array you’re
looping through.
1
- Here’s how it looks (Syntax):
for (Type item: collection) { // code to be executed }
In summary, use the regular for loop when you need tight control over the loop, like when
specific conditions or changes are involved. Use the for-each loop for a
straightforward, easy-to-read way to go through items one by one without modifying
them.
2
Q4. Answer of Q8 in sheet 5: