(Display five messages) Write a program that displays Welcome to Java five times.
Answer
/**
* Program - 02
* Write a Program that displays:
* Welcome to Java
* five times
**/
public class HelloWorld
{
public static void main(String args[])
{
System.out.println("Welcome to Java");
System.out.println("Welcome to Java");
System.out.println("Welcome to Java");
System.out.println("Welcome to Java");
System.out.println("Welcome to Java");
}
}
Output:
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
We can also write the program using loops:
1) for loop
public class HelloWorld
{
public static void main(String[] args)
{
for(int i = 1; i <= 5; i++){
System.out.println("Welcome to Java");
}
}
}
In this program, after each iteration, the value of i gets incremented by '1'. And each time i increments, it prints the statement "Welcome to Java".
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
2) while loop
public class HelloWorld
{
public static void main(String[] args)
{
int i = 0;
while(i <= 5){
System.out.println("Welcome to Java");
i++;
}
}
}
In while loop, the condition is written after while keyword in the ()parenthesis.
value of variable i is declared and initialized with 0. And in the while block, the print statement is written. On the next line, i++ is written. This is wrote to increment the value of i. The loop terminates when the value of i becomes greater than 5.
If i++ is not written, then an infinite loop starts running.
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
.
.
.
.
.
.
.
.
.
.
.
This is because the condition written in () is always true as i <=5 (True). So to avoid an infinite loop, we add i++.
3) do while loop
public class HelloWorld
{
public static void main(String[] args)
{
int i = 0;
do{
System.out.println("Welcome to Java");
i++;
}
while(i <= 5);
}
}
The do while loop is written in such a way, that the print statement is written in the do-block and the loop-continuation condition is written in the while block.
Note: i++ is written in the do block.
If you have any doubts or questions, please let me know.