0% found this document useful (0 votes)
9 views5 pages

Java Programs for Basic Calculations

Java

Uploaded by

Jeromy R
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)
9 views5 pages

Java Programs for Basic Calculations

Java

Uploaded by

Jeromy R
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

Program - Simple Calculator using switch case

Source code:
import [Link];
public class CalculatorUsingSwitch {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter value of 1st number ::");
int a = [Link]();
[Link]("Enter value of 2nd number ::");
int b = [Link]();
[Link]("Select operation");
[Link]("Addition-a: Subtraction-s: Multiplication-m: Division-d: ");
char ch = [Link]().charAt(0);
switch(ch) {
case 'a' :
[Link]("Sum of the given two numbers: "+(a+b));
break;
case 's' :
[Link]("Difference between the two numbers: "+(a-b));
break;
case 'm' :
[Link]("Product of the two numbers: "+(a*b));
case 'd' :
[Link]("Result of the division: "+(a/b));
break;
default :
[Link]("Invalid operation");
}
}
}
Output:
Program - Checking for Armstrong number using while loop
Source code:
Import [Link].*;
Class Armstrong{
Public static void main(string args[]){
Scanner sc= new Scanner([Link]);
Int n,sum,r,temp;
N=[Link]();
[Link](“enter the value:”);
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(sum==temp)
[Link](“given number is Armstrong number”);
else
[Link](“not a Armstrong number”);
}
}

Output:
Program - Reversing a number and finding sum using do… while
Source code:
import [Link];
class reverseandsum {
public static void main(String[] args{
int num, rem;
int rev = 0, sum = 0;
Scanner sc = new Scanner([Link]);
[Link]("Enter the number: ");
num = [Link]();
do {
rem = num % 10;
rev = rev * 10 + rem;
sum = sum + rem;
num = num / 10;
}while (num > 0)
[Link]("Reverse of given number: "+ rev);
[Link]("Sum of digits of given number: "+ sum);
}
}
Output:
Program - Finding Fibonacci series using for loop
Source code:
import [Link].*;
class FibonacciExample1{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int n1=0,n2=1,n3,i,count;
[Link]("Enter the number:");
count=[Link]();
[Link](n1+" "+n2+" ");
for(i=2;i<count;++i)
{
n3=n1+n2;
[Link](" "+n3);
n1=n2;
n2=n3;
}
}
}
Output:

Common questions

Powered by AI

Default cases in switch statements act as catch-all handlers for inputs that do not match any specified case, ensuring the program can respond appropriately to unexpected input with an error message, preventing crashes. Improvements include providing more informative feedback to the user about valid inputs or steps to correct the input, along with logging such cases for debugging purposes .

The switch case construct in Java provides a more organized and readable way to select one among multiple operations to be performed on input numbers based on user input. In the calculator program, it checks the character entered to determine the desired operation: addition, subtraction, multiplication, or division. The switch case allows for jumping directly to the relevant case without evaluating all conditions, making the decision-making process efficient .

Integer division truncates the decimal fraction in Java, potentially leading to unexpected zero or inaccurate results when dividing integers, especially if one number is not a multiple of the other. To address this, the program could cast operands to double before division or provide warnings or alternative operations for integer-only division, ensuring results adhere to user expectations for precision .

An Armstrong number is one whose value is equal to the sum of its digits each raised to the power of the number of digits. The while loop in the program computes this by iterating until all digits are processed. In each iteration, it isolates the last digit using `% 10`, raises it to the necessary power, and adds it to a cumulative sum. After processing all digits, it checks if the computed sum equals the original number, confirming if it is an Armstrong number .

The program initializes the first two Fibonacci numbers, 0 and 1. Using a for loop, it iteratively calculates the next numbers in the sequence by adding the last two numbers computed. This continues for a specified count of iterations. The for loop aids performance by a constant step increment and reduces overhead due to its iterative nature, while the inline initialization of Fibonacci numbers enhances readability due to direct tracking of sequence progressions .

The do-while loop ensures that the code block executes at least once, which is useful when the number can be zero. Compared to a while loop, it avoids initial checks before execution, reducing unnecessary evaluations and potentially speeding up execution for small inputs. However, for performance optimization, a for loop might offer improved clarity with boundaries explicitly set. The trade-off involves improved simplicity with do-while, against potential overhead when `num` equals zero .

Java requires variable initialization to establish a starting point for their use in expressions, which helps avoid null references or undefined behavior. In the Armstrong number program, not initializing `sum` would lead to an incorrect comparison since default primitive integer values start at zero. Proper initialization prevents logical errors and ensures correctness in calculations .

The primary consideration is to handle division by zero, which is a common runtime error in division operations. When a division operation is chosen, the program should include a conditional check to ensure the divisor is not zero before proceeding with the division. Additionally, the program should handle user input carefully to ensure non-numeric characters do not lead to type mismatch errors .

User input handling is crucial, as it ensures inputs are valid and within expected formats, reducing runtime errors. The program uses `Scanner` for input and checks characters for operation selection. Improvements include adding input validation to check for valid numeric inputs, handling exceptions especially in operations that involve division, and guiding users with prompts or error messages for invalid input formats .

The do-while loop ensures that the block of statements for reversing and summing executes at least once, which is crucial for valid input processing. It extracts the last digit of the number, appends it to a new reversed number, and adds it to a sum variable. The number is then divided by 10 to remove the processed digit. This continues until all digits are processed and the number becomes zero, ensuring both tasks are completed regardless of initial number size .

You might also like