[go: up one dir, main page]

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

Java Assign em NT

The document contains Java programming assignments that cover various concepts such as loops, conditionals, and string manipulation. Each question provides a specific task, including calculating the sum of digits, reversing a string, checking for leap years, generating Fibonacci numbers, validating passwords, finding the GCD using the Euclidean algorithm, categorizing grades, generating multiplication tables, simulating an ATM menu, and counting vowels in a string. The code snippets demonstrate the implementation of these tasks using appropriate Java syntax and logic.

Uploaded by

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

Java Assign em NT

The document contains Java programming assignments that cover various concepts such as loops, conditionals, and string manipulation. Each question provides a specific task, including calculating the sum of digits, reversing a string, checking for leap years, generating Fibonacci numbers, validating passwords, finding the GCD using the Euclidean algorithm, categorizing grades, generating multiplication tables, simulating an ATM menu, and counting vowels in a string. The code snippets demonstrate the implementation of these tasks using appropriate Java syntax and logic.

Uploaded by

chuksottih
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 19

Name:

Index number:
Group
course:

Question 1:
import java.util.Scanner;

public class SecondAss1 {


public static void main(String[] args) {
// Assignment 1;
// Write a Java program using a do-while loop to find the sum of digits of
a number until the sum becomes a single digit.

// now the process


Scanner scanner = new Scanner(System.in);

// now variables to store the data for the processes


int userNumber;
int sum;

System.out.print("Enter a number to find sum till it becomes a single


digit: ");
userNumber = scanner.nextInt();

// now the do while loop for the process execution


do {
// first we are going to reset the sum for each iterations
sum = 0;

// this while loop is to perform the excution of the code


while (userNumber > 0){
sum += userNumber % 10; // then find sum , then find the remainder
after its divided by 10(add a last digit to the sum).
userNumber /= 10; //remove the last digit
}
userNumber = sum;

}while (sum > 9);// this continues to excute if the sum is greater the 9 (a
double digit)
System.out.println("The single digit sum is: " + sum);

scanner.close();

}
}

