Demo Code

/******************************************************************************

*******************************************************************************/

public class Main
{
    void palindrome(String w)
{
    StringBuilder s2 = new StringBuilder(w);
        s2.reverse();
     
        String s = s2.toString();
        System.out.print("The String is "+s+" and is");
       
        if(w.equals(s))
          System.out.println(" a Palindrome");
         else
           System.out.println(" not a Palindrome");
}

int fibonacci (int i){
 
   if(i==0)
        return 0;
   else if(i==1 || i==2)
       return 1;
 
    return fibonacci(i-1)+fibonacci(i-2);
 
}

int factorial (int factorial_number){
 
    if(factorial_number==0)
        return 1;
    else
        return factorial_number*factorial(factorial_number-1);
}

void countFrequency(String str, char ch, int count){
 
    int occ = 0, i;

  // If given count is 0
  // print the given string and return
  if (count == 0) {
   System.out.println(str);
   return;
  }

  // Start traversing the string
  for (i = 0; i < str.length(); i++) {

   // Increment occ if current char is equal
   // to given character
   if (str.charAt(i) == ch)
    occ++;

   // Break the loop if given character has
   // been occurred given no. of times
   if (occ == count)
    break;
  }

  // Print the string after the occurrence
  // of given character given no. of times
  if (i < str.length() - 1)
   System.out.println(str.substring(i + 1));

  // Otherwise string is empty
  else
   System.out.println("Empty string");
 
}

public static void main(String[] args) {
 
    Main demo = new Main();
    demo.palindrome("atata");
 
    int number=5;
    System.out.println("Entered Number is "+number);
    System.out.println("The "+number+"th fibonacci number is: "+demo.fibonacci(number));
 
    System.out.print("Fibonacci Series: ");
    for (int i=0;i<number;i++)
            System.out.print(demo.fibonacci(i)+", ");
     
System.out.println("\nFactorial of "+number+" is "+demo.factorial(number));
 
        //Find Duplicate Items in Array List
    int [] arr = new int [] {1,2,3,4,3,5,6,6,8,9};
    System.out.print("Duplicate elements in given array: ");
    for(int i=0;i<arr.length;i++)
    {
        for(int j=i+1;j<arr.length;j++)
        {
            if(arr[i]==arr[j])
            System.out.print(arr[j]+" ");
        }
    }

    System.out.println(" ");
    demo.countFrequency("geeksforgeeks",'e',3);
 
}
}

No comments:

Post a Comment