Tuesday, 23 August 2016

Java Program to swap first and last word of a Sentence

Java Program to swap first and last word of a Sentence

Answer :

import java.util.Scanner;

public class StringWordSwap {

 public static void main(String[] args) {
 
  
  Scanner scan=new Scanner(System.in);
  System.out.println("Enter the String :");
  String s=scan.nextLine();
  String[] ori=s.split(" ");
//split method return type is array type. Example-if input is "give your best performance"
                          //after split method ori[]={"give","your","best","performance"};
  String temp=ori[0];                    
  
  ori[0]=ori[ori.length-1]; //"performance" will store at ori[0]
  
   ori[ori.length-1]=temp;//"give" will store at last index    
  
  for(int i=0;i<(ori.length);i++){
   System.out.print(ori[i]+" ");
  }

 }
}
Example:
 input:give your best performance
 ouput:performance your best give

Sunday, 21 August 2016

Java Program to print triangle Alphabetically

Java Program to print triangle Alphabetically
Example:

A
B C
D E F
G H I J

Answer :

public class TriangleAlphabet {

 public static void main(String[] args) 
 {
  
  char c=65;
 
  int rowNum=4;
  for(int i=1;i<=rowNum;i++)
  {
   for(int j=0;j<(i);j++)
   {
    System.out.print(c+" ");
    c++;
   }
   System.out.println();
  }

A java program to find missing element in a sorted int array.

A java program to find missing element in a sorted int array
Example-input  array={1,2,4,5,6,7,9}
        output:3,8

Answer :


public class MissingElementInArray {

 public static void main(String[] args) 
 { 
  int[] arr={1,2,4,5,6,7,9};
  for(int i=0;i<(arr.length-1);i++)
  {
   int temp=arr[i];
   
     if((temp+1)!=arr[i+1])
     {
       System.out.println(temp+1);
     }
   
  }

 }

}


Sunday, 14 August 2016

Write a java program to print following pattern

Write a java program to print following pattern
0
1 0
0 1 0
1 0 1 0

Answer :

class Output2{
public static void main(String args[]){
for(int i=1;i<=4;i++){
for(int j=1;j<=i;j++){
 System.out.print(((i+j)%2)+" ");
 }
 System.out.print("\n");
    }
  }
}

Write a java program to print the following pattern

Write a java program to print the following pattern
1
2 3
4 5 6
7 8 9 10

Answer :

public class Triangle {

 public static void main(String[] args) {
  
  int count=1;
  for(int i=1;i<=4;i++){
   for(int j=1;j<=i;j++){
    System.out.print(count+" ");
    count++;
   }
   System.out.println();
  }

 }

}