[Go to site: main page, start]

0% found this document useful (0 votes)
12 views19 pages

Java Programs for Basic Calculations and Logic

The document outlines a series of Java programming exercises, including creating a simple calculator, using ternary operators, converting decimal numbers, simulating a login system, and generating Fibonacci numbers. Each exercise includes explanations of user input, processing logic, error handling, and output display. The document provides code snippets for each task along with explanations of their functionality.

Uploaded by

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

Java Programs for Basic Calculations and Logic

The document outlines a series of Java programming exercises, including creating a simple calculator, using ternary operators, converting decimal numbers, simulating a login system, and generating Fibonacci numbers. Each exercise includes explanations of user input, processing logic, error handling, and output display. The document provides code snippets for each task along with explanations of their functionality.

Uploaded by

pratyush.pgat2nd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lab module 1

Name: SIDDHARTHA
Registration NO. : 23BCE11143
Roll no. : 94

Question-1:Write a Java program to simulate a simple


calculator that performs arithmetic operations (+, -, *, /, %)
based on user input.

Explanation:

Taking User Input:


 The program first asks the user to enter two numbers.
 It then prompts the user to input an arithmetic operator (+, -, *, /, %).

 Processing the Arithmetic Operation:

 A switch statement is used to determine the operation based on the user’s


input.
 Each case performs one of the following operations:
 + → Addition
 - → Subtraction
 * → Multiplication
 / → Division (only if the divisor is not zero)
 % → Modulo (only if the divisor is not zero)

 Handling Errors:

 If the user attempts to divide or find the remainder with zero, the program
displays an error message and stops execution.
 If the user enters an invalid operator, the program notifies the user and exit.
 Displaying the Result:

 If no errors occur, the calculated result is displayed.


Code

Question-2 Write a Java program to demonstrate the use of


ternary operators to simplify if-else statements.
Explanation:

User Input:
 The program asks the user to enter a number.
Even or Odd Check:
 The ternary operator (num % 2 == 0) ? "Even" : "Odd"
determines whether the number is even or odd.
Positive, Negative, or Zero Check:
 The ternary operator (num > 0) ? "Positive" : (num <
0) ? "Negative" : "Zero" is used to classify the number.
Output Display:
 The results are printed.

Code:
Q.3 Write a Java program to convert a decimal number
to binary, octal, and hexadecimal using bitwise
operators.

Explanation:

Binary Conversion:
 Use bitwise AND (& 1) to extract the last bit.
 Use right shift (>> 1) to move to the next bit.

 Octal Conversion:

 Extract three bits at a time (& 7 which is 111 in binary).


 Use right shift (>> 3) to process the next set of bits.

 Hexadecimal Conversion:

 Extract four bits at a time (& 15 which is 1111 in binary).


 Use right shift (>> 4) to process the next set

CODE:
Q.4 Write a Java program to simulate a simple login
system that checks for valid username and password
using if-else statements.
Explanation:

Predefined Credentials:
 The program stores a valid username ("admin") and password ("password123").

User Input:
 The program prompts the user to enter a username and password.
Credential Validation:
 It checks if the entered username and password match the stored credentials.
 If they match, it prints "Login successful!".
 Otherwise, it prints "Invalid username or password"

CODE
Q.5 Write a Java program to simulate a simple menu-
driven system that uses switch statements to
perform different actions based on user input.

Explanation:
Menu Display:
 The program shows a menu with options for addition, subtraction,
multiplication, division, and exit.
 User Input Handling:
 The user selects an option from the menu.
 If they choose 5, the program exits.
 Performing Operations:
 The program asks for two numbers.
 Based on the user’s choice, it performs the corresponding arithmetic
operation.
 If division is chosen, it checks for division by zero.
 Looping Until Exit:
 The program runs inside a while loop until the user selects the exit
option.

CODE:
OUTPUT:
Q.6 Write a Java program to print the first 10
Fibonacci numbers using a for loop.
Explanation:
Initialize First Two Numbers:
 The first two numbers in the Fibonacci sequence are 0 and 1.

 Loop to Generate Fibonacci Sequence:

 A for loop runs 10 times to generate and print the sequence.


 Each number is calculated as the sum of the previous two (next =
first + second).
 The values of first and second are updated in each iteration.
CODE:

OUTPUT:

Q.7 Write a Java program to simulate a simple game


of chance that uses a for-each loop to generate
random numbers.
Explanation:
Generating Random Numbers:
 The program initializes an integer array of size 5.
 A for loop fills the array with random numbers between 1 and 100.

 Displaying the Numbers Using a For-Each Loop:

 A for-each loop (for (int num : randomNumbers)) iterates through


the array.
 It prints each random number.
CODE:

