Tuesday 24 November 2015

cs java programs


Question 1:
Write the following method that retruns the maximum value in an ArrayList of Integers. The
methods returns null if the list is nul or the list size is 0.
public static Integer max(ArrayList<Integer> list)
Write a test program that prompts the user to enter a sequence of numbers ending with 0, and
invokes this method to return the largest number in the input.
Program:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package week10s;
/**
*
* @author kishore
*/
import java.util.*;
public class ArrayListMax {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter the elements : ");
int temp;
do {
temp = input.nextInt();
if (temp != 0) {
list.add(temp);
}
} while (temp != 0);
System.out.println("Maximum number is " + max(list));
}
public static Integer max(ArrayList<Integer> list) {
if (list == null || list.isEmpty()) return null;
int max = list.get(0);
for (int i : list) {
if (i > max) {
max = i;
}
}
return max;

}
}
Output:
run:
Enter the elements : 76
6
5
3
0
Maximum number is 76

Question 2:
Write a program the meets the following requirements:
• Creates an array with 100 randomly chosen integers.
• Prompts the user to enter the index of the array, then displays the corresponding element value.
If the specified index is out of bounds, display the message Out of Bounds. ( Use try-catch
block)
Program:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package week10s;
/**
*
* @author kishore
*/
import java.io.*;
public class RandomArray {
public static void main(String ar[]) throws NumberFormatException, IOException{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int arr[]=new int[100];
for(int i=0;i<arr.length;i++){
int randomnumber=(int) (Math.random()*100);
arr[i]=randomnumber;
}
for(int i=0;i<arr.length;i++){
System.out.println("Random Numbers are"+i+"="+ arr[i]);
}
System.out.println("Enter which index element do you want?");
for(int i=0;i<100;i++){
try{
int index=Integer.parseInt(br.readLine());
if(index>100){
System.out.println("Out of Bounds");
}
else{
System.out.println("Given Index Having Element "+arr[index]);

}
}catch(Exception e){
System.out.println("Please enter a valid number");
}
}
}
}
Output:
run:
Enter which index element do you want?
34
Given Index Having Element 71
123
Out of Bounds
101
Out of Bounds

Thursday 8 October 2015

cs java progrmes

                                       
1) Write a test program that prompts the user to enter an integer
and reports whether the integer is a palindrome
Program:
/*
* To change this license header, choose License Headers in
Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clshm2.hm3;
/**
*
* @author kishore
*/
import java.util.*;
public class PalindromeNumber {
public static boolean isPalindrome(int number) {
int palindrome = number;
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}

if (number == reverse) {
System.out.println(number+" Is a Palindrome");
return true;
}
System.out.println(number+" Is Not a Palindrome");
return false;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int number=sc.nextInt();
PalindromeNumber.isPalindrome(number);
}
}
Output:
run:
Enter a number
575
575 Is a Palindrome
BUILD SUCCESSFUL (total time: 12 seconds)
run:
Enter a number

