Friday, 7 November 2014

JAVA Basic Examples

KANERIA DHAVAL


1.Write Java program to check if a number is palindrome in Java?
public class palindrome
{
public static void main(String args[]){
int num,rev=0;
int mod,temp;
num=1001;
temp=num;
while(temp!=0){
mod=temp%10;
temp=temp/10;
rev=(rev*10)+mod;
}
if(num==rev)
System.out.println("number is palindrome");
else
System.out.println("number is not palindrome");
}
}
2. Write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to an upperbound (e.g., 100). Also compute and display the average. The output shall look like:The sum is 5050 The average is 50.5


public class SumAndAverage
{
public static void main(String args[])
{
int sum=0;
float avg;
for (int i=1;i<=100;i++){
sum=sum+i;
}
avg=sum/100;
System.out.println("the sum is "+sum);
System.out.println("the average is "+avg);
}
}


3. Write a program called Fibonacci to display the first 20 Fibonacci numbers F(n), where F(n)=F(nñ1)+F(nñ2) and F(1)=F(2)=1. Also compute their average. The output shall look like:
The first 20 Fibonacci numbers are:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 The average is 885.5


public class Fibonacci
{
public static void main(String args[])
{
int f=0,sum=0;
int a=0,b=1;
float avg;
System.out.println("the first 20 fibonnaci numbers are ");
for(int i=0;i<20;i++){
f=a+b;
b=a;
a=f;
sum=sum+f;
System.out.print(f+"\t");
}
avg=sum/20;
System.out.println("\nthe average is "+avg);
}
}
4. Write a program called SquareBoard that displays the following n?n (n=5) pattern using two nested for-loops.
Expected output:
# # # # #
# # # # #
# # # # #


public class SquareBoard
{
public static void main(String args[])
{
int n=5;
for(int i=0;i<5;i++){
for(int j=0;j<5;j++)
System.out.print("# ");
System.out.println("");
}

}

No comments:

Post a Comment