0% found this document useful (0 votes)
77 views79 pages

Introduction To Computer Programming Practise Quetions

Uploaded by

amar.khera1504
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views79 pages

Introduction To Computer Programming Practise Quetions

Uploaded by

amar.khera1504
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Assignment-I

1. Write a java program to display following messages.


Hello World!
Hello Again
I like typing this.
This is fun.
Yay! Printing.
I'd much rather you 'not'.
I "said" do not touch this.

public class A1Q1 {


public static void main(String[] args) {
System.out.println(“Hello World!”);
System.out.println(“Hello Again”);
System.out.println(“I like typing this.”);
System.out.println(“This is fun.”);
System.out.println(“Yay! Printing.”);
System.out.println(“I'd much rather you 'not'.”);
System.out.println(“I \”said\” do not touch this.”);
}
}

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.

public class A1Q5 {


public static void main(String[] args) {
int regd=171123142;
int year=2017;
System.out.println("My Regd. No is “+regd+ “and I have taken admission in B. Tech. In”+year+”.”);
}
}
6. Let we have two values 113, 2.71828. Then, declare two different variables to hold the given values. Write the java
program to display the values of these two variables on the screen, one per line.
This is room # 113
e is close to 2.71828

public class A1Q6 {


public static void main(String[] args) {
double e=2.71828;
int a=113;
System.out.println("This is room # “+a);
System.out.println(“e is close to “+e);
}
}
7. Write a java program to exchange the values of two variables of integer type A and B using third temporary variable C.
public class A1Q7 {
public static void main(String[] args) {
int a,b,c;
a=12;
b=15;
System.out.println("Before swapping a="+a+"b="+b);
c=a;
a=b;
b=c;
System.out.println("After swapping a="+a+"b="+b);
}
}
Output
Before swapping a=12b=15
After swapping a=15b=12
8. Write a java program to exchange the values of two variables of integer type A and B without using third temporary
variable.
public class A1q8 {
public static void main(String[] args) {
int a=14;
int b=17;
System.out.println("Before swapping a="+a+"b="+b);
a=a+b;
b=a-b;
a=a-b;
System.out.println("After swapping a="+a+"b="+b);
}
Output
Before swapping a=14b=17
After swapping a=17b=14

9. What do each of the following print?


a.System.out.println(2 + "bc");
b.System.out.println(2 + 3 + "bc");
c.System.out.println((2+3) + "bc");
d.System.out.println("bc" + (2+3));
e.System.out.println("bc" + 2 + 3);
public class A1q9 {
public static void main(String[] args) {
System.out.println(2+"bc");
System.out.println(2 + 3+ "bc");
System.out.println((2+3) + "bc");
System.out.println("bc" + (2+3));
System.out.println("bc"+ 2 +3);
}
}
Output
2bc
5bc
5bc
bc5
bc23

10. What do each of the following print?


a. System.out.println('b');
b. System.out.println('b' + 'c');
c. System.out.println((char) ('a' + 4));
public class A1q10 {
public static void main(String[] args) {
System.out.println('b');
System.out.println('b'+'c');
System.out.println((char)('a'+4));
}
}
output
b
197
e

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.

public class A2q16 {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double l,b,r;
System.out.println("Enter the Length and breadth of a rectangle");
l=sc.nextDouble();
b=sc.nextDouble();
double area=l*b;
double perimeter=2*(l+b);
System.out.println("area of the rectangle="+area+" perimeter="+perimeter);
System.out.println("Enter the radius of a circle");
r=sc.nextDouble();
double area1=3.141*r*r;
double circum=2*3.141*r;
System.out.println("area of the circle="+area1+" circumference="+circum);
}
}
Output
Enter the Length and breadth of a rectangle
5
6
area of the rectangle=30.0 perimeter=22.0
Enter the radius of a circle
10
area of the circle=314.1 circumference=62.82

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int mark;
System.out.println("Enter the mark of the student");
mark=sc.nextInt();
if(mark>=40)
System.out.println("Congratulations! You have passed the exam");
else
System.out.println("sorry! you have failed the exam");
}
}
Output
Enter the mark of the student
45
Congratulations! You have passed the exam

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
double a,b;
System.out.println("Enter the value of a and b");
a=sc.nextDouble();
b=sc.nextDouble();
boolean res=(a>0&&a<1)&&(b>0&&b<1);
System.out.println(res);
}
}
Output
Enter the value of a and b
5
6
False

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int x1,x2,x3,y1,y2,y3;
System.out.println("Enter the first coordinate (x&y)");
x1=sc.nextInt();
y1=sc.nextInt();
System.out.println("Enter the second coordinate");
x2=sc.nextInt();
y2=sc.nextInt();
System.out.println("Enter the third coordinate");
x3=sc.nextInt();
y3=sc.nextInt();
double slope1=((y2-y1)/(x2-x1));
double slope2=((y3-y2)/(x3-x2));
if(slope1==slope2)
System.out.println("The points are coolinear");
else
System.out.println("The points are not coolinear");
}
}
Output
Enter the first coordinate (x&y)
45
Enter the second coordinate
65
Enter the third coordinate
96
The points are coolinear

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

