You are on page 1of 10

Lab 2 Manual- OOP in Java

Targeted Group: IT 3rd Year [2015]

1. Write a Java Program to Make a Simple Calculator Using switch...case


The user should feed the data from the keyboard
This program should support addition, subtraction, multiplication, division and Modulus
(+, -, *, / and %) operators and for any other operator it prints error message on screen
saying "Invalid Operator". It uses switch case statement to select an arithmetic operation
based on the 'operator' variable (You can use your own variable).

Solution

1|Page
2|Page
You can implement this program in the following way also

3|Page
2. Write a Java Program to Find Sum of Numbers from 1 to 10 using:

a. Java for Loop


b. Java while Loop
c. Java do—while loop

Solution

a. Using Java for Loop

b. Using While Loop

While loop arises into play where beforehand there is no conclusive evidence that how
many times a loop is to be executed. This is the primary reason as there is no strict tight

4|Page
bound over how many numbers the sum is to be evaluated. Situations in which the output
can be displayed using test condition abiding hardcoded outputs by simply running the
programs, while the loop is taken for consideration.

Syntax:
while (test_expression)
{
// statements
update_expression;
}

5|Page
c. Using do while Loop

3. Display Numbers from 1 to 5 using While Loop

6|Page
4. Write a java Program that will print the following Patterns

a. b. c. d. e.

Java pattern program enhances the coding skill, logic, and looping concepts. It is mostly asked
in Java interview to check the logic and thinking of the programmer. We can print a Java pattern
program in different designs. To learn the pattern program, we must have a deep knowledge of
the Java loop, such as for loop do-while loop. In this section, we will learn how to print a pattern
in Java.

7|Page
Each pattern program has two or more than two loops. The number of the loop depends on the
complexity of pattern or logic. The first for loop works for the row and the second loop works for
the column. In the pattern programs, Java for loop is widely used.

Let we write the problem on 4a option

In the above pattern, the row is denoted by i and the column is denoted by j. We see that the first-
row prints only a star. The second-row prints two stars, and so on. The colored blocks print
the spaces.

Let's create the logic for the pattern, give above. In the following code snippet, we are starting row
and column value from 0. We can also start it from 1, it's your choice.

In the above code snippet, the first for loop is for row and the second for loop for columns.

8|Page
Let's see the execution of the code step by step, for n=4 (the number of rows we want to print).

9|Page
Do Others by Yourself!!!

10 | P a g e

You might also like