345
345 Is Not a Palindrome
BUILD SUCCESSFUL (total time: 3 seconds)
2) write a java program to calculate BMI
Program:
/*
* To change this license header, choose License Headers in
Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clshm2.hm3;
/**
*
* @author kishore
*/
import java.util.Scanner;
public class BMI {
Scanner input = new Scanner(System.in);
public static void calculateBMI(double weight, double
height){
double pounds=weight;
double inches=height;
double inches2=inches*inches;
double bmi = (pounds / inches2)*703;

System.out.println("Your Body Mass Index is " + bmi);
if (bmi < 18.5)
System.out.println("You are underweight");
else if (bmi < 24.99)
System.out.println("You are normal weight");
else if (bmi < 29.99)
System.out.println("You are overweight");
else if (bmi < 34.99)
System.out.println("You are seriously overweight");
else
System.out.println("You are gravely overweight");
}
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("if u want to convert kgs to pounds enter
1 else 0");
int ch = sc.nextInt();
if(ch==1)
{
System.out.println( "enter the kgs");
double kgs=sc.nextDouble();
double pounds=kgs*2.20462;
System.out.println("you are weight in pounds=
"+pounds);

}
System.out.println("Enter weghit in pounds");
double pounds=sc.nextDouble();
System.out.println("if u want to convert feets to inches
enter 1 else 0");
int ch1 = sc.nextInt();
if(ch1==1)
{
System.out.println( "enter the feets");
double feets=sc.nextDouble();
double inches=feets*12;
System.out.println("you are height in inches= "+inches);
}
System.out.println("enter heghit in inches");
double inches=sc.nextDouble();
calculateBMI(pounds,inches);
}
}
Output:
1.
run:
if u want to convert kgs to pounds enter 1 else 0
1
enter the kgs
56
you are weight in pounds= 123.45871999999999
Enter weghit in pounds
123.45

if u want to convert feets to inches enter 1 else 0
1
enter the feets
5.7
you are height in inches= 68.4
enter heghit in inches
68.4
Your Body Mass Index is 18.549585769980503
You are normal weight
BUILD SUCCESSFUL (total time: 22 seconds)
2.
run:
if u want to convert kgs to pounds enter 1 else 0
0
Enter weghit in pounds
123.459
if u want to convert feets to inches enter 1 else 0
0
enter heghit in inches
68.4
Your Body Mass Index is 18.55093810916179
You are normal weight
BUILD SUCCESSFUL (total time: 28 seconds)

3a) Linear Search
Program:
package clshm3;
public class LinearSearch {
public static void main(String args[]){
LinearSearch ls=new LinearSearch();
ls.lineraSearch(4);
ls.lineraSearch(-4);
ls.lineraSearch(-3);
}
public void lineraSearch (int num){
int list[]={1,4,-4,2,5,-3,6,2};
for(int i=0;i<list.length;i++){
if(num==list[i])
{
System.out.println(num+" number found at index position "+i);
}
}
}
}
Output:
4 number found at index position 1
-4 number found at index position 2
-3 number found at index position 5
3b) Binary Search:
Program:
package clshm3;
public class BinarySearch {
public static void main(String[] args) {
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
int i = BinarySearch.binarySearch(list, 2);
System.out.println(i);
int j = BinarySearch.binarySearch(list, 11);
System.out.println(j);
int k = BinarySearch.binarySearch(list, 12);
System.out.println(k);
int l = BinarySearch.binarySearch(list, 1);
System.out.println(l);
int m = BinarySearch.binarySearch(list, 3);
System.out.println(m);
}
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key ==list[mid])
return mid;
else
low = mid + 1;
}
return - 1;
}
}
Output: 0
4
-1
-1
-1
3c) Selection Sort
Program:
package clshm3;
import java.util.Scanner;
public class SelectionSort
{
public void Selectionsort(double[] arr){
for(int i=0; i<arr.length; i++)
{
for(int j=i+1; j<arr.length; j++)
{
if(arr[i] > arr[j] )
{
double temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
for(int i=0; i<arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int n = sc.nextInt();
double [] x = new double[n];
System.out.print("Enter "+ n +" numbers: ");
for(int i=0; i<n; i++)
{
x[i] = sc.nextDouble();
}
SelectionSort access = new SelectionSort();
System.out.print("The Sorted numbers: ");
access.Selectionsort(x);

}
}
Output:
Enter the size of the array: 5
Enter 5 numbers: 1.9
4.5
6.6
5.7
-4.5
The Sorted numbers: -4.5 1.9 4.5 5.7 6.6


4) Write a program that prompts the user to enter two sorted lists
and displays the merged list.
Program:
package clshm3;
import java.util.*;
public class Merge {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter list1 size and elements : ");
int n = sc.nextInt();
int[] array1 = new int[n];
for(int i = 0 ; i < n ; i++){
array1[i]=sc.nextInt();
}
System.out.println("Enter list2 size and elements : ");
int m = sc.nextInt();
int[] array2 = new int[m];
for(int i =0 ; i < m ; i++){
array2[i]=sc.nextInt();
}
display(merge(array1,array2));
sc.close();
}
public static int[] merge(int[] list1 , int[] list2){
int count = 0;
boolean WTF = false;
int k = 0;
int[] m = new int[list1.length + list2.length];
for(int i = 0 ; i < list1.length; i++){
for(int j = k ; j < list2.length ; j++){

if(list1[i] < list2[j]){
m[count] = list1[i];
count++;
break;
}
if(list1[i]> list2[j]){
m[count] = list2[j];
count++;
k= j + 1 ;
}
if(list1[i] == list2[j]){
m[count] =list1[i] ;
count++;
break;
}
}
if (k > list2.length -1){
m[count] = list1[i];
count++;
}
}
int left = list1[list1.length -1];
for(int i = 0 ; i < list2.length ; i++ ){
if(list2[i] > left){
left = i;
WTF = true;
break;}
}
if(WTF){
for(int i = left ; i < list2.length ; i++){
m[count] = list2[i];
count++;
}
}
return m;
}
public static void display(int[] array){
System.out.print("the merged list is "
+ " ");
for(int i = 0 ; i < array.length ; i++){
System.out.print(array[i]+" ");
}
}
}
Output:
Enter list1 size and elements :
5
1 5 16 61 111
Enter list2 size and elements :
4
2 4 5 6
the merged list is 1 2 4 5 5 6 16 61 111

Tuesday 6 October 2015

cs java progrmes

                                      CS480 – Java and Internet Applications Homework 2 (Fall 2015)

1. [25 points] Write a program that plays the popular scissorrock-
paper game.( A scissor can cut paper, a rock can knock a
scissor and a paper can wrap a rock). The program randomly
generates a number 0,1 or 2 representing scissor, rock and
paper. The program prompts the user to enter a number 0,1 or
2 and displays a message indicating whether the user or the
computer wins, loses or draws. Here are sample runs:
Scissor
(0),
rock
(1),
paper
(2)
:
1
The
computer
is
scissor,
You
are
rock.
You
won.
Scissor
(0),
rock
(1),
paper
(2)
:
2
The
computer
is
paper,
You
are
paper
too.
It
is
a
draw.
2. [20 points] Write a program that reads three edges for a
triangle and computes the perimeter if the input is valid.
Otherwise display that the input is invalid. The input is valid if
the sum of every pair of two edges is greater than the
remaining edge.
3. [20 pts] Write a program that reads an unspecified number of
integers, determines how many positive and negative values
have been read, and computes the total and average of the input
values. Your program ends with the input 0. Display the
average as a floating point number. Here are sample runs:
Enter integers (input ends if it is 0): 1 2 2 -2 1 0
The number of positives is 4
The number of negatives is 1
The total is 4
The average is 0.8
Enter integers (input ends if it is 0): 0
No numbers are entered except 0
4. [ 20 points] Write a program that prompts the user to enter the
number of students and each student’s name and score.
Display the student name with the highest score.
5. [15 points] Modify program 4 to display the student with
highest score and second highest score with their names.
Here is a sample run:
Enter the number of students: 5
Enter a student name: Alex
Enter a student score: 25
Enter a student name: Bobby
Enter a student score: 30
Enter a student name: Carmen
Enter a student score: 15
Enter a student name: Denis
Enter a student score: 44
Enter a student name: Emma
Enter a student score: 20
Top two students:
Denis's score is 44.0
Bobby's score is 30.0




answers:


1. Write a program that plays the popular scissor rock-paper game.( A scissor can cut paper, a rock can knock a scissor and a paper can wrap a rock). The program randomly generates a number 0,1or2representing scissor, rock and paper. The program prompts the user to enter a number 0,1 or 2 and displays a message indicating whether the user or the computer wins, loses or draws.
program:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clshm2;
/**
*
* @author kishore
*/
import java.util.*;
public class Scissor_Rock_Paper_Game {
public static void main(String[] args)
{

Scanner sc = new Scanner(System.in);
int computer, human;
System.out.print("scissor (0), rock (1), paper (2):");
human = sc.nextInt();
computer = (int)(Math.random() * 3);
if(computer == 0)
{
System.out.print("The computer is scissor");
}
else if(computer == 1)
{
System.out.print("The computer is rock");
}
else if(computer == 2)
{
System.out.print("The computer is paper");
}
if((human == 0 && computer == 2) || (human == 1 && computer == 0) || (human == 2 && computer == 1))
{
if(human == 0)
{
System.out.print(" You are scissor You won");
}
else if(human == 1)
{
System.out.print(" You are rock You won");
}
CS480(N)_HW2_17464_KISHORE_ELCHURI
else if(human == 2)
{
System.out.print(" You are paper You won");
}
}
else if(human == computer)
{
if(human == 0)
{
System.out.print(" You are scissor too It is a draw");
}
else if(human == 1)
{
System.out.print(" You are rock too It is a draw");
}
else if(human == 2)
{
System.out.print(" You are paper too It is a draw");
}
}
else
{
if(human == 0)
{
System.out.print(" You are scissor You lose");
}
else if(human == 1)
{
System.out.print(" You are rock You lose");
}
else if(human == 2)
CS480(N)_HW2_17464_KISHORE_ELCHURI
{
System.out.print(" You are paper You lose");
}
}
}
}
Output:
sample1:
scissor (0), rock (1), paper (2):1
The computer is scissor You are rock You won
sample2:
scissor (0), rock (1), paper (2):3
Invalid choice please enter 0 or 1 or 2 and try
CS480(N)_HW2_17464_KISHORE_ELCHURI
CS480(N)_HW2_17464_KISHORE_ELCHURI
2.Write a program that reads three edges for a triangle and computes the perimeter if the input is valid. Otherwise display that the input is invalid. The input is valid if the sum of every pair of two edges is greater than the remaining edge.
Program:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clshm2;
/**
*
* @author kishore
*/
import java.util.*;
public class Perimeter {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double side1, side2, side3;
double perimeter;
System.out.print("Enter the 3 sides of the rectangle:");
CS480(N)_HW2_17464_KISHORE_ELCHURI
side1 = s.nextDouble();
side2 = s.nextDouble();
side3 = s.nextDouble();
if((side1 + side3 >= side2) && (side1 + side2 >= side3) && (side2 + side3 >= side1)) {
perimeter = side1 + side2 + side3;
System.out.print("You entered valid values ");
System.out.println("The perimeter of the triangle is " + perimeter);
}
else {
System.out.println("You entered Invalid values ");
}
}
}
Output:
Enter the 3 sides of the rectangle:4
9
6
You entered valid values The perimeter of the triangle is 19.0
BUILD SUCCESSFUL (total time: 7 seconds)
CS480(N)_HW2_17464_KISHORE_ELCHURI
CS480(N)_HW2_17464_KISHORE_ELCHURI
3. Write a program that reads an unspecified number of integers,
determines how many positive and negative values have been read, and computes the total and average of the input values. Your program ends with the input 0. Display the average as a floating point number.
Program:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clshm2;
/**
*
* @author kishore
*/
import java.util.*;
public class TotalAndAverage {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CS480(N)_HW2_17464_KISHORE_ELCHURI
int positive = 0, negative = 0, total = 0, count = 0;
double average;
System.out.println("Enter the number: ");
int number;
while ((number = input.nextInt()) != 0) {
total += number;
count++;
if (number > 0) {
positive++;
}
else if (number < 0) {
negative++;
}
}
average = (double)total / count;
System.out.println("The no of positive number is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total is " + total);
System.out.printf("The average is %f ", average);
}
}
Output:
Enter the number:
3
CS480(N)_HW2_17464_KISHORE_ELCHURI
4
8
-1
-3
0
The no of positive number is 3
The number of negatives is 2
The total is 11
The average is 2.200000 BUILD SUCCESSFUL (total time: 13 seconds)
CS480(N)_HW2_17464_KISHORE_ELCHURI
4. [ 20 points] Write a program that prompts the user to enter the
number of students and each student’s name and score. Display the student name with the highest score.
Program:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clshm2;
/**
*
* @author kishore
*/
import java.util.*;
public class StudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.println("How many students grades do you want to enter? ");
CS480(N)_HW2_17464_KISHORE_ELCHURI
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("Please enter the student #" + (i + 1) + "'s name? ");
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("Please enter the student #" + (i + 1) + " score? ");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Student with the highest score: " + highName + " " + highScore);
System.out.println("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
}
CS480(N)_HW2_17464_KISHORE_ELCHURI
Output:
How many students grades do you want to enter?
3
Please enter the student #1's name?
narendra
Please enter the student #1 score?
99
Please enter the student #2's name?
chandu
Please enter the student #2 score?
98
Please enter the student #3's name?
kishu
Please enter the student #3 score?
97
Student with the highest score: narendra 99
Student with the second highest score: chandu 98
BUILD SUCCESSFUL (total time: 22 seconds)
CS480(N)_HW2_17464_KISHORE_ELCHURI
CS480(N)_HW2_17464_KISHORE_ELCHURI
5. [15 points] Modify program 4 to display the student with highest score and second highest score with their names.
Program:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clshm2;
import java.util.Scanner;
/**
*
* @author kishore
*/
import java.util.*;
public class DisplayStudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
CS480(N)_HW2_17464_KISHORE_ELCHURI
System.out.println("enter the number of students:");
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("enter a student name :");
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("enter a student score:");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Top Two Students");
System.out.println(highName + "'s score is " + highScore);
System.out.println(secondHighName + "'s score is " + secondHighScore);
}
}
Output:
CS480(N)_HW2_17464_KISHORE_ELCHURI
enter the number of students:
3
enter a student name :
pavan
enter a student score:
97
enter a student name :
venky
enter a student score:
98
enter a student name :
ramesh
enter a student score:
99
Top Two Students
ramesh's score is 99
venky's score is 98
BUILD SUCCESSFUL (total time: 48 seconds)
CS480(N)_HW2_17464_KISHORE_ELCHURI

