Today we learnt Loops in JAVA.
There may be a sitution when we need to execute a block of code several number of times, and is often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
for Each Loop
Components of a Loop
Initialization
Condition
Increment/Decrement
We made following Programs :
Reverse a number with Loop.
Calculate power of a number without Math library
Calculate Perfect Squareroot without Math library
Sum of Odd number Series
Print the Table Of any Number
Program to Reverse a number with Loop.
import javax.swing.*;
public class reversee {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a,b;
a= Integer.parseInt(JOptionPane.showInputDialog("Enter the number"));
while (a!=0)
{
b=a;
b=b%10;
System.out.print(b);
a=a/10;
}
}
}
Program to Calculate power of a number without Math library.
import javax.swing.*;
public class powercal {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int tmp,num,pow;
num = Integer.parseInt(JOptionPane.showInputDialog("enter the number"));
pow = Integer.parseInt(JOptionPane.showInputDialog("enter the power"));
tmp = num;
pow= pow-1;
while (pow!= 0)
{
pow = pow-1;
tmp = tmp * num;
}
System.out.print("the answer is "+tmp);
}
}
Program to Calculate Perfect Squareroot without Math library.
import javax.swing.JOptionPane;
class sqrot {
public void abc (){
// TODO Auto-generated method stub
int num,a,b,c,flag;
flag=0;
num= Integer.parseInt(JOptionPane.showInputDialog("Enter the number"));
b= num/2;
for (a=1;a
{
c = a*a;
if (num == c){
flag = 1;
System.out.print("the perfect square root of "+num +" is "+a);
}
}
if (flag == 0)
{
System.out.print("the entered no "+num +" is not a perfect square");
}
}
}
public class sqroot_class {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
sqrot s = new sqrot();
s.abc();
}
}
Program to Calculate Sum of Odd number Series
import javax.swing.*;
public class sumofodd {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int limit,a,sum;
sum= 0;
limit = Integer.parseInt(JOptionPane.showInputDialog("enter the no. upto which you want to fint the sum"));
a=1;
while (a<=limit)
{
sum = sum + a;
a= a+2;
}
System.out.print("the sum is "+sum);
}
}
Program To Print The Table Of Any Number.
import javax.swing.*;
public class table {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int num,a,ans;
num = Integer.parseInt(JOptionPane.showInputDialog("Enter the number"));
for (a=1;a<=10;a++)
{
ans = num * a;
System.out.println(num +" x "+a +" = "+ans);
}
}
}
0 comments:
Post a Comment