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

Java Programming Assignments by Lawrence

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

Java Programming Assignments by Lawrence

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

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 [Link];

public class Assignment1 {


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

[Link]("Enter a number to find sum till it becomes a single


digit: ");
userNumber = [Link]();

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

[Link]("The single digit sum is: " + sum);


[Link]();
}
}

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

Java Code:

import [Link];

public class Assignment2 {


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

[Link]("*************** Word Reverse Simulator


*******************");
[Link]("Enter a random word: ");
word = [Link]();

int length = [Link]() - 1;


while (length >= 0){
[Link]([Link](length));
length--;
}

[Link]("Reversed word is: " + reverseWord);


[Link]();
}
}

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 [Link];

public class Assignment3 {


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

[Link]("******************** Leap Year checker


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

do {
[Link]("Enter the year: ");
year = [Link]();

if (year >= 1000){


if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)){
[Link]("Leap year: " + year);
} else {
[Link]("Not a leap year");
}
} else {
[Link]("Error: failed to parse data \nInput must be
above 1000 to find leap year");
}

[Link]("\nPress q to quit/ c to continue: ");


quit = [Link]().charAt(0);
if (quit == 'q'){
running = false;
}
} while (running);

if (!running){
[Link]("Bye, you've exit the program.");
}
[Link]();
}
}

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;

[Link]("The Fibonacci Sequence numbers:");


[Link](num1 + ", " + num2);

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


nextNum = num1 + num2;
[Link](", " + 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 [Link];

public class Assignment5 {


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

do {
[Link]("Create your password: ");
password = [Link]();

if ([Link]() >= 8 && hasUppercase(password) &&


hasNumber(password)){
isValid = false;
} else {
[Link]("Error: password must contain at least 8
characters, one uppercase letter, and one digit");
}
} while (isValid);

[Link]("Password accepted!");
[Link]();
}

public static boolean hasUppercase(String str) {


return ![Link]([Link]());
}

public static boolean hasNumber(String str) {


return [Link](".*\\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 [Link];

public class Assignment6 {


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

[Link]("Enter the first number: ");


int num1 = [Link]();
[Link]("Enter the second number: ");
int num2 = [Link]();

while (num2 != 0){


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

[Link]("The Greatest common divisor is: " + num1);


[Link]();
}
}

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 [Link];

public class Assignment7 {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter your percentage score: ");
double score = [Link]();

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


[Link]("Grade: A");
} else if (score >= 80 && score < 90) {
[Link]("Grade: B");
} else if (score >= 70 && score < 80) {
[Link]("Grade: C");
} else if (score >= 60 && score < 70) {
[Link]("Grade: D");
} else if (score >= 0 && score < 60) {
[Link]("Grade: F");
} else {
[Link]("Invalid score entered!");
}
[Link]();
}
}

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 [Link];

public class Assignment8 {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter number: ");
int num = [Link]();

[Link]("Multiplication Table for " + num + ":");


for (int i = 1; i <= 10; i++) {
[Link](num + " x " + i + " = " + (num * i));
}
[Link]();
}
}

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 [Link];

public class Assignment9 {


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

do {
[Link]("\n1. Check Balance");
[Link]("2. Deposit");
[Link]("3. Withdraw");
[Link]("4. Exit");
[Link]("Select your option: ");
int option = [Link]();

switch (option) {
case 1:
[Link]("Current Balance: $" + balance);
break;
case 2:
[Link]("Enter deposit amount: ");
balance += [Link]();
break;
case 3:
[Link]("Enter withdrawal amount: ");
double amount = [Link]();
if (amount <= balance) {
balance -= amount;
} else {
[Link]("Insufficient funds!");
}
break;
case 4:
isOperating = false;
break;
default:
[Link]("Invalid option!");
}
} while (isOperating);

[Link]("Thank you for using our ATM!");


[Link]();
}
}

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 [Link];

public class Assignment10 {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a word: ");
String word = [Link]().toLowerCase();

int vowels = 0;
int index = 0;
while (index < [Link]()) {
char c = [Link](index);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
}
index++;
}

[Link]("Number of vowels: " + vowels);


[Link]();
}
}

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 [Link];

public class Assignment11 {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter upper limit: ");
int limit = [Link]();

[Link]("Prime numbers up to " + limit + ":");


for (int num = 2; num <= limit; num++) {
boolean isPrime = true;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
[Link](num + " ");
}
}
[Link]();
}
}

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++) {
[Link]("*");
}
[Link]();
}
}
}

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 [Link];

public class Assignment13 {


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

double amount = principal;


int years = 0;

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

[Link]("It will take %d years for your investment to double to $


%.2f", years, amount);
[Link]();
}
}

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 [Link];