cs java programs

                          CS480 –Java and Internet Applications Homework 1 (Fall 2015)

1. [20 points] Write a program that reads the subtotal and the gratuity rate, then computes the gratuity and total. For example, if the user enters 10 for subtotal and 15% for gratuity rate, the program displays $1.5 as gratuity and $11.5 as total. Here is a
sample run:
2. [20 points] Write a program that receives an ASCII code (an
integer between 0 and 127) and displays its character. For
example, if the user enters 97, the program displays character a.
Here is a sample run:
Enter an ASCII code : 69
The character is E Enter the subtotal and a gratuity rate:
10
15
The gratuity is $1.5 and total is $11.5
3. [20 pts] Write a program that prompts the user to enter an
integer. If the number is a multiple of 5, print HiFive. If the
number is divisible by 2 or 3, print Georgia. Here are the sample
runs:
<Output>
Enter an integer: 6
Georgia
<End Output>
<Output>
Enter an integer: 15
HiFive Georgia
<End Output>
<Output>
Enter an integer: 25
HiFive
<End Output>
4. [ 25 points] Write a program that prompts the user to enter an integer for today’s day of the week(Sunday is 0, Monday- 1,…….Saturday-6). Also prompt the user to enter the number of
days after today for a future day and display the future day of the week.
Hint: if today is Sunday, we would enter 0 and we want to know
what day it is after 10 days.We can do this by:
(0+10)%7 =3 which implies that it would be Wednesday after 10
days.
Here is a sample run:
Enter today’s day : 1
Enter the number of days elapsed since today : 17
Today is Monday and the future day is Thursday.
5.[15 points] Subraction Quiz
Write a program to teach a first grade child how to learn
subtractions. The program randomly generates two single-digit
integers number1 and number2 with number1 >= number2 and
displays a question such as “What is 9 – 2?” to the student. After
the student types the answer, the program displays whether the
answer is correct.




