Page 338 - CITS - Computer Software Application -TT
P. 338
COMPUTER SOFTWARE APPLICATION - CITS
}
}
Output:
The sum of first 10 natural numbers is 55
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop,
we don’t need to update the loop variable. The syntax to use the for-each loop in java is given below.
for(data_type var : array_name/collection_name){
//statements
}
Consider the following example to understand the functioning of the for-each loop in Java.
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {“Java”,”C”,”C++”,”Python”,”JavaScript”};
System.out.println(“Printing the content of the array names:\n”);
for(String name:names) {
System.out.println(name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
Java while loop
The while loop is also used to iterate over the number of statements multiple times. However, if we don’t know
the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and
increment/decrement doesn’t take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition
is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
The syntax of the while loop is given below.
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
325
CITS : IT&ITES - Computer Software Application - Lesson 85 - 93