2. while :
Syntax:
while(expression)
{
statements;
Increment / decrement
}
Cool warning : Don't give semicolon after while
- According to the syntax, the checking of expression will be done before the code got executed.
- while loop holds an expression.
- expression gives the result either true or false.
· if the result is true then while loop statements will executes.
· if the result is false then while loop terminates the execution.
· So, if expression result is false then it displays nothing.
--------------------------------------------------------------------------------
Program : A program to print Happy Bday 5 times
Program name : WhileDemo1.java
Output :
Happy Birthday
Happy Birthday
Happy Birthday
Happy Birthday
Happy Birthday
class WhileDemo1
{
public static void main(String args[])
{
int i = 1;
while(i<=5)
{
System.out.println("Happy Birthday");
i++;
}
}
}
Compile : javac WhileDemo1.java
Run : java WhileDemo1
Output :
Happy Birthday
Happy Birthday
Happy Birthday
Happy Birthday
Happy Birthday
--------------------------------------------------------------------------------
Program : A program to print 1 to 5 values
Program name : WhileDemo2.java
Output :
i value is : 1
i value is : 2
i value is : 3
i value is : 4
i value is : 5
class WhileDemo2
{
public static void main(String args[])
{
int i = 1;
while(i<=5)
{
System.out.println("i value is : "+i);
i++;
}
}
}
Compile : javac WhileDemo2.java
Run : java WhileDemo2
Output :
i value is : 1
i value is : 2
i value is : 3
i value is : 4
i value is : 5
--------------------------------------------------------------------------------
Conclusions :
do while - if condition fails once executes.
while - if condition fails it won’t executes.
--------------------------------------------------------------------------------
Thanks for your time.
Thanks for your time.
- Nireekshan