Вы находитесь на странице: 1из 22

Flow of Control

Sequence construct means the statements are being executed sequentially.


Selection construct means the execution of statements depend on a condition.
Examples include if statement, if-else statements, if-else-if statements,
conditional operators, switch statements.
Iteration construct means repetition of statements as long as the specified
condition holds true.
Comparing if statement and conditional operator:
1. The conditional operator offers more compact code.
2. The if statement is more flexible.
3. The conditional operator becomes more complex when used in nested form.
The switch statement is a multiple-branch selection statement.
The break keyword is used to exit from switch. The default keyword is used to
provide statements to be executed when none of the cases match.
If the break statement is missing in each case, then the flow will continue
executing the statements in the following cases as well. This is called fall
through.
Comparing switch and if-else:
1. The switch statement can only test for equality, whereas the if statement can
use other relational operators as well.
2. The switch statement doesn’t support ranges, whereas the if-else statement
supports range of values.
3. The switch case only supports values of integer type, but if-else statement
supports values of other data types as well.
4. The switch case label value must be a constant.
5. The switch statement is more efficient in situations that involve testing a value
against a set of constants.
6. No two switch case labels can be identical.
Different parts of a loop include initialization expression, test expression, update
expression, and body of the loop.

The for loop is the easiest among other loops. All its parts are gathered in one
place. It is an entry-controlled loop.
An infinite loop is a loop that never terminates. It can be created in for loop by
omitting the test expression. For other loops, the test expression should always
evaluate to true.
An empty loop is one that does not contain any loop body.
The while loop is another entry-controlled loop. In this loop, the loop control
variable is initialized before the loop begins, and the variable is updated inside
the loop body.
The do-while loop is an exit-controlled loop. it evaluates the test expression at
the bottom of the loop, after executing the loop body.
A nested loop is one in which a loop may contain another loop within its body.
The break keyword is used to exit from loops, by skipping the rest of the
statements in the loop body.
The continue keyword skips the rest of the statements in the loop body and
starts the next iteration of the loop.
Labels can be used with break and continue in cases where nested loops are
present, and we want to specify which loop to target with break/continue.