public class Assignment14 {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

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

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;
}
}
[Link]("Even numbers: ");
for (int num : evens) [Link](num + " ");

[Link]("\nOdd numbers: ");


for (int num : odds) [Link](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 < [Link] - 1; i++) {


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

[Link]("Sorted array: ");


for (int num : arr) [Link](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 [Link];

public class Assignment17 {


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

do {
[Link]("\nEnter a number to check (or 0 to exit): ");
int num = [Link]();
if (num == 0) break;

int original = num;


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

[Link]("Goodbye!");
[Link]();
}
}

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 [Link];

public class Assignment18 {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a decimal number: ");
int decimal = [Link]();

if (decimal == 0) {
[Link]("Binary: 0");
return;
}

StringBuilder binary = new StringBuilder();


while (decimal > 0) {
[Link](0, decimal % 2);
decimal /= 2;
}

[Link]("Binary: " + binary);


[Link]();
}
}

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 [Link];

public class Assignment19 {


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

[Link]("Side 1: ");
double a = [Link]();
[Link]("Side 2: ");
double b = [Link]();
[Link]("Side 3: ");
double c = [Link]();

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


[Link]("Invalid sides - all must be positive");
} else if (a + b <= c || a + c <= b || b + c <= a) {
[Link]("Not a valid triangle");
} else if (a == b && b == c) {
[Link]("Equilateral triangle");
} else if (a == b || b == c || a == c) {
[Link]("Isosceles triangle");
} else {
[Link]("Scalene triangle");
}
[Link]();
}
}

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) {
[Link]("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) [Link](num);
}
}
}

Common questions

Powered by AI

To determine if a number is a palindrome, use a do-while loop to repeatedly check whether the user's input forms a palindrome. Read the number into 'original', reverse it through a loop by extracting and then reversing its digits, and compare the reversed number with the original. The loop allows users to repeat the process with different numbers or exit by inputting zero .

The Euclidean algorithm for finding the GCD uses the principle that GCD(a, b) = GCD(b, a mod b). In Java, start by accepting two integers, representing them as num1 and num2. While num2 is not zero, replace num1 with num2, and num2 with num1 % num2 (this calculates the remainder of the division of num1 by num2). When num2 becomes zero, num1 holds the greatest common divisor .

A do-while loop in Java can repeat a block of code until a condition is met. To find the sum of the digits of a number until the sum is a single digit, initialize a scanner for user input, declare variables for storing the user's number and the sum, then use a do-while loop to repeatedly sum the digits. Inside the loop, another while loop is used to break down the number into its digits by using the modulus and division operations. This process continues until the sum becomes a single digit .

Nested if-else statements evaluate conditions in sequence to categorize a student's score into grades. For each score range, a specific grade is assigned, starting with the highest possible score. If the score is within 90 to 100, assign 'A'; if 80 to 89, assign 'B'; 70 to 79, 'C'; 60 to 69, 'D'; and anything below 60, 'F'. It also has a condition to check for invalid scores outside 0-100 range .

To reverse a string without using built-in methods, initialize a Scanner to read the input string. Use a StringBuilder to build the reversed string. Compute the length of the string and iterate backward through it with a while loop, appending each character to the StringBuilder. Finally, output the reversed string .

To convert a decimal number to binary without built-in methods, initialize a loop that continues until the number becomes zero. Use modulus operation to find remainders when dividing the number by 2, building the binary result by inserting remainders at the start of a StringBuilder. Divide the number by 2 iteratively in a while loop until it is reduced to zero, achieving the binary representation .

To find prime numbers, use a for loop to iterate through numbers starting from 2 up to a specified limit. For each number, an inner for loop checks divisibility by each number up to its square root, setting a boolean flag 'isPrime' to false if divisibility is found. If no divisibility is detected, the flag remains true, and the number is printed as prime. This method minimizes unnecessary checks for non-factors .

The program initializes the principal amount and calculates the new amount by applying the compound interest formula within a do-while loop. The amount is increased in each iteration by multiplying with (1 + rate), and the count of years is incremented. The loop continues until the accumulated amount exceeds double the original principal amount. This loop structure ensures the interest is compounded annually .

To validate user input for a password with specific requirements, use a do-while loop that continues prompting the user until a valid password is entered. The loop checks the password's length, the presence of an uppercase letter using a helper method that compares the string to its lowercase version, and the presence of a digit using a regex that checks for any number. If the conditions are not met, print an error message and re-prompt the user .

Recursion involves solving a problem by solving smaller instances of the same problem, which for Fibonacci means using the relation fib(n) = fib(n-1) + fib(n-2). Iteration, as demonstrated in Java using a for loop, sequentially calculates Fibonacci numbers without recalculating previously computed values, which makes it more efficient in terms of time and space compared to naive recursive implementations that don't use memoization .

You might also like