OUTPUT:
Q.8 Write a Java program to print the first 100 prime
numbers using a while loop.

Explanation:
Initialize Counters:
 count keeps track of how many prime numbers have been printed.
 num starts from 2 (the first prime number).

While Loop Execution:


 The loop continues until count reaches 100.
 It checks if the number is prime using the isPrime() method.
 If prime, it prints the number and increments count.

Prime Checking Method:


 If a number is less than 2, it is not prime.
 It checks divisibility from 2 to √n. If divisible, it's not prime.

CODE:

OUTPUT:
Q.9 Write a Java program to find the sum of all
numbers from 1 to 10 that are not divisible by 2
using a break statement to exit a loop.

Explanation:
Initialize sum to 0
 This variable stores the total sum.
 For Loop Iteration (1 to 10):

 If a number is even (i % 2 == 0), it is skipped using continue.


 If a number is odd, it is added to sum.

 Output the Result:

 The program prints the sum of all odd numbers from 1 to 10

CODE:
OUTPUT:
Q.10 Write a Java program to simulate a simple
calculator that uses a continue statement to skip an
iteration of a loop when an invalid input is entered.

Explanation:
Looping for Continuous Calculation:
 The program runs inside a while (true) loop, allowing multiple calculations.
 It asks for two numbers and an operator.
 Handling Invalid Inputs with continue:

 If the user enters a non-numeric value, it prints an error message, skips the iteration,
and asks for input again.
 If division by zero is attempted, the program displays an error and skips that
calculation.
 Performing Arithmetic Operations:

 It supports addition, subtraction, multiplication, and division using a switch


statement.
 Asking for Continuation:

 The user can choose to continue or exit the calculator.

CODE:
CODE:

Common questions

Powered by AI

The Java program uses a switch statement within a menu-driven system to perform arithmetic operations as selected by the user. Options include addition, subtraction, multiplication, and division. It runs inside a while loop, allowing continuous execution until the user selects the exit option. This structure ensures that the program remains interactive, repeatedly asking the user for inputs and performing calculations until explicitly told to exit .

The Java program ensures continued operation in a calculator with invalid inputs by running within a while (true) loop. It employs the continue statement to skip iterations when non-numeric inputs are detected or when the division by zero is attempted, displaying errors without crashing. This prevents system interruptions and maintains stability by prompting for new input despite errors .

The ternary operator simplifies if-else statements by providing a concise syntax for conditional expressions. To check a number's parity, the expression (num % 2 == 0) ? "Even" : "Odd" evaluates to "Even" if the number is divisible by 2, and "Odd" otherwise. Similarly, the expression (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero" categorizes the number as positive, negative, or zero in one line .

The Java program simulates a calculator by prompting the user to input two numbers and an arithmetic operation (+, -, *, /, %). It uses a switch statement to determine and perform the selected operation. If the user attempts division or modulo by zero, the program displays an error message and halts execution. If an invalid operator is entered, it notifies the user and exits the program. This approach ensures that only valid operations are attempted .

The Java program converts a decimal number to binary, octal, and hexadecimal using bitwise operations. For binary conversion, it extracts individual bits using the AND operator (& 1) and shifts bits using right shift (>> 1). Octal conversion uses (& 7) to extract groups of three bits, and the right shift (>> 3). Hexadecimal conversion employs (& 15) to capture four-bit groups, shifting right (>> 4) accordingly .

The Java program generates the first 10 Fibonacci numbers using a for loop. It initializes the first two numbers of the sequence as 0 and 1. In each iteration of the loop, the next number in the sequence is calculated as the sum of the previous two numbers (next = first + second). After each calculation, the program updates the values of the first and second variables to move forward in the sequence .

The Java program simulates a game of chance by filling an integer array with random numbers within the range of 1 to 100 using a for loop. A for-each loop then iterates over the array to print each generated random number, letting users view the output of their "chance" in this simple simulation .

The program calculates the sum of odd numbers from 1 to 10 using a for loop. It initializes a sum variable to 0 and iterates through the range. If a number is even, the loop skips it using the continue statement. Only odd numbers are added to the sum. The break statement is not explicitly used in this process; rather, the continue statement ensures that even numbers do not affect the sum .

The program prints the first 100 prime numbers using a while loop controlled by a count variable that tracks the number of primes printed. Starting with num initialized to 2, a nested method isPrime() checks each number's primality by confirming non-divisibility from 2 to √n. If a number is prime, it's printed, and the count is incremented. The loop continues until 100 primes are output .

The Java program defines a simple login system by storing known sets of credentials: a username "admin" and a password "password123". When the user inputs their details, the program checks them against the stored credentials using if-else statements. A match results in "Login successful!" being displayed, while mismatches result in "Invalid username or password". This simple verification is achieved through conditional checks .

You might also like