Java Fundamentals
Character set is a set of valid characters that a language can recognize. Java uses
the Unicode character set.
Unicode is a 16-bit character code set that has characters representing almost all
characters in almost all human alphabets.
Token is the smallest individual unit in a program. Keywords, identifiers, literals,
punctuators and operators are various types of tokens.
Keywords are the words that convey a special meaning to the language
compiler.
Identifiers are used as the general terminology for the names given to different
parts of the program.
Rules for naming identifiers:
a) It can include alphabets, digits, underscore and dollar sign.
b) It must not be a keyword.
c) It must not begin with a digit.
d) It can be of any length.
e) It is case-sensitive.
Literals are constants, which are data values that are fixed.
Java supports three types of integer literals: decimal, octal and hexadecimal.
Octal literals are preceded with 0. Hexadecimal literals are preceded with 0x or
0X.
Real literals in exponent for has two parts: a mantissa and an exponent. The
mantissa can be an integer or real literal. The exponent must be an integer.
Boolean literal can be either true or false.
Character literal is a single character, enclosed in single quotes. Escape
sequence is a non-graphic character that cannot be typed directly from
keyboard. An escape sequence is always preceded by a backslash.
String literal is a sequence of zero or more characters, enclosed in double
quotes.
Data types are means to identify the type of data and its associated operations.
There are two types of data types in Java:
a) Primitive data type
b) Reference data type
Primitive data types are basic data types. Java provides eight primitive data
types:
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)
float (4 bytes)
double (8 bytes)
char (2 bytes)
boolean (1 byte)
float data type has a precision of up to 6 digits, whereas double has a precision
of up to 15 digits.
Reference data types are constructed from primitive data types. They mainly
store memory addresses. Examples include classes, arrays, interfaces.
Variable is a named memory location which holds a data value of a particular
data type.
A class variable of boolean type has the default value true. A char variable will
have a default value ‘\u0000’. All reference types are initialized with null. Other
numeric variables are initialized with 0.
The keyword final makes a variable constant.
Operators represent the operations being carried out in an expression.
Arithmetic operators allows us to perform arithmetic operations. +, -, *, / and %
are arithmetic operators.
Unary operators are operators that act on one operand. Binary operators are
operators that act on two operands.
The + operator with strings is used for concatenating strings.
The increment operator (++) adds 1 to the operand, whereas the decrement
operator (–) subtracts 1 from the operand. Both of them have two variations:
prefix (change then use) and postfix (use then change).
Relational operators determine the relation between different operands. <, <=,
>, >=, == and != are relational operators.
Logical operators are also known as conditional operators. They allow us to
construct complex decision making expressions. &&, || and ! are logical
operators.
Conditional operator (?:) is also known as ternary operator because it requires
three operands. It is a shorthand alternative for if-else statement.
The [] operator is used to declare arrays. The . (dot) operator allows us to access
members of an object or a class. The () operator is used in methods.
The (type) operator is used in type-casting. The new operator is used to create a
new object for a class, or a new array.
Operator precedence determines the order in which expressions are
evaluated. Associativity rules determine grouping of operands and operators in
an expression with more than one operator of the same precedence.
An expression in Java is any valid combination of operators, constants and
variables.
Arithmetic expressions can be either pure or mixed. In pure expressions, all the
operands are of same type. In mixed expressions, the operands are of different
data types.
Math class is in java.lang package that provides us with several mathematical
functions. Following are some of the commonly used mathematical functions:
a) sin(x) returns the sine of the angle x in radians.
b) cos(x) returns the cosine of the angle x in radians.
c) tan(x) returns the tangent of the angle x in radians.
d) asin(y) returns the angle whose sine is y.
e) acos(y) returns the angle whose cosine is y.
f) atan(y) returns the angle whose tangent is y.
g) atan2(x, y) returns the angle whose tangent is x / y.
h) pow(x, y) returns x raised to y.
i) exp(x) returns e raised to x.
j) log(x) returns the natural logarithm of x.
k) sqrt(x) returns the square root of x.
l) ceil(x) returns the smallest whole number greater than or equal to x.
m) floor(x) returns the largest whole number less than or equal to x.
n) rint(x) returns the rounded value of x.
o) abs(x) returns the absolute value of x.
p) max(a, b) returns the greater value among a and b.
q) min(a, b) returns the smaller value among a and b.
Type casting is the process of converting one predefined type into
another. Implicit type conversion is performed by the compiler without
programmer’s intervention. Explicit type conversion is user-defined that forces
an expression to be of specific type. The implicit type conversion in which data
types are promoted is known as coercion. You cannot typecast boolean type to
another primitive type and vice-versa.
A statement forms a complete unit of execution. They always terminate with a
semicolon. Assignment expressions, using ++ or –, method calls, object creation
expressions are various kinds of statements.
Without classes, there can be no objects, and without objects, no computation
can take place. Thus, class forms the basis of all computation.
A class is declared using the keyword class. Java file can only have one public
class. A class variable/static variable is one which is shared by all objects of that
class type. Instance variable is one that is created for every object of the class.

Multiple Choice Questions


1. When the statements are repeated sequentially for a number of times in a
program, the construct is known as:
(a) iteration
(b) sequence
(c) selection
(d) none
2. Which of the following statement is an exit-controlled loop?
(a) for
(b) while
(c) do-while
(d) if-else
3. Which of the following loop does not execute even once if the condition is
false in the beginning?
(a) do-while
(b) while
(c) for
(d) nested loop
4. To execute a loop 10 times, which of the following statement satisfies?
(a) for(i = 6;i <= 26; i = i + 2)
(b) for(i = 3; i <= 30; i = i + 3)
(c) for(i = 0; i < 10; i = i++)
(d) all of the above
5. Which of the following statement uses multiple branches?
(a) loop
(b) continue
(c) switch
(d) break
6. Which of the following loop checks the condition first and then execution
begins?
(a) do-while
(b) do
(c) while loop
(d) for
7. To find the sum of whole numbers up to 10, a loop runs:
(a) once
(b) ten times
(c) eleven times
(d) any number of times
8. How many times the loop: for(i = 1;; i++) will execute, if there is no
statement to terminate the loop?
(a) 1
(b) 0
(c) infinite
(d) none
9. Which of the following statements uses a case called default?
(a) do-while
(b) while
(c) switch
(d) all of the above
10. A loop statement is given as:
for(i = 10; i < 10; i++){
statement
}
For how many times will the given loop statement be executed?
(a) never
(b) 1 time
(c) 10 times
(d) infinite

Answer the following questions:


