0% found this document useful (0 votes)
11 views7 pages

Java Programming Assignments Solutions

The document contains a series of Java programming assignments for a Computer Science student, Okemini Malvina Amarachi. It includes tasks such as printing natural numbers, checking for prime numbers, calculating factorials, reversing numbers, summing even numbers, and checking for palindromes, among others. Each assignment is accompanied by sample code demonstrating the required functionality.

Uploaded by

khaleex21
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)
11 views7 pages

Java Programming Assignments Solutions

The document contains a series of Java programming assignments for a Computer Science student, Okemini Malvina Amarachi. It includes tasks such as printing natural numbers, checking for prime numbers, calculating factorials, reversing numbers, summing even numbers, and checking for palindromes, among others. Each assignment is accompanied by sample code demonstrating the required functionality.

Uploaded by

khaleex21
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

Name: Okemini Malvina Amarachi

ID:20220868

Department: Computer Science

Assignment

1- Write a Java program to print the first 10 natural numbers using a for loop.
2- public class NaturalNumbers {
3- public static void main(String[] args) {
4- int i;
5- for (i = 1; i <= 10; i++) {
6- [Link](i + " ");
7-
8- }
9-
10- }
11-
12- }

2. Write a program that prompts the user to enter a number and checks if the number is
prime using a while loop.

import [Link];

public class PrimeNumber {


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

while (true) {
[Link]("Enter a number: ");
num = [Link]();

if (num <= 1) {
[Link](num + " is not a prime number.");
} else if (num == 2) {
[Link](num + " is a prime number.");
break;
} else {
boolean isPrime = true;

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


if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime) {
[Link](num + " is a prime number.");
break;
} else {
[Link](num + " is not a prime
number.");
}
}
}
}
}

3. Write a Java program to print the multiplication table of a given number using a do-while
loop.

import [Link];

public class multi {


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

[Link]("Enter a number: ");


num = [Link]();

int i = 1;

do {
[Link](num + " * " + i + " = " + (num * i));
i++; // Increment i within the loop
} while (i <= 10); // Loop condition

[Link]();
}
}

4. Write a Java program that calculates the factorial of a given number using a for loop.

import [Link];
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter a number: ");


int num = [Link]();

int factorial = 1;

for (int i = num; i >= 1; i--) {


factorial *= i;

[Link](i);

if (i > 1) {
[Link](" * ");
}
}
[Link](" = " + factorial);

[Link]();
}
}

5. Write a program to reverse a given number using a while loop.

import [Link];
public class Reverse {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number to reverse: ");
int number = [Link]();
int reversed = 0, remainder, original;

original = number;

while (number != 0) {
remainder = number % 10;
reversed = reversed * 10 + remainder;
number /= 10;
}
if (original != 0) {
[Link]("Reversed number: " + reversed);
} else {
[Link]("Invalid input, please enter a non-
zero number.");
}
[Link]();
}
}

6. Create a Java program to find the sum of all even numbers between 1 and 100 using a for
loop.

public class SumOfEvenNumbers {


public static void main(String[] args)
{
int sum = 0,count;
int start = 1;
int end = 100;

for(count = start; count <= end; count++)

if (count % 2 == 0)
sum = sum + count;

[Link]("the sum is:" + sum);

}
}

7. Write a Java program to display all the numbers between 1 and 50 that are divisible by 3
using a while loop.

public class numbers {


public static void main(String[] args) {
int count = 1; // Starting number
int end = 50; // Ending number

[Link]("Numbers between " + count + " to " + end


+ ":");
[Link]("These numbers are divisible by 3: ");

while (count <= end) {


if (count % 3 == 0) {
[Link](count + " ");
}
count++;
}

[Link]();
}
}

8. Write a Java program that takes an integer input from the user and prints whether it is a
perfect square using a do-while loop.

import [Link];

public class PerfectSquare {


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

int i = 1;
while (i < n) {
if (n % i == 0) {
sum += i;
}
i++;
}

if (sum == n) {
[Link](n + " is a perfect number."); //
Correct output message
} else {
[Link](n + " is not a perfect number."); //
Correct output message
}

[Link]();
}

9. Write a Java program to print Fibonacci series up to n terms using a for loop.
import [Link];

