Loops in Java
When we
execute one or more sets of instructions or statements repetitively of any
programming language with the given condition is known as Loop. Or execute one or
more sets of instructions with a condition is called Loop. It is also called repetition
structure and this structure allows an action is to be repeated until a given
condition is true.
Any loop contains three parts
- First, it has a starting point or initialization
- Second, it has a condition
- Third, it has iteration or step
Types of Loop in java
Depending on control
The entry-controlled loop: The loop that
checks it’s a condition at the entry point of the loop. For and while() loop are examples
of an entry-controlled loop.
The exit control loop: The loop that checks
its condition at an exit point or at the end of from loop is known as an exit
controlled loop. Do..while() is the example of an exit control loop.
Depending on execution
Definite loop: This kind of loop performs a fixed number of repetitions. For() loop is the example of a definite loop.
Indefinite loop: This kind of loop perform
execution indefinite number of times while() and do..while() are the example of
indefinite loop.
Java for loop
Java for will executes its
operation a fixed number of times or we can say for loop is a repetition
control structure that lets you to efficiently execute a specific number of
times.
A for loop is useful when you
know how many times a task is to be repeated.
All the parts of for loop are optional.
Anyone can be left empty, but the two semi-colon must be included.
For Loop
syntax
for ( initialization ; test condition
; increment / decrement ) {
// statements
}
In for loop, we can give curly
brace if multiple of statements are there but if single statement curly brace
is optional.
for(i=1; i<=5; i++)
Statement;
for(i=1; i<=5; i++)
{
Statement 1;
Statement 2;
Statement 3;
…….
}
The initialization part is used
to declare and initialize variables that will be used by the loop. For example,
we can write the initialization part as
int i = 1
The condition is the loop condition similar to the one in while
and do-while loops. The increment/decrement part is commonly used to include
statements like i++, i– etc.
Algorithm:
The for loop is executed in the
following way:
Step 1. Firstly the statements in initialization is executed.
Step 2. The loop condition is evaluated. If it is true, go to step
3 else move out of the loop.
Step 3. Execute the statement in the loop body.
Step 4. Execute the increment /decrement part.
Step 5. Go to step 2.
We can take the
following example
fact=1;
for(i=1; i<=5; i++)
{
fact =
fact * I;
}
Statement
1 i =1 is executed before the execution of the code block and the initialization
will not again.
Statement
2 i<=5 will defines the condition for executing the next code
block and if it is true then body part of the loop will execute.
Statement
3 i++ is executed after the code block has been executed and it
will execute till the condition satisfied. In this it will execute 5 times and
the body part of loop will produce 120 after repetition of times as follows
fact = 1 * 1;
fact = 1 * 2;
fact = 2 * 3;
fact = 6 * 4;
fact = 24 * 5;
the final value will be
120.
For loop has some unusual
construct.
First type
int i=0;
for( ; i<5; i++)
{
expression 1;
expression 2;
expression 3;
…………………. ;
}
Here the initialization
done outside loop.
Second type
int i=0;
for( ; i<5; )
{
expression 1;
expression 2;
expression 3;
…………………. ;
i++;
}
Here the initialization
done outside loop and iteration i++ will done within the block.
Third type
int i, s;
for(i=1, s=0 ; i<=5;
i++)
{
expression 1;
expression 2;
expression 3;
…………………. ;
}
Here the initialization done
within the for loop and also one extra variable initialize with 0 within the
for loop.
So for loop can be deferent variant as long as it satisfies three components of a loop.
Few examples of the for loop in java.
Perfect number in Java
A number can be a Perfect
Number if the sum of its positive divisors except the number itself is equal to
that number. For example, 6 is a perfect number because 6 is divisible by 1, 2,
3 the sum of these values is 1 + 2 + 3 = 6.
public class PerfectNumber
{
public static void main(String args[])
{
int i, num=6, sum=0;
for(i=1; i<num; i++)
{
if(num % i ==0)
{
sum = sum + i;
}
}
if(num==sum)
{
System.out.println("Perfect
Number");
}
else
{
System.out.println("Perfect
Number");
}
}
}
Prime number in java
Any number which is divisible 1 and by itself
is called prime number. For example 2, 3, 5, 7, 11, 19, 23, 29....
are the prime numbers.
public class PrimeNumberFirstMetod
{
public static void main(String args[])
{
int i, n=5, f=1;
for(i=2; i<n; i++)
{
if(n %i == 0)
{
f=0;
break;
}
}
if(f==1)
{
System.out.println("Prime Number");
}
else
{
System.out.println("Not a Prime Number");
}
}
}
Amicable number in Java
Amicable numbers are those two numbers are the the sum of the proper divisors of each is equal to the other number. For example amicable
pairs is: (220, 284)
public class
AmicableNumber
{
public static void main(String args[])
{
int s1,s2,i;
int n1=220, n2=284; // pair of two number
s1=s2=0;
// First number sum
for(i=1;i<n1;i++)
{
if(n1%i==0)
s1=s1+i;
}
// Second number sum
for(i=1;i<n2;i++)
{
if(n2%i==0)
s2=s2+i;
}
// checking of first number sum to the second number and vice versa
// second to first
if(s1==n2 && s2==n1)
{
System.out.println("Amicable Number");
}
else
{
System.out.println("Not amicable Number");
}
}
}
While Loop
The second type of loop is ‘while loop’. It is
used we do not know how many times the loop will execute. This is an
entry-controlled loop. In a while loop, if the initial condition is true then the execution
will enter into the loop.
The syntax for the while loop
While(condition)
{
statement
1;
statement
2;
statement
3;
---------------;
---------------;
}
The parentheses at the condition is same as
the if condition and it will execute as long as the condition is true. The body
of the loop will execute until the condition become false.
The while loop will execute the following
expression perfectly
While(i = i+1)
While(i++)
While(i+=1)
All the above expression will evaluate to 0
then the loop will fail and exit.
Why do we use while 1or 0?
The while loop with 1
or 0, while (1) or while (any non-zero value) is used for infinite loop or
unending of the loop. 1 or any non-zero value is present, then the condition is
always true. So the loop will execute forever and to come out from this unending
loop, we must use conditional statements and break statements.
Example of while loop in java
Print series in while loop in java 1 2 3 4……….
class
WhileLoopExample1
{
public static void main(String args[])
{
int i=10;
while(i!=0) // entry control loop
{
System.out.print(i + "
"); // print 1 2 3 4 5 6 7 8 9 10
i--;
}
}
}
Reverse number in java
class Reverse
{
public static void main()
{
int n=154,a, rev=0, m=n;;
while(n!=0) // entry control loop
{
a=n % 10;
rev=rev*10 + a;
n=n/10;
}
System.out.println("Reverse "
+ rev );
}
}
Palindrome number in java
An integer is said to
be a palindrome, if it’s reverse is also the same as the number.
Like 121, 141, 242
etc.
class Palindrome
{
public static void main(String args[])
{
int number=151,a, rev=0, m=number;;
while(number!=0) // entry control loop
{
a=number % 10;
rev=rev*10 + a;
number=number/10;
}
if(m == rev)
{
System.out.println("Palindrome
number");
}
else
{
System.out.println("Not a
Palindrome number");
}
}
}
Fibonacci series in java using while loop
import java.util.*;
public class
Fibonacci
{
public static void main(String arg[])
{
Scanner sc = new Scanner (System.in);
int f1, f2, fib, i, number;
System.out.println ("Enter a
number to generate Fibonacci Series:");
number = sc.nextInt();
f1 = fib = 0;
f2 = 1;
i=0;
System.out.print (fib+" ");
while (i < number)
{
f1 = f2;
f2 = fib;
fib = f1 + f2;
System.out.print (fib+"
");
i++;
}
}
}
Sample output
Enter a number to
generate the Fibonacci Series:
10
0 1 1 2 3 5 8 13 21
34 55
do..while loop in java
this loop is the same as
the while loop except it tests the condition at the bottom of the loop. This loop
will execute at least once. This an example of an exit-controlled loop.
The syntax for the
loop is
do{
expression 1;
expression 2;
expression 3;
expression 4;
----------------;
}while(condition);
Generally we use do
while in menu driven program because we enter the menu before any condition
Example
of do-while loop in java
Calculator
program in java using a do-while loop with a switch statement
import java.util.*;
public class
MenuCalculator
{
static void menu() // menu method
{
System.out.println ("Press 1 for
Addition");
System.out.println ("Press 2 for Subtraction");
System.out.println ("Press 3 for
Multiplication");
System.out.println ("Press 4 for
Division");
System.out.println ("Press 5 for
Exit\n\n");
System.out.println ("Enter Your
Choice");
}
// main method
public static void main (String args[])
{
int num1, num2, result, choice;
Scanner sc=new Scanner (System.in);
do{
menu(); // static method
choice = sc.nextInt();
System.out.println ("Enter two
Numbers:");
num1=sc.nextInt ();
num2=sc.nextInt ();
switch(choice)
{
case 1:
result=num1+num2;
System.out.println("Sum="
+ result);
break;
case 2:
result=num1-num2;
System.out.println("Subs=" + result);
break;
case 3:
result=num1*num2;
System.out.println("Mult=" + result);
break;
case 4:
result=num1/num2;
System.out.println ("Div="
+ result);
break;
case 5:
System.exit (0);
default:
System.out.println ("Wrong
Choice, please press(1-5)");
}
} while(choice!=5); // do while loop
condition
}
}