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

Lawrence Adade Boateng - Java-Assignment

The document contains a series of Java programming assignments that cover various concepts such as loops, conditionals, and data structures. Each question includes a specific task, such as calculating the sum of digits, reversing a string, checking for leap years, and implementing algorithms like GCD and bubble sort. The document serves as a comprehensive guide for practicing Java programming skills through practical coding exercises.

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)
9 views11 pages

Lawrence Adade Boateng - Java-Assignment

The document contains a series of Java programming assignments that cover various concepts such as loops, conditionals, and data structures. Each question includes a specific task, such as calculating the sum of digits, reversing a string, checking for leap years, and implementing algorithms like GCD and bubble sort. The document serves as a comprehensive guide for practicing Java programming skills through practical coding exercises.

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/ 11

Name:Lawrence Adade Boateng

Index Number:1698695869
Group D
Course BIT

Question 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:

Code to execute:

import java.util.Scanner;

public class Assignment1 {


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

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


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

do {
sum = 0;
while (userNumber > 0){
sum += userNumber % 10;
userNumber /= 10;
}
userNumber = sum;
} while (sum > 9);

System.out.println("The single digit sum is: " + sum);


scanner.close();
}
}

Question 2:
Create a program using a while loop to reverse a string without using any built-in
reverse methods.

Java Code:

import java.util.Scanner;

public class Assignment2 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word;
StringBuilder reverseWord = new StringBuilder();

System.out.println("*************** Word Reverse Simulator


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

int length = word.length() - 1;


while (length >= 0){
reverseWord.append(word.charAt(length));
length--;
}

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


scanner.close();
}
}

Question 3:
Use if/else statements to determine if a given year is a leap year, considering all
edge cases (e.g., century years).

Java Code:

import java.util.Scanner;

public class Assignment3 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int year;
boolean running = true;
char quit;

System.out.println("******************** Leap Year checker


************************");

do {
System.out.print("Enter the year: ");
year = scanner.nextInt();

if (year >= 1000){


if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 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:
Write a Java program with a for loop to generate the first 10 numbers in the
Fibonacci sequence.

Java Code:

public class Assignment4 {


public static void main(String[] args) {
int num1 = 0;
int num2 = 1;
int nextNum;

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


System.out.print(num1 + ", " + num2);

for (int i = 2; i <= 10; i++) {


nextNum = num1 + num2;
System.out.print(", " + nextNum);
num1 = num2;
num2 = nextNum;
}
}
}

Question 5:
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.

Java Code:

import java.util.Scanner;

public class Assignment5 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String password;
boolean isValid = true;

do {
System.out.print("Create your password: ");
password = scanner.nextLine();

if (password.length() >= 8 && hasUppercase(password) &&


hasNumber(password)){
isValid = false;
} else {
System.out.println("Error: password must contain at least 8
characters, one uppercase letter, and one digit");
}
} while (isValid);

System.out.println("Password accepted!");
scanner.close();
}

public static boolean hasUppercase(String str) {


return !str.equals(str.toLowerCase());
}

public static boolean hasNumber(String str) {


return str.matches(".*\\d.*");
}
}

Question 6:
Using a while loop, write a program to find the greatest common divisor (GCD) of
two numbers using the Euclidean algorithm.

Java Code:

import java.util.Scanner;

public class Assignment6 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("************* Euclidean Algorithm & Finding the GCD
*******************");

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


int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();

while (num2 != 0){


int remainder = num1 % num2;
num1 = num2;
num2 = remainder;
}

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


scanner.close();
}
}

Question 7:
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.

Java Code:

import java.util.Scanner;

public class Assignment7 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your percentage score: ");
double score = scanner.nextDouble();

if (score >= 90 && score <= 100) {


System.out.println("Grade: A");
} else if (score >= 80 && score < 90) {
System.out.println("Grade: B");
} else if (score >= 70 && score < 80) {
System.out.println("Grade: C");
} else if (score >= 60 && score < 70) {
System.out.println("Grade: D");
} else if (score >= 0 && score < 60) {
System.out.println("Grade: F");
} else {
System.out.println("Invalid score entered!");
}
scanner.close();
}
}

Question 8:
Write a Java program using a for loop to print a multiplication table (1 to 10) for
a user-specified number.

Java Code:

import java.util.Scanner;

public class Assignment8 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number: ");
int num = scanner.nextInt();

System.out.println("Multiplication Table for " + num + ":");


for (int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
scanner.close();
}
}

Question 9:
Use a do-while loop to simulate a simple ATM menu that allows users to check
balance, deposit, withdraw, or exit, with input validation.

Java Code:

import java.util.Scanner;

public class Assignment9 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double balance = 5000;
boolean isOperating = true;

do {
System.out.println("\n1. Check Balance");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Exit");
System.out.print("Select your option: ");
int option = scanner.nextInt();

switch (option) {
case 1:
System.out.println("Current Balance: $" + balance);
break;
case 2:
System.out.print("Enter deposit amount: ");
balance += scanner.nextDouble();
break;
case 3:
System.out.print("Enter withdrawal amount: ");
double amount = scanner.nextDouble();
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds!");
}
break;
case 4:
isOperating = false;
break;
default:
System.out.println("Invalid option!");
}
} while (isOperating);