public class Fibonacci {


public static void main(String[] args) {
int n;

int t1 = 0, t2 = 1;

Scanner scanner = new Scanner([Link]);


[Link]("Enter the number of terms: ");
n = [Link]();

if (n >= 1) {
[Link]("Fibonacci Series: " + t1);
}
if (n >= 2) {
[Link](", " + t2);
}

for (int i = 3; i <= n; i++) {


int nextTerm = t1 + t2;
[Link](", " + nextTerm);

t1 = t2;
t2 = nextTerm;
}

[Link]();
[Link]();
}
}

10. Create a Java program that checks if a given string is a palindrome using a while loop.

import [Link];

public class PalindromeCheck {


public static void main(String[] args) {
int num, reversedNum = 0, originalNum;

Scanner scanner = new Scanner([Link]);


[Link]("Input a number: ");
num = [Link]();
originalNum = num;

while (num != 0) {
int remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}

if (originalNum == reversedNum) {
[Link](originalNum + " is a palindrome.");
} else {
[Link](originalNum + " is not a
palindrome.");
}

[Link]();
}
}

Common questions

Powered by AI

Loops in programming provide essential control structures for managing repetition and iteration, crucial in these computational tasks. The programs leverage different types of loops—while, do-while, and for loops—each selected for its operational suitability: while loops for indefinite iteration until a condition changes, do-while loops for ensuring at least one iteration, and for loops for bounded, counted iterations. Their effectiveness is judged by the clear handling of complex tasks with minimal code and logical structure, simplifying tasks such as series generation, factorial computation, and conditional checks while maintaining performance efficiency within typical input ranges .

A for loop is suitable for generating a Fibonacci series since it neatly manages the progression of terms through a bounded number of iterations, as defined by the desired number of Fibonacci numbers (n). Each iteration computes the next term by summing the last two terms, adjusting variables accordingly, and provides a straightforward iterative structure ideal for this type of sequence generation .

Conditional statements in the number reversal process handle validity and edge cases. Upon receiving the number, the program checks if it is non-zero to proceed; otherwise, it prompts the user to enter a valid number, as reversing zero is unconventional and would always yield zero. During the reversing process, no specific conditional statement checks are needed as each digit is methodically slotted into its new position .

It is necessary to check for a perfect number using a loop that calculates the sum of all divisors excluding the number itself. This verification procedure uses a while loop to iterate through possible divisors. If the sum of these divisors equals the number, it is declared a perfect number. Checking provides assurance against false positives and ensures only numbers that genuinely meet the criteria of being perfect are declared as such .

To determine if a number is a palindrome, the program reverses the number using a while loop. It extracts digits by obtaining the remainder when divided by 10 and constructs the reversed number by progressively building it in the reversed order. After completing the loop, it compares the original number to the reversed number; if they are equal, the number is a palindrome. This process efficiently checks for palindromes by verifying structural symmetry through numerical reversal .

The code determines if a user-inputted number is a prime by first eliminating all numbers less than or equal to 1, as they cannot be prime. It then handles the special case of 2, the smallest and only even prime number, by directly printing that it is prime. For numbers greater than 2, the code uses a for loop to attempt division of the number by all integers from 2 up to the number minus one. If the number is divisible by any of these integers, it is marked as not a prime; otherwise, it is classified as prime after exiting the loop without finding a divisor .

Using a do-while loop for generating a multiplication table requires careful initialization and loop condition management. The initial setup involves reading a number from the user and setting a multiplier starting value, usually 1. The do-while loop iterates to perform multiplication until a specified condition, such as reaching a multiplier of 10. A challenge lies in ensuring the loop terminates correctly after the final multiplication, which requires accurate condition formulation and ensuring that the loop body is executed at least once, thus leveraging the do-while loop's post-check nature .

The program uses a for loop to iterate through each number from 1 to 100, inclusive. Within each iteration, it applies a conditional check (count % 2 == 0) to determine if the current number is even. If the condition is satisfied, the number is added to a running total ('sum'). This process ensures that only even numbers are added, leading to a correct sum upon completion of the loop .

The program efficiently identifies numbers divisible by three by using a while loop that iterates through numbers from 1 to 50. At each iteration, it checks divisibility using the modulus operation (count % 3 == 0). If the condition holds true, it immediately prints the number. This direct approach with linear complexity (O(n), where n is the range length) effectively finds and displays all numbers up to 50, making it suitable for such a constrained range .

The document does not use a do-while loop for calculating the factorial; instead, a for loop is used. The for loop iterates from the given number down to 1, multiplying the current value of the loop variable to a running product, which accumulates the factorial result. This approach is straightforward for decremental looping and naturally fits the factorial computation's requirements .

You might also like