answers:



1)Write a program that reads the subtotal and thegratuity rate, then computes the gratuity and total?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package classweek1;
/**
*
* @author kishu
*/
import java.util.*;
public class Gratuity
{
public static void main(String[] ar)
{
Scanner sc = new Scanner(System.in);
double subtotal, gratuityRate, total, gratuity;
System.out.print("Enter a value for subtotal:");
subtotal = sc.nextDouble();
System.out.print("Enter a value for gratuity rate:");
gratuityRate = sc.nextDouble();
gratuity = (subtotal * gratuityRate) / 100;
total = subtotal + gratuity;
System.out.print("The gratuity is $" + gratuity + " and total is $" + total + ".");
}
}
Out put:
Enter a value for subtotal:10 15
Enter a value for gratuity rate:The gratuity is $1.5 and total is $11.5

2)Write a program that receives an ASCII code (an integer between 0 and 127) and displays its character.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package classweek1;
/**
*
* @author kishu
*/
import java.util.*;
public class ASCIIcode {
public static void main(String ar[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter number between 0 to 127 ");
int i = sc.nextInt();
char c = (char)i;
System.out.println("charecter is="+c);
}
}
Output:
enter number between 0 to 127
65charecter is=A
3) Write a program that prompts the user to enter an integer. If the number is a multiple of 5, print HiFive. If thenumber is divisible by 2 or 3, print Georgia.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package classweek1;
/**
*
* @author kishu
*/
import java.util.Scanner;
public class MulDiv {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int num = input.nextInt();
if (num % 5 == 0)
{
System.out.println("HiFive");
CS480_HW1_17464_Kishore_Elchuri
}
else if (num % 2 == 0|| num% 3 == 0)
{
System.out.println("Georgia");
}
else if ((num % 5 == 0)&& (num % 2 == 0 || num % 3 == 0))
{
System.out.println("HiFive Georgia");
}
}
}
Output:
Enter an integer: 26
Georgia

