Note: In an entry-controlled loop, first the test expression is evaluated and if it is non-zero, the body of the loop is executed; if the test expression evaluates to be zero, the loop is terminated. In an exit-controlled loop, the body of the loop is executed first, and then the test expression is evaluated. If it evaluates to be zero, the loop is terminated, otherwise repeated.
The for loop is the easiest to understand of the java loops.
All its loop-control elements are gathered in one place, while in the other loop construction of java, they are scattered about the program.
The general form (syntax) of the for loop statement is:
for(initialization-expression ; test-expression; update-expression )
{
//body of the loop
}
class HelloWorld {
public static void main(String[] args) {
int sum=0;
System.out.println("20 Natural Numbers and their sum :\n");
for(int i=1;i<=20;i++)
{
System.out.println(i+"\n");
sum+=i;
}
System.out.println("\nSUM: "+sum);
sum=0;
}
}
20 Natural Numbers and their sum :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
SUM: 210
public class ForDemo2
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
for(int j=i;j>=1;j--)
{
System.out.print("* ");
}
System.out.println();
}
}
}
*
* *
* * *
* * * *
* * * * *
The second loop available in Java is the while loop.
It is an entry-controlled loop.
initialization;
while(condition)
//loop body
updation;
public class ForDemo2
{
public static void main(String[] args)
{
int num=6,fact=1;
int n=num;
while(n!=0){
fact*=n;
--n;
}
System.out.println("The factorial of "+num+" is "+fact);
}
}
The factorial of 6 is 720
Unlike the for and while loops, the do-while is an exit-controlled loop i.e, it evaluates its test expression at the bottom of the loop after executing its loop-body statements. This means that a do-while loop always executes at least once.
initialization;
do{
//loop body
updation;
}while(condition);
class demo {
public static void main(String args[])
{
int x = 21, sum = 0;
do {
sum += x;
x--;
}
while (x > 10);
System.out.println("Summation: " + sum);
}
}
Summation: 176
Note: also read about the The switch vs if-else
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…