Question 2:
import java.util.Scanner;
public class SecondAss2 {
public static void main(String[] args) {
//. Create a program using a while loop to reverse a string without using
any built-in reverse methods
// now to accept user input
Scanner scanner = new Scanner(System.in);

// now the variables


String word;
StringBuilder reverseWord = new StringBuilder();

// welcome message
System.out.println("************** Word Reverse Simulator
*******************");
System.out.print("Enter a random word: ");
word = scanner.nextLine();

//now the process and here we are going to be dealing with indexing
int length = word.length() - 1;// this is to turn the word around and start
from the last letter;

while (length >= 0){


reverseWord.append(word.charAt(length));
length --;
}

System.out.println("Reversed word is: " + reverseWord);

scanner.close();

}
}

Question 3:
import java.util.Scanner;

public class SecondAss3 {


public static void main(String[] args) {
//Use if/else statements to determine if a given year is a leap year,
considering all edge cases (e.g., century years).
// now we are going to be creating a leap year checker
Scanner scanner = new Scanner(System.in);

// now to accept user input and then rationalize to find the leap
year per the user input
int year;
boolean running = true;
char quit;
System.out.println("******************* Leap Year checker
******************");
/* System.out.print("Enter the year: ");
year = scanner.nextInt();

if (year < 0){


// now to check
if ((year % 4 == 0) && (year % 100 != 0)){
System.out.println("Leap year: " + year);
}
else {
System.out.println("Not a leap year");
System.out.println("Sample of previous leap years and events which
occurred on that year");
System.out.println("2024: India's Chandrayaan-3 successfully landed
on the Moon \n The Summer Olympics were held in Paris, France");
System.out.println("2020: The COVID-19 pandemic \n The Black Lives
Matter movement gained significant momentum");
System.out.println("2016: The United Kingdom voted to leave the
European Union (Brexit) \n Donald Trump was elected President of the United
States");
System.out.println("2012: The Summer Olympics were held in London,
United Kingdom \n The Costa Concordia cruise ship disaster");
}

}
else {
System.out.println("Error: invalid input.");
}*/

// now we are going to be using while loops for this


do {
System.out.print("Enter the year: ");
year = scanner.nextInt();
if (year >= 1000){
// now to check
if ((year % 4 == 0) && (year % 100 != 0)){
System.out.println("Leap year: " + year);
}
else {
System.out.println("Not a leap year");
}

}
else {
System.out.println("Error: failed to parse data \nInput
must be above 1000 to find leap year");
}

System.out.print("\nPress q to quit/ c to continue: ");


quit = scanner.next().charAt(0);
if (quit == 'q'){
running = false;
}

}while (running);

if (!running){
System.out.println("Bye, you've exit the program.");
}

scanner.close();
}
}

Question 4:
public class SecondAss4 {
public static void main(String[] args) {
//here we will be iterating over a loop using the Fibonacci sequence
//Write a Java program with a for loop to generate the first 10 numbers in
the Fibonacci sequence.
// The Fibonacci sequence is a series of numbers where:
//The first two numbers are 0 and 1.
//Every subsequent number is the sum of the two preceding numbers.
int num1 = 0;
int num2 = 1;// these are the numbers that begin the sequence
int nextNum;

System.out.println("The Fibonacci Sequence numbers:");


System.out.print(num1 + ", " + num2); // Print first two numbers
// now the for loop to execute the sequence
for (int i = 2; i <= 10 ; i++) {
nextNum = num1 + num2;
System.out.print(", " + nextNum);

// Update num1 and num2 for next iteration


num1 = num2;
num2 = nextNum;
}
}
}

Question 5:
import java.util.Scanner;

public class SecondAss5 {


public static void main(String[] args) {
//Implement a do-while loop to validate user input for a password that must
contain at least 8 characters, one uppercase letter, and one digit.

Scanner scanner = new Scanner(System.in);

String password;
boolean isValid = true;

do {
System.out.print("Create your password: ");
password = scanner.nextLine();
if ((hasUppercase(password)) && (hasLowercase(password)) &&
(hasNumber(password)) && (hasSymbol(password)) & (password.length() > 8) & (!
password.equals("V7#pL9@qW2$mN5&xR!"))){
isValid = false;
}
else {
System.out.println("Error: password not strong enough try again:
");
System.out.println("Password should be something like this:
V7#pL9@qW2$mN5&xR!");
}
}while (isValid);

// now to print out the password and


if (!isValid){
String pass4 = password.substring(0, 4);

// Replace the rest with *


StringBuilder maskedPart = new StringBuilder();
for (int i = 5; i < password.length(); i++) {
maskedPart.append("*");
}

String masked = pass4 + maskedPart.toString();

System.out.println("Password: " + password);


System.out.println("Masked password: " + masked);
}

scanner.close();
}
// reference from the java main website
// this is used to initialize the hasUppercase method
public static boolean hasUppercase(String str) {
return str.matches(".*[A-Z].*");
}
// this is for lower case
public static boolean hasLowercase(String str) {
return !str.equals(str.toUpperCase());
}
// and this is to check for numbers
public static boolean hasNumber(String str) {
return str.chars().anyMatch(Character::isDigit);
}
// Check for symbols
public static boolean hasSymbol(String str) {
return str.chars().anyMatch(c -> !Character.isLetterOrDigit(c));
}
}

Question 6:
import java.util.Scanner;

public class SecondAss6 {


public static void main(String[] args) {
//The Euclidean Algorithm is an efficient way to find the GCD of two
numbers.
//It works by repeatedly replacing the larger number with the remainder of
dividing the larger number by the smaller number until one of them becomes zero.
// The non-zero remaining number is the GCD.

// and before we proceed we have to check and make sure num1 is always
greater than num2
Scanner scanner = new Scanner(System.in);

int num1;
int num2;

System.out.println("***************** Euclidean Algorithm & Finding the GCD


********************");
System.out.print("Enter the first number: ");
num1 = scanner.nextInt();

System.out.print("Enter the second number: ");


num2 = scanner.nextInt();

// now to check and validate and assign booleans


// Ensure num1 is always the larger number initially
if (num2 > num1) {
System.out.println("Error: failed to parse data");
System.exit(1);
}

while (num2 != 0){


int remainder = num1 % num2;
num1 = num2; // Replace num1 with num2
num2 = remainder; // Replace num2 with remainder
}

System.out.println("The Greatest common divisor is: " + num1);

scanner.close();
}
}

Question 7:
import java.util.Scanner;

public class SecondAss7 {


public static void main(String[] args) {
//Create a program with nested if/else statements to categorize a student's
grade into A, B, C, D, or F based on a percentage score.
// this is more like a grade checker

Scanner scanner = new Scanner(System.in);


int numSubjects;

// now to accept the number of subjects


System.out.print("\uD83D\uDCDA Enter the number of subjects you offered
this sem: ");
numSubjects = scanner.nextInt();

if (numSubjects > 0) {
double[] grades = new double[numSubjects];
System.out.println("\\n\uD83D\uDCDD Enter your results for each
subject: ");
for (int i = 0; i < numSubjects; i++) {
System.out.print("Subject #" + (i + 1) + "➡\uFE0F ");
grades[i] = scanner.nextDouble();

if (grades[i] < 0 || grades[i] > 100) {


System.out.println("Error: results must be btwn (1-100)");
System.exit(1);
}
}

System.out.println(" ");
// now to validate
for (double figures: grades){
// to check grades
if (figures >= 90 && figures <= 100) {
System.out.println("Result:" + figures +"\nRating: \uD83C\uDF89
(Excellent!), You got an A");
} else if (figures >= 80 && figures < 90) {
System.out.println("Result:" + figures +"\nRating: \uD83D\uDC4D
(Great!), You got a B");
} else if (figures >= 70 && figures < 80) {
System.out.println("Result:" + figures +"\nRating: \uD83D\uDE0A
(Good), You got a C");
} else if (figures >= 60 && figures < 70) {
System.out.println("Result:" + figures +"\nRating: \uD83D\uDE42
(Average), You got a D");
} else if (figures >= 50 && figures < 60) {
System.out.println("Result:" + figures +"\nRating: \uD83D\uDE10
(Pass), You got an E");
}
else {
System.out.println("Result:" + figures +"\nRating: \uD83D\uDE22
(Fail), You got an F");
}

}
else {
System.out.println("Error: input invalid");
System.exit(1);
}
scanner.close();
}
}

Question 8:
import java.util.Scanner;

public class SecondAss8 {


public static void main(String[] args) {
// Write a Java program using a for loop to print a multiplication table (1
to 10) for a user-specified number.
// so this is a multiplication table generator
// and here we are going to accept the number which the user wants the
multiplication table
Scanner scanner = new Scanner(System.in);
int numTable;

System.out.println("*************************** Multiplication Table


Generator *******************************");
System.out.print("Enter number: ");
numTable = scanner.nextInt();

System.out.println("\nMultiplication Table for " + numTable + ":");

// now for loop to perform the iteraction and excution


for (int i = 0; i <= 10; i++) {
int product = (numTable * i);// now finding the product based on the
current value of i
System.out.println(numTable + " x " + i + " = " + product);
}

scanner.close();
}
}

Question 9:
import java.util.Scanner;

public class SecondAss9 {


public static void main(String[] args) {
// Use a do-while loop to simulate a simple ATM menu that allows users to
check balance, deposit, withdraw, or exit, with input validation.
// now this is going to be done using a do while loop and the easiet so far

Scanner scanner = new Scanner(System.in);

//to values
double balance = 5000;
double deposit;
double withdraw;
int numberWith =0;
int failWith = 0;
int numDeposit= 0;
int failDep = 0;
int option;
boolean isOperating = true;

// welcome message

System.out.println("***************************************************************
*****");
System.out.println("Welcome to SOHO ATM Center");

System.out.println("***************************************************************
*****\n");

do {

// now the options list and the procedures


System.out.println("Select your option");
System.out.println("1. Check Balance");
System.out.println("2. Deposit");
System.out.println("3. WithDraw");
System.out.println("4. exist");
System.out.print("Select your option: ");
option = scanner.nextInt();

// to check the user input to display the appropraite info


if (option == 1){
System.out.println("\nProcessing.....");
System.out.println("Current Account Balance: ");
System.out.println(" $" + balance);
System.out.println("*************************************\n");
} else if (option == 2) {
System.out.println("\nProcessing........");
System.out.print("Enter dpeosit amount: ");
deposit = scanner.nextDouble();

// to check if the deposit is less than 0


if (deposit <= 0){
System.out.println("Error: deposit amount cannot be less than
0\n");
failDep++;
continue;
}
balance += deposit;
System.out.println("\nDeposit of $"+deposit + " - Successful\nHave
a great day.");
numDeposit++;
} else if (option == 3) {
System.out.println("\nProcessing withdrawal...........");
System.out.print("Enter withdrawal amount: ");
withdraw = scanner.nextDouble();

if (withdraw < 0 || withdraw > balance){


System.out.println("Error: failed to withdraw, check balance
and try again\n");
failWith++;
continue;
}
balance -= withdraw;
System.out.println("Withdrawal of $"+ withdraw + " - successful\
nEnjoy your day\n");
numberWith++;
} else if (option == 4) {
isOperating = false;
}
}while (isOperating);
// now the last statement for the user to see
if (!isOperating){
System.out.println("\n********************** Account Statement
***************************");
System.out.println("Current Balance: $" + balance);
System.out.println(numberWith + " successful withdrawals , " + failWith
+ " failed withdrawals" );
System.out.println(numDeposit + " successful deposits , " + failDep +
" failed deposits\n");
System.out.println("Enjoy your day, Thanks for using SOHO ATM");
}

scanner.close();
}
}

Question 10:
import java.util.Scanner;

public class SecondAss10 {


public static void main(String[] args) {
// Write a program with a while loop to count the number of vowels in a
given string, ignoring case sensitivity
// now this program is to count the number of vowels in a word

Scanner scanner = new Scanner(System.in);


int vowels = 0;
int index = 0;
String word;

System.out.println("Vowel Checker Program");


System.out.println("**********************\n");
System.out.print("Enter a word: ");
word = scanner.nextLine();

while (index < word.length()){


// now this is to convert to lowercase
char letters = Character.toLowerCase(word.charAt(index));

// now to check if the word contains any vowels then takes note of them
if (letters == 'a' || letters == 'e' || letters == 'i' || letters ==
'o' || letters == 'u'){
vowels++;
}
index++;
}
System.out.println("Number of vowels: " + vowels + "\nin "+ word);

scanner.close();
}
}

Question 11:
import java.util.Scanner;
public class SecondAss11 {
public static void main(String[] args) {
//Using if/else and a for loop, write a program to check if a number is
prime and print all prime numbers up to a given limit
Scanner input = new Scanner(System.in);

System.out.print("Enter upper limit: ");


int limit = input.nextInt();

System.out.println("Prime numbers up to " + limit + ":");

// Check each number from 2 to limit


for (int num = 2; num <= limit; num++) {
boolean isPrime = true;

// Check if current num is prime


for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime) {
System.out.print(num + " ");
}
}

}
}

Question 12:
public class SecondASS12 {
public static void main(String[] args) {
//Create a Java program with a nested for loop to print a pattern of stars
in a right-angled triangle with 5 rows.
int row = 5;

for (int i = 0; i <= row ; i++) {


// Inner loop for stars in each row to iterate over it
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();

}
}
}
Question 13:
import java.util.Scanner;

public class SecondAss13 {


public static void main(String[] args) {
//Implement a do-while loop to calculate compound interest for a principal
amount until it doubles, given an annual interest rate.

// now we are going to be creating a compound interest calculator simulator


Scanner scanner = new Scanner(System.in);
// the values we are going to be dealing with
double CI; // this is the total final result to store the value of hte
compound interest
double Principal=0;// now this is the principal amount
double interestRate;
double finalRate = 0;// this is the rate converted to percentage format for
calculations
int compoundedInterestTime;
double time = 0;

// now the magic begins


System.out.println("------------------ Compound Interest Calculator:
------------------");

// begin
System.out.print("Enter the principal amount(investment loan): ");
Principal = scanner.nextDouble();

System.out.print("Enter the annual rate(in percentage): ");


interestRate = scanner.nextDouble();
// now to check the interstrate
if (interestRate < 0 || interestRate > 100){
System.out.println("Please enter a valid rate(0 - 100)");
System.exit(1);// so this causes the code to exist abruptly
}
else {
finalRate = interestRate / 100;
}

scanner.nextLine();

// Get and validate compounding frequency


System.out.print("Enter compounding times per year (1, 2, 4, 12): ");
compoundedInterestTime = scanner.nextInt();
if (compoundedInterestTime != 1 && compoundedInterestTime != 2 &&
compoundedInterestTime != 4 && compoundedInterestTime != 12) {
System.out.println("Error: Invalid compounding frequency. Must be 1, 2,
4, or 12.");
System.exit(1);
}

// Fix: Consume the leftover newline character


scanner.nextLine();
System.out.print("Select the time period (m (Month) / y (Years)): ");
String selectTime = scanner.nextLine().toLowerCase();
if (!selectTime.equals("m") && !selectTime.equals("y")) {
System.out.println("Error: Please select 'm' or 'y' to proceed!");
System.exit(1);
}

if (selectTime.equals("m")) {
System.out.print("Please enter the number of months: ");
double calcTime = scanner.nextDouble();
time = calcTime / 12.0; // Convert months to years (as a double)
} else if (selectTime.equals("y")) {
System.out.print("Please enter the number of years: ");
time = scanner.nextDouble();
}

// now the magic and final calculation


CI = Principal * Math.pow(1 + (finalRate/compoundedInterestTime),
compoundedInterestTime * time);
// this is the final calculation by subtracting the principal from the CI
double CompoundInterst = CI - Principal;

// now to print out the compound interest


System.out.printf("Compound Interest: $% .2f\n", CompoundInterst);
double TotalAmount = Principal + CI;
System.out.printf("The total amount amassed is: $% .2f\n", TotalAmount);

// now to close
scanner.close();
}
}

Question 14:
import java.util.Scanner;

public class SecondAss14 {


public static void main(String[] args) {
//Write a program using a while loop to find the factorial of a number,
handling cases where the input is negative or zero.
// factorial finder simulator

Scanner scanner = new Scanner(System.in);


int userInput;
// now accept user input
System.out.println("******************* Factorial Finder
*************************\n");
System.out.print("Enter a number: ");
userInput = scanner.nextInt();

// now to handle and validate the input


if (userInput < 0){
System.out.println("Factorial doesn't exist for negative numbers.");
} else if (userInput == 0) {
System.out.println("Factorial of 0 is 1.");
}else {
// here we are introduced to the long keyword to handle large
factorials
long factorial =1;
int index = userInput;

// now the while loop to execute the code


while (index > 0){
factorial *= index; // Multiply factorial by i
index--; // Decrement i
}

System.out.println("Factorial of " + userInput + " is: " + factorial);


}

scanner.close();
}
}

Question 15:
public class SecondAss15 {
public static void main(String[] args) {
//Use if/else statements within a for loop to separate even and odd numbers
from 1 to 100 and store them in two separate arrays.

// now we are going to create a n array container to store the two types
int[] evenNumbers = new int[50]; // since we are working with a range of
numbers from 1 - 100 half will be even and the other half odd
int[] oddNumbers = new int[50];

// now to track the even number


int evenIndex = 0;
int oddIndex = 0;

// we are going to creating a various loops


// this to iterate over the numbers 1 -100
for (int i = 1; i <= 100 ; i++) {
if (i % 2 == 0){
evenNumbers[evenIndex] =i;// this is store the even numbers
evenIndex++;
}
else {
oddNumbers[oddIndex] = i; // to store the odd number
oddIndex++;
}
}

System.out.println("Even numbers (1-100): ");


// to iterate and print out the even numbers
for (int num : evenNumbers){
System.out.print(num + " ");
}

System.out.println("\n\nOdd numbers (1-100): ");


// to iterate and print the odd numbers
for (int num : oddNumbers){
System.out.print(num + " ");
}
}
}

Question 16:
public class SecondAss16 {
public static void main(String[] args) {
// Initialize an unsorted array
int[] arr = {5, 3, 8, 6, 2};

System.out.println("Original Array:");
printArray(arr);

// Call the bubble sort method


bubbleSort(arr);

System.out.println("\nSorted Array (Ascending Order):");


printArray(arr);
}

public static void bubbleSort(int[] arr) {


int n = arr.length;

// Outer loop: controls the number of passes through the array


// We need n-1 passes to ensure the array is fully sorted
for (int i = 0; i < n - 1; i++) {

// Inner loop: performs the pairwise comparisons


// After each pass, the largest unsorted element bubbles to the end,
// so we can reduce the range by i each time (n-i-1)
for (int j = 0; j < n - i - 1; j++) {

// Compare adjacent elements


if (arr[j] > arr[j + 1]) {
// Swap if they're in the wrong order
int temp = arr[j]; // Temporary variable for swapping
arr[j] = arr[j + 1]; // Move the smaller element left
arr[j + 1] = temp; // Move the larger element right
}
}

// Optional: Print array state after each pass (for debugging)


// System.out.println("After pass " + (i+1) + ":");
// printArray(arr);
}
}

public static void printArray(int[] arr) {


// Enhanced for loop to iterate through array elements
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println(); // Move to next line after printing
}
}

Question 17:
import java.util.Scanner;

public class SecondAss17 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;

// Main program loop


do {
System.out.println("\nPalindrome Checker Menu");
System.out.println("1. Check a number");
System.out.println("2. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

// Process user choice


switch (choice) {
case 1:
checkPalindrome(scanner);
break;
case 2:
System.out.println("Exiting program...");
break;
default:
System.out.println("Invalid choice! Please try again.");
}
} while (choice != 2); // Continue until user chooses to exit

scanner.close();
}

// Method to check if a number is palindrome


private static void checkPalindrome(Scanner scanner) {
System.out.print("Enter a number to check: ");
int number = scanner.nextInt();
int original = number;
int reversed = 0;

// Reverse the number


while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}

// Check if palindrome
if (original == reversed) {
System.out.println(original + " is a palindrome!");
} else {
System.out.println(original + " is NOT a palindrome.");
}
}
}

Question 18:
import java.util.Scanner;

public class SecondAss18 {


public static void main(String[] args) {
// Using a while loop, write a program to convert a decimal number to its
binary representation without using built-in methods.
// the process

Scanner scanner = new Scanner(System.in);

int decimal;

System.out.println("************************ Decimal to Binary Program


***************************\n");
System.out.print("Enter a decimal number: ");
decimal = scanner.nextInt();

// Handle edge case: 0


if (decimal == 0) {
System.out.println("Binary: 0");
return;
}

// Convert decimal to binary


String binaryStr = "";
while (decimal > 0) {
binaryStr = (decimal % 2) + binaryStr; // Prepend remainder
decimal /= 2;
}

System.out.println("Binary: " + binaryStr);

scanner.close();
}
}

Question 19:
import java.util.Scanner;

public class SecondAss19 {


public static void main(String[] args) {
// Implement a nested if/else structure to determine the type of triangle
(equilateral, isosceles, scalene) based on three side lengths, with input
validation.
// now to verify the type of triangle

Scanner scanner = new Scanner(System.in);


System.out.println("Enter three side lengths of a triangle:");

// now the container for the values


double side1, side2, side3;
// a while loop for the executions
while (true){
System.out.print("Side 1: ");
side1 = scanner.nextDouble();
System.out.print("Side 2: ");
side2 = scanner.nextDouble();
System.out.print("Side 3: ");
side3 = scanner.nextDouble();

// Check if all sides are positive


if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
System.out.println("Error: All sides must be positive numbers. Try
again.");
continue;
}

// Check triangle inequality


if (side1 + side2 <= side3 ||
side1 + side3 <= side2 ||
side2 + side3 <= side1) {
System.out.println("Error: These sides violate triangle inequality.
Try again.");
} else {
break; // Valid input, exit loop
}
}

// now the final process


if (side1 == side2 && side2 == side3) {
System.out.println("This is an EQUILATERAL triangle (all sides
equal).");
}
else if (side1 == side2 || side1 == side3 || side2 == side3) {
System.out.println("This is an ISOSCELES triangle (exactly two sides
equal).");
}
else {
System.out.println("This is a SCALENE triangle (no sides equal).");
}

scanner.close();
}
}

Question 20:
public class SecondAss20{
public static void main(String[] args) {
System.out.println("Perfect numbers between 1 and 1000:");
// Outer loop: Check each number from 1 to 1000
for (int num = 1; num <= 1000; num++) {
int sumOfDivisors = 0;

// Inner loop: Find proper divisors and sum them


for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sumOfDivisors += i;
}
}

// Check if the number is perfect


if (sumOfDivisors == num) {
System.out.println(num);
}
}
}
}

You might also like