Department of Computer Science and Engineering: Lab Manual
Department of Computer Science and Engineering: Lab Manual
Department of Computer Science and Engineering: Lab Manual
Engineering
Lab Manual
2018-19
LIST OF EXPERIMENTS
4. Conditional Statements
5. Looping Constructs
6. Functions
7. Arrays
8. Strings
9. Files
10.Classes
GRADING POLICY
Problem 1:
Input Format:
Input consists of an integer.
Output Format:
Output consists of a single line. Refer sample output for details.
Sample Input 1:
42
Sample Output 1:
The number of digits in 42 is 2
2
Problem 2:
Input Format:
Input consists of an integer which corresponds to n.
Output Format:
Refer Sample Input and Output for exact formatting specifications.
Sample Input 1 :
65
Sample output 1 :
1000001
Sample Input 2 :
82
Sample output 2 :
1010010
3
4
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
Scanner Class:
Scanner is a class in java.util package used for obtaining the input of the primitive types like int,
double etc. and strings. It is the easiest way to read input in a Java program, though not very
efficient if you want an input method for scenarios where time is a constraint like in competitive
programming.
• To create an object of Scanner class, we usually pass the predefined object System.in,
which represents the standard input stream. We may pass an object of class File if we
want to read input from a file.
• To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For
example, to read a value of type short, we can use nextShort()
• To read strings, we use nextLine().
• To read a single character, we use next().charAt(0). next() function returns the next
token/word in the input as a string and charAt(0) funtion returns the first character in that
string.
Be it a last minute get together, a birthday party or corporate events, the "Pine Tree" Event
Management Company helps you plan and execute it better and faster. Nikhil, the founder of the
company wanted the Amphi Event Management System to get and display the event details from
his Customers for every new order of the Company.
Write a program that will get the input of the event details like name of the event, type of the
event, number of people expected, a string value (Y/N) telling whether the event is going to be a
paid entry and the projected expenses (in lakhs) for the event. The program should then display
the input values as a formatted output.
Input Format:
First input is a string that corresponds to the name of the event. Assume the maximum length of
the string as 50.
Second input is a string that corresponds to the type of the event. Assume the maximum length
of the string as 50.
5
Third input is an integer that corresponds to the number of people expected for the event.
Fourth input is a character that corresponds to Y/N telling whether the event is going to be a paid
entry or not.
Fifth input is a double value that corresponds to the projected expenses (in lakhs) for the event.
Output Format:
Output should display the event details as given in the sample output.
All double values need to be displayed correct to 1 decimal place
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and rest corresponds to output.]
Program :
import java.util.*;
class Main {
public static void main(String args[]) {
System.out.println("Enter the name of the event");
Scanner s= new Scanner(System.in);
String st=s.nextLine();
System.out.println("Enter the type of the event");
String str=s.nextLine();
System.out.println("Enter the number of people expected");
int n=s.nextInt();
System.out.println("Is it a paid entry? (Type Y or N)");
char c=s.next().charAt(0);
System.out.println("Enter the projected expenses (in lakhs) for this event");
float f=s.nextFloat();
System.out.println("Event Name : " +st+ "\nEvent Type : " +str+ "\nExpected Count
: " +n+ "\nPaid Entry : "+c);
System.out.printf("Projected Expense : %.1fL",f);
}
}
Write a program that accepts a “Integer” class type value as input and invokes some of the
methods defined in the Integer Wrapper class.
Refer sample input and output. All functions should be performed using the methods defined in
the Integer class.
7
Enter an integer
540
The binary equivalent of 540 is 1000011100
The hexadecimal equivalent of 540 is 21c
The octal equivalent of 540 is 1034
Byte value of 540 is 28
Short value of 540 is 540
Long value of 540 is 540
Float value of 540 is 540.0
Double value of 540 is 540.0
Test Cases:
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter an integer");
int n= sc.nextInt();
long b;
int n1=n,n2=n,n3=n;
int r;
long i=1,sum=0;
while(n1>0)
{
r=n1%2;
sum=sum+(r*i);
i=i*10;
n1=n1/2;
}
System.out.println("The binary equivalent of " +n+ " is "+sum);
char ch[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
int rem;
String hd="";
while (n2>0)
{rem=n2%16;
hd=ch[rem]+hd;
n2=n2/16;
}
System.out.println("The hexadecimal equivalent of "+n+" is "+hd);
long o;
int r1;
long i1=1,sum1=0;
while (n3>0)
{
r1=n3%8;
sum1=sum1+(r1*i1);
i1=i1*10;
n3=n3/8;
}
9
Operators in java
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
• Unary Operator,
• Arithmetic Operator,
• Shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
Consider a currency system in which there are notes of seven denominations, namely, Rs. 1, Rs.
2, Rs. 5, Rs. 10, Rs. 50, Rs. 100. If the change given to Pranav Rs. N is input, write a program to
computer smallest number of notes that will combine to give Rs. N.
Note:
Refer to problem specifications.
Input Format:
First line of the input is an integer N, the change to be given to Pranav.
Output Format:
Output should display the the smallest number of notes that will combine to give N.
Refer sample input and output for formatting specifications.
Sample Input 1:
1200
Sample Output1:
12
Sample Input 2:
242
Sample Output2:
7
Test Cases:
9 T4 250 3 Private
10 T3 500 5 Private
11 T6 100 1 Private
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int rupees[]={100,50,10,5,2,1};
int amount=sc.nextInt();
int count=0;
for (int i=0;i<rupees.length;i++)
{
int c=amount/rupees[i];
amount=amount-c*rupees[i];
count=count+c;
}
System.out.println(count);
}
}
The Magic Castle, the home of the Academy of Magical Arts at California has organized the
great ‘WonderWorks Magic Show’. 3 renowned magicians were invited to mystify and thrill the
crowd with their world’s spectacular magic tricks. At the end of each of the 3 magicians’ shows,
the audience were requested to give their feedback in a scale of 1 to 10. Number of people who
watched each show and the average feedback rating of each show is known. Write a program to
find the average feedback rating of the WonderWorks Magic show.
Input Format:
First line of the input is an integer value that corresponds to the number of people who watched
show 1.
Second line of the input is a float value that corresponds to the average rating of show 1.
Third line of the input is an integer value that corresponds to the number of people who watched
show 2.
Fourth line of the input is a float value that corresponds to the average rating of show 2.
Fifth line of the input is an integer value that corresponds to the number of people who watched
show 3.
Sixth line of the input is a float value that corresponds to the average rating of show 3.
Output Format:
Output should display the overall average rating for the show. Display the rating correct to 2
decimal places.
13
Test Cases:
SNo Name Input Output Visibility
1 T4 50 Enter the number of people who watched show 1 Private
2 Enter the average rating for show 1
34 Enter the number of people who watched show 2
2.7 Enter the average rating for show 2
15 Enter the number of people who watched show 3
1 Enter the average rating for show 3
The overall average rating for the show is 2.09
2 T3 1000 Enter the number of people who watched show 1 Private
90.8 Enter the average rating for show 1
500 Enter the number of people who watched show 2
78.0 Enter the average rating for show 2
2000 Enter the number of people who watched show 3
67.9 Enter the average rating for show 3
The overall average rating for the show is 75.89
3 T2 200 Enter the number of people who watched show 1 Private
5.8 Enter the average rating for show 1
100 Enter the number of people who watched show 2
4 Enter the average rating for show 2
300 Enter the number of people who watched show 3
9.1 Enter the average rating for show 3
The overall average rating for the show is 7.15
4 T1 400 Enter the number of people who watched show 1 Public
9.8 Enter the average rating for show 1
500 Enter the number of people who watched show 2
9.6 Enter the average rating for show 2
100 Enter the number of people who watched show 3
5 Enter the average rating for show 3
The overall average rating for the show is 9.22
14
Program :
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of people who watched show 1");
int a=sc.nextInt();
System.out.println("Enter the average rating for show 1");
double a1=sc.nextDouble();
System.out.println("Enter the number of people who watched show 2");
int b=sc.nextInt();
System.out.println("Enter the average rating for show 2");
double b1=sc.nextDouble();
System.out.println("Enter the number of people who watched show 3");
int c=sc.nextInt();
System.out.println("Enter the average rating for show 3");
double c1=sc.nextDouble();
double r=((a*a1)+(b*b1)+(c*c1))/(a+b+c);
System.out.printf("The overall average rating for the show is %.2f",r);
}}
The shape of the college ground is Square. For the Independence day Flag Hoisting Function, it
has been decided to place the flag post at the exact center of the ground. Can you please help
them in placing the flag post at the exact center?
Given the coordinates of the left bottom vertex of the square ground and the length of the side,
you need to write a program to determine the coordinates of the centre of the ground.
Input Format:
Input consists of 3 integers. The first integer corresponds to the x-coordinate of the left bottom
vertex. The second integer corresponds to the y-coordinate of the left bottom vertex. The third
integer corresponds to the length of the square.
Output Format:
Refer Sample Input and Output for exact formatting specifications.
Test cases:
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the x-coordinate of the left bottom vertex");
int a=sc.nextInt();
System.out.println("Enter the y-coordinate of the left bottom vertex");
int b=sc.nextInt();
System.out.println("Enter the length of a side");
int c=sc.nextInt();
int x=(a+(a+c))/2;
int y=(b+(b+c))/2;
System.out.println("The centre of the ground is at (" +x+","+y+")");
}
}
16
Switch syntax:
...
for ( initialization; condition; incrementor )
statement;
switch ( int expression )
{
case int constantExpression :
statement; break;
17
A break causes Java to stop the current block statement and resume execution after it:
...
while( true ) {
if ( condition( ) )
break;
}
// after while
...
A continue statement causes loops to move on to their next iteration by returning to the point
where they check their condition:
...
for( int i=0; i < 100; i++ ) {
if ( i == 33 )
continue;
System.out.println( i );
}
...
Super Quiz Bee is a famous quiz Competition that tests students on a wide variety of academic
subjects. This week’s participants were kids of age 12 to 15 and the quiz questions were based on
Gregorian calendar.
In the first round of the competition, the Host of the event told the participants that it was Monday on
the date 01/01/2001. Later he questioned each one of the participant what would be the day on the
1st January, giving them a particular year. Write a program to help the Host validate the answers
given by the participants.
Input Format:
The first line contains an integer that corresponds to a year.
18
Output Format:
Output the day on the 1st January of that given year.
Refer sample input and output for formatting specifications.
Sample Input 1:
1994
Sample Output 1:
Saturday
Sample Input 2:
2014
Sample Output 2:
Wednesday
Test Cases:
Program :
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int y=sc.nextInt();
int i,s4,d=0;
if(y>0)
{
if (y<2001)
{
for(i=2000;i>=y;i--)
{
if((i%400==0)||(i%4==0)&&(i%100!=0))
d=d+2;
else
d=d+1;
}
s4=d%7;
19
if (s4==6)
System.out.println("Tuesday");
else if(s4==5)
System.out.println("Wednesday");
else if(s4==4)
System.out.println("Thursday");
else if(s4==3)
System.out.println("Friday");
else if(s4==2)
System.out.println("Saturday");
else if(s4==1)
System.out.println("Sunday");
else
System.out.println("Monday");
}
else if (y>2001)
{
for(i=2002;i<=y;i++)
{
if((i%400==0)||(i%4==0)&&(i%100!=0))
d=d+2;
else
d=d+1;
}
if((y%400==0)||(y%4==0)&&(y%100!=0))
d--;
s4=d%7;
if (s4==1)
System.out.println("Tuesday");
else if(s4==2)
System.out.println("Wednesday");
else if(s4==3)
System.out.println("Thursday");
else if(s4==4)
System.out.println("Friday");
else if(s4==5)
System.out.println("Saturday");
else if(s4==6)
System.out.println("Sunday");
else
System.out.println("Monday");
}
else
System.out.println("Monday");
}
}
}
20
Input Format:
First line of the input consists of 3 integers that gives the Hurl Factor, Spin Factor and Speed
Factor of the ride, each separated by a space.
Output Format:
Output should display the grade of the ride depending on Conditions.
Refer sample input and output for formatting specifications.
Sample Input 1:
51 89 150
Sample Output 1:
10
Sample Input 2:
45 69 102
Sample Output 2:
8
Test Cases:
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n1=sc.nextInt();
int n2=sc.nextInt();
int n3=sc.nextInt();
if (n1>50 && n2>60 && n3>100)
System.out.println("10");
else if(n1>50 && n2>60)
System.out.println("9");
else if(n2>60 && n3>100)
System.out.println("8");
else if(n1>50 && n3>100)
System.out.println("7");
else if(n1>50 || n2>60 ||n3>100)
System.out.println("6");
else
System.out.println("5");
}
}
Please help him by giving a command by telling the direction in which he should go, so as to
reach his home. If you give him a direction, he will keep moving in that direction till he reaches
home. There are four possible directions you can give as command - "left", "right", "up", "down".
22
It might be possible that you can't instruct Harry in such a way that he reaches his home. In that
case, display the output as "sad".
Input Format:
First line of the input contains four space separated integers x1, y1, x2, y2.
Output Format:
Output a single line containing "left" or "right" or "up" or "down" or "sad" (without quotes).
Refer sample input and output for formatting specifications.
Sample Input 1:
0010
Sample Output 1:
right
Sample Input 2:
0011
Sample Output 2:
sad
Test cases:
Program :
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int x1=sc.nextInt();
int y1=sc.nextInt();
int x2=sc.nextInt();
int y2=sc.nextInt();
23
if (x1==x2 || y1==y2)
{ if (x1>x2)
System.out.println ("left");
else if (x2>x1)
System.out.println("right");
else if (y1>y2)
System.out.println("down");
else if (y2>y1)
System.out.println("up");
}
else
System.out.println("sad");
}
}
24
while will perform a logical test, and if this results in a true condition execute subsequent
statements bounded by {} brackets.
do while will first execute statements bounded by {} brackets and than perform a logical test. If
the logical test results in a true condition execute the statements bounded by {} brackets again.
• A for loop is divided into three parts, an initialization part, a conditional part and an
increment part
• You should sett all initial values in the initialization part of the loop.
• A true from the condition part will execute subsequent statements bounded by {} brackets.
A false from the condition part will end the loop.
• For each loop the increment part will be executed.
Hotel Royal Gardenia has arranged for an elite business party for the lead industrialists and
celebrities of the City. Followed by a dinner buffet, the Event coordinators planned for some
casino game events for the high-toned crowd. Peter was a visitor at the party and he takes some
number of rubles to the casino with the intention of becoming rich. He plays three machines in
turn. Unknown to him, the machines are entirely predictable. Each play costs one ruble. The first
machine pays 20 rubles every 25th time it is played; the second machine pays 80 rubles every
120th time it is played; the third pays 8 rubles every 12th time it is played.
Given the number of rubles with Peter initially (there will be at least one and fewer than 1000),
and the number of times each machine has been played since it last paid, write a program that
calculates the number of times Peter plays until he goes broke.
Input Format:
First line of the input is an integer that corresponds to the number of rubles with Peter initially.
Next 3 lines of the input is an integer that corresponds to the number of times each machine has
been played since it last paid.
Output Format:
Output a single line that gives the number of times Peter plays until he goes broke.
Refer sample input and output for formatting specifications.
Sample Input 1:
48
3
12
4
Sample Output 1:
Peter plays 56 times before going broke
Sample Input 2:
35
10
30
9
Sample Output 2:
Peter plays 71 times before going broke
26
Test Cases:
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a1=sc.nextInt();
int a2=sc.nextInt();
int a3=sc.nextInt();
int b1=25,b2=120,b3=12,c1=20,c2=80,c3=8,i,c=0;
while (n>0)
{for(i=1;i<=3;i++)
{
switch(i)
{
case 1:
if(n>0)
{
++c;
27
n--;
if (++a1%b1==0)
n+=c1;}
break;
case 2:
if(n>0)
{
++c;
n--;
if (++a2%b2==0)
n+=c2;}
break;
case 3:
if(n>0)
{
++c;
n--;
if (++a3%b3==0)
n+=c3;}
break;
}
}
System.out.println("Peter plays "+c+" times before going broke");
}
}
WeCanNGO Trust is organizing a charity dinner at St. John’s College. Since older students are
both wiser and richer, the members of the trust decide that the price of each ticket will be based
on how many years the students have been in the school. A first year student will buy a PINK
ticket, a second year student will buy a GREEN ticket, a third year student will buy a RED ticket,
and a fourth year student will buy an ORANGE ticket.
Assume that all tickets are sold. Each colour of ticket is uniquely priced. Write a program to
output all combinations of tickets that produce exactly the desired amount to be raised. The
combinations may appear in any order. Also display the total number of combinations found and
the smallest number of tickets to be printed to raise the desired amount so that printing cost is
minimized.
28
Input Format:
First 4 lines of the input correspond to the cost of a PINK, GREEN, RED, ORANGE ticket (in the
exact order).
Last line of the input corresponds to the exact amount of money to be raised by selling tickets.
Output Format:
Output all combinations of tickets that produce exactly the desired amount to be raised. The
combinations may appear in any order. Output the total number of combinations found. Output
the smallest number of tickets to print to raise the desired amount so that printing cost is
minimized.
Refer sample input and output for formatting specifications.
Sample Input 1:
1
2
3
4
3
Sample Output 1:
# of PINK is 0 # of GREEN is 0 # of RED is 1 # of ORANGE is 0
# of PINK is 1 # of GREEN is 1 # of RED is 0 # of ORANGE is 0
# of PINK is 3 # of GREEN is 0 # of RED is 0 # of ORANGE is 0
Total combinations is 3
Minimum number of tickets to print is 1
Sample Input 2:
1
2
4
3
4
Sample Output 2:
# of PINK is 0 # of GREEN is 0 # of RED is 1 # of ORANGE is 0
# of PINK is 0 # of GREEN is 2 # of RED is 0 # of ORANGE is 0
# of PINK is 1 # of GREEN is 0 # of RED is 0 # of ORANGE is 1
# of PINK is 2 # of GREEN is 1 # of RED is 0 # of ORANGE is 0
# of PINK is 4 # of GREEN is 0 # of RED is 0 # of ORANGE is 0
Total combinations is 5
Minimum number of tickets to print is 1
29
Test cases:
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int p=sc.nextInt();
int g=sc.nextInt();
int r=sc.nextInt();
int o=sc.nextInt();
int t=sc.nextInt();
int a,b,c,d,i,j,k,l,x,m,count=0;
a=t/p;
b=t/g;
c=t/r;
d=t/o; //max times a loop can run
m=a+b+c+d; //random value dp wanted
for(i=0;i<=a;i++)
{
30
for(j=0;j<=b;j++)
{
for(k=0;k<=c;k++)
{
for(l=0;l<=d;l++)
{ if((i*p)+(j*g)+(k*r)+(l*o)==t)
{count++;
x=i+j+k+l;
if(x<m)
m=x;
System.out.println("# of PINK is "+i+" # of GREEN is "+j+" # of RED is "+k+"
# of ORANGE is "+l);
}
}
}
}}
System.out.println("Total combinations is "+count);
System.out.println("Minimum number of tickets to print is "+m);
}
}
Input Format:
The first line of input consists of a character c corresponding to the character upto which the
pattern needs to proceed.
Output Format:
The output consists of n lines. The ith line consists of i uppercase character(s) separated by a
space.
Print “Invalid Input” if n is not an uppercase alphabet.
Refer sample input and output for further specifications.
Sample Input 1:
E
Sample Output 1:
ABCDE
ABCD
ABC
AB
A
31
Sample Input 2:
G
Sample Output 2:
ABCDEFG
ABCDEF
ABCDE
ABCD
ABC
AB
A
Sample Input 3:
a
Sample Output 3:
Invalid Input
Test Cases:
ABCDEFGHIJKLMNOPQRS
ABCDEFGHIJKLMNOPQR
ABCDEFGHIJKLMNOPQ
ABCDEFGHIJKLMNOP
ABCDEFGHIJKLMNO
ABCDEFGHIJKLMN
ABCDEFGHIJKLM
ABCDEFGHIJKL
ABCDEFGHIJK
ABCDEFGHIJ
ABCDEFGHI
ABCDEFGH
ABCDEFG
ABCDEF
ABCDE
ABCD
ABC
AB
A
7 t5 6 Invalid Input Private
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
char c=sc.next().charAt(0);
int x=(int)c;
int y=65;
char i,j,ch;
if (x>=65 && x<=90)
{
for(i='A';i<=c;i++)
{
for(j=c;j>=i;j--)
{ch=(char)y;
System.out.print(ch+" ");
y++;}
System.out.println();
y=65;
}}
else
System.out.println("Invalid Input");
}
}
33
Ex No. 6 FUNCTIONS
Creating Method
Syntax
Here,
Method definition consists of a method header and a method body. The same is shown in
the following syntax −
Syntax
• modifier − It defines the access type of the method and it is optional to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
• method body − The method body defines what the method does with the
statements.
34
Method Calling
For using a method, it should be called. There are two ways in which a method is called i.e.,
method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the program
control gets transferred to the called method. This called method then returns control to the
caller in two conditions, when −
The methods returning void is considered as call to a statement. Lets consider an example
−
System.out.println("This is tutorialspoint.com!");
In the Mini project 7th module is to evaluate the expression y = x + x^2+........+x^n. Rita
allotted this function to Malini. Collect and display the values returned by the called function.
Test your program and report the results obtained.
Help Malini to write a program to evaluate the expression?
Function Specification:
int calculate(int,int);
where the first argument corresponds to the value of x and second corresponds to n.
Input Format:
The first line of the input contains an integer x.
The second line of the input contains an integer n (n>=0).
Output Format:
Output displays an integer.
Refer sample input and output for formatting details.
2
Enter the value of n
3
The result is
14
Function Definitions:
Test Cases:
Program:
import java.util.*;
import java.lang.*;
class Main {
int calculate(int x,int n)
{
int i=0,sum=0;
if(n==0)
{
return 1;
}
else
{
for(i=1;i<=n;i++)
{
sum=sum+(int)Math.pow(x,i);
}
return sum;
}
}
}
}
37
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.
Syntax:
1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }
Asha’s birthday is shortly coming and her parents have planned to arrange for a house
party. Deepa was Asha’s best friend and was expecting her birthday since a month. This is
because Deepa’s Dad has promised her that he and Deepa together would design a
Reverse Talking kitty toy all by themselves and gift it to Asha. Deepa believed that Asha
might be overjoyed with this gift from her dear friend.
Deepa’s Dad put the best of his efforts to design the toy. As a first module in the design he
intended to write a program that would reverse a numeric input given to it. He needs your
help to write a recursive function for reversing the digits of the given number N. Please
assist him in the task.
Function Specifications:
Use the function name, return type and the argument type as:
int reverse(int)
This recursive function should return the reverse of a N digit number.
Input Format:
The first line of the input is an integer N.
Output Format:
Print the reverse of a N digit number.
Refer sample input and output for formatting specifications.
Sample Input 1:
1234
Sample Output 1:
4321
Sample Input 2:
32333333
38
Sample Output 2:
33333323
Test Cases:
1 T3 200 2 Private
2 T2 32333333 33333323 Public
3 T1 1234 4321 Public
Program:
import java.util.*;
import java.lang.*;
class Main {
}
}
39
Ex No. 7 ARRAYS
Java Array
Normally, an array is a collection of similar type of elements that have a contiguous memory
location.
Java array is an object which contains elements of a similar data type. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in java is index-based, the first element of the array is stored at the 0 index.
1. arrayRefVar=new datatype[size];
We can declare, instantiate and initialize the java array together by:
In such case, data is stored in row and column based index (also known as matrix form).
"Shades" Television Channel organizes a fun-filled event named "Best Couple 2017", where
in married couples would be invited and given many tasks and activities. Based on some
criteria decided by the jury, a best couple will be chosen.
N couples registered for the event and each couple was given a unique registration number.
One specific couple's registration Id got missed. The event coordinators wanted your help in
finding the missing Id.
Write a program which takes an array of registration numbers as input and outputs the
missing registration Id.
Input Format:
First line of the input contains the number of couples N who registered for the event.
Assume that the maximum value for N as 50.
Second line of input contains N registration Id of each of the couple, separated by a space.
Output Format:
Output in a single line the missing registration Id.
Refer sample input and output for formatting specifications.
Sample Input 1:
3
121
Sample Output 1:
2
Sample Input 2:
5
11223
Sample Output 2:
3
41
Test Cases:
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
int[] a=new int[50];
int i,j,temp=0,flag=0;
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
/* for(i=0;i<n;i++)
{
System.out.print(a[i]+" ");
42
}*/
for(i=0;i<n;i=i+2)
{
if(a[i]!=a[i+1])
{
flag =1;
}
if(flag==1)
{
System.out.println(a[i]);
break;
}
}
}
}
Problem 2: Nationality
The Pan Am 73 flight from Bombay to New York en route Karachi and Frankfurt was
hijacked by a few Palestinian terrorists at the Karachi International Airport. The senior flight
purser Neerja Banhot had to wither her fear and rescue the passengers on board.
The hijackers targetted passengers of a specific nationality and threatened to kill them.
Neerja did not want this to happen and plotted a plan to evacuate the passengers.
Before proceeding, she wanted to know the count of passengers from the specific country x,
who are threatened by the hijackers. Given r the number of rows, c the number of columns,
and the description of the nationality of each passenger in the grid r*c, can you find the
number of passengers from a particular country c ?
Input Format :
The first line of input consists of an integer r, corresponding to the number of rows of seats
in the aircraft.
The second line of input consists of an integer c, corresponding to the number of seats in a
row.
The following r lines each with c columns of inputs, consist of uppercase alphabets that
corresponds to the nationalities of passengers.
The next line of input is a character that corresponds to a specific country.
Output Format :
The output consists of an integer corresponding to the number of passengers from country
x.
Refer sample input and output for further specifications.
43
Sample Input 1:
6
5
ICBIC
IABIS
IVBIG
GHIHI
OMOMO
OIUIU
B
Sample Output 1:
3
Test Case:
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
int i,j,r,c,count=0;
r=sc.nextInt();
c=sc.nextInt();
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
a[i][j]=sc.next().charAt(0);
}
}
char ch=sc.next().charAt(0);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(a[i][j]==ch)
{
count++;
}
}
}
System.out.println(count);
}
}
45
Ex No. 8 STRINGS
Generally, String is a sequence of characters. But in Java, string is an object that represents
a sequence of characters. The java.lang.String class is used to create a string object.
1. By string literal
2. By new keyword
Input consists of a string. Assume that the input string consists of only letters and the
maximum length of the string is 20.
All text in bold corresponds to input and the rest corresponds to output.
AmphiSoft
Test Cases:
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the input string");
String str=sc.next();
String str2=str.toLowerCase();
System.out.printf("The output string is %s",str2);
}
}
Input consists of a string. Assume that all characters in the string are lowercase letters and
the maximum length of the string is 200.
All text in bold corresponds to input and the rest corresponds to output.
Sample Input and Output:
Enter the input string
amphisoft
The output string is mphsft
48
Test Cases:
Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the input string");
String str=sc.nextLine();
String str1=str.replaceAll("[aeiouAEIOU]", "");
System.out.printf("The output string is %s",str1);
}
}
49
Ex No. 9 FILES
OutputStream vs InputStream
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given
below.
OutputStream class
Method Description
1) public void write(int)throws is used to write a byte to the current output
IOException stream.
2) public void write(byte[])throws is used to write an array of byte to the
IOException current output stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
50
OutputStream Hierarchy
InputStream class
Method Description
1) public abstract int reads the next byte of data from the input stream. It
read()throws IOException returns -1 at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can
IOException be read from the current input stream.
3) public void close()throws is used to close the current input stream.
IOException
InputStream Hierarchy
51
Program 1:
import java.io.*;
public class CopyFile {
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes are,
FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an
input file (having unicode characters) into an output file
52
Program 2:
import java.io.*;
public class CopyFile {
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Standard Streams
All the programming languages provide support for standard I/O where the user's program
can take input from a keyboard and then produce an output on the computer screen. If you
are aware of C or C++ programming languages, then you must be aware of three standard
devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three
standard streams −
• Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
• Standard Output − This is used to output the data produced by the user's program
and usually a computer screen is used for standard output stream and represented
as System.out.
• Standard Error − This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as System.err.
53
FileInputStream
This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of
this file output stream is called when there are no more references to this stream.
Throws an IOException.
3 public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int.
Returns the next byte of data and -1 will be returned if it's the end of the file.
4 public int read(byte[] r) throws IOException{}
This method reads r.length bytes from the input stream into an array. Returns the
total number of bytes read. If it is the end of the file, -1 will be returned.
5 public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream. Returns an
int.
FileOutputStream
This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of
this file output stream is called when there are no more references to this stream.
Throws an IOException.
3 public void write(int w)throws IOException{}
Writes w.length bytes from the mentioned byte array to the OutputStream.
54
Program 3:
import java.io.*;
public class fileStreamTest {
try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();
Ex No. 10 CLASSES
Classes in Java
Example
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
A class can have any number of methods to access the value of various kinds of methods.
In the above example, barking(), hungry() and sleeping() are methods.
Creating an Object
56
As mentioned previously, a class provides the blueprints for objects. So basically, an object
is created from a class. In Java, the new keyword is used to create new objects.
Program 1:
If we compile and run the above program, then it will produce the following result −
Output
Instance variables and methods are accessed via created objects. To access an instance
variable, following is the fully qualified path −
Example
57
This example explains how to access instance variables and methods of a class.
Program 2:
If we compile and run the above program, then it will produce the following result −
Output
For our case study, we will be creating two classes. They are Employee and EmployeeTest.
58
First open notepad and add the following code. Remember this is the Employee class and
the class is a public class. Now, save this source file with the name Employee.java.
The Employee class has four instance variables - name, age, designation and salary. The
class has one explicitly defined constructor, which takes a parameter.
Example
import java.io.*;
public class Employee {
String name;
int age;
String designation;
double salary;