Wednesday, March 11, 2015

Even or Odd number and large and small in array in java



Calculate Rectangle Perimeter

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; 
public class CalculateRectPerimeter
{
public static void main(String[] args)
{               
int width = 0;
int length = 0;                         
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                    
System.out.println("Please enter length of a rectangle");
length = Integer.parseInt(br.readLine());
System.out.println("Please enter width of a rectangle");
width = Integer.parseInt(br.readLine());
                        
}
catch(NumberFormatException ne)
{
System.out.println("Invalid value" + ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println("IO Error :" + ioe);
System.exit(0);
}
int perimeter = 2 * (length + width);               
System.out.println("Perimeter of a rectangle is " + perimeter);
}             
}

Even Odd Number

public class FindEvenOrOddNumber
{
public static void main(String[] args)
{          
int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};             
for(int i=0; i < numbers.length; i++)
{
if(numbers[i]%2 == 0)
System.out.println(numbers[i] + " is even number.");
else
System.out.println(numbers[i] + " is odd number.");                           
   }               
  }
}

Find Largest and Smallest Number in an Array

public class FindLargestSmallestNumber
public static void main(String[] args)
{
int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
int smallest = numbers[0];
int largetst = numbers[0];             
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > largetst)
largetst = numbers[i];
else if (numbers[i] < smallest)
smallest = numbers[i];                       
}                 
System.out.println("Largest Number is : " + largetst);
System.out.println("Smallest Number is : " + smallest);
   }
}

No comments:

Post a Comment