BMI. BMI category


less than 18.5 underweight
18.5 to 24.9 normal weight
25.0 to 29.9 overweight
30.0 or more obese

import java.util.Scanner;
public class A3q11 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter the weight of a person in kg and height in meter");
double wt=sc.nextDouble();
double ht=sc.nextDouble();
double BMI=wt/(ht*ht);
System.out.println("BMI= "+BMI);
if(BMI<18.5)
System.out.println("Under weight");
else if(BMI>=18.5 &&BMI<25)
System.out.println("Normal weight");
else if(BMI>=25 &&BMI<30)
System.out.println("Over weight");
else
System.out.println("Abese");
}
}
Output
60
1.7
BMI= 20.761245674740486
Normal weight

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter the year of birth of a person ");
int year=sc.nextInt();
if(year>=1966 && year<=1980)
System.out.println("Generation of the person is X");
else if(year>=1981 && year<=1999)
System.out.println("Generation of the person is Y");
else if(year>=2000 && year<=2012)
System.out.println("Generation of the person is Z");

}
}
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]

Mark Range Letter Grade


>=90 O
>=80 AND <90 A
>=70 AND <80 B
>=60 AND <70 C
>=50 AND <60 D
>=40 AND <50 E
<40 F
import java.util.Scanner;
public class p1 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter the marks of a student out of 100 full mark ");
int mark=sc.nextInt();
if(mark>=90)
System.out.println("O grade");
else if(mark>=80&& mark<90)
System.out.println("A grade");
else if(mark>=70&& mark<80)
System.out.println("B grade");
else if(mark>=60&& mark<70)
System.out.println("C grade");
else if(mark>=50&& mark<60)
System.out.println("D grade");
else if(mark>=40&& mark<50)
System.out.println("E grade");
else
System.out.println("F grade");
}
}
Output:
Enter the marks of a student out of 100 full mark
46
E grade

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter the length of 3 sides of a triangle ");
int s1=sc.nextInt();
int s2=sc.nextInt();
int s3=sc.nextInt();
int c=0;
if(s1==s2)
c++;
if(s2==s3)
c++;
if(s1==s3)
c++;
if(c==0)
System.out.println("Triangle is irregular");
else if(c==1)
System.out.println("Triangle is symmetric");
else
System.out.println("triangle is regular");
}
}
Output
Enter the length of 3 sides of a triangle
444
triangle is regular

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.

public class A4q2 {


public static void main(String[] args) {
int i=1,n;
n=Integer.parseInt(args[0]);
while(i<=n)
{
if(i%10==1&&i%100!=11)
System.out.println(i+"st Hello");
else if(i%10==2&&i%100!=12)
System.out.println(i+"nd Hello");
else if(i%10==3&&i%100!=13)
System.out.println(i+"rd Hello");
else
System.out.println(i+"th Hello");
i++;
}
}
}
Output
1st Hello
2nd Hello
3rd Hello
4th Hello
5th Hello
6th Hello
7th Hello
8th Hello
9th Hello
10th Hello
11th Hello
12th Hello
13th Hello
14th Hello
15th Hello
16th Hello
17th Hello
18th Hello
19th Hello
20th 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 {

public static void main(String[] args) {


int i,n;
Scanner sc=new Scanner(System.in);
System.out.println(“enter n”);
n=sc.nextInt();
for(i=0;i<=n;i++)
{
System.out.print(i+" ");
}
}
}
Output
enter n
20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

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 {

public static void main(String[] args) {


int i,ctr=0;
for(i=1000;i<=2000;i++)
{
System.out.print(i+" ");
ctr++;
if(ctr%5==0)
System.out.println();
}
}
}
Output
1000 1001 1002 1003 1004
1005 1006 1007 1008 1009
- ---------
1990 1991 1992 1993 1994
1995 1996 1997 1998 1999
2000

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 {

public static void main(String[] args) {


int n,i;
double r,s=0,avg=0;
n=Integer.parseInt(args[0]);
for(i=1;i<=n;i++)
{
r=Math.random();
System.out.println("Random no."+i+"="+r);
s+=r;
}
System.out.println("Sum of the random numbers="+s);
avg=s/n;
System.out.println("average="+avg);
}
}
Output
5
Random no.1=0.09319553918346446
Random no.2=0.5481667959578703
Random no.3=0.5208896643129193
Random no.4=0.42485737596864337
Random no.5=0.5912085458169021
Sum of the random numbers=2.1783179212397994
average=0.43566358424795987

