Advertisements

Archive

Archive for January 7, 2009

Java Program to find the Week Day of given date – Q14

January 7, 2009 Leave a comment

Q14: Java Program to find the Week Day of given date

import javax.swing.*;

class cal{
	public static void main(String args[]){
		int dd, mm, yy, t_y, odd=0;
		String inp;
		
		inp = JOptionPane.showInputDialog("Enter a Day (dd): ");
		dd = Integer.parseInt(inp);
		
		inp = JOptionPane.showInputDialog("Enter a Day (mm): ");
		mm = Integer.parseInt(inp);
		
		inp = JOptionPane.showInputDialog("Enter a Day (yy): ");
		yy = Integer.parseInt(inp);
		
		if( ((dd <= 0) || (dd >= 32)) &&
			((mm <= 0) || (mm >= 13)) &&
			(yy <= 0) ){
			System.out.println("Enter a Valid date.");
			System.exit(0);
			}
		
		t_y = (yy-1) % 400;
		
		if(t_y == 0)
			odd = 0;
		if(t_y >= 300 && t_y < 400){
			odd = 1;
			t_y -= 300;
			}
		if(t_y >= 200 && t_y < 300){
			odd = 3;
			t_y -= 200;
			}
		if(t_y >= 100 && t_y < 200){
			odd = 5;
			t_y -= 100;
			}
		
		odd += t_y/2;
		t_y -= t_y/4;
		odd += t_y;
		
		for(int i=0; i<mm-1; i++)
			odd += DaysThisMonth(i, yy);
		
		odd += dd;
		
		odd = odd % 7;
		
		System.out.println("\n Day on Date " + dd + "/" + mm + "/" 
     + yy + " is: " + week[odd]);
	}
	
	public static String week[] = { "Sunday", "Monday", "Tuesday", 
  "Wednesday", "Thursday",
  "Friday", "Saturday" };
	
	public static int months[] = { 31, 29, 31, 30, 31, 30, 31,
							 31, 30, 31, 30, 31 };
	
	public static int DaysThisMonth(int m, int y){
		if (m != 1)
			return months[m];
		
		if ((y % 4) != 0)		// Not leap year
			return 28;
		if ((y % 100) != 0)		// It is leap year
			return 29;
		if ((y % 400) != 0)		// Not leap year
			return 28;
		return 29;			// It is leap year
	}
}

… from College notes (BCA/MCA assignments):


Advertisements

Java Program to print Pascal Triangle – Q13

January 7, 2009 Leave a comment

Q13: Java Program to print Pascal Triangle

import javax.swing.*;

class pascal{
	public static void main(String args[]){
		int lim, n, r, item, l;
		double x;
		String inp;
		
		inp = JOptionPane.showInputDialog("Enter Limit: ");
		lim = Integer.parseInt(inp);
		
		// For 1st Line
		for(l=0; l<=lim; l++)
			System.out.print("  ");
		System.out.println(" 1");
		
		//For rest Lines
		for(n=2; n<=lim; n++){
			for(l=n; l<=lim; l++){	// Loop for blank Pyramid
				System.out.print("  ");
			}
			for(r=0; r<=n; r++){	// Loop for Pascal Triangle
				x = fact(n)/(fact(r)*fact(n-r));
				item = (int)x;
				System.out.print("  " +  item);
			}
			System.out.println("");
		}
	}
	
	public static long fact(int a){
		if(a <= 0)
			return (1);
		else
			return (a * fact(a-1));
	}
}

… from College notes (BCA/MCA assignments):