Friday, October 31, 2014

Java Palindrome Pro



Check palindrome string using recursion

package beginnersbook.com;
import java.util.Scanner;
class PalindromeCheck
{
 public static boolean isPal(String s)
 {   
        if(s.length() == 0 || s.length() == 1)
            return true; 
        if(s.charAt(0) == s.charAt(s.length()-1))
        return isPal(s.substring(1, s.length()-1));
                   return false;
    }
           public static void main(String[]args)
 {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the String for check:");
        String string = scanner.nextLine();
         if(isPal(string))
            System.out.println(string + " is a palindrome");
        else
            System.out.println(string + " is not a palindrome");
    }
}

Find factorial of a given number using recursion

import java.util.Scanner;
class FactorialDemo
{
public static void main(String args[])
{
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the number:");
      int num = scanner.nextInt();
      int factorial = fact(num);
      System.out.println("Factorial of entered number is: "+factorial);
   }
   static int fact(int n)
   {
       int output;
       if(n==1)
      {
         return 1;
       }
       output = fact(n-1)* n;
       return output;
   }
}

Java program to sum the elements of an array

class SumOfArray
{
 public static void main(String args[])
{
      int[] array = {10, 20, 30, 40, 50, 10};
      int sum = 0;
      for( int num : array) 
     {
          sum = sum+num;
      }
      System.out.println("Sum of array elements is:"+sum);
   }
}
User enters the array’s elements
 
import java.util.Scanner;
class SumDemo
{
 public static void main(String args[])
{
      Scanner scanner = new Scanner(System.in);
      int[] array = new int[10];
      int sum = 0;
      System.out.println("Enter the elements:");
      for (int i=0; i<10; i++)
      {
                 array[i] = scanner.nextInt();
      }
      for( int num : array) 
     {
          sum = sum+num;
      }
      System.out.println("Sum of array elements is:"+sum);
   }
}

No comments:

Post a Comment