LOOPs
1.) for loop
2.) while loop
3.) do while loop
FIRSTLY WE ARE GOING TO TALK ABOUT FOR LOOP
In programming language FOR loop is used to allow code executed repeatedly. For loop is useful when you know how many times a task to be repeatedly.
example :-
for(exp1; exp2; exp3)
{
statements;
}
where :
exp1 :- initialization expression
exp2 :- test expression
exp3 :- update expression.
EXAMPLE FOR CHECK WEATHER NUMBER IS PRIME OR NOT
class prime
{
public static void main(string args[]){
int n = Integer.parseInt(args[0]);
boolean flag = true;
for(int i=2; i<n/2; i++)
{
if(n%i==0)
{
d=i;
flag = false
break;
}
}
if(flag)
system.out.println("number is prime");
else
system.out.println("number is not prime");
}
}
NESTED LOOP
The placing of one loop inside the body of another loop is called nesting. The most common nested loop are for loop.
Example of nested loop a table up to n numbers :-
class table
{
public static void main(string args[]){
for(int i=1; i<=10; i++)
{
for(int j=1; j<=10; j++)
{
system.out.println(i + "" + j);
}
}
}
WHILE LOOP
In programming language WHILE loop is used to control flow statement that allow code to repeatedly executed based on the condition.
example :-
while(condition)
{
statements
________
________
}
Example for sum of digits
class digitSum
{
public static void main(string args[]){
int n = Integer.parseInt(args[0]);
int r,s = 0;
while (n!=0)
{
r = n%10;
s = s+r;
n = n/10;
}
system.out.println("sum of digits="+s);
}
}
DO WHILE LOOP
In programming language DO WHILE loop is used to control flow statement that executes a part of code single time and then repeatedly executes the part of code, its depend on the giving condition in the program.
example:-
do
{
statements;
_______
_______
}
while(condition)
Example to print number from 1 to 19
class example
{
public static void main(string args[]){
int x= 1;
do
{
system.out.println("x is :=" +x);
x++;
system.out.println("/n");
}
while(x=<20);
}
}