1. What do you understand by iterative process? How can it be resolved
by using loop?
It is a construct in which a statement or a set of statements are repeatedly
executed till the condition is satisfied.
It can be resolved by using loops because it allows us to easily specify what
task needs to be executed and for how many times.
2. Explain for loop with an example.
The for loop is an entry-controlled loop which is suitable when the number
of iterations is fixed.
Example:
for(i = 1; i <= 10; i++){
System.out.println(“Google Pay”);
System.out.println(“Money made simple, by Google”);
}
3. Name the different types of loop statements.
Different types of loop statements are:
a) for loop
b) while loop
c) do-while loop
4. What are the parameters needed to create a for loop?
Following are the parameters needed to create a for loop:
a) Initial value for the counter variable.
b) Test condition to terminate the loop at a certain point.
c) Update expression to modify the counter variable after each iteration.
d) Loop body to be executed in each iteration.
5. Define the following with their constructs:
(a) Entry-controlled loop: Condition is checked before executing the loop
body. Constructs: for loop and while loop.
(b) Exit-controlled loop: Condition is checked after executing the loop
body. Construct: do-while loop.
6. Write down the general format of:
(a) for loop
for(initial value; test condition; update){
task
}
(b) do-while loop
do{
task
}while(test condition);
(c) while loop
while(test condition){
task
}
7. What is the purpose of using:
(a) break statement: It is used for forceful termination of a loop block.
(b) continue statement: It is used to skip the current iteration of the loop,
and move to the next iteration.
8. What do you understand by inter-conversion of loops?
Inter-conversion of loops is about converting one form of repetitive
structure to another form to model our program logic as per our
convenience.
9. What are the different ways to inter-convert the loops? Name them.
Following are the different ways to inter-conversion of loops:
a) for loop to while loop
b) for loop to do-while loop
c) do-while loop to while loop
d) do-while loop to for loop
e) while loop to do-while loop
f) while loop to for loop
10. Define the following:
(a) Finite loop: Loop in which the statements run for a fixed number of
times.
(b) Delay loop: Loop that is used to create a delay in the execution by
creating a null loop.
(c) Infinite loop: Loop in which a looping structure will never come to an
end, created by omitting one or more parameters.
(d) Null loop: Loop which doesn’t include any statement to be repeated.
11. Distinguish between:
(a) for and while loop
The for loop is a suitable choice when the number of iterations is fixed,
whereas the while loop is a suitable choice when the number of iterations
is not fixed.
(b) while and do-while loop
The while loop is entry-controlled, whereas the do-while loop is exit-
controlled.
12. State one difference and one similarity between while and do-while
loop.
Similarity: Both while and do-while loops are used when the number of
iterations is not fixed.
Dissimilarity: The while loop is entry-controlled, but the do-while loop is
exit-controlled.
13. State one similarity and one difference between while and for loop.
Similarity: Both while and for loops are entry-controlled loops.
Dissimilarity: The for loop is a suitable choice when the number of
iterations is fixed. The while loop is a suitable choice when the number of
iterations is not fixed.
14. Give two differences between step loop and continuous loop.
Step loop is a system of creating a loop where the control variable is
updated by a given value after each iteration. The loop starts with an initial
value, repeats execution of the statements by updating the value with the
given step.
Continuous loop is a type of looping structure in which the control
variable is updated only by 1 after each iteration. The loop is terminated as
soon as the control variable exceeds the last limit.