8. Write a java program to print the following output using loop.


1
121
1213121
121312141213121
1213121412131215121312141213121
public class A4q8 {

public static void main(String[] args) {


int i;
String p="";
for(i=1;i<=5;i++)
{
p+=i+p;
System.out.println(p);
}
}
}

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 {

public static void main(String[] args) {


int i,r=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number whose multiplication table you want to find: ");
int num=sc.nextInt();
for(i=1;i<=10;i++)
{
r=1;
r=num*i;
System.out.println(num+"x"+i+"="+r);
}
}
}
Output
Enter a no. for which you want to find the multiplication table: 8
8x1=8
8x2=16
8x3=24
8x4=32
8x5=40
8x6=48
8x7=56
8x8=64
8x9=72
8x10=80

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 {

public static void main(String[] args) {


int i,sum1=0,sum2=0,diff=0,s=0;
for(i=1;i<=10;i++)
{
sum1+=i*i;
sum2+=i;
}
s=sum2*sum2;
diff=s-sum1;
System.out.println("The sum of squares of the integers="+sum1);
System.out.println("The square of the sum of the integers="+s);
System.out.println("The difference of sum1 and sum2 is= "+diff);
}
}
Output
The sum of squares of the integers=385
The square of the sum of the integers=3025
The difference of sum1 and sum2 is= 2640

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 {

public static void main(String[] args) {


int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
}

public class A4q16b {

public static void main(String[] args) {


int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j+" ");
}
System.out.println();
}
}
}
public class A4q16c {

public static void main(String[] args) {


int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(i+" ");
}
System.out.println();
}
}
}
public class A4q16d {

public static void main(String[] args) {


int i,j,k=1;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(k);
k++;
}
System.out.println();
}
}
}

17. Write a java program to print the following pattern using nested loops.

import java.util.Scanner;
public class A4q17 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of n");
int n=sc.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if((i%j==0)||(j%i==0))
System.out.print("* ");
else
System.out.print(" ");
}
System.out.println(i);
}
}
}
Assignment-V

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n,i;
System.out.println("Enter the value of n:");
n=sc.nextInt();
for(i=0;i<=n;i++)
{
double r=Math.pow(2,i);
System.out.println("2^"+i+"="+r);
}

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int i,n,sum=0;
double avg=0;
System.out.println("Enter the number of numbers u want to enter");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
System.out.println("Enter the number");
int num=sc.nextInt();
sum+=num;
}
avg=sum/n;
System.out.println("The sum is"+sum);
System.out.println("The average is"+avg);
}

3. Write a java program to compute the harmonic mean.


import java.util.*;
public class A5q3 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n,a;
double s=0,H=0;
System.out.println("Enter the value of n");
n=sc.nextInt();
for(int i=1;i<=n;i++)
{
System.out.println("Enter the value of a["+i+"]");
a=sc.nextInt();
s+=(1/a);

}
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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int i,sign=1,term=0,sum=0,m=1;
System.out.println("Enter the range");
int n=sc.nextInt();
for(i=1;i<=n;i++)
{
term=1;
term=sign*m;
sum+=term;
m+=2;
sign*=-1;
}
System.out.println("The sum is= "+sum);
}

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n,i,fact=1;
System.out.println("enter the no whose factorial u want to find");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
fact*=i;
}
System.out.println("Factorial of "+n+ " is = "+fact);

6. For a given x and a given n, write a java program to compute x n /n!.


import java.util.*;
public class A5q6 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int x,n,fact=1;
System.out.println("Enter the value of x");
x=sc.nextInt();
System.out.println("Enter the value of n");
n=sc.nextInt();
for(int i=1;i<=n;i++)
{
fact*=n;

}
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;

public class A5q7 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
double x;
System.out.println("Enter the value of x in radians");
x=sc.nextDouble();
double tsin=x;
double term=x;
double error=0.000001;
int i=1;
while(Math.abs(term)>error)
{
i+=2;
term=-term*(x*x)/(i*(i-1));
tsin+=term;
}
System.out.println("The value of sin("+x+") = "+tsin);

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 {

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 error=0.000001;
double tcos=1;
double term=1;
int i=0;
while(Math.abs(term)>error)
{
i+=2;
term=-term*(x*x)/(i*(i-1));
tcos+=term;
}
System.out.println("cos("+x+") = "+tcos);
}

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 + " ");

