[go: up one dir, main page]

0% found this document useful (0 votes)
5 views11 pages

Class Solved Progz

The document discusses four problems related to writing Java programs that define methods. The solutions provided code to define methods that find the largest of two or three numbers, return the ASCII code of a character, and convert a height in inches to centimeters.

Uploaded by

prantik ban
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)
5 views11 pages

Class Solved Progz

The document discusses four problems related to writing Java programs that define methods. The solutions provided code to define methods that find the largest of two or three numbers, return the ASCII code of a character, and convert a height in inches to centimeters.

Uploaded by

prantik ban
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/ 11

SOLVED PROGRAMSE

Problem 1 :
1irom the

Write a
program O denne
a method void largest( int x, int y ) and print the
B gest
rom X and y.
Darameters/arguments

Solution:

1 The program that finds the largest from two numbers


public class Question_1
arguments X, y
public void largest( int x, int y function definition with

nt large; Ivariable declaration


I/finding below the largest numbers
and Y
large (x =
>y)? x:y Ifinding largest from X Printing resuis
="+large );
"

"

and "+ y+ is
Sy'stem.out.printinThe largest from "+ x+

//end of the function largest()


Wend of the class termina
click OK, the
input the parameter values,
Output: Compile the
and r u n program,
window appears with the output:
aBluet Method Call

void largesn Blue: Teminal Window-d


Ontions
Opo
uesbon 1.argest (82 41 1s 82
Irom 82 aid
The argest

Cancen

Problem 2
int y, int z ) to decide and return the
Write program to define
a
a method static int largest( int x,
and zZ.
parameters/arguments x, y
largest from the three integer

Solution:
largest from three numbers
7 The program that finds the
public class Question_2
int z )function definition with arguments x, y andz
public static int largest( int x, int y,
IIvariable declaration
int large;
from x and y, and store in variable L
/finding below the largest
Iif (x>y) then variable L' stores * otherwise y
int L = ( x> y ) ? x : y
Inow finding below the largest irom prev1ous and z, and store in variable large

Z; IRE (L>z) then variable large' stores L' otherwise z


large =( L > z ) ? L : /returning largest number stored in variable large
return ( large ),
Wlend of the function largest()
/end of the class

Classes and Methods (or Functions) 121


Output: Compile and run the program, input the parameter values, click OK, the Ma
Result window appears that contains the final return value as
the output
Blue Method Call a Bluek Method Result

nt largestnt x, int y, int 2


nt largest(mt x, int yY, nt2)

QuesBon2.rgest25 ntx Ques tion 2.largest(25, 13, 86) nspect

reurned: Get
hty
nt B6

Ok Cance Ooe
Problem 3
Write a program to define a method/function int ASCIL code( char ch), to return the ascii value ot
the parameter/argument ch. Define another method/function void result , to invoke the metho
ASCILcode( ) by passing the relevant value to the parameter/argument and print the AsC code.

Solution:
This program prints the ASCII code
public class Question3

public int ASCII codel char ch ) I/function or method definition with parameter 'ch'

int code = ch; of character in 'ch'


return code;
finding the ASCII
I/returning the ASCII code
W/end of function
ASCILcode(O
/the function below invokes the above function to pass parameter and get return value

public void result( ) kanetion or method definition with parameter 'oh'

char s=G; /assign a character 'G' in the character variable 's'


i n t ascii = ASCI_code( 8 );
lcalling function
' s (G') to formal
by passing value is
character variable
parameter 'ch' and receives the retu
Ivalue of variable 'code' into variable 'ascii'
System.out.println
(The AScIl code of +8 + is = "+ ascii );
result( ) ends here
/function
M/class closes here
Output: The following is a computer generated output when function result( ) is called
Bluel:Teminal Window d

Options
The ASCII code of G is =
71

olsd lbeit
Problem 4:
Write a program to create class
Measurement with a method/function
a
height containing height of a person in inches as the
) void ConvertHe fed
and inches and print the neght along parameter/argument, Convert the height 1
with
nches), Also, define a main method/function to
the converted
height in feet and inches (where 1 e
lass type and by callinginvoking the method voldassign
the height of a person. Create suitable o
ConvertHelght(.) print the result.
22
Classea and Method for Funeto
ogram converts height in inches into feet and inches, input using sCan
This
b l i c class Measuremement

nblic void ConvertHeight int height )/function definition with height as paraee