Java Programs:
Question 1: Write the programs in Java to display the first ten terms of the
following series:
a) 1, 4, 9, 16, …
b) 1, 2, 4, 7, 11, …
c) 3, 6, 9, 12, …
d) 4, 8, 16, 32, …
e) 1.5, 3.0, 4.5, 6.0, …
f) 0, 7, 26, …
g) 1, 9, 25, 49, …
h) 4, 16, 36, 64, …
i) 0, 3, 8, 15, …
j) 24, 99, 224, 399, …
k) 2, 5, 10, 17, …
class Series1{
public static void main(String args[]){
for(int i = 1; i <= 10; i++)
System.out.print(i * i + "\t");
System.out.println();
}
}
class Series2{
public static void main(String args[]){
int value = 1;
for(int i = 1; i <= 10; i++){
System.out.print(value + "\t");
value += i;
}
System.out.println();
}
}
class Series3{
public static void main(String args[]){
for(int i = 1; i <= 10; i++)
System.out.print((i * 3) + "\t");
System.out.println();
}
}
class Series4{
public static void main(String args[]){
int value = 4;
for(int i = 1; i <= 10; i++){
System.out.print(value + "\t");
value *= 2;
}
System.out.println();
}
}
class Series5{
public static void main(String args[]){
double value = 1.5;
for(int i = 1; i <= 10; i++){
System.out.print(value + "\t");
value += 1.5;
}
System.out.println();
}
}
class Series6{
public static void main(String args[]){
for(int i = 1; i <= 10; i++){
int term = (int)(Math.pow(i, 3) - 1);
System.out.print(term + "\t");
}
System.out.println();
}
}
class Series7{
public static void main(String args[]){
int value = 1;
for(int i = 1; i <= 10; i++){
int term = value * value;
System.out.print(term + "\t");
value += 2;
}
System.out.println();
}
}
class Series8{
public static void main(String args[]){
int value = 2;
for(int i = 1; i <= 10; i++){
int term = value * value;
System.out.print(term + "\t");
value += 2;
}
System.out.println();
}
}
class Series9{
public static void main(String args[]){
for(int i = 1; i <= 10; i++){
int term = i * i - 1;
System.out.print(term + "\t");
}
System.out.println();
}
}
class Series10{
public static void main(String args[]){
int value = 5;
for(int i = 1; i <= 10; i++){
int term = value * value - 1;
System.out.print(term + "\t");
value += 5;
}
System.out.println();
}
}
class Series11{
public static void main(String args[]){
int value = 2;
int add = 3;
for(int i = 1; i <= 10; i++){
System.out.print(value + "\t");
value += add;
add += 2;
}
System.out.println();
}
}
Question 2: Write a program to input any 50 numbers (including positive and
negative) and perform the following tasks:
a) Count the positive numbers.
b) Count the negative numbers.
c) Sum of positive numbers.
d) Sum of negative numbers.
import java.io.*;
class Counting{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int cp = 0;
int cn = 0;
int sp = 0;
int sn = 0;
System.out.print("Enter 50 numbers: ");
for(int i = 1; i <= 50; i++){
int n = Integer.parseInt(br.readLine());
if(n >= 0){
cp++;
sp += n;
}
else{
cn++;
sn += n;
}
}
System.out.println("Number of positive numbers: " + cp);
System.out.println("Sum of positive numbers: " + sp);
System.out.println("Number of negative numbers: " + cn);
System.out.println("Sum of negative numbers: " + sn);
}
}
Question 3: Write a program to calculate the sum of all odd numbers and even
numbers between a range of numbers from m to n (both inclusive) where m < n.
Input m and n.
import java.io.*;
class Sum{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int odd = 0;
int even = 0;
System.out.print("M = ");
int m = Integer.parseInt(br.readLine());
System.out.print("N = ");
int n = Integer.parseInt(br.readLine());
if(m < n){
for(int i = m; i <= n; i++){
if(i % 2 == 0)
even += i;
else
odd += i;
}
System.out.println("Sum of positive numbers: " + even);
System.out.println("Sum of negative numbers: " + odd);
}
else
System.out.println("Invalid range!");
}
}
Question 4: Write a program to enter any 50 numbers and check whether they
are divisible by 5 or not. If divisible, then perform the following tasks:
a) Display all the numbers ending with the digit 5.
b) Count those numbers ending with 0.
import java.io.*;
class Five{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int zero = 0;
for(int i = 1; i <= 50; i++){
System.out.print("Number = ");
int n = Integer.parseInt(br.readLine());
if(n % 5 == 0){
if(n % 10 == 5)
System.out.println(n + " ends with 5.");
else
zero++;
}
}
System.out.println("Number of values ending with zero: " + zero);
}
}
Question 5: Write a program to display all the numbers between m and n input
from the keyboard where m < n, m > 0 and n > 0. Check and print the numbers
that are perfect square. Example: 25, 36, 49 are perfect square numbers.
import java.io.*;
class PerfectSquares{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int zero = 0;
System.out.print("M = ");
int m = Integer.parseInt(br.readLine());
System.out.print("N = ");
int n = Integer.parseInt(br.readLine());
if(m < n && m > 0 && n > 0){
for(int i = m; i <= n; i++){
System.out.println("Number = " + i);
double s = Math.sqrt(i);
if(s == (int)s)
System.out.println(i + " is a perfect square.");
}
}
else
System.out.println("Invalid range!");
}
}
Question 6: Write a program to display all the buzz numbers between p and q
where p < q. A buzz number is the number which either ends with 7 or is divisible
by 7.
import java.io.*;
class Buzz{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("p = ");
int p = Integer.parseInt(br.readLine());
System.out.print("q = ");
int q = Integer.parseInt(br.readLine());
if(p < q){
for(int i = p; i <= q; i++){
if(i % 10 == 7 || i % 7 == 0)
System.out.print(i + "\t");
}
System.out.println();
}
else
System.out.println("Invalid range!");
}
}
Question 7: Write a program to input marks in English, Math and Science of 40
students who have passed ICSE Examination 2019. Now perform the following
tasks:
a) Number of students who have secured 95% or more in all the subjects.
b) Number of students who have secured 90% or more in English, Math and
Science.
import java.io.*;
class Student{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int math = 0;
int science = 0;
int english = 0;
int all = 0;
for(int i = 1; i <= 40; i++){
System.out.print("Math: ");
int m = Integer.parseInt(br.readLine());
System.out.print("Science: ");
int s = Integer.parseInt(br.readLine());
System.out.print("English: ");
int e = Integer.parseInt(br.readLine());
if(m >= 95 && s >= 95 && e >= 95)
all++;
if(m >= 90)
math++;
if(s >= 90)
science++;
if(e >= 90)
english++;
}
System.out.println("95% or above in all subjects: " + all);
System.out.println("90% or above in Math: " + math);
System.out.println("90% or above in Science: " + science);
System.out.println("90% or above in English: " + english);
}
}
Question 8: Write a program in Java to find the sum of the given series:
a) 1 + 4 + 9 + … + 400
class Sum1{
public static void main(String args[]){
int s = 0;
for(int i = 1; i <= 20; i++)
s += i * i;
System.out.println("Series sum: " + s);
}
}
b) 1 + 1/2 + 1/3 + … + 1/20
class Sum2{
public static void main(String args[]){
double s = 0.0;
for(int i = 1; i <= 20; i++)
s += 1.0 / i;
System.out.println("Series sum: " + s);
}
}
c) 1 + 1/3 + 1/5 + … + 1/19
class Sum3{
public static void main(String args[]){
double s = 0.0;
for(int i = 1; i <= 19; i += 2)
s += 1.0 / i;
System.out.println("Series sum: " + s);
}
}
d) 1/2 + 2/3 + 3/4 + … + 19/20
class Sum4{
public static void main(String args[]){
double s = 0.0;
for(double i = 1.0; i <= 19.0; i++)
s += i / (i + 1);
System.out.println("Series sum: " + s);
}
}
e) 2 – 4 + 6 – 8 + … – 20
class Sum5{
public static void main(String args[]){
int s = 0;
int sign = 1;
for(int i = 2; i <= 20; i += 2){
s += i * sign;
sign *= -1;
}
System.out.println("Series sum: " + s);
}
}
f) (1 * 2) + (2 * 3) + … + (19 * 20)
class Sum6{
public static void main(String args[]){
int s = 0;
for(int i = 1; i <= 19; i++)
s += i * (i + 1);
System.out.println("Series sum: " + s);
}
}
Question 9: Write a program to input a number and count the number of digits.
The program further checks whether the number contains odd number of digits
or even number of digits.
import java.io.*;
class Digits{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int count = 0;
System.out.print("Enter the number: ");
int num = Integer.parseInt(br.readLine());
if(num == 0)
count = 1;
for(int i = num; i > 0; i /= 10)
count++;
if(count % 2 == 0)
System.out.println("It has even number of digits.");
else
System.out.println("It has odd number of digits.");
}
}
Question 10: Write a program to input a number and display the new number
after reversing the digits of the original number. The program also displays the
absolute difference between the original number and the reversed number.
import java.io.*;
class Reverse{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int rev = 0;
System.out.print("Enter the number: ");
int num = Integer.parseInt(br.readLine());
for(int i = num; i > 0; i /= 10)
rev = rev * 10 + i % 10;
System.out.println("Reverse = " + rev);
int diff = Math.abs(num - rev);
System.out.println("Absolute difference = " + diff);
}
}
Question 11: The Greatest Common Divisor (GCD) of two integers is calculated
by the continued division method. Divide the larger number by the smaller, the
remainder then divides the previous divisor. The process repeats unless the
remainder reaches to zero. The last divisor results in GCD.
import java.io.*;
class GCD{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int rev = 0;
System.out.print("Enter first number: ");
int a = Integer.parseInt(br.readLine());
System.out.print("Enter second number: ");
int b = Integer.parseInt(br.readLine());
int rem = a % b;
while(rem != 0){
a = b;
b = rem;
rem = a % b;
}
System.out.println("GCD = " + b);
}
}
Question 12: Write a program in Java to find the sum of the given series:
a) s = a2 + a2/2 + a2/3 + … + a2/10
import java.io.*;
class Series{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
double sum = 0.0;
System.out.print("a = ");
int a = Integer.parseInt(br.readLine());
for(double i = 1.0; i <= 10.0; i++)
sum += a * a / i;
System.out.println("Sum = " + sum);
}
}
Question 13: In order to reach the top of a pole, a monkey in his first attempt
reaches to a height of 5 feet and in the subsequent jumps, he slips down by 2%
of the height attained in the previous jump. The process repeats and finally, the
monkey reaches the top of the pole. Write a program to input height of the pole.
Calculate and display the number of attempts the monkey makes to reach the
top of the pole.
import java.io.*;
class Monkey{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int attempts = 1;
double a = 5.0;
System.out.print("Height of the pole = ");
double height = Double.parseDouble(br.readLine());
while(a < height){
a += 5.0;
a -= 2.0 / 100 * a;
attempts++;
}
System.out.println("Number of attempts: " + attempts);
}
}
Question 14: Write a program to input principal, rate and time. Calculate and
display the amount which is compounded annually for each year by using the
formula:
SI = PRT / 100 and P = P + SI
import java.io.*;
class Interest{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Principal: ");
double p = Double.parseDouble(br.readLine());
System.out.print("Rate: ");
double r = Double.parseDouble(br.readLine());
System.out.print("Time: ");
int t = Integer.parseInt(br.readLine());
double si = 0.0;
double amt = 0.0;
for(int i = 1; i <= t; i++){
si = p * t * r / 100;
amt = p + si;
p = amt;
}
System.out.println("Amount = " + amt);
}
}
Question 15: Write a menu-driven program to input two positive numbers m and
n where m > n and perform the following tasks:
a) Find the sum of two numbers without using ‘+’ operator.
b) Find the product of two numbers without using ‘*’ operator.
c) Find the quotient and remainder of two numbers without using ‘/’ and ‘%’
operator.
import java.io.*;
class Menu{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("1. Sum");
System.out.println("2. Product");
System.out.println("3. Quotient and Remainder");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(br.readLine());
switch(choice){
case 1:
System.out.print("M = ");
int m = Integer.parseInt(br.readLine());
System.out.print("N = ");
int n = Integer.parseInt(br.readLine());
if(m > n){
int sum = (m * m - n * n) / (m - n);
System.out.println("Sum = " + sum);
}
else
System.out.println("Invalid range!");
break;
case 2:
int prod = 0;
System.out.print("M = ");
m = Integer.parseInt(br.readLine());
System.out.print("N = ");
n = Integer.parseInt(br.readLine());
if(m > n){
for(int i = 1; i <= n; i++)
prod += m;
System.out.println("Product = " + prod);
}
else
System.out.println("Invalid range!");
break;
case 3:
int quo = 0;
int rem = 0;
System.out.print("M = ");
m = Integer.parseInt(br.readLine());
System.out.print("N = ");
n = Integer.parseInt(br.readLine());
if(m > n){
while(m > n){
m -= n;
quo++;
}
rem = m;
System.out.println("Quotient = " + quo);
System.out.println("Remainder = " + rem);
}
else
System.out.println("Invalid range!");
break;
default:
System.out.println("Invalid choice!");
}
}
}
Question 16: Write a menu-driven class to accept a number from the user and
check whether it is a palindrome or a perfect number.
a) A number is palindrome which when read in reverse order is same as in the
right order.
b) A number is perfect if it is equal to the sum of its factors other than the
number itself.
import java.io.*;
class Menu2{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("1. Palindrome");
System.out.println("2. Perfect");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(br.readLine());
switch(choice){
case 1:
System.out.print("Enter the number: ");
int num = Integer.parseInt(br.readLine());
int rev = 0;
for(int i = num; i != 0; i /= 10)
rev = rev * 10 + i % 10;
if(num == rev)
System.out.println(num + " is palindrome.");
else
System.out.println(num + " is not palindrome.");
break;
case 2:
int sum = 0;
System.out.print("Enter the number: ");
num = Integer.parseInt(br.readLine());
for(int i = 1; i < num; i++){
if(num % i == 0)
sum += i;
}
if(num == sum)
System.out.println(num + " is a perfect number.");
else
System.out.println(num + " is not a perfect number.");
break;
default:
System.out.println("Invalid choice!");
}
}
}

Вам также может понравиться