int sum = t1 + t2;


t1 = t2;
t2 = sum;
}
}
}

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt();
int rev=0;
while(n>0)
{
int rem=n%10;
rev=(rev*10)+rem;
n/=10;
}
System.out.println("Reverse is = "+rev);

13. Write a java program to compute the square root of a number using Newton’s method.
import java.util.*;
public class A5q13 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter the number whos square root is to be found");
int n=sc.nextInt();
double g1,g2;
g2=n/2;
do
{
g1=g2;
g2=(g1+(n/g1))/2.0;
} while (Math.abs(g1-g2)>0.000001);
double root=g2;
System.out.println("The root of "+ n+" is ="+root);
}

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter the number to find the given root");
int n=sc.nextInt();
System.out.println("Enter the root");
int k=sc.nextInt();
double g1,g2;
g2=n/2;
do
{
g1=g2;
g2=((k-1)*g1+n/Math.pow(g1,k-1))/k;
}while(Math.abs(g1-g2)>0.000001);
System.out.println("The square root of "+n+" is = "+g2);

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt();
String str="";
while(n>0)
{
int rem=n%2;
str=rem+str;
n=n/2;
}
System.out.println(str);
}

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 {

public static void main(String[] args) {


int n;
n=Integer.parseInt(args[0]);
for(int i=1;i<=n;i++)
{
if(i%2==0)
{
for(int j=1;j<=n;j++)
{
System.out.print("* ");
}
}
else
{
for(int j=1;j<=n;j++)
{
System.out.print(" *");
}
}
System.out.println();
}

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 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int x=sc.nextInt();
System.out.println("Enter the second number");
int y=sc.nextInt();
while(y>0)
{
int rem=x%y;
x=y;
y=rem;
}
System.out.println("GCD = "+x);

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.

public class A5q20 {


public static void main(String[] args) {
System.out.println("Enter the range");
int n=Integer.parseInt(args[0]);
int flag;
for(int i=2;i<=n;i++)
{
flag=0;
for(int j=2;j<=i;j++)
{
if(i%j==0)
flag++;
}
if(flag==1)
System.out.println(i+" is prime");
else
System.out.println(i+" is not prime");
}

}
}

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;

for (long b = a; b <= n; b++)


{
b5 = b*b*b*b*b;
if (a5 + b5 + b5 + b5 > e5) break;

for (long c = b; c <= n; c++)


{
c5 = c*c*c*c*c;
if (a5 + b5 + c5 + c5 > e5) break;

for (long d = c; d <= n; d++)


{
d5 = d*d*d*d*d;
if (a5 + b5 + c5 + d5 > e5) break;
if (a5 + b5 + c5 + d5 == e5)
System.out.println(a + "^5 + " + b + "^5 + " + c + "^5 + " + d + "^5 = " + e + "^5");
}
}
}
}
}
}
}

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 {

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];
for(int i=0;i<n;i++)
{
System.out.println("enter value");
a[i]=in.nextInt();
}
int sum=0;
for(int j=0;j<n;j++)
{
sum+=a[j];
}
System.out.println("sum="+sum+"average="+(sum/n));
}

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 {

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;int flag=0;
for(i=0;i<n;i++)
{
System.out.println("enter value");
a[i]=in.nextInt();
}
System.out.println("enter search value");
int sv=in.nextInt();
for(i=0;i<n;i++)
{
if(a[i]==sv)
{
flag=1;
break;
}
}
if(flag==1)
System.out.println(sv+"is present");
else
System.out.println(sv+"is not present");
}

}
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 {

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];
for(int i=0;i<n;i++)
{
System.out.println("enter value");
a[i]=in.nextInt();
}
int max=a[0];int min=a[0];
for(int j=0;j<n;j++)
{
if(a[j]>max)
max=a[j];
if(a[j]<min)
min=a[j];
}
int maxpos=n-1;int minpos=0;
for(int k=0;k<n;k++)
{
if((a[k]==max)&&(k<maxpos))
maxpos=k;
if((a[k]==min)&&(k>minpos))
minpos=k;
}
System.out.println(max+" "+maxpos);
System.out.println(min+" "+minpos);
}