System.out.println("Thank you for using our ATM!");


scanner.close();
}
}

Question 10:
Write a program with a while loop to count the number of vowels in a given string,
ignoring case sensitivity.

Java Code:

import java.util.Scanner;

public class Assignment10 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = scanner.nextLine().toLowerCase();

int vowels = 0;
int index = 0;
while (index < word.length()) {
char c = word.charAt(index);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
}
index++;
}

System.out.println("Number of vowels: " + vowels);


scanner.close();
}
}

Question 11:
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.

Java Code:

import java.util.Scanner;

public class Assignment11 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter upper limit: ");
int limit = scanner.nextInt();

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


for (int num = 2; num <= limit; num++) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(num + " ");
}
}
scanner.close();
}
}

Question 12:
Create a Java program with a nested for loop to print a pattern of stars in a
right-angled triangle with 5 rows.

Java Code:

public class Assignment12 {


public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}

Question 13:
Implement a do-while loop to calculate compound interest for a principal amount
until it doubles, given an annual interest rate.

Java Code:

import java.util.Scanner;

public class Assignment13 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter annual interest rate (%): ");
double rate = scanner.nextDouble() / 100;

double amount = principal;


int years = 0;

do {
amount *= (1 + rate);
years++;
} while (amount < principal * 2);

System.out.printf("It will take %d years for your investment to double to $


%.2f", years, amount);
scanner.close();
}
}

Question 14:
Write a program using a while loop to find the factorial of a number, handling
cases where the input is negative or zero.

Java Code:

import java.util.Scanner;

public class Assignment14 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

if (num < 0) {
System.out.println("Factorial doesn't exist for negative numbers.");
} else if (num == 0) {
System.out.println("Factorial of 0 is 1.");
} else {
long factorial = 1;
int i = num;
while (i > 0) {
factorial *= i;
i--;
}
System.out.println("Factorial of " + num + " is: " + factorial);
}
scanner.close();
}
}

Question 15:
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.

Java Code:

public class Assignment15 {


public static void main(String[] args) {
int[] evens = new int[50];
int[] odds = new int[50];
int evenIndex = 0, oddIndex = 0;

for (int i = 1; i <= 100; i++) {


if (i % 2 == 0) {
evens[evenIndex++] = i;
} else {
odds[oddIndex++] = i;
}
}
System.out.print("Even numbers: ");
for (int num : evens) System.out.print(num + " ");

System.out.print("\nOdd numbers: ");


for (int num : odds) System.out.print(num + " ");
}
}

Question 16:
Write a Java program with a for loop to implement bubble sort for an array of
integers in ascending order.

Java Code:

public class Assignment16 {


public static void main(String[] args) {
int[] arr = {5, 3, 8, 6, 2};

for (int i = 0; i < arr.length - 1; i++) {


for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

System.out.print("Sorted array: ");


for (int num : arr) System.out.print(num + " ");
}
}

Question 17:
Create a program using a do-while loop to repeatedly prompt the user for a number
and check if it is a palindrome until they choose to exit.

Java Code:

import java.util.Scanner;

public class Assignment17 {


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

do {
System.out.print("\nEnter a number to check (or 0 to exit): ");
int num = scanner.nextInt();
if (num == 0) break;

int original = num;


int reversed = 0;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
if (original == reversed) {
System.out.println(original + " is a palindrome!");
} else {
System.out.println(original + " is NOT a palindrome.");
}
} while (true);

System.out.println("Goodbye!");
scanner.close();
}
}

Question 18:
Using a while loop, write a program to convert a decimal number to its binary
representation without using built-in methods.

Java Code:

import java.util.Scanner;

public class Assignment18 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = scanner.nextInt();

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

StringBuilder binary = new StringBuilder();


while (decimal > 0) {
binary.insert(0, decimal % 2);
decimal /= 2;
}

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


scanner.close();
}
}

Question 19:
Implement a nested if/else structure to determine the type of triangle
(equilateral, isosceles, scalene) based on three side lengths, with input
validation.

Java Code:

import java.util.Scanner;

public class Assignment19 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter three side lengths of a triangle:");

System.out.print("Side 1: ");
double a = scanner.nextDouble();
System.out.print("Side 2: ");
double b = scanner.nextDouble();
System.out.print("Side 3: ");
double c = scanner.nextDouble();

if (a <= 0 || b <= 0 || c <= 0) {


System.out.println("Invalid sides - all must be positive");
} else if (a + b <= c || a + c <= b || b + c <= a) {
System.out.println("Not a valid triangle");
} else if (a == b && b == c) {
System.out.println("Equilateral triangle");
} else if (a == b || b == c || a == c) {
System.out.println("Isosceles triangle");
} else {
System.out.println("Scalene triangle");
}
scanner.close();
}
}

Question 20:
Write a Java program using a for loop to find all perfect numbers (where the sum of
proper divisors equals the number) between 1 and 1000.

Java Code:

public class Assignment20 {


public static void main(String[] args) {
System.out.println("Perfect numbers between 1 and 1000:");

for (int num = 1; num <= 1000; num++) {


int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) sum += i;
}
if (sum == num) System.out.println(num);
}
}
}

You might also like