int feet = height/ 12; convert height into feet and store in variable 1eet
int inches = height % 12; "inches
VConvert height into inches and store in variable
lInow printing the results

and "+inches+" inches";


incnes5
System.out.printin The Height ="+ height feets and "*inches+
"
+ "inches 18=
e s is ="+feet+
+feet+ "feets
/function ConvertHeight( ) ends her here
void main() Imain( ) function definition starts here
publicstatic
intH 79; / assign height
person of a

Measurement obj = new Measurement(); /making objectinstance 'obj' of class


obj. ConvertHeight( H); l calling function using object 'obi' by passing value
W Or actual parameter "H' to formal parameter "height
lend of main( ) function
V/class closes here

Output: The following


1s a computer generated output after calling main( ) function:
emnal Window d
Opbions
Input the height 79
The He1ght =79 inches is 6 feets and 7 1nches

Problem 5
Write a program to create a method/function void show( char st ), to print the original character in
e parameter 'st and next two characters. For example:ifst M then output will be M,'A'N, X otherwise
'a'
will be g h, i. It is assumed that the characters
are between or x.
-B g then the output
>olution:
characters and their conversions
nis program uses

public class Question4


l/method or function definition with parameter 'st'
public void Show( char st)

System.out.println("Original character =+8t


it will not do
lyou may also write st++, but st stl will not work because
Bt + 1
fautomatic type conversion, means character to ASCT and back to character

ystem.out.println("Next character+Bt);
I inding the second next character arter previous st + 1. The rules
B+ 1 Itor finding varlous characters as same as mentloned above that use
/st++ o r s t l instead of stmst+1
next character 8t);
/tunetivem.out.println("Second

M/elna n Show( ) ends here


Viclass closes here

hd
Method (or Funetions) 128
Output:The following is a computer generated output after calling function sSh
(1) If parameter value st E' then output is: (ii) If parameter value st = th
then outpu
Bluek Teminal Window- d aBluel: Terminal Window-d
Opbons Ophons
original character =
j
original character E
Next character =k
Next character =F
Second next character
=1
Second next character =G

Problem 6:
Write a program to define a method/function void Swap_Numbers( int x, int y ), to swapinter
the integer parameters x and y, and print the interchanged numbers (TOr example: it x=12 and
after swapping'interchange x=9 and y=9 t
y=12).
Also define a method/function void Result( ), to assign two integers and print them as oin.
integers before swap/interchange. Create a suitable object/instance of the class and by callinginat
method Swap_numbers(..), swap and print the integers after interchange. /invok
Solution:
W This program performs swapping of numbers
class SwapNumbers
void Swap_Numbers( int x, I/method definition with parameters
int y) x,y

l to interchange the values of two nu ers use the following process


int temp =
x; / store or assign the number in * into a temporary variable tem
l store or assign the second number y' into the previous number =
y = tempP / store
assign the value of temporary variable "temp'
now or
into
System.outprintin("The numbers after interchange or swap are = "+x +""ty)
W function Swap_Numbers() ends here
void Result() l definition
of function Result()

int F = 14; l assign first number


int S = 8; assign second number
SwapNumbers obj = new SwapNumbers();
lImaking object/instance 'obj' of ch
System.out.printin("The numbers before interchange or swap are"+ F +" "+S;
=
/to pr
the original numbers or numbers before interchan=
obj. Swap_Numbers( F, S); l
calling function using object 'obj' by passing valu
o f actual parameter "F, 'S' to the formal parameter *
lend of function Result()
W/the class closes here

Output:
The numbers before interchange or swap are = 14 8
The numbers after interchange or swap are = 8 14

Classes and Methods (or Func


probiem gram to input the side of a square and print area of square.
progra

Wrie you may take any class


along with methoa
name
Darametore o8ram " do

hwith vour own


1:
own parerers to represent input. This question requires
side of square
me
one
your
may be integer or fractional, here nothing is mentioned so take it of your c
e.)

of square
aaot rogram calculates
area
WpThis
ublic class Square

double side) the Area( ) is method name and side is parameter


public
void
Area
data
double area, declaration of variables to input and calculate
area Side side; nding area of square on the parameter value "side as
inp
Printing results
Svstem.out.println(The value of side is ="+ side );
The area or
square 18 +area );
System.out.printin
/lend of the function Area(
V/end of t h e c l a s s
is called:
is a computer generated output when function Area(
Output: The following
then output will be:
value of parameter side is: 15.6,
Ifthe
aBluek Teminal Window-d
ntione

The value of side is = 15.6

of is = 243.35999999999999
The area square

Problem 8 :
Wnte a program to input the length and breadth in whole numbers. Print area of rectangle.

bolution:
This program calculates the area of rectangle

public class Rectangle

len, int bred ) t h e rectangle_Area() is the name of method


publie void
rectangle Area( int
int /declaration of variables to input and calculate data
len, bred; double area;
area len * area of Rectangle
bred; Iinding
em.out.println("OUTPUT "); IPrinting results
. o u t . p r i n t l n ( " T h e length of rectangle 1s + len )

is + b r e d
stem.out.println("The breadth of rectangle
n . o u t . p r i n t l n ( " T h e area of rectangle is = + area )

)
ondofofthe
Wlend
the function rectangleArea(
class
laases nd
a
Methods (or Functions) 125
rectangle_Area()
18 invoked
method
when
following is the
output l0
function len
=

Output: The the


argument of
Assume that the value of first
of the
function
bred 1

first argument
Assume that the value of

OUTPUT
is= 16
The length of rectangle
is 14
The breadth of rectangle 224.0
area of rectangle is =

The
Wnte a program to define a method/function long sumDigits() along with a long integeralsoararetun
Problem 9
number and alsn
o
tuwo the last digits the
the last and and s u m 18 52).
number and to print be s, 48
digit output will
accept four is : 3648, then
a
to (for example: if
the number four digt long integer number and
theirsum
void accept()
to initialize a Sum or the last and la
another function
with
Also define the results along
methodfunction sumDigits( ), print
the
invoking
digits
Solution:
public class Question_l5. num
f u n c t i o n definition
with tong parame
or
num) llmethod
public long sumDigits( long
variables
Wdeclaration of long integer type
long last_digit, last_two_digits; last digit of a
remainder (divide by 10) to get the
% 10; /finding the last two dig
last_digit = num
(divide by 100) to get
num "e 100; I/find remainder
last two_digits =
IPrinting results
System.out.printin( OUTPUT ";
+num
System.out.printin(" The number 18
System.out.println("The last digit =+last_digit
last digit =
last two_digits);
Sy'stem.out printint The ) ; l/returning sum

return (( last_digit
+
last two_digits)
Wlend of the function sumDigits(
or function
definition
void accept) Ila n e w method

number 6753 to variable '


long N=2365; Iinitialize a long integer four digit
Wdeclaration of long integer type variables to receive sum
>long sum; actual argument N the form to
sum =
sumDigits( N; llcalling function by passing sum
and receives the return value in variable
l argument 'num'
sum ot last and last two digits
=+8um Printing results
System.out.printin( The
Wlend of the function accept
Wend of the class
is
Output: The following is a computer generated output when function accept() caie
The number is = 2365

The last digt=


The last digit = 65
The sum of last and last two digits = 70

Problem 10: n l sn

Write a program to define a method/function double average( ) with the parameters/argube


number (rn), marks in three subjects scored by the student in ml, m2 and m3 (the marks a t
fractions also). Print the details of student. Compute the average marks and return (assume
maximum marks of each subject is 100).

ctio

126 Classes and Methods (or Fune


public class Student

function definition contains formal parameters considered as npue


/the following
averagel int loat ml, float m2, loat m3)
blic float
puo
m,

tloat avg
ldeclaration of fractional variable to store the average
)/3;
Vg=(mi + mz +m3 lcalculate of average marks
tem.out.println OUTPUT "); Printing results
System.out.printinRoll number : +1

System.out.printin Marks in subject 1=


Syste t. Drintln( "Marks2 =+ in subject
Sy'stem.e
System.out.printin Marks in subject 3 = "+ m3 );
m2
return av8 e n g avarage marks, as here there in no function to call this method
return value will be displayed in the "Method Resule" window
Ifunction
so
the
average()
Jlend of the
of the c l a s s
W/end
i s called:
Output:
The rollowing 15 a computer generated output when method average()
Bue ethod all
Bue Method Ca

Method call This is the


oat averagefint rm, Toat mi, loat m2, float m3)
wndow to input
correct way to
input tloat
parameters studert11.averoge (2331 int m
values i.e.
foat m1
1his error appears 79.5fE oatmi 79.5f etc.
ue to wrong input 0.0F foat m2
ie 79.5 should be 81.5 ot m3
79.5, refer chapter
Eror pos3ible loss of predsion
required Noat
"Method
O aLues ypes) 1O0noOOUDie Result"
window
containss
This Blue: Method Result the
B l u e lerminal Window- d
ninal foat averagefnt rn, foatml, foat m2, return
puons foat m3)
value
e Roll number 2331 shudentil.average(2S1, 79.5t, 80.0f, 81.S)
print
Marks in subject 1= 79.5
reurned:
Get
This is
Btatements D.333336 oat type
Marks in s u b j e c t 2 80.0
nsidethe return
Ethod Marks in subject 3= 81.5 Cose value

Problem 111:
Wri a
program to define a
mistry, Biology and Computer Applications.
method/function void Scores( )toinput marks in English, Maths,
the marks obtained in all the subjects, total
Print
marke in each subject 1s 100).
(assume that the maximum marks
Percentage
Hint: eE a t the subject names are mentioned, so for each suoject tare a ariable of your choice.

Solution:
public class
Student into
the following function definition contains parameters to input marks in 'subjects
void Sco o a t eng, float mat, float phy, tloat che, tloat bio, float cta )

tloat Ilvariables to store the results


total =
total, per ;
ng + mat + phy + che + bio+ cta Ilcalculation of total marks
lasnesand
c ethods (or Functions) 127
lcalculation of total percentage
per ( total 100)/ 600 P r i n t i n g results
System.out println OUTPUT "; eng
English
System.out println Marks in Maths
System.out.println Marks in mat
System.out println Marks in physics
=+
phyche
in chemistry
ystem.out.println( Marks
System.out-println Marks in biology= bio
+cta
in computer applications=
ystem.out printlní Marks total );
marks=
System.out.println The total
=+ per
System.out.println( Percentage
function Scores()
Mlend of the
V/end of the class
when function Scores() is call
Out The following is a computer generated output
Teminel Vindow- d

Parameter
input 81.0
window Harks in
English
88.5
Marks in Maths 79.5
Marks in phyBics
Marks an cheamis ErY

erminal Marks in biology 4


in camputer aPPL1cationa 95.s
Marks
or output The total nat
window Percentage 86.083336

Problem 12:

input details of a product as, Product code (pc-integer, Quantity (qty)-integ


Write a program to Calcula
and Price of product (pr-in decimals, as argument of a method/function void CashMemoO.
cost and total amount to be paid (less discount). Al
the total cost of the product, 10.5% discount o n total
amount to be paid. Print all the details of th
add 14% VAT on the net amount then calculate the final
product.

Solution:
class Product Info
) I/method definition with formal argumens
public void CashMemol int pe, int qty, double pr

Ivariables to store results


double total _cost, dis, net amount, vat, paid_amount;
total cost qty
=
pr lcalculation of total cost of product
dis = (otal_cost 10.5 ) / 100.0 ; calculation of discount 10.5%
dis; lcalculation of net amount after discou
net amount= total _cost 100.0 lcalculation of VAT 14%
vat= (
net amount 14 7 be pai
paid_amount= net amount+vat ; Icalculation of final amount to
System.out.println("OUTPUT "); Printing results
System.out.printinProduct code =+pe
System.out.printlnQuantity of product qty =
);
ol
product +pr =
;
System.Out.printlnDnit price
System.out.println(Total cost + total _cost );
="+dis );
System.out.println( Discount
System.out.printin Net amount alter discount = + n e t a m o u n t ;

System.out.println("14% VAT on net amount+is _+vat ;


System.out.println("Total amount to be paid including VAT = "+ paid_amount
Wlend of the function CashMemo()
lend of the class
e t i o n

Classes and Methods (or


128
Output: The tollowing is a computer generated output when function Cashve
braces)
Blue: Method Call Deermina window d

p
vold Cash Memo(int pc, Rnt qy, doubile pr)
OUTPUT
Product code 22113

product 106
prodct L.e 22113 nt pc QuantitY of
nt q y
Onit price of product 572. 75
Total cOst 60711.5

$72.73 Discount 6374.7075


5 4 3 3 6 . 7 9 2 4 9 9 9 9 9 9 9 6

discount
arter
O Cancel ount 54336.792499999996
is=
7607.150949999999

VAT on including VAT


61943.94344999999

paid
Oa
amount
to be
Problem 13:
Write a program to create a class Larger and overload method m a x i m u m ) as TOIOWS
nl and
int maximum( int nl, int n2) return the largest integer from the arguments
) to the suitable
mathematical method.
n2, using and
return the larger character
from the arguments xl,
(ii) char maximum( char xl, char x2 ) to
x2.
relevant
Also define a main) method to invoke the above overloaded methods/functions by pasSing
and print the results.
parameters/argument
Solution:
class the the method/function overloading concept
program uses
Larger in this class
note, that there is NO data members
definition
int maximum int nl, int n2 /1st overloaded function

=(nl n2 ) ? nl: from nl, n2 using ternary operator


n2; /Einding largest
int large >
variable large
return large, /returning largest number stored in
dt
/end of 1st method maximum)
char maximum( char x1, char x2 )
/2nd overloaded function definition

char large = xl > x2? xl :/deciding largest character from xl and x2


x2;
in variable "large
return large, I/returning largest character stored
Wlend of 2nd method maximum)
function definition
public void main( / main()
1st overloaded function that passes value 15 to nl'
nt big = maximum( 15, 24) llcalling
and 24 to 'n2' and return value is received by big
char big_letter= maximum( W, E); calling Znd overloaded function that passes W to x1
Il and E to x2' and return is received in big_letter
System.out.println(The greater from 15 and 25 1s = + big ); printing results
character irom w and E 18 = + big_letter );
System.out.println( The greater
W/end of main() function

Wend of the class


is computer generated result when method main() is called:
Output: The following a

3 Blue: Teminal Window - Projectl

Opuos
25 is =
24
The greater from 15 and
The greater character irom W and E is = W

Classes and Methods (or Functions) 129


UMMARY object, and an object is an instance of a
class
A class is a blueprint (or template) for an

A class is declared with the help


of class keyword.
declarations for all its
variables and methods.
Class body contains the variables or instance variables,
known as member
The variables defined in the
class are
knoOwn
statements to pertorm
a task 18 wn as
as
containing executable set of ember
Thecompound body
methods or methods or functions.
of the as members

The member variables and members methods are


collectively known
known as a n instance variah
clasu
instance of the class is
A variable that is created separately for every
'static' is known as Statin
iable
with the help of a keyword tic or
only once for class a
The variable declared static int y;).
Class variable (for example:
constructors or compound blocks are called local
local
The variables defined inside the methods,

variables with modifiers/access specifiers


variables of class can be declared as

The data members instance private static int


with or without static keyword for example:
private or public ar protected or protected
static int y; or protected
public static int y; or public int y;
ar private int y; or
the declaration becomes default
not mentioned then
or
int y. If modifiers/access specifiers
are

friendly.
be defined with modifiers/access specifiers as, private or publie
The methods/functions of class can

without static keyword (for example: private


static void show) or private
or protected, with or show( ) or public void show) or protected static void
void show() public static void
or

void show() etc.).


show)
or protected also known as modifiers/access specifiers.
The private or public o r protected,
terms
keyword are

will be discusSsed in class X syllabus.


The details of private, public and protected
cannot be
method has completed i.e. the local variable
The local variable will be destroyed when the
m e a n s the area within the curly
braces ).
used or executed outside its scope (scope
structure that performs a specific task.
A method (or function) is a self-contained program
A method or function begins with a modifier/access specifier (optional) followed by
(compulsory) and optional
return_data_type (compulsory) than name of_method
within the brackets "().
listof parameters_with_data type
The modifier/access specifier may be public, private, protected, default or friendly if nothing the
mentioned then it is default or friendly).
String
The
return_data type may be void, short, int, long, float, double, byte, char, boolean,
or class name.
and use
other than a keyword
The
name of method may be any name
int ) or puo
list of parameters_with_data type is optional (for example: public static void display(
void display(int c) or void display() etc.).
ning
The keyword void is known as non-return data type. It means, the void does not reurn any
from a method or it returns empty set of values.
e t h o d

The first line of a method or function is known as method/function prototype or me


function declaration (for example: public static void display( int c) etc.). sue
The list of parameters or variables used with the function are also known as method/function snature
is
(for example: public void show( int y, char ch), then int y and char ch are function signa

t i o n a )

Classes and Methods (or F u n e t


also Bupportstandard method/funetion known aa main( ) method/functionraces
orad
'.
heava
Vtatie void main( String argol 1 ) followed by the statements within the eury
statie

puD new o oDerator creates anobject of the specified class and returns a reference to
(2) Instan
he
contains tWO Wpes ot methods or functions as: (1) Class Methods and
he
class
Methods, methods/functions

A l l t h e
nctions defined using the
m e t h o d s / f u n c t i o

keyword 'static are known as static


methods/function

or class

WilHOUT the static keyword are known instance methods/functtons o


methods defined as
non-static methods /functions8.
Al tethods/functions
ect
or
all the statements
method/function definition body to run/execute
process of execuing the
or executing or accessing a method/function.
invoking or
was calling or executed
througn ne

rh e instance methods (or non-static methods) are called or invoked


t(or instance) of the class tollowed by the dot operator. the cla5S name
o0ect
(or static methods) are called or invoked or executed through
The class methods
the dot operator.
followed by
calling or invoking execution, or some values may be passea topuo
At the time of method/function of the method/function. These
parameters/arguments
variables usea as parameters/arguments
to the
into two categories as:
are divided Actual parameters
(or Local or Dummy) parameters, and, (2)
(1) Formal definition are

data types declared at the


time of method/function
The list of variables along with parameters/arguments.
Formal (or Local or Dummy) or
known as calling
without data types declared
at the time of method/function
The list of values
or
variables parameters/arguments.
are knoWn a s Actual
invoking or executing within the method
formal parameters
will transfer information to
parameters
Theactual
definition. return statement causes the shifting
method or
returns the value to the calling sends the return value
The return statement the return statement
statement or
method/function calling
of control to the called or invoked.
or function is
at that place, where the method the called method back
to the
statement immediately
transfers fromcontrol
control the immediately c o m e s
out of
of return
Execution s o o n as the return
s t a t e m e n t activates,
o r as
cauling method definition body.
the method/function
different purposes,
same thing tor
verloading refers to
the use
of the the same name but with different data
various methods/functions by
logical process of defining overloading
ne is known as
method/function

o n d arguments

131
Claaaes and Methods (or Functions)

You might also like