5. Write a java program to find the second largest value in an array of n elements.
import java.util.Scanner;
public class p5a6 {

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];
for(int i=0;i<n;i++)
{
System.out.println("enter value");
a[i]=in.nextInt();
}
int pos=0;
int max=0;int max1=0;
for(int i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
pos=i;
}

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 {

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];
for(int i=0;i<n;i++)
{
System.out.println("enter value");
a[i]=in.nextInt();
}
for(int i=0;i<n;i++)
{
System.out.println(a[i]+" ");

}
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 {

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 c=n-1;int temp=0;


for(i=0;i<(n/2);i++)
{
temp=a[i];
a[i]=a[c];
a[c]=temp;
c--;
}
for(i=0;i<n;i++)
{
System.out.println(a[i]+" ");

}
}

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();

System.out.println("enter array elements");


for(i=0;i<n;i++)
a[i]=sc.nextInt();
break;

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 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
System.out.println("enter dec no");
int n=in.nextInt();
int a[]=new int[100];
int c=0;
while(n>0)
{
a[c++]=n%8;
n/=8;
}
int i;
for(i=c-1;i>=0;i--)
System.out.print(a[i]);
}

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.

public class p10a6 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
System.out.println("enter limit");
int m=Integer.nextInt(args[0]);
int n=Integer.nextInt(args[1]);
double ran[]=new double[m];
for(int i=0;i<m;i++)
{
ran[i]=(int)(Math.random()*n);
}
for(int i=0;i<m;i++)
System.out.print(ran[i]+" ");
}
}

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 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
System.out.println("enter limit");
int i=0;
int n=in.nextInt();
double ran[]=new double[n];
while(i<n)
{
ran[i++]=(int)((n-1)+Math.random()*n);
}
for(i=0;i<n;i++)
System.out.print(ran[i]+" ");
}

}
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();
}
}

7. Write a java program to convert a decimal integer to its corresponding octal


representation.

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

the execution time:

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)

1. Write a java program to print M-by-N array in the tabular format.

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);
}
}

2. Design a class named Rectangle to represent a rectangle. The class contains:


 Two double data fields named width and height that specify the width and height of
the rectangle. The default values are 1 for both width and height.
 A no-argument constructor that creates a default rectangle.
 A constructor that creates a rectangle with the specified width and height.
 A method named getArea() that returns the area of this rectangle.
 A method named getPerimeter() that returns the perimeter.
Write a java program that creates two Rectangle objects—one with width 4 and height 40
and the other with width 3.5 and height 35.9. Display the width, height, area, and perimeter
of each rectangle in this order.

//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);
}
}

3. Design a class named QuadraticEquation for a quadratic equation ax2+ bx + c = 0. The


class contains:
 Private data fields a, b, and c that represent three coefficients.
 A constructor for the arguments for a, b, and c.
 Three getter methods for a, b, and c.
A method named getDiscriminant() that returns the discriminant, which is b The methods
named getRoot1() and getRoot2() for returning two roots of the Equation

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.

public class Exercise_09_07 {


public static void main(String[] args) {
Account account = new Account(1122, 20000);
account.setAnnualInterestRate(4.5);
account.withdraw(2500.0);
account.deposit(3000.0);
System.out.println("Balance: $" + account.getBalance());
System.out.println("Monthly Interest: " +
account.getMonthlyInterest());
System.out.println("Date Created: " + account.getDateCreated());

}
}

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();
}

public Account(int id, double balace) {


this();
this.id = id;
this.balance = balance;
}

public int getId() {


return this.id;
}

public double getBalance() {


return this.balance;
}

public double getAnnualInterestRate() {


return annualInterestRate;
}

public String getDateCreated() {


return this.dateCreated.toString();
}

public void setId(int id) {


this.id = id;
}

public void setBalance(double balance) {


this.balance = balance;
}

public void setAnnualInterestRate(double annualInterestRate) {


this.annualInterestRate = annualInterestRate;
}

public double getMonthlyInterestRate() {


return (annualInterestRate / 100) / 12 ;
}

public double getMonthlyInterest() {


return balance * getMonthlyInterestRate();
}

public void withdraw(double amount) {


this.balance -= amount;
}

public void deposit(double amount) {


this.balance += amount;
}
}
5. Design a class named Fan to represent a fan. The class contains:
Write a java program that creates two Fan objects. Assign maximum speed, radius 10, color
yellow, and turn it on to the first object. Assign medium speed, radius 5, color blue, and turn
it off to the second object. Display the objects by invoking their toString method.

public class Exercise_09_08 {


/** Main method */
public static void main(String[] args) {
final int SLOW = 1;
final int MEDIUM = 2;
final int FAST = 3;

Fan fan1 = new Fan();


Fan fan2 = new Fan();

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());
}
}

You might also like