Introduction To Computer Programming Practise Quetions
Introduction To Computer Programming Practise Quetions
5. Write a java program that stores your Regd. No and year of admission into two variables, and displays their values on
the screen.
My Regd. No is 171123142 and I have taken admission in B. Tech. In 2017.
11. Suppose that a variable a is declared as int a = 2147483647 (or equivalently, Integer.MAX_VALUE ). What do each of
the following print?
a. System.out.println(a);
b. System.out.println(a+1);
c. System.out.println(2-a);
d. System.out.println(-2-a);
e. System.out.println(2*a);
f. System.out.println(4*a);
public class A1q11 {
public static void main(String[] args) {
int a = 2147483647;
System.out.println(a);
System.out.println(a+1);
System.out.println(2-a);
System.out.println(-2-a);
System.out.println(2*a);
System.out.println(4*a);
}
}
Output
2147483647
-2147483648
-2147483645
2147483647
-2
-4
12. Suppose that a variable a is declared as double a = 3.14159. What do each of the following print?
a. System.out.println(a);
b. System.out.println(a+1);
c. System.out.println(8/(int) a);
d. System.out.println(8/a);
e. System.out.println((int) (8/a));
public class A1q12 {
public static void main(String[] args) {
double a = 3.14159;
System.out.println(a);
System.out.println(a+1);
System.out.println(8/(int) a);
System.out.println(8/a);
System.out.println((int) (8/a));
}
}
Output
3.14159
4.14159
2
2.5464812403910124
2
13. Assume a string variable ruler1 contains “1” initially i.e. String ruler1=”1”
Write a java program to print the following output using string concatenation. (You can take extra string variables)
1
121
1213121
121312141213121
public class A1q13 {
public static void main(String[] args) {
String ruler1="1";
String ruler2="2";
String ruler3="3";
String ruler4="4";
System.out.println(ruler1);
System.out.println(ruler1+ruler2+ruler1);
System.out.println(ruler1+ruler2+ruler1+ruler3+ruler1+ruler2+ruler1);
System.out.println(ruler1+ruler2+ruler1+ruler3+ruler1+ruler2+ruler1+ruler4+ruler1+ruler2+ruler1+ruler3+ruler1+ruler2+ruler1)
}
}
Output
1
121
1213121
121312141213121
ASSIGNMENT 2
1. Write a java program that takes two positive integers as command-line arguments and prints true if either evenly
divides the other.
public class A2q1 {
public static void main(String[] args) {
int a,b;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
boolean ans=((a%b==0)||(b%a==0));
System.out.println(ans);
}
}
Output
5
6
False
2. Write a java program that takes three positive integers as command-line arguments and prints true if any one of them is
greater than or equal to the sum of the other two and false otherwise. (Note: This computation tests whether the three
numbers could be the lengths of the sides of some triangle.)
public class A2q2 {
public static void main(String[] args) {
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[2]);
boolean res=((a+b)>=c)||((b+c)>=a)||((a+c)>=b);
System.out.println(res);
}
}
Output
567
true
3. Write a java program that takes two int values a and b from the command line and prints a random integer between a
and b.
public class A2q3 {
public static void main(String[] args) {
int min;
int max;
min=Integer.parseInt(args[0]);
max=Integer.parseInt(args[1]);
int c=min+(int)(Math.random()*(max-min+1));
System.out.println(“c=”+c);
}
}
Output
1
6
C=4
4. Write a java program that prints the sum of two random integers between 1 and 6 (such as you might get when rolling
dice).
public class A2q4 {
public static void main(String[] args) {
int a,b,res1,res2;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
res1=a+(int)(Math.random()*(a-b+1));
res2=a+(int)(Math.random()*(a-b+1));
int sum=res1+res2;
System.out.println(sum);
}}
Output
1
-1
0
5. Write a java program that takes a double value t from the command line and prints the value of sin (2t) + sin (3t).
public class A2q5 {
public static void main(String[] args) {
double t,sum;
t=Double.parseDouble(args[0]);
t=Math.toRadians(t); // convert degree to radian
sum=(Math.sin(2*t)+Math.sin(3*t));
System.out.println(sum);
}
}
Output
0.13688836327308107
6. Write a java program that takes three double values x0, v0, and t from the command line and prints the value of x0 +
v0t + g t 2 / 2, where g is the constant 9.78033. (Note: This value the displacement in meters after t seconds when an object
is thrown straight up from initial position x0 at velocity v0 meters per second.)
public class A2q6 {
public static void main(String[] args) {
double x0,v0,t,g;
g=9.78033;
x0=Double.parseDouble(args[0]);
v0=Double.parseDouble(args[1]);
t=Double.parseDouble(args[2]);
double X=(x0+(v0*t)+((g*t*t)/2));
System.out.println(“X=”+X);
}
}
Output
10 10 10
X=599.0165
7. Write a program that takes two int values m and d from the command line and prints true if day d of month m is
between 3/20 and 6/20, false otherwise.
public class A2q7 {
public static void main(String[] args) {
int m,d;
m=Integer.parseInt(args[0]);
d=Integer.parseInt(args[1]);
boolean res=(m==3&&d>=20)||(m==4&&d<=30)||(m==5&&d<=31)||(m==6&&d<=20);
System.out.println(res);
}
}
Output
5 31
true
8. Write a java program that calculates the monthly payments you would have to make over a given number of years to
pay off a loan at a given interest rate compounded continuously, taking the number of years t, the principal P, and the
annual interest rate r as command-line arguments. The desired value is given by the formula Pert. Use Math.exp ().
public class A2q8 {
public static void main(String[] args) {
double p,r,t;
p=Double.parseDouble(args[0]);
r=Double.parseDouble(args[1]);
t=Double.parseDouble(args[2]);
double monthly_payment=p*Math.exp(r*t);
System.out.println(monthly_payment);
}
}
Output
100 5 10
5.184705528587072E23
9. Write a java program that takes three double values x, y, and z as command-line arguments and prints true if the values
are strictly ascending or descending ( x < y < z or x > y > z ), and false otherwise.
public class A2q9 {
public static void main(String[] args) {
int x,y,z;
x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
z=Integer.parseInt(args[2]);
boolean res=((x<y&&y<z)||(x>y&&y>z));
System.out.println(res);
}
}
Output
567
true
10. Write a java program that prints five uniform random values between 0 and 1, their average value, and their minimum
and maximum value. Use Math.random(), Math.min(), and Math.max().
public class A2q10 {
public static void main(String[] args) {
double r1,r2,r3,r4,r5;
r1=Math.random();
r2=Math.random();
r3=Math.random();
r4=Math.random();
r5=Math.random();
System.out.println(r1+" "+r2+" "+r3+" "+r4+" "+r5);
double sum=r1+r2+r3+r4+r5;
double avg=sum/5;
System.out.println(“Average =”+avg);
double max=Math.max(r1,Math.max(r2,Math.max(r3,Math.max(r4, r5))));
double min=Math.min(r1,Math.min(r2,Math.min(r3,Math.min(r4, r5))));
System.out.println(“Max=”+max);
System.out.println(“Min=”+min);
}
}
Output
0.43867322924267294 0.9380513393943634 0.7249588917162044 0.4277911675596985 0.28403812916041526
Average =0.5627025514146708
Max=0.9380513393943634
Min=0.28403812916041526
11. Write a program that takes three int values from the command line and prints them in ascending order. Use
Math.min() and Math.max().
public class A2q11 {
public static void main(String[] args) {
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[2]);
int max=Math.max(a,Math.max(b,c));
int min=Math.min(a,Math.min(b,c));
int median=(a+b+c)-max-min;
System.out.println(min+" "+median+" "+max);
}
}
Output
657
567
Using Keyboard Input
12. Write a java program which requests the user to enter a number. The number and the square of the number are then
printed on the same line. For example, if 4 is entered, the program outputs:
Number=4 Square of Number=16
import java.util.*;
public class A2q12 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of a");
int a=sc.nextInt();
int sqr=a*a;
System.out.println("The number is "+a+" and the square is "+sqr);
}
}
Output
Enter the value of a
10
The number is 10 and the square is 100
13. Write a java program to input some kind of information of a person from the keyboard.
Age of a person , Height of a person , Weight of a person and display it in the following manner. e.g.
So, you're 35 years old, 6'2" tall and 60KG heavy.
import java.util.*;
public class A2q13 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int age,weight;
String height;
System.out.println("Enter age weight and height of a person");
age=sc.nextInt();
weight=sc.nextInt();
height=sc.next();
System.out.println("So,you\'re "+age+"years old "+height+"tall"+weight+"Kg heavy");
}
}
Output
Enter age weight and height of a person
20
60
5'6"
So,you're 20years old 5'6"tall60Kg heavy
14. Input the basic salary of an employee of an organization through the keyboard. His dearness allowance (DA) is 40% of
basic salary, and house rent allowance (HRA) is 20% of basic salary. Write a java program to calculate his gross salary.
import java.util.*;
public class A2q14 {
public static void main(String[] args) {
double basic,HRA,DA,gross;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the basic salary of the person");
basic=sc.nextDouble();
DA=0.40*basic;
HRA=0.20*basic;
gross=basic+DA+HRA;
System.out.println("The gross salary is: "+gross);
}
}
Output
Enter the basic salary of the person
10000
The gross salary is: 16000.0
15. Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a java program to convert this
temperature into Centigrade degrees.
import java.util.*;
public class A2q15 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double F,C;
System.out.println("Enter the temperature of your city in Farenheit");
F=sc.nextDouble();
C=((F-32)*5)/9;
System.out.println("The temperature of your city in Centigrade is "+C);
}
}
Output
Enter the temperature of your city in Farenheit
98.4
The temperature of your city in Centigrade is 36.888888888888886
16. The length & breadth of a rectangle and radius of a circle are inputted through the keyboard. Write a java program to
calculate the area & perimeter of the rectangle, and the area & circumference of the circle.
17. Write a java program that helps the user count his change. The program should ask how many 25 paisa users have,
then how many 50 paisa, then how many one rupees. Then the program should tell the user how much money he has,
expressed in rupees.
import java.util.*;
public class A2q17 {
public static void main(String[] args) {
int paisa25,paisa50,rupee;
Scanner sc=new Scanner(System.in);
System.out.println("How many 25 paisa coins do you have?");
paisa25=sc.nextInt();
System.out.println("How many 50 paisa coins do you have?");
paisa50=sc.nextInt();
System.out.println("How many 1 rupee coins do you have?");
rupee=sc.nextInt();
double total=(0.25*paisa25)+(0.50*paisa50)+(1*rupee);
System.out.println("The total money you have is "+total);
}
}
Output
How many 25 paisa coins do you have?
10
How many 50 paisa coins do you have?
15
How many 1 rupee coins do you have?
20
The total money you have is 30.0
18. If you have N eggs, then you have N/12 dozen eggs, with N%12 eggs left over. (This is essentially the definition of the /
and % operators for integers.) Write a java program that asks the user how many eggs she has and then tells the user how
many dozen eggs she has and how many extra eggs are left over. A gross of eggs is equal to 144 eggs. Extend your program
so that it will tell the user how many gross, how many dozen, and how many left over eggs she has. For example, if the user
says that she has 1342 eggs, and then your program would respond with
Your number of eggs is 9 gross, 3 dozen, and 10.
import java.util.*;
public class A2q18 {
public static void main(String[] args) {
int num,dozen,gross;
Scanner sc=new Scanner(System.in);
System.out.println("How many eggs do you have?");
num=sc.nextInt();
gross=num/144;
num=num%144;
dozen=num/12;
num=num%12;
System.out.println("Your number of eggs is "+gross+"gross,"+dozen+"dozens,"+"and"+num);
}
}
Output
How many eggs do you have?
1000
Your number of eggs is 6 gross, 11 dozens,and 4
Assignment 3
Programming Assignment-III
(Conditional Statements)
1. Write a java program to input the height of the person and check if the height of the person is greater than or equal to 6
feet then print the message “The person is tall”.
import java.util.Scanner;
public class A3q1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int h;
System.out.println("Enter the height of the person");
h=sc.nextInt();
if(h>6)
System.out.println("The person is tall");
}
}
Output
Enter the height of the person
7
The person is tall
2. Write a java program to input the mark of a student and check if the student mark is greater than or equal to 40, then it
generates the following message.
”Congratulation! You have passed the exam.”
Otherwise the output message is
”Sorry! You have failed the exam.”
import java.util.*;
public class A3q2 {
3. Input an integer through the keyboard. Write a java program to find out whether it is an odd number or even number.
import java.util.*;
public class A3q3 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter a number");
n=sc.nextInt();
if(n%2==0)
System.out.println("Even number");
else
System.out.println("Odd number");
}
}
Output
Enter a number
10
Even number
4. Write a java program that takes three integers as command-line arguments and prints equal if all three are equal, and
not equal otherwise.
public class A3q4 {
public static void main(String[] args) {
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[2]);
if(a==b&&b==c&&c==a)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
Output
555
Equal
5. Write a java program that prints true if the double variables x and y are both strictly between 0 and 1 and false
otherwise.
import java.util.*;
public class A3q5 {
6. Any character is entered through the keyboard, write a java program to determine whether the character entered is a
capital letter, a small case letter, a digit or a special symbol. The following table shows the range of ASCII values for
various characters.
Characters ASCII Values
A–Z 65 – 90
a–z 97 – 122
0–9 48 – 57
special symbols 0 - 47, 58 - 64, 91 - 96, 123 – 127
import java.util.*;
public class A3q6 {
public static void main(String[] args) {
char c;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a character");
c=sc.next().charAt(0);
int n=(int) c;
if(n>=65&&n<=90)
System.out.println("The entered character is an uppercase");
else if(n>=97&&n<=122)
System.out.println("The entered character is a lower case");
else if(n>=48&&n<=57)
System.out.println("It is a digit");
else if((n>=0&&n<=47)||(n>=58&&n<=64)||(n>=91&&n<=96)||(n>=123&&n<=127))
System.out.println("It is a special Character");
}
}
Output
Enter a character
A
The entered character is an uppercase
Enter a character
a
The entered character is a lower case
Enter a character
5
It is a digit
Enter a character
#
It is a special Character
7. Given three points (x1, y1), (x2, y2) and (x3, y3), write a C program to check if all the three points fall on one straight
line. Hint: Three points are collinear, if slope of one set of points = slope of other set of points.
import java.util.Scanner;
public class A3q7 {
8. If the ages of Rahul, Ayush and Ajay are input through the keyboard, write a java program to determine the youngest of
the three.
import java.util.*;
public class A3q8 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int Rahul,Ayush,Ajay,y;
String s="Rahul";
String p="Ayush";
String q="Ajay";
System.out.println("Entert the ages of Rahul,Ayush,Ajay respectively");
Rahul=sc.nextInt();
Ayush=sc.nextInt();
Ajay=sc.nextInt();
if(Rahul<Ayush&&Rahul<Ajay)
{y=Rahul;
System.out.println("Youngest is Rahul");
}
else if(Ayush<Rahul&&Ayush<Ajay)
{
y=Ayush;
System.out.println("The youngest is Ayush");
}
else
{
y=Ajay;;
System.out.println("The youngest is Ajay");
}
}
}
Output
Entert the ages of Rahul,Ayush,Ajay respectively
18
20
17
The youngest is Ajay
9. Write a java program that takes the x – y coordinates of a point in the Cartesian plane and prints a message telling
either an axis on which the point lies or the quadrant in which it is found.
import java.util.*;
public class A3q9 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double x,y;
System.out.println("Enter teh x and y coordinate respectively");
x=sc.nextDouble();
y=sc.nextDouble();
if(x==0)
System.out.println("("+x+","+y+")is on the y-axis");
else if(y==0)
System.out.println("("+x+","+y+") is on the x-axis");
else if(x>0&&y>0)
System.out.println("("+x+","+y+") is on the first quadrant");
else if(x<0&&y>0)
System.out.println("("+x+","+y+") is on the second quadrant");
else if(x<0&&y<0)
System.out.println("("+x+","+y+" is on the third quadrant");
else
System.out.println("("+x+","+y+") is on the fourth quadrant");
}
}
Output
(-1.0, -2.5) is in quadrant III
(0.0, 4.8) is on the y-axis
10. Write a java program that prints the roots of the polynomial ax2 + bx + c, prints an appropriate message if the
discriminate is negative, and behaves appropriately (avoiding division by zero) if a is zero.
import java.util.Scanner;
public class A3q10 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double a,b,c,d,r1=0,r2=0;
System.out.println("Enter a, b and c");
a=sc.nextDouble();
b=sc.nextDouble();
c=sc.nextDouble();
if(a==0)
{
System.out.println("not a quadratic equation");
}
else
{
d=b*b-4*a*c;
if(d==0)
{
r1=r2=-b/(2*a);
System.out.println("root1=root2= "+r1);
}
else if(d>=0)
{
r1=-b+Math.sqrt(d)/(2*a);
r2=-b-Math.sqrt(d)/(2*a);
System.out.println("root1= "+r1+" root2 = "+r2);
}
else
{
System.out.println("roots are imaginary");
}
}
}
}
Output
Enter a, b and c
184
root1= -4.535898384862246 root2 = -11.464101615137753
11. The body mass index (BMI) is commonly used by health and nutrition professionals to estimate human body fat in
populations. It is computed by taking the individual's weight (mass) in kilograms and dividing it by the square of their
height in meters. i.e. ������:���=���� ℎ(��)(ℎ���ℎ�(�))2
Then use some if statements to show the category for a given
import java.util.Scanner;
public class A3q11 {
12. Write a java program which inputs one positive integer specifying the year of birth of a person and returns an output
the name of the generation that the person is part of (’X’, ’Y’, or ’Z ’) according to the table below. For births before 1966,
return ’O’ for Old and for births after 2012, return ’K’ for Kid.
Generation Born
X 1966-1980
Y 1981-1999
Z 2000-2012
import java.util.Scanner;
public class p1 {
}
}
Output
Enter the year of birth of a person
1970
Generation of the person is X
13. A University conducts a 100 mark exam for its student and grades them as follows. Assigns a grade based on the value
of the marks. Write a java program to print the grade according to the mark secured by the student. [Use switch-case]
14. Write a java program that reads the lengths of the three sides of a triangle and determines the type of the triangle
according to the following pseudo code.
Step 1: Input the length of three sides of a triangle
Step 2: compare each pair of sides and count how many pairs are equal
Step 3: if the number of equal pairs is 0 then it is irregular
otherwise if the number of equal pairs is 1 it is symmetric
otherwise it is regular
Step 4: Exit
import java.util.Scanner;
public class p1 {
15. Make a java program which displays an appropriate name for a person, using a combination of nested ifs and
compound conditions. Ask the user for a gender, first name, last name and age. If the person is female and 20 or over, ask
if she is married. If so, display "Mrs." in front of her name. If not, display "Ms." in front of her name. If the female is
under 20, display her first and last name. If the person is male and 20 or over, display "Mr." in front of his name.
Otherwise, display his first and last name. Note that asking a person if they are married should only be done if they are
female and 20 or older, which means you will have a single if and else nested inside one of your if statements. Also, did you
know that with an if statements (or else), the curly braces are optional when there is only one statement inside?
import java.util.Scanner;
public class A3q15 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Gender (M/F) ");
char g=sc.next().charAt(0);
System.out.println("Enter First Name");
String fn=sc.next();
System.out.println("Enter last Name");
String ln=sc.next();
System.out.println("Enter Age");
int age=sc.nextInt();
if(g=='F')
{
if(age>=20)
{
System.out.println("Are you married"+fn+"(y or n)?");
char m=sc.next().charAt(0);
if(m=='y')
System.out.println("Then I shall call you Mrs."+ fn+" "+ln);
else
System.out.println("Then I shall call you Ms."+ fn+" "+ln);
}
else
{
System.out.println("Then I shall call you "+ fn+" "+ln);
}
}
else
{
if(g=='M')
{
if(age>=20)
{
System.out.println("Then I shall call you Mr."+ fn+" "+ln);
}
else
{
System.out.println("Then I shall call you "+ fn+" "+ln);
}
}
}
}
}
Output:
What is your gender (M or F): F
First name: Gita
Last name: Pattanayak
Age: 32
Are you married, Gita (y or n)? y
Then I shall call you Mrs. Gita Pattanayak.
What is your gender (M or F): F
First name: Anjali
Last name: Mishra
Age: 48
Are you married, Anjali(y or n)? n
Then I shall call you Ms. Anjali.
What is your gender (M or F): M
First name: Ashok
Last name: Mohanty
Age: 23
Then I shall call you Mr. Ashok.
What is your gender (M or F): M
First name: Rahul
Last name: Pati
Age: 15
Then I shall call you Rahul Pati.
Programming Assignment-IV
(Iterative Statements/Looping)
1. Write a java program to input a string message and display it 10 times in the following manner. Use a while loop. Let the
string message be “Hello”.
public class A4q1 {
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
String msg;
System.out.println("Enter the message");
msg=sc.next();
int i=1;
while(i<=10)
{
if(i==1)
System.out.println(i+"st "+msg);
else if(i==2)
System.out.println(i+"nd "+msg);
else if(i==3)
System.out.println(i+"rd "+msg);
else
System.out.println(i+"th "+msg);
i++;
}
}
}
Output
Enter the message
hello
1st hello
2nd hello
3rd hello
4th hello
5th hello
6th hello
7th hello
8th hello
9th hello
10th hello
2. Rewrite the above java program in such a way that takes the number of lines to print as a command-line argument. You
may assume that the argument is less than 1000.
Hint: Use i % 10 and i % 100 to determine when to use st, nd, rd, or th for printing the ith Hello.
3. Write a java program that gets an integer from the user. Count from 0 to that number. Use a for loop to do it.
Count to: 20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
import java.util.*;
public class A4q3 {
4. Write a java program that gets three integers from the user. Count from the first number to the second number in
increments of the third number. Use a for loop to do it.
Count from: 4
Count to: 13
Count by: 3
4 7 10 13
import java.util.*;
public class A4q4 {
public static void main(String[] args) {
int cf,ct,cb,i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the countfrom");
cf=sc.nextInt();
System.out.println("Enter the countto");
ct=sc.nextInt();
System.out.println("Enter the countby");
cb=sc.nextInt();
for(i=cf;i<=ct;i+=cb)
{
System.out.println(i+" ");
}
}
}
Output
Enter the count from
4
Enter the count to
20
Enter the count by
5
4
9
14
19
5. Write a java program that uses a for loop. With the loop, make the variable x go from -2 to 2, counting by 0.5. (This
means that x can't be an int.)
public class A4q5 {
public static void main(String[] args) {
double x
for(x=-2;x<=2;x+=0.5)
{
System.out.println(x);
}
}
}
Output
-2.0
-1.5
-1.0
-0.5
0.0
0.5
1.0
1.5
2.0
6. Write a java program that, using one for loop and one if statement, prints the integers from 1,000 to 2,000 with five
integers per line. Hint: Use the % operation.
public class A4q6 {
7. Write a java program that takes an integer N as a command-line argument, uses Math.random() to print N uniform
random values between 0 and 1, and then prints their average value.
public class A4q7 {
9. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23. Write a java program to find the sum of all the multiples
of 3 or 5 below 1000.
public class A4q9 {
public static void main(String[] args) {
int i,sum=0;
for(i=1;i<1000;i++)
{
if(i%3==0||i%5==0)
sum+=i;
}
System.out.println("Sum of multiples of 3&5 below 1000 is= "+sum);
}
}
Output
Sum of multiples of 3&5 below 1000 is= 233168
10. Write a java program to print the multiplication table of a number entered by the user.
import java.util.*;
public class A4q10 {
11. Write a java program to find the difference between the sum of the squares of the first one hundred natural numbers
and the square of the sum.
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 −
385 = 2640.
public class A4q11 {
12. Write a java program called FunctionGrowth that prints a table of the values log N, N, N log N, N2, N3, and 2N for N =
16, 32, 64, ..., 2048. Use tabs (\t characters) to line up columns.
public class A4q12 {
public static void main(String[] args) {
int N;
double s=0,t=0,p=0;
System.out.println("log N, N, NlogN, N2, N3, 2N ");
for(N=16;N<=2048;N=N*2)
{
System.out.println(Math.log(N)+"\t"+N+"\t"+N*Math.log(N)+"\t"+Math.pow(N,2)+"\t"+Math.pow(N, 3)+"\t"+Math.pow(2, N));
} }
}
Output
log N, N, NlogN, N2, N3, 2N
2.772588722239781 16 44.3614195558365 256.0 4096.0 65536.0
3.4657359027997265 32 110.90354888959125 1024.0 32768.0 4.294967296E9
4.1588830833596715 64 266.168517335019 4096.0 262144.0 1.8446744073709552E19
4.852030263919617 128 621.059873781711 16384.0 2097152.0 3.4028236692093846E38
5.545177444479562 256 1419.565425786768 65536.0 1.6777216E7 1.157920892373162E77
6.238324625039508 512 3194.022208020228 262144.0 1.34217728E8 1.3407807929942597E154
6.931471805599453 1024 7097.82712893384 1048576.0 1.073741824E9 Infinity
7.6246189861593985 2048 15615.219683654448 4194304.0 8.589934592E9 Infinity
13. An integer n is divisible by 9 if the sum of its digits is divisible by 9. Write a java program to display each digit,
starting with the rightmost digit.
Your program should also determine whether or not the number is divisible by 9. Test it on the following numbers:
n = 154368
n = 621594
n = 123456
Hint: Use the % operator to get each digit; then use / to remove that digit. So 154368 % 10 gives 8 and 154368 / 10 gives
15436. The next digit extracted should be 6, then 3 and so on.
import java.util.*;
public class A4q13 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n,r=0,s=0;
System.out.println("Enter the number");
n=sc.nextInt();
int n1=n;
while(n>0)
{
r=n%10;
s+=r;
n/=10;
System.out.println(r+" ");
}
if(s%9==0)
System.out.println(n1+" is divisible by 9");
else
System.out.println(n1+" is not divisible by 9");
}
}
Output
Enter the number
154368
8
6
3
4
5
1
sum of the digits=27
154368 is divisible by 9
14. Write a java program to print largest power of two less than or equal to N.
import java.util.*;
public class A4q14 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n;
double s=0,res=0;
System.out.println("Enter the value of n");
n=sc.nextInt();
int x=0;
int v=1;;
while(v<=n)
{
x=v;
v=v*2;
}
System.out.println(x);
}
}
15. Write a java program to print the below given pattern using while loop as well as for loop in two different programs.
*****
*****
*****
*****
public class A4q15b {
public static void main(String[] args)
{
int i=1,j;
while(i<=4)
{
j=1;
while(j<=4)
{
System.out.print("* ");
j++;
}
System.out.println();
i++;
}
}
16. Write the java programs to print the following four patterns using for loop using four different programs.
(a) (b) (c) (d)
* 1 1 1
** 12 22 23
*** 123 333 456
**** 1234 4444 7 8 9 10
***** 12345 55555 11 12 13 14 15
public class A4q16a {
17. Write a java program to print the following pattern using nested loops.
import java.util.Scanner;
public class A4q17 {
1. Write a java program that takes the value of N through keyboard and prints a table of the
power of 2 that are less than or equal to 2N.
import java.util.*;
public class A5q1 {
2. Given a set of n numbers. Write a java program that adds these numbers and returns the resultant sum and compute
the average. Assume n is greater than or equal to zero.
import java.util.*;
public class A5q2 {
}
H=n/s;
System.out.println("The harmonic mean is= "+H);
4. Write a java program to compute the sum of the first n terms (n>=1) of the series.
S=1-3+5-7+9- .........
import java.util.*;
public class A5q4 {
5. Input a number n, write a java program to compute n factorial (written as n!) where n>=0.
import java.util.*;
public class A5q5 {
}
double term=((Math.pow(x, n))/n);
System.out.println(term);
}
7. Write a java program to evaluate the function sin(x) as defined by the infinite series expansion.
sin (x) = x- x 3 /3! + x 5 /5! - x 7 /7! +...
The acceptable error for computation is 10 -6 .
import java.util.Scanner;
8. Write a java program to evaluate the function cos(x) as defined by the infinite series
expansion.
cos (x) =1- x 2 /2! + x 4 /4! - x 6 /6! +....
The acceptable error for computation is 10 -6 .
import java.util.*;
public class A5q8 {
9. Assume that x is a positive variable of type double. Write a code fragment that uses the Taylor
series expansion to set the value of sum to e x = 1 + x + x 2 /2! + x 3 /3! + ......
import java.util.*;
public class A5q8 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of x in radians");
double x=sc.nextDouble();
double sum = 0.0;
double term = 1.0;
for (int i = 1; sum != sum + term; i++)
{
sum = sum + term;
term = term * x / i;
}
System.out.println("e("+x+") = "+sum);
10. Write a java program to generate and print the first n terms of the Fibonacci sequence where
n>=1.The first few terms are:
0, 1, 1, 2, 3, 5, 8, 13, ......
Each term beyond the first two is derived from the sum of its two nearest predecessors i.e. a
new term in the series (Except the first two) is found by the following formula.
new term=preceding term +term before the preceding term
Let us define:
c as new term
b as the preceding term
a as the term before the preceding term
So, c=b+a
Your program should handle for all positive values of n.
Example: If n=1, it will display as: Fibonacci Series is: 0
If n=2, it will display as: Fibonacci Series is: 0, 1
If n=3, it will display as: Fibonacci Series is: 0, 1, 1 ....
If n=10, it will display as: Fibonacci Series is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
import java.util.*;
public class A5Q10
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n, t1 = 0, t2 = 1;
System.out.println("Enter number of terms ");
n=sc.nextInt();
System.out.println("Fibonacci series");
for (int i = 1; i <= n; ++i)
{
System.out.print(t1 + " ");
11. Write a java program to generate and print the first n terms of the Fibonacci numbers using
an efficient algorithm. In this case, you need to find a pair of Fibonacci terms, in each iteration
and display them and adjust the preceding term b and the term before the preceding term a.
Your program should handle all positive values of n.
Example:
If n=10, it will display as: Fibonacci Series is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
If n=11, it will display as: Fibonacci Series is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
import java.util.Scanner;
public class A5q11 {
public static void main (String args[])
{
Scanner sc=new Scanner(System.in);
int a=0;
int b=1;
int i=2;
System.out.println("Enter the range");
int n=sc.nextInt();
while(n>i)
{
System.out.println(a+"\n"+b);
a=a+b;
b=a+b;
i+=2;
}
if(i%n==0)
{
System.out.println(a+"\n"+b);
}
else
System.out.println(a);
12. Write a java program that accepts a positive integer n and reverses the order of its digits.
import java.util.Scanner;
public class A5q12 {
13. Write a java program to compute the square root of a number using Newton’s method.
import java.util.*;
public class A5q13 {
14. Using Newton’s method, write a java program that takes integers N and k as command-line
arguments and prints the k th root of N.
import java.util.*;
public class A5q14 {
15. Write a java program that puts the binary representation of a positive integer N into a String
s.
import java.util.*;
public class A5q15 {
16. Write a java program Checkerboard that takes one command-line argument N and uses a loop
within a loop to print out a two-dimensional N-by-N checkerboard pattern with alternating
spaces and asterisks.
import java.util.*;
public class A5q16 {
17. Write a java program GCD that finds the greatest common divisor (gcd) of two integers using
Euclid’s algorithm, which is an iterative computation based on the following observation: ifx is greater than y, then if y
divides x, the gcd of x and y is y; otherwise, the gcd of x and y is
the same as the gcd of x % y and y.
import java.util.*;
public class A5q17 {
19. Write a java program to check a number n is prime or not. The number to be inputted through
keyboard.
import java.util.*;
public class A5q19 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt();
int flag=0;
for(int i=2;i<n;i++)
{
if(n%i==0)
{
flag=1;
break;
}
}
if(flag==0)
System.out.println(n+" is prime");
else
System.out.println(n+" is not prime");
}}
20. Write a java program called PrimeCounter that takes a commandline argument N and finds
the number of primes less than or equal to N.
}
}
21. Write a java program that prints the prime factorization of any positive integer.
import java.util.*;
public class A5q21 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt();
int c;
for(int i=2;i<=n;i++)
{
if(n%i==0)
{
c=1;
for(int j=2;j<=i/2;j++)
{
if(i%j==0)
{
c=0;
break;
}
if(c==1)
System.out.println(i);
}
}
}
}
24. Write a java program to disprove Euler’s conjecture (which stood until 1967), using a quintuply nested loop to find
four positive integers whose 5 th power sums to the 5 th power of another positive integer. That is, find a, b, c, d, and e such
that a 5 + b 5 +c 5 + d 5 = e 5 . Use the long data type.
public class A5Q24
{
public static void main(String[] args)
{
long n = Long.parseLong(args[0]);
long a5, b5, c5, d5, e5;
for (long e = 1; e <= n; e++)
{
e5 = e*e*e*e*e;
for (long a = 1; a <= n; a++)
{
a5 = a*a*a*a*a;
if (a5 + a5 + a5 + a5 > e5) break;
Assignment-VI
One-Dimensional Array
1. Write a java program to create an array of size N and store the random values in it and find
the sum and average.
import java.util.*;
public class p1a6 {
2. Write a java program to input 10 integers from keyboard and store them into an array. Then find out how many of
them are positive, how many are negative, how many are even and how many are odd.
import java.util.*;
public class p2a6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
System.out.println("enter array limit");
int n=in.nextInt();
int a[]=new int[n];int i;
for(i=0;i<n;i++)
{
System.out.println("enter value");
a[i]=in.nextInt();
}
int p=0;int ne=0;int e=0;int o=0;
for(i=0;i<n;i++)
{
if(a[i]>0)
p++;
if(a[i]<0)
ne++;
if(a[i]%2==0)
e++;
if(a[i]%2!=0)
o++;
}
System.out.println("positve number="+p);
System.out.println("negetive number="+ne);
System.out.println("even number="+e);
System.out.println("odd number="+o);
}
3. Input 10 integers from the keyboard into an array. The number to be searched is entered through the keyboard by the
user. Write a java program to find if the number to be searched is present in the array and if it is present, display the
number of times it appears in the array.
import java.util.Scanner;
public class p3a6 {
}
4. Write a java program to find the maximum and minimum and how many times they both occur in an array of n
elements. Find out the positions where the maximum first occurs and the minimum last occurs.
import java.util.Scanner;
public class p4a6 {
5. Write a java program to find the second largest value in an array of n elements.
import java.util.Scanner;
public class p5a6 {
for(int i=0;i<n;i++)
{
if((i==pos)&&(a[i]==max))
continue;
if(a[i]>max1)
{
max1=a[i];
}
}
System.out.println("2nd largest= "+max1);
}
}
6. Write a java program to rearrange the elements in an integer array so that they appear in reverse order.
import java.util.Scanner;
public class p6a6 {
}
for(int i=n-1;i>0;i--)
{
System.out.println(a[i]+" ");
}
}
7. Write a java program that implements the array reversal algorithm suggested in Note 1.
Note 1: There is a simpler algorithm for array reversal that starts out with two indices, i=0 and j=n-1. With each iteration i
is increased and j is decreased for i<j.
import java.util.Scanner;
public class p7a6 {
}
}
8. Design and develop a menu driven program in java for the following array operations.
a. Create an array of N integers
b. Display the array elements
c. Insert an element at specific position
d. Delete an element at a given position
e. Exit
import java.util.Scanner;
public class q8
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=0,i,option,pos=0,item,ch;
int a[]=new int[100];
do
{
System.out.println("1. Creation of array");
System.out.println("2. Display array elements");
System.out.println("3. Insert at any position");
System.out.println("4. Delete from any position");
System.out.println("5. Exit");
System.out.println("enter option");
option=sc.nextInt();
switch(option)
{
case 1:
System.out.println("enter size of array");
n=sc.nextInt();
case 2:
System.out.println("Array elements");
for(i=0;i<n;i++)
System.out.println(a[i]);
break;
case 3:
System.out.println("Enter position of new item to be inserted");
pos=sc.nextInt();
System.out.println("Enter the value");
item=sc.nextInt();
for(i=n;i>pos;i--)
a[i]=a[i-1];
a[pos]=item;
n=n+1;
for(i=0;i<n;i++)
System.out.println(a[i]);
break;
case 4:
System.out.println("Enter position of item to be deleted");
pos=sc.nextInt();
for(i=0;i<n;i++)
{
if(i==pos)
continue;
System.out.println(a[i]);
}
break;
case 5:
System.out.println("you have press the exit option");
break;
default:
System.out.println("wrong input! Please try again");
}
System.out.println("Do you want to continue?1.Yes 2.No");
ch=sc.nextInt();
}while(ch==1);
}
9. Write a java program to convert a decimal integer to its corresponding octal representation.
import java.util.Scanner;
public class p9a6 {
10. Write a java program that takes two command-line arguments M and N and produces a sample
of M of the integers from 0 to N-1.
11. Write a java program that simulates coupon collection by taking a command-line argument N and generating random
numbers between 0 to N-1 until getting every possible value.
import java.util.Scanner;
public class p11a6 {
}
Programming Assignment-VII
(Single-Dimensional Arrays)
1. Write a java program to create an array of size N and store the random values in it and find
the
sum and average.
import java.util.*;
class a7q1
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the Size of Array :");
int n=in.nextInt();
double r[] = new double[n];
for(int a=0; a<n; a++)
{
r[a]=Math.random();
}
System.out.println("Values Stored in Array ");
for(int a=0; a<n; a++)
{
System.out.println(r[a]);
}
double s=0;
for(int a=0; a<n; a++)
{
s=s+r[a];
}
System.out.println("Sum ="+s);
System.out.println("Average ="+(s/n));
}
}import java.util.*;
class a7q15
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the length of array :");
int n=in.nextInt();
int arr[] = new int[n];
for(int a=0; a<n; a++)
{
System.out.print("Enter the value of arr["+a+"] = ");
arr[a]=in.nextInt();
}
int arrn[]=partition(arr);
for(int a=0; a<arrn.length; a++)
{
System.out.print(arrn[a]+"\t");
}
}
public static int[] partition(int arr[])
{
int arrt[] = new int[arr.length];
arrt=arr.clone();
for(int a=0; a<arrt.length-1; a++)
{
int v=arrt[a],l=a;
for(int b=a+1; b<arrt.length; b++)
{
if(arrt[b]<v)
{
v=arrt[b];
l=b;
}
}
int t=arrt[a];
arrt[a]=arrt[l];
arrt[l]=t;
}
int p=arr[0];
for(int a=0; a<arrt.length; a++)
{
if(p==arrt[a])
{
p=a;
break;
}
}
int t=arr[p];
arr[p]=arr[0];
arr[0]=t;
int n=arr.length;
for(int a=0; a<p; a++)
{
int v=arr[a],l=a;
for(int b=p+1; b<n; b++)
{
if(arr[b]<v)
{
v=arr[b];
l=b;
}
}
t=arr[a];
arr[a]=arr[l];
arr[l]=t;
}
return arr;
}
}
2. Write a java program using an array that reads the integers between 1 and 100 and counts
the
occurrences of each. Assume the input ends with 0. Here is a sample run of the program:
import java.util.*;
class a7q2
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int no[] = new int[100];
System.out.println("Enter the integer between 1 and 100 :");
while(true)
{
int n=in.nextInt();
if(n==0)
break;
else if(n>0 && n<=100)
{
no[n-1]++;
}
}
for(int a=0; a<100; a++)
{
if(no[a]!=0)
{
if(no[a]==1)
System.out.println((a+1)+" occurs "+no[a]+" time");
else
System.out.println((a+1)+" occurs "+no[a]+" times");
}
}
}
}
3. Input 10 integers from the keyboard into an array. The number to be searched is entered
through
the keyboard by the user. Write a java program to find if the number to be searched is
present in
the array and if it is present, display the number of times it appears in the array.
import java.util.*;
class a7q3
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int arr[] = new int[10];
for(int a=0; a<10; a++)
{
System.out.print("arr["+a+"]=");
arr[a]=in.nextInt();
}
int c=0;
System.out.print("Enter the Number to Find :");
int f=in.nextInt();
for(int a=0; a<10; a++)
{
if(arr[a]==f)
{
c++;
}
}
if(c!=0)
{
System.out.println(f+" is found "+c+" times");
}
else
{
System.out.println(f+" is not found");
}
}
}
4. Write a method that finds the smallest element in an array of double values using the
following
header:
import java.util.*;
class a7q4
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter Ten Numbers :");
double n[] = new double[10];
for(int a=0; a<10; a++)
{
System.out.print("n["+a+"]=");
n[a]=in.nextDouble();
}
System.out.println("Smallest Number is the array ="+min(n));
}
public static double min(double array[])
{
double t=array[0];
for(int a=1; a<10; a++)
{
if(t>array[a])
t=array[a];
}
return t;
}
}
5. Write a java program to find the second largest value in an array of n elements.
import java.util.*;
class a7q5
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the Length of the Array :");
int n=in.nextInt();
int arr[] = new int[n];
for(int a=0; a<n; a++)
{
System.out.print("arr["+a+"]=");
arr[a]=in.nextInt();
}
for(int a=0; a<(n-1); a++)
{
for(int b=0; b<(n-a-1); b++)
{
if(arr[b]>arr[b+1])
{
int t=arr[b];
arr[b]=arr[b+1];
arr[b+1]=t;
}
}
}
System.out.println("Second smallest Number in the array ="+arr[1]);
}
}
6. Write a java program that implements the array reversal algorithm suggested in Note 1.
import java.util.*;
class a7q6
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the Length of the Array :");
int n=in.nextInt();
int arr[] = new int[n];
for(int a=0; a<n; a++)
{
System.out.print("arr["+a+"]=");
arr[a]=in.nextInt();
}
System.out.println("Original Array ");
for(int a=0; a<n; a++)
{
System.out.print(arr[a]+"\t");
}
System.out.println();
for(int a=0; a<(n/2); a++)
{
int t=arr[a];
arr[a]=arr[n-1-a];
arr[n-1-a]=t;
}
System.out.println("Array after Reversal");
for(int a=0; a<n; a++)
{
System.out.print(arr[a]+"\t");
}
System.out.println();
}
}
import java.util.*;
class a7q7
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the decimal number :");
String s=Integer.toOctalString(in.nextInt());
System.out.println("Octal Value of the entered number is "+s);
}
}
8. Design and develop a menu driven java program for the following array operations.
import java.util.*;
class a7q8
{
public static void main(String args[])throws Exception
{
int arr[];
boolean k=true;
Scanner in = new Scanner(System.in);
System.out.print("Enter the Value of n :");
int n=in.nextInt();
arr = new int[n];
for(int a=0; a<n; a++)
{
arr[a]=0;
}
while(k)
{
System.out.println("Choose Your Option :");
System.out.println("a. Display the array elements\nb. Insert an
element at specific position\nc. Delete an element at a given position\nd.
Exit");
char c=in.next().charAt(0);
switch(c)
{
case 'a':
for(int a=0; a<arr.length; a++)
{
System.out.println(arr[a]);
}
break;
case 'b':
System.out.print("Enter the Value to Insert :");
int i=in.nextInt();
System.out.print("Enter the position number to Insert :");
int p=in.nextInt();
for(int a=arr.length-2; a>=p; a--)
{
arr[a+1]=arr[a];
}
arr[p]=i;
break;
case 'c':
System.out.print("Enter the Position Number to Delete :");
int ps=in.nextInt();
System.out.println(arr[ps]+" at position number "+ps+"
deleted");
for(int a=ps; a<arr.length-1; a++)
{
arr[a]=arr[a+1];
}
arr[arr.length-1]=0;
break;
case 'd':
k=false;
break;
default :
System.out.println("Invalid Option");
}
}
System.out.println("Exiting Program");
}
}
9. You can compute the standard deviation with the following formula; you have to store the
individual numbers using an array, so that they can be used after the mean is obtained.
import java.util.*;
class a7q9
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the Values :");
double arr[] = new double[10];
for(int a=0; a<10; a++)
{
arr[a]=in.nextDouble();
}
System.out.println("Mean ="+mean(arr));
System.out.println("Deviation ="+deviation(arr));
}
public static double mean(double x[])
{
double s=0;
for(int a=0; a<10; a++)
{
s=s+x[a];
}
return s/10;
}
public static double deviation(double x[])
{
double m=mean(x);
double d=0;
for(int a=0; a<10; a++)
{
d=d+(x[a]-m)*(x[a]-m);
}
d=d/9;
d=Math.sqrt(d);
return d;
}
}
10. Write a method that returns a new array by eliminating the duplicate values in the array
using
the following method header:
import java.util.*;
class a7q10
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter ten numbers :");
int arr[] = new int[10];
for(int a=0; a<10; a++)
{
arr[a]=in.nextInt();
}
int arrn[]=eliminateDuplicates(arr);
System.out.println("The distict numbers are :");
for(int a=0; a<arrn.length; a++)
{
System.out.print(arrn[a]+"\t");
}
System.out.println();
}
public static int[] eliminateDuplicates(int list[])
{
boolean k[] = new boolean[10];
for(int a=0; a<10; a++)
{
k[a]=true;
}
for(int a=0; a<9; a++)
{
for(int b=a+1; b<10; b++)
{
if(list[a]==list[b])
{
k[b]=false;
}
}
}
int c=0;
for(int a=0; a<10; a++)
{
if(k[a])
c++;
}
int rt[] = new int[c];
int b=0;
for(int a=0; a<10; a++)
{
if(k[a])
{
rt[b]=list[a];
b++;
}
}
return rt;
}
}
11. Write a sort method that uses the bubble-sort algorithm. The bubble sort algorithm
makes
several passes through the array. On each pass, successive neighbouring pairs are compared.
If a
pair is not in order, its values are swapped; otherwise, the values remain unchanged. The
technique is called a bubble sort or sinking sort because the smaller values gradually “bubble”
their way to the top and the larger values “sink” to the bottom. Write a java program that
reads
in ten double numbers, invokes the method, and displays the sorted numbers.
import java.util.*;
class a7q11
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter 10 numbers :");
double arr[] = new double[10];
for(int a=0; a<10; a++)
{
arr[a]=in.nextDouble();
}
System.out.println("After Sorting :");
double arrn[]=bubbleSort(arr);
for(int a=0; a<10; a++)
{
System.out.println(arrn[a]);
}
}
public static double[] bubbleSort(double arr[])
{
for(int a=0; a<9; a++)
{
for(int b=1; b<(9-a); b++)
{
if(arr[b]>arr[b+1])
{
double t=arr[b];
arr[b]=arr[b+1];
arr[b+1]=t;
}
}
}
return arr;
}
}
13. Write the following method that returns true if the list is already sorted in increasing
order.
import java.util.*;
class a7q13
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Number of Elements in the Array :");
int n=in.nextInt();
System.out.println("Enter the Values in the Array :");
int arr[] = new int[n];
for(int a=0; a<n; a++)
{
arr[a]=in.nextInt();
}
if(isSorted(arr))
{
System.out.println("The list is Sorted");
}
else
{
System.out.println("The list is not Sorted");
}
}
public static boolean isSorted(int list[])
{
for(int a=0; a<list.length-1; a++)
{
if(list[a]>list[a+1])
return false;
}
return true;
}
}
14. Write a java program that randomly generates an array of 100 integers and a key.
Estimate the
execution time of invoking the linearSearch method. Sort the array and estimate the
execution
time of invoking the binarySearch method. You can use the following code template to obtain
import java.util.*;
class a7q14
{
public static void main(String args[])
{
long st=System.currentTimeMillis();
int arr[] = new int[100];
//Adding Random Numbers to the Array
for(int a=0; a<100; a++)
{
arr[a]=(int)(Math.random()*2147483647);
}
//Getting a random number present in the array by generating a random
number and then getting the value of array at that position number
int key=(int)(Math.random()*100);
key=arr[key];
//sorting
for(int a=0; a<99; a++)
{
for(int b=0; b<99-a; b++)
{
if(arr[a]>arr[a+1])
{
int t=arr[a];
arr[a]=arr[a+1];
arr[a+1]=t;
}
}
}
//linear search
for(int a=0; a<100; a++)
{
if(arr[a]==key)
{
System.out.println("Key found at position number "+a+" with
value = "+arr[a]);
break;
}
}
long et=System.currentTimeMillis();
System.out.println("Time Taken for Linear Search "+(et-st));
st=System.currentTimeMillis();
//Adding Random Numbers to the Array
int arrn[] = new int[100];
for(int a=0; a<100; a++)
{
arrn[a]=(int)(Math.random()*2147483647);
}
//Getting a random number present in the array by generating a random
number and then getting the value of array at that position number
key=(int)(Math.random()*100);
key=arrn[key];
//sorting
for(int a=0; a<99; a++)
{
for(int b=0; b<(99-a); b++)
{
if(arrn[a]>arrn[a+1])
{
int t=arrn[a];
arrn[a]=arrn[a+1];
arrn[a+1]=t;
}
}
}
//binary search
int f = 0, l = arrn.length-1, m = (f+l)/2;
while(f <= l)
{
if(arrn[m] < key)
{
f = m+1;
}
else if(arrn[m] == key)
{
System.out.println(key+ " Found at Location " +m);
break;
}
else
{
l = m - 1;
}
m = (f+l)/2;
}
if(f > l)
{
System.out.println("Not Found..!! " +key+ " is not Present in the
List.");
}
et=System.currentTimeMillis();
System.out.println("Time Taken for Binary Search "+(et-st));
}
}
15. Write the following method that partitions the list using the first element, called a pivot.
import java.util.*;
class a7q15
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the length of array :");
int n=in.nextInt();
int arr[] = new int[n];
for(int a=0; a<n; a++)
{
System.out.print("Enter the value of arr["+a+"] = ");
arr[a]=in.nextInt();
}
int arrn[]=partition(arr);
for(int a=0; a<arrn.length; a++)
{
System.out.print(arrn[a]+"\t");
}
}
public static int[] partition(int arr[])
{
int arrt[] = new int[arr.length];
arrt=arr.clone();
for(int a=0; a<arrt.length-1; a++)
{
int v=arrt[a],l=a;
for(int b=a+1; b<arrt.length; b++)
{
if(arrt[b]<v)
{
v=arrt[b];
l=b;
}
}
int t=arrt[a];
arrt[a]=arrt[l];
arrt[l]=t;
}
int p=arr[0];
for(int a=0; a<arrt.length; a++)
{
if(p==arrt[a])
{
p=a;
break;
}
}
int t=arr[p];
arr[p]=arr[0];
arr[0]=t;
int n=arr.length;
for(int a=0; a<p; a++)
{
int v=arr[a],l=a;
for(int b=p+1; b<n; b++)
{
if(arr[b]<v)
{
v=arr[b];
l=b;
}
}
t=arr[a];
arr[a]=arr[l];
arr[l]=t;
}
return arr;
}
}
Programming Assignment-VIII
(Multidimensional Arrays)
import java.util.*;
class a8q1
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the value of m :");
int m=in.nextInt();
System.out.print("Enter the value of n :");
int n=in.nextInt();
int arr[][] = new int[m][n];
for(int a=0; a<m; a++)
{
for(int b=0; b<n; b++)
{
System.out.print("arr["+a+"]["+b+"]=");
arr[a][b]=in.nextInt();
}
}
System.out.println("Printing array ");
for(int a=0; a<m; a++)
{
for(int b=0; b<n; b++)
{
System.out.print(arr[a][b]+"\t");
}
System.out.println();
}
}
}
2. Write a method that returns the sum of all the elements in a specified column in a matrix
using
the following header:
import java.util.*;
class a8q2
{
public static void main(String args[])
{
double arr[][] = new double[3][4];
Scanner in = new Scanner(System.in);
System.out.println("Enter the values in array :");
for(int a=0; a<3; a++)
{
for(int b=0; b<4; b++)
{
System.out.print("arr["+a+"]["+b+"]=");
arr[a][b]=in.nextDouble();
}
}
System.out.println("Entered array :");
for(int a=0; a<3; a++)
{
for(int b=0; b<4; b++)
{
System.out.print(arr[a][b]+"\t");
}
System.out.println();
}
for(int b=0; b<4; b++)
{
System.out.println("Sum of the elements at column "+b+" is
"+sumColumn(arr, b));
}
}
public static double sumColumn(double m[][], int columnIndex)
{
double s=0;
for(int a=0; a<3; a++)
{
s=s+m[a][columnIndex];
}
return s;
}
}
3. Write a method that sums all the numbers in the major diagonal in an n * n matrix of
double
values using the following header:
import java.util.*;
class a8q3
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
double arr[][] = new double[4][4];
for(int a=0; a<4; a++)
{
for(int b=0; b<4; b++)
{
System.out.print("arr["+a+"]["+b+"]=");
arr[a][b]=in.nextDouble();
}
}
System.out.println("Sum of the elements in the major diagonal is
"+sumMajorDiagonal(arr));
}
public static double sumMajorDiagonal(double m[][])
{
double s=0;
int l=m[0].length;
for(int a=0; a<l; a++)
{
s=s+m[a][a];
}
return s;
}
}
4. Write a java program to create a two-dimensional array b[][] that is a copy of an existing
two-
dimensional array a[][], under each of the following assumptions:
import java.util.*;
class a8q4
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int arr[][] = new int[4][];
arr[0] = new int[2];
arr[1] = new int[4];
arr[2] = new int[6];
arr[3] = new int[8];
for(int a=0; a<4; a++)
{
for(int b=0; b<arr[a].length; b++)
{
arr[a][b]=(int)(Math.random()*10);
}
}
int arrn[][]=arr.clone();
for(int a=0; a<4; a++)
{
for(int b=0; b<arr[a].length; b++)
{
System.out.print(arrn[a][b]+"\t");
}
System.out.println();
}
}
}
5. Suppose a teacher with M students and N Marks of each student is maintained in an (M+1)-
by-
(N+1) array, reserving the last column for each student’s average mark and the last row for
average test mark. Write a java program to compute the average mark for each student
(average
values of each row) and calculate the average test mark (average values of each column).
import java.util.*;
class a8q5
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the value of m :");
int m=in.nextInt();
System.out.print("Enter the value of n :");
int n=in.nextInt();
int arr[][] = new int[m+1][n+2];
for(int a=0; a<m; a++)
{
for(int b=0; b<n; b++)
{
arr[a][b]=in.nextInt();
}
}
for(int a=0; a<m; a++)
{
int s=0;
for(int b=0; b<n; b++)
{
s=s+arr[a][b];
}
s=s/n;
arr[a][n]=s;
}
for(int b=0; b<n; b++)
{
int s=0;
for(int a=0; a<m; a++)
{
s=s+arr[a][b];
}
s=s/m;
arr[m][b]=s;
}
for(int a=0; a<=m; a++)
{
for(int b=0; b<=n; b++)
{
System.out.print(arr[a][b]+"\t");
}
System.out.println();
}
}
}
6. Write a method to add two matrices. The header of the method is as follows:
public static double[][] addMatrix(double[][] a, double[][] b)
In order to be added, the two matrices must have the same dimensions and the same or
compatible types of elements. Let c be the resulting matrix. Each element cij is aij + bij. For
example, for two 3 * 3 matrices a and b, c is
import java.util.*;
class a8q6
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
double n1[][] = new double[3][3];
double n2[][] = new double[3][3];
for(int a=0; a<3; a++)
{
for(int b=0; b<3; b++)
{
System.out.print("n1["+a+"]["+b+"]=");
n1[a][b]=in.nextDouble();
}
}
for(int a=0; a<3; a++)
{
for(int b=0; b<3; b++)
{
System.out.print("n2["+a+"]["+b+"]=");
n2[a][b]=in.nextDouble();
}
}
double arr[][]=addMatrix(n1,n2);
for(int a=0; a<3; a++)
{
for(int b=0; b<3; b++)
{
System.out.print(arr[a][b]+"\t");
}
System.out.println();
}
}
public static double[][] addMatrix(double a[][], double b[][])
{
double arr[][] = new double[a.length][a[0].length];
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
arr[i][j]=a[i][j]+b[i][j];
}
}
return arr;
}
}
7. Write a java program to transpose a square two-dimensional array in place without
creating a
second array.
import java.util.*;
class a8q7
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the value of side length :");
int m=in.nextInt();
int n=m;
int arr[][] = new int[m][m];
System.out.println("Enter the values in the matrix");
for(int a=0; a<m; a++)
{
for(int b=0; b<n; b++)
{
System.out.print("arr["+a+"]["+b+"]=");
arr[a][b]=in.nextInt();
}
}
System.out.println("Before Transposing");
for(int a=0; a<m; a++)
{
for(int b=0; b<n; b++)
{
System.out.print(arr[a][b]+"\t");
}
System.out.println();
}
for(int a=0; a<m; a++)
{
for(int b=a; b<n; b++)
{
int t=arr[a][b];
arr[a][b]=arr[b][a];
arr[b][a]=t;
}
}
System.out.println("After Transposing");
for(int a=0; a<m; a++)
{
for(int b=0; b<n; b++)
{
System.out.print(arr[a][b]+"\t");
}
System.out.println();
}
}
}
8. Write a java program that takes an integer N from the command line and creates an N-by-N
boolean array a[][] such that a[i][j] is true if i and j are relatively prime (have no common
factors), and false otherwise.
import java.util.*;
class a8q8
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("enter the value of n:");
int n=in.nextInt();
boolean arr[][] = new boolean[n][n];
for(int a=0; a<n; a++)
{
for(int b=0; b<n; b++)
{
if(gcd(a,b)==1)
arr[a][b]=true;
else
arr[a][b]=false;
}
}
for(int a=0; a<n; a++)
{
for(int b=0; b<n; b++)
{
System.out.print(arr[a][b]+"\t");
}
System.out.println();
}
}
public static int gcd(int n1, int n2)
{
for(int a=Math.min(n1, n2); a>=1; a--)
{
if(n1%a==0 && n2%a==0)
return a;
}
return 1;
}
}
9. Write a method to multiply two matrices. The header of the method is:
public static double[][] multiplyMatrix(double[][] a, double[][] b)
To multiply matrix a by matrix b, the number of columns in a must be the same as the
number
of rows in b, and the two matrices must have elements of the same or compatible types. Let c
be
the result of the multiplication. Assume the column size of matrix a is n. Each element cij is
ai1
* b1j + ai2 * b2j + .... + ain * bnj
import java.util.*;
class a8q9
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
double arr1[][] = new double[3][3];
double arr2[][] = new double[3][3];
for(int a=0; a<3; a++)
{
for(int b=0; b<3; b++)
{
System.out.print("arr1["+a+"]["+b+"]=");
arr1[a][b]=in.nextDouble();
}
}
for(int a=0; a<3; a++)
{
for(int b=0; b<3; b++)
{
System.out.print("arr2["+a+"]["+b+"]=");
arr2[a][b]=in.nextDouble();
}
}
double prod[][]=multiplyMatrix(arr1, arr2);
for(int a=0; a<3; a++)
{
for(int b=0; b<3; b++)
{
System.out.print(arr1[a][b]+"\t");
}
System.out.print("\t");
if(a==1)
System.out.print("*");
else
System.out.print(" ");
System.out.print("\t");
for(int b=0; b<3; b++)
{
System.out.print(arr2[a][b]+"\t");
}
System.out.print("\t");
if(a==1)
System.out.print("=");
else
System.out.print(" ");
System.out.print("\t");
for(int b=0; b<3; b++)
{
System.out.print(prod[a][b]+"\t");
}
System.out.println();
}
}
public static double[][] multiplyMatrix(double arr1[][], double arr2[][])
{
double prod[][] = new double[arr1[0].length][arr1[0].length];
for(int a=0; a<prod.length; a++)
{
for(int b=0; b<prod[0].length; b++)
{
double s=0;
for(int c=0; c<prod[0].length; c++)
{
s=s+arr1[c][a]*arr2[a][c];
}
prod[a][b]=s;
}
}
return prod;
}
}
10. Write a java program that randomly fills in 0s and 1s into a 4-by-4 matrix, prints the
matrix, and finds the first row and column with the most 1s. Here is a sample run of the
program:
class a8q10
{
public static void main(String args[])
{
int arr[][] = new int[4][4];
for(int a=0; a<4; a++)
{
for(int b=0; b<4; b++)
{
arr[a][b]=(int)(Math.random()*2);
}
}
for(int a=0; a<4; a++)
{
for(int b=0; b<4; b++)
{
System.out.print(arr[a][b]+"\t");
}
System.out.println();
}
int p=0,v=0;
for(int a=0; a<4; a++)
{
int c=0;
for(int b=0; b<4; b++)
{
c=c+arr[a][b];
}
System.out.println(c);
if(c>v)
{
v=c;
p=a;
}
}
System.out.println("The Largest row index ="+p);
p=0;
v=0;
for(int a=0; a<4; a++)
{
int c=0;
for(int b=0; b<4; b++)
{
c=c+arr[b][a];
}
System.out.println(c);
if(c>v)
{
v=c;
p=a;
}
}
System.out.println("The Coloumn row index ="+p);
}
}
Programming Assignment-IX
(Classes and Objects)
1. Design a class Student with instance variables name, roll, mark and instance methods
setData(), display(). Write a Java program to create three objects of Student class to
input details of three different students and display the details. Enclose main() method
inside another class StudentDetails. (Use the setter method setData() to input details.)
//a9q1.java
import java.util.*;
public class StudentDetails
{
public static void main(String args[])
{
Student ob = new Student();
ob.setData();
ob.display();
}
}
class Student
{
String name;
int roll, mark;
Student()
{
name="";
roll=0;
mark=0;
}
void setData()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Name =");
name=in.nextLine();
System.out.print("Enter Roll Number =");
roll=in.nextInt();
System.out.print("Enter Marks =");
mark=in.nextInt();
}
void display()
{
System.out.println("Name = "+name);
System.out.println("Roll = "+roll);
System.out.println("Mark = "+mark);
}
}
//a9q2.java
public class Rectangle
{
double width, height;
public static void main(String args[])
{
Rectangle ob1 = new Rectangle(4,40);
Rectangle ob2 = new Rectangle(3.5,35.9);
System.out.println("Area = "+ob1.getArea());
System.out.println("Perimeter ="+ob1.getPerimeter());
System.out.println("Area ="+ob2.getArea());
System.out.println("Perimeter ="+ob2.getPerimeter());
}
Rectangle()
{
width=1;
height=1;
}
Rectangle(double a, double b)
{
width=a;
height=b;
}
double getArea()
{
return width*height;
}
double getPerimeter()
{
return 0.5*(width+height);
}
}
These methods are useful only if the discriminant is nonnegative. Let these methods return 0
if the discriminant is negative.
Write a java program that prompts the user to enter values for a, b, and c and displays the
result based on the discriminant. If the discriminant is positive, display the two roots. If the
discriminant is 0, display the one root. Otherwise, display “The equation has no roots.”
//a9q3.java
import java.util.*;
class QuadraticEquation
{
private double a, b, c;
QuadraticEquation(double i, double j, double k)
{
a=i;
b=j;
c=k;
}
double getDiscriminant()
{
return b*b-4*a*c;
}
double geta()
{
return a;
}
double getb()
{
return b;
}
double getc()
{
return c;
}
double getRoot1()
{
double r = -b+Math.sqrt(getDiscriminant());
r=r/(2*a);
return r;
}
double getRoot2()
{
double r = -b-Math.sqrt(getDiscriminant());
r=r/(2*a);
return r;
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the Value of a :");
double i=in.nextDouble();
System.out.print("Enter the Value of b :");
double j=in.nextDouble();
System.out.print("Enter the Value of c :");
double k=in.nextDouble();
QuadraticEquation ob = new QuadraticEquation(i,j,k);
double d=ob.getDiscriminant();
if(d>0)
{
System.out.println("Root 1 ="+ob.getRoot1());
System.out.println("Root 2 ="+ob.getRoot2());
}
else if(d==0)
{
System.out.println("Roots are same and equal to = "+ob.getRoot1());
}
else
{
System.out.println("Imaginary Roots ");
}
}
}
4. Design a class named Account that contains:
Write a java program that creates an Account object with an account ID of 1122, a balance of
Rs. 20,000, and an annual interest rate of 4.5%. Use the withdraw method to withdraw Rs.
2,500, use the deposit method to deposit Rs. 3,000, and print the balance, the monthly
interest, and the date when this account was created.
}
}
class Account {
private int id = 0;
private double balance = 0.0;
private static double annualInterestRate = 0.0;
private java.util.Date dateCreated;
public Account() {
dateCreated = new java.util.Date();
}
fan1.setSpeed(FAST);
fan1.setRadius(10);
fan1.setColor("yellow");
fan1.turnOn();
fan2.setSpeed(MEDIUM);
fan2.setRadius(5);
fan2.setColor("blue");
fan2.turnOff();
System.out.println(fan1.toString());
System.out.println(fan2.toString());
}
}