4) Write a program that prompts the user to enter an integer for today’s day of the week(Sunday is 0, Monday-1,…….Saturday-6). Also prompt the user to enter the number of days after today for a future day and display the future day of the week.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package classweek1;
/**
*
* @author kishu
*/
import java.util.*;
public class WeekProgram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int today, elapsedDays;
int daysToAdd, dayToFind;
System.out.print("Enter today's day:");
today = sc.nextInt();
System.out.print("Enter the number of days elapsed since today:");
elapsedDays = sc.nextInt();
daysToAdd = elapsedDays % 7;
dayToFind = today + daysToAdd;
CS480_HW1_17464_Kishore_Elchuri
if(today == 0) {
System.out.print("To day is Sunday");
} else if(today == 1) {
System.out.print("To day is Monday");
} else if(today == 2) {
System.out.print("To day is Tuesday");
} else if(today == 3) {
System.out.print("To day is Wednesday");
} else if(today == 4) {
System.out.print("To day is Thursday");
} else if(today == 5) {
System.out.print("To day is Friday");
} else if(today == 6) {
System.out.print("To day is Saturday");
}
if(dayToFind == 0) {
System.out.print(" and the future day is Sunday.");
} else if(dayToFind == 1) {
System.out.print(" and the future day is Monday.");
} else if(dayToFind == 2) {
System.out.print(" and the future day is Tuesday.");
} else if(dayToFind == 3) {
System.out.print(" and the future day is Wednesday.");
} else if(dayToFind == 4) {
System.out.print(" and the future day is Thursday.");
} else if(dayToFind == 5) {
System.out.print(" and the future day is Friday.");
} else if(dayToFind == 6) {
System.out.print(" and the future day is Saturday.");
}
}
}
Output :
Enter today's day:1
Enter the number of days elapsed since today:17
To day is Monday and the future day is Thursday

5) Write a program to teach a first grade child how to learnsubtractions. The program randomly generates two single-digit integers number1 and number2 with number1 >= number2 and displays a question such as “What is 9 – 2?” to the student. After
the student types the answer, the program displays whether the answer is correct.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package classweek1;
/**
*
* @author kishu
*/
import java.util.*;
CS480_HW1_17464_Kishore_Elchuri
public class SubtractionQuiz {
public static void main(String ar[])
{
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
System.out.print("What is " + number1 + " - " + number2 + "? ");
Scanner input = new Scanner(System.in);
int answer = input.nextInt();
if (number1 - number2 == answer)
System.out.println("You are correct");
else
System.out.println("Your answer is wrong.\n" + number1 + " - "
+ number2 + " should be " + (number1 - number2));
}
}
Output :
What is 7 - 5? 2
You are correct

Monday 2 February 2015

RecursiveLinearSearchDemo


1)write java programs that use recursive function for implementing Linear Search  method?

import java.util.*;
class RecursiveLinearSearchDemo
{
static int[] a;
static int key;
public static void main(String args[])
{
int i,num;
Scanner input=new Scanner(System.in);
    System.out.println("enter no of items");
    num=input.nextInt();
     a=new int[num];
    System.out.println("enter " + num + "items");
      for(i=0;i<num;i++)
          a[i]=input.nextInt();

 System.out.println("enter element u want to search");
             key=input.nextInt();

if( linearSearch(a.length-1) )
System.out.println(key + " found in the list" );
else
System.out.println(key + " not found in the list");
}
static boolean linearSearch(int n)
{
if( n < 0 ){
    return false;
}
if(key == a[n]){
return true;
}
else{
return linearSearch(n-1);
}

}
}

LINEAR SEARCH


1) write java programs that use non-recursive function for implementing Linear Search  method?

import java.util.Scanner;
class Linear
{
public static void main(String ar[])
{
int i,n,item,a[];
Scanner sc=new Scanner(System.in);
System.out.println("enter the size of the array");
n=sc.nextInt();
a=new int[n];
System.out.println("enter " + n + "  values");
for(i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println("enter element u want to search");
item=sc.nextInt();
for(i=0;i<n;i++)
{
if(a[i]==item)
{
System.out.println(item + "   found at index    " + i);
break;
}
}
if(i==n)
{
System.out.println("element not found");
}
}
}

Saturday 31 January 2015

palindrome by using stack


import java.util.Stack;
import java.util.Scanner;
class Palindromstack
 {
     public static void main(String[] args)
        {
           System.out.print("Enter any string:");
           Scanner in=new Scanner(System.in);
           String inputString = in.nextLine();
           Stack stack = new Stack();
           for (int i = 0; i < inputString.length(); i++)
             {
                stack.push(inputString.charAt(i));
             }

             String reverseString = "";
             while (!stack.isEmpty())
                {
                    reverseString = reverseString+stack.pop();
                }
               if (inputString.equals(reverseString))
                  System.out.println("The input String is a palindrome.");
              else
                 System.out.println("The input String is not a palindrome.");
         }
   }





palindrome using queues


import java.util.Queue;
import java.util.Scanner;
import java.util.LinkedList;
class Palindromequeue {

    public static void main(String[] args) {

        System.out.print("Enter any string:");
        Scanner in=new Scanner(System.in);
        String inputString = in.nextLine();
        Queue queue = new LinkedList();

        for (int i = inputString.length()-1; i >=0; i--) {
            queue.add(inputString.charAt(i));
        }

        String reverseString = "";

        while (!queue.isEmpty()) {
            reverseString = reverseString+queue.remove();
        }
        if (inputString.equals(reverseString))
            System.out.println("The input String is a palindrome.");
        else
            System.out.println("The input String is not a palindrome.");

    }
}





Friday 23 January 2015

convert a given infix expression into postfix form using stack



      import java.lang.*;
      import java.io.*;
      import java.util.*;
      class charstack
 {
 int top,size;
 char stack[],ele;
 charstack(int n)
 {
 size=n;
 top=-1;
stack=new char[n];
}
void push(char x)
{
ele=x;
if(!isfull())
{
stack[++top]=ele;
}
else
System.out.println("stack is full");
}
char pop()
{
if(!isempty())
{
return stack[top--];
}
else
{
System.out.println("stack is empty");
return 'a';
}
}
boolean isempty()
{
if(top==-1)
return true;
else
return false;
}
boolean isfull()
{

if(top>size)
return true;
else
return false;
}
void display()
{
if(!isempty())
System.out.println("="+stack[top]);
else
System.out.println("stack is empty");
}
char peek()
{
return stack[top];
}
}
class iftopf
{
charstack cs;
char pf[];
iftopf()
{
cs=new charstack(50);
pf=new char[50];
}
boolean iop(char op)
{
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='('||op==')'||op=='^'||op=='%')
return true;
else
return false;
}
int prec(char op)
{
if(op=='+'||op=='-')
return 1;
else if(op=='/'||op=='*')
return 2;
else if(op=='%'||op=='^')
return 3;
return 0;
}
void infixtop(String infix)
{
char isym;
int j=0;
char ir[]=infix.toCharArray();
for(int i=0;i<ir.length;i++)
{
isym=ir[i];
if(!iop(isym))
{
pf[j]=isym;
j++;
}
else
{
if(isym=='('||cs.isempty())
cs.push(isym);
else if(isym==')')
{
while(cs.peek()!='(')
{
pf[j]=cs.pop();
j++;
}
char v=cs.pop();
}
else if(cs.isempty())
cs.push(isym);
else if(cs.isempty()||cs.peek()=='('||(prec(cs.peek())<prec(isym)))
cs.push(isym);
else
{
while((!cs.isempty())&&(cs.peek()!='(')&&prec(cs.peek())>=prec(isym))
{
pf[j]=cs.pop();
j++;
}
cs.push(isym);
}
}
}
while(!cs.isempty())
{
pf[j]=cs.pop();
j++;
}
}
void display1()
{
for(int i=0;i<pf.length-1;i++)
System.out.print(pf[i]);
}
public static void main(String args[])throws Exception
{
iftopf ob=new iftopf();
Scanner r=new Scanner(System.in);
System.out.println("enter any equation:");
String s=r.nextLine();
ob.infixtop(s);
ob.display1();
}
}
Output:

circular queue ADT using an array.


import java.util.*;
class CirQue
{
int front,rear,next=0;
int que[];
int max,count=0;
CirQue(int n)
{
max=n;
que=new int[max];
front=rear=-1;
}
boolean isfull()
{
if(front==(rear+1)%max)
return true;
else
return false;
}
boolean isempty()
{
if(front==-1&&rear==-1)
return true;
else
return false;
}
int delete()
{
if(isempty())
{
return -1;
}
else
{
count --;
int x=que[front];
if(front==rear)
front=rear=-1;
else
{
next=(front+1)%max;
front=next;
}
return x;
}
}
void insert(int item)
{
if(isempty())
{
que[++rear]=item;
front=rear;
count ++;
}
else if(!isfull())
{
next=(rear+1)%max;
if(next!=front)
{
que[next]=item;
rear=next;
}
count ++;
}
else
System.out.println("q is full");
}
void display()
{
if(isempty())
System.out.println("queue is empty");
else
next=(front)%max;
while(next<=rear)
{
System.out.println(que[next]);
next++;
}
}
int size()
{
return count;
}
public static void main(String args[])
{
int ch;
Scanner s=new Scanner(System.in);
System.out.println("enter limit");
int n=s.nextInt();
CirQue q=new CirQue(n);
do
{
System.out.println("1.insert");
System.out.println("2.delete");
System.out.println("3.display");
System.out.println("4.size");
System.out.println("enter ur choice :");
ch=s.nextInt();
switch(ch)
{
case 1:System.out.println("enter element :");
int n1=s.nextInt();
q.insert(n1);
break;
case 2:int c1=q.delete();
if(c1>0)
System.out.println("deleted element is :"+c1);
else
System.out.println("can't delete");
break;
case 3:q.display();
break;
case 4:System.out.println("queue size is "+q.size());
break;
}
}
while(ch!=0);
}
}



implement the Stack ADT,Queue ADT using an array.

stack ADT
import java.io.*;
class stackclass
{
int top,ele,stack[],size;
stackclass(int n)
{
stack=new int[n];
size=n;
top=-1;
}
void push(int x)
{
ele=x;
stack[++top]=ele;
}
int pop()
{
if(!isempty())
{
System.out.println("Deleted element is");
return stack[top--];
}
else
{
System.out.println("stack is empty");
return -1;
}
}
boolean isempty()
{
if(top==-1)
return true;
else
return false;
}
boolean isfull()
{
if(size>(top+1))
return false;
else
return true;
}
int peek()
{
if(!isempty())
return stack[top];
else
{
System.out.println("stack is empty");
return -1;
}
}
void size()
{
System.out.println("size of the stack is :"+(top+1));
}
void display()
{
if(!isempty())
{
for(int i=top;i>=0;i--)
System.out.print(stack[i]+" ");
}
else
System.out.println("stack is empty");
}
}class stacktest
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the size of stack");
int size=Integer.parseInt(br.readLine());
stackclass s=new stackclass(size);
int ch,ele;
do
{
System.out.println();
System.out.println("1.push");
System.out.println("2.pop");
System.out.println("3.peek");
System.out.println("4.size");
System.out.println("5.display");
System.out.println("6.is empty");
System.out.println("7.is full");
System.out.println("8.exit");
System.out.println("enter ur choise :");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:if(!s.isfull())
{
System.out.println("enter the element to insert: ");
ele=Integer.parseInt(br.readLine());
s.push(ele);
}
else
{
System.out.print("stack is overflow");
}
break;
case 2:int del=s.pop();
if(del!=-1)
System.out.println(del+" is deleted");
break;
case 3:int p=s.peek();
if(p!=-1)
System.out.println("peek element is: "+p);
break;
case 4:s.size();
break;
case 5:s.display();
break;
case 6:boolean b=s.isempty();
System.out.println(b);
break;
case 7:boolean b1=s.isfull();
System.out.println(b1);
break;
}
}
while(ch!=0);
}
}


queue ADT
import java.util.*;
class queue
{
int front,rear;
int que[];
int max,count=0;
queue(int n)
{
max=n;
que=new int[max];
front=rear=-1;
}
boolean isfull()
{
if(rear==(max-1))
return true;
else
return false;
}
boolean isempty()
{
if(front==-1)
return true;
else
return false;
}
void insert(int n)
{
if(isfull())
System.out.println("list is full");
else
{
rear++;
que[rear]=n;
if(front==-1)
front=0;
count++;
}
}
int delete()
{
int x;
if(isempty())
return -1;
else
{
x=que[front];
que[front]=0;
if(front==rear)
front=rear=-1;
else
front++;
count--;
}
return x;
}
void display()
{
if(isempty())
System.out.println("queue is empty");
else
for(int i=front;i<=rear;i++)
System.out.println(que[i]);
}
int size()
{
return count;
}
public static void main(String args[])
{
int ch;
Scanner s=new Scanner(System.in);
System.out.println("enter limit");
int n=s.nextInt();
queue q=new queue(n);
do
{
System.out.println("1.insert");
System.out.println("2.delete");
System.out.println("3.display");
System.out.println("4.size");
System.out.println("enter ur choise :");
ch=s.nextInt();
switch(ch)
{
case 1:System.out.println("enter element :");
int n1=s.nextInt();
q.insert(n1);
break;
case 2:int c1=q.delete();
if(c1>0)
System.out.println("deleted element is :"+c1);
else
System.out.println("can't delete");
break;
case 3:q.display();
break;
case 4:System.out.println("queue size is "+q.size());
break;
}
}
while(ch!=0);
}
}

implement the Stack ADT,Queue ADT using a singly linked list

stack ADT
import java.io.*;
class Stack
{
Stack top,next,prev;
int data;
Stack()
{
data=0;
next=prev=null;
}
Stack(int d)
{
data=d;
next=prev=null;
}
void push(int n)
{
Stack nn;
nn=new Stack(n);
if(top==null)
top=nn;
else
{
nn.next=top;
top.prev=nn;
top=nn;
}
}
int pop()
{
int k=top.data;
if(top.next==null){
top=null;
return k;}
else{
top=top.next;
top.prev=null;
return k;
}
}
boolean isEmpty()
{
if(top==null)
return true;
else
return false;
}
void display()
{
Stack ptr;
for(ptr=top;ptr!=null;ptr=ptr.next)
System.out.print(ptr.data+" ");
}
public static void main(String args[ ])throws Exception
{
int x;
int ch;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
Stack a=new Stack();
do{
System.out.println("enter 1 for pushing");
System.out.println("enter 2 for poping");
System.out.println("enter 3 for isEmpty");
System.out.println("enter 4 for display");
System.out.println("Enter 0 for exit");
System.out.println("enter ur choice ");
ch=Integer.parseInt(b.readLine());
switch(ch)
{
case 1:System.out.println("enter element to insert");
int e=Integer.parseInt(b.readLine());
a.push(e);
break;
case 2:if(!a.isEmpty())
{
int p=a.pop();
System.out.println("deleted element is "+p);
}
else
{
System.out.println("stack is empty");
}
break;
case 3:System.out.println(a.isEmpty());
break;
case 4:if(!a.isEmpty())
{
a.display();
}
else
{
System.out.println("list is empty");
}
}
}while(ch!=0);
}
}
OUTPUT:


