Thursday, 28 December 2017

2.6 Basic Program for Practice

1. Palindrome


class palindrome
{
public static void main(String args[])
{
int r,sum=0,temp;    
int n=12321;//It is the number variable to be checked for palindrome  
  
temp=n;    
while(n>0)
{    
r=n%10;  //getting remainder  
sum=(sum*10)+r;    
n=n/10;    
}    
  if(temp==sum)    
   System.out.println("palindrome number ");    
  else    
   System.out.println("not palindrome");    
}

}

2. Prime Number


public class PrimeNumber{    
public static void main(String args[])
{    
  int i,flag=0;      
  int n=3;//check this number    
  int m=n/2;      
  if(n==0||n==1){  
   System.out.println(n+" is not prime number");      
  }
  else
  {
for(i=2;i<=m;i++)
{      
if(n%i==0)
{      
System.out.println(n+" is not prime number");      
flag=1;      
break;      
}      
}      
if(flag==0)  { System.out.println(n+" is prime number"); }  
}  
}    
}   


3. Factorial


class Factorial
{  
public static void main(String args[])
{  
  int i,fact=1;  
  int number=5;//Check this number    
  for(i=1;i<=number;i++){    
  fact=fact*i;    
}    
  System.out.println("Factorial of "+number+" is: "+fact);    
}  
}  

4. Armstrong Number

class Armstrong
{  
  public static void main(String[] args)  
  {  
int c=0,a,temp;  
int n=153;//Check this number  
temp=n;  
while(n>0)  
{  
a=n%10;  
n=n/10;  
c=c+(a*a*a);  
}  
if(temp==c)  
System.out.println("armstrong number");   
else  
System.out.println("Not armstrong number");   
}  
}  

5. Fibonacci Series

class Fibonacci
{
public static void main(String args[])
{
int n=20;
int j=0;
int k=1;
int num=0;
System.out.println(k);
while (num<=n)
{
num=j+k;
System.out.println(num);
j=k;
k=num;
}
}
}

No comments:

Post a Comment