b. queue ADT
import java.io.*;
class Qlnk
{
Qlnk front,rear,next;
int data;
Qlnk()
{
data=0;
next=null;
}
Qlnk(int d)
{
data=d;
next=null;
}
Qlnk getFront()
{
return front;
}
Qlnk getRear()
{
return rear;
}
void insertelm(int item)
{
Qlnk nn;
nn=new Qlnk(item);
if(isEmpty())
{
front=rear=nn;
}
else
{
rear.next=nn;
rear=nn;
}
}
int delelm()
{
if(isEmpty())
{
System.out.println("deletion failed");
return -1;
}
else
{
int k=front.data;
if(front!=rear)
front=front.next;
else
rear=front=null;
return k;
}
}
boolean isEmpty()
{
if(rear==null)
return true;
else
return false;
}
int size()
{
Qlnk ptr;
int cnt=0;
for(ptr=front;ptr!=null;ptr=ptr.next)
cnt++;
return cnt;
}
void display()
{
Qlnk ptr;
if(!isEmpty())
{
for(ptr=front;ptr!=null;ptr=ptr.next)
System.out.print(ptr.data+" ");
}
else
System.out.println("q is empty");
}
public static void main(String arr[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Qlnk m=new Qlnk();
int ch;
do
{
System.out.println("enter 1 for insert");
System.out.println("enter 2 for deletion");
System.out.println("enter 3 for getFront");
System.out.println("enter 4 for getRear");
System.out.println("enter 5 for size");
System.out.println("enter 6 for display");
System.out.println("enter 0 for exit");
System.out.println("enter ur choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:System.out.println("enter ele to insert");
int item=Integer.parseInt(br.readLine());
m.insertelm(item);break;
case 2:int k=m.delelm();
System.out.println("deleted ele is "+k);break;
case 3:System.out.println("front index is"+(m.getFront()).data);break;
case 4:System.out.println("rear index is"+(m.getRear()).data);break;
case 5:System.out.println("size is"+m.size());break;
case 6:m.display();break;
}
}while(ch!=0);
}
}



implement the List ADT using Arrays

import java.io.*;
interface ListADT
{
void traversal();
boolean isFull();
boolean isEmpty();
int search(int key);
void insertAtBeg(int item);
void insertAtEnd(int item);
void insertAtPos(int pos,int item);
void insertAfterPos(int pos,int item);
void insertAfterKey(int key,int item);
void delete(int key);
void deletePos(int pos);
}
class ArrayDS implements ListADT
{
int a[],n,max;
ArrayDS(int cap)
{
max=cap;
a=new int[max];
n=0;
}
public void traversal()
{
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
System.out.println("\n");
}
public boolean isFull()
{
if(n==max)
return true;
return false;
}
public boolean isEmpty()
{
if(n==0)
return true;
return false;
}
public int search(int key)
{
for(int i=0;i<n;i++)
if(a[i]==key)
return i;
return -1;
}
public void insertAtBeg(int item)
{
if(!isFull())
{
for(int i=n-1;i>=0;i--)
a[i+1]=a[i];
a[0]=item;
n++;
}
else
System.out.println("Array is Full, cannot insert");
}
public void insertAtEnd(int item)
{
if(!isFull())
{
a[n++]=item;
}
else
System.out.println("Array is Full, cannot insert");
}
public void insertAtPos(int pos,int item)
{
if(!isFull())
{
for(int i=n-1;i>=pos;i--)
a[i+1]=a[i];
a[pos]=item;
n++;
}
else
System.out.println("Cannot insert, Array is Full");
}
public void insertAfterPos(int pos,int item)
{
if(pos<n)
insertAtPos(pos+1,item);
else
System.out.println("Array is Full, cannot insert");
}
public void insertAfterKey(int key,int item)
{
int p=search(key);
if(p==-1)
System.out.println("Cannot insert");
else
insertAfterPos(p,item);
}
public void delete(int key)
{
if(!isEmpty())
{
int p=search(key);
deletePos(p);
}
else
System.out.println("Array is Empty");
}
public void deletePos(int pos)
{
if(!isEmpty())
{
if(pos<0||pos>n-1)
{
System.out.println("Cannot delete, Element not found");
}
else
{
for(int i=pos;i<n-1;i++)
a[i]=a[i+1];
n--;
}
}
else
System.out.println("Array is Empty");
}
}
class ArrayTest
{
public static void main(String arg[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the size of the Array");
int n=Integer.parseInt(br.readLine());
ArrayDS ar=new ArrayDS(n);
System.out.println("Array is created");
ar.traversal();
int t,k,m=1;
do
{
System.out.println("Enter ur choice of operation");
System.out.println("1-insertAtBeg\n2-insertAtEnd\n3-insertAtPos\n4-insertAfterPos\n5-insertAfterKey\n6-deleteItem\n7-deletePos\n0-exit");
n=Integer.parseInt(br.readLine());
switch(n)
{
case 1:
System.out.println("Enter the element to be inserted");
t=Integer.parseInt(br.readLine());
ar.insertAtBeg(t);
ar.traversal();
break;
case 2:
System.out.println("Enter the element to be inserted");
t=Integer.parseInt(br.readLine());
ar.insertAtEnd(t);
ar.traversal();
break;
case 3:
System.out.println("Enter the element to be inserted:");
t=Integer.parseInt(br.readLine());
System.out.println("Enter the index position to insert at:");
k=Integer.parseInt(br.readLine());
ar.insertAtPos(k,t);
ar.traversal();
break;
case 4:
System.out.println("Enter the element to be inserted");
t=Integer.parseInt(br.readLine());
System.out.println("Enter the index position to insert after");
k=Integer.parseInt(br.readLine());
ar.insertAfterPos(k,t);
ar.traversal();
break;
case 5:
System.out.println("Enter the element to be inserted:");
t=Integer.parseInt(br.readLine());
System.out.println("Enter the key element to insert aftter:");
k=Integer.parseInt(br.readLine());
ar.insertAfterKey(k,t);
ar.traversal();
break;
case 6:
System.out.println("Enter the element to be deleted");
t=Integer.parseInt(br.readLine());
ar.delete(t);
ar.traversal();
break;
case 7:
System.out.println("Enter the position to be deleted");
t=Integer.parseInt(br.readLine());
ar.deletePos(t);
ar.traversal();
break;
case 0:
m=0;
break
default:
System.out.println("INVALID CHOICE");
}
}while(m==1);
ar.traversal();
}
}