Exercise 2 Basic Java Programs
MOHAMED YOUSUFF (AP/CI/SCOPE, VIT)
Contents
1 Basic Java Programs – Part 2 1
1.1 Program 11: Displaying the Multiplication Table of a Number . . . . . . . . . . . . . 1
1.2 Program 12: Finding the Sum of the First n Natural Numbers . . . . . . . . . . . . . . 2
1.3 Program 13: Finding the Factorial of a Number . . . . . . . . . . . . . . . . . . . . . 3
1.4 Program 14: Finding the Sum of the Digits of a Number . . . . . . . . . . . . . . . . 5
1.5 Program 15: Reversing a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6 Program 16: Checking Whether a Number is a Palindrome . . . . . . . . . . . . . . . 8
1.7 Program 17: Checking Whether a Number is Prime . . . . . . . . . . . . . . . . . . . 9
1.8 Program 18: Generating the Fibonacci Series . . . . . . . . . . . . . . . . . . . . . . 11
1.9 Program 19: Checking Whether a Number is an Armstrong Number . . . . . . . . . . 13
1.10 Program 20: Reading and Displaying Array Elements . . . . . . . . . . . . . . . . . . 15
1.11 Program 21: Finding the Sum and Average of Array Elements . . . . . . . . . . . . . 17
1.12 Program 22: Finding the Largest Element in an Array . . . . . . . . . . . . . . . . . . 18
1.13 Program 23: Searching for an Element Using Linear Search . . . . . . . . . . . . . . . 20
1.14 Program 24: Finding the Square of a Number Using a Method . . . . . . . . . . . . . 22
1 BASIC JAVA PROGRAMS – PART 2
1 Basic Java Programs – Part 2
1.1 Program 11: Displaying the Multiplication Table of a Number
import [Link];
public class MultiplicationTable {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int number;
[Link]("Enter a number: ");
number = [Link]();
for (int i = 1; i <= 10; i++) {
[Link](
number + " x " + i + " = " + number * i
);
}
}
}
Sample Output
1 Enter a number : 5
2 5 x 1 = 5
3 5 x 2 = 10
4 5 x 3 = 15
5 5 x 4 = 20
6 5 x 5 = 25
1 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.2 Program 12: Finding the Sum of the First n Natural 1Numbers
BASIC JAVA PROGRAMS – PART 2
7 5 x 6 = 30
8 5 x 7 = 35
9 5 x 8 = 40
10 5 x 9 = 45
11 5 x 10 = 50
Explanation of Terms and Logic
Term or Statement Explanation
for A loop statement used to repeat a block of code for a fixed number
of times.
int i = 1 Initializes the loop-control variable i with the value 1.
i <= 10 The loop continues while the value of i is less than or equal to
10.
i++ Increments the value of i by 1 after every iteration.
number * i Calculates the product of the entered number and the current
value of i.
" x " A string used to present the multiplication operation in a readable
form.
1.2 Program 12: Finding the Sum of the First n Natural Numbers
import [Link];
public class SumNaturalNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n;
int sum = 0;
[Link]("Enter the value of n: ");
n = [Link]();
2 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.3 Program 13: Finding the Factorial of a Number 1 BASIC JAVA PROGRAMS – PART 2
for (int i = 1; i <= n; i++) {
sum = sum + i;
}
[Link](
"Sum of first " + n + " natural numbers = "
+ sum
);
}
}
Sample Output
1 Enter the value of n: 5
2 Sum of first 5 natural numbers = 15
Explanation of Terms and Logic
Term or Statement Explanation
int sum = 0 Declares an accumulator variable and initializes it to zero.
i <= n Repeats the loop until the loop variable reaches the entered value
of n.
sum = sum + i Adds the current value of i to the existing value of sum.
Accumulator A variable that continuously stores the updated result of an op-
eration.
1.3 Program 13: Finding the Factorial of a Number
import [Link];
3 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.3 Program 13: Finding the Factorial of a Number 1 BASIC JAVA PROGRAMS – PART 2
public class FactorialNumber {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int number;
long factorial = 1;
[Link]("Enter a non-negative
integer: ");
number = [Link]();
if (number < 0) {
[Link](
"Factorial is not defined for negative
numbers."
);
} else {
for (int i = 1; i <= number; i++) {
factorial = factorial * i;
}
[Link](
"Factorial of " + number + " = " +
factorial
);
}
}
}
4 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.4 Program 14: Finding the Sum of the Digits of a Number
1 BASIC JAVA PROGRAMS – PART 2
Sample Output
1 Enter a non - negative integer : 5
2 Factorial of 5 = 120
Explanation of Terms and Logic
Term or Statement Explanation
Factorial The product of all positive integers from 1 to a given non-negative
integer.
long An integer data type capable of storing values larger than those
stored by the int data type.
long factorial = 1 Initializes the factorial variable with 1 because multiplication
with zero would always produce zero.
number < 0 Checks whether the entered number is negative.
factorial = Multiplies the current factorial value by the loop variable during
factorial * i each iteration.
1.4 Program 14: Finding the Sum of the Digits of a Number
import [Link];
public class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int number;
int digit;
int sum = 0;
[Link]("Enter a positive integer:
");
number = [Link]();
5 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.5 Program 15: Reversing a Number 1 BASIC JAVA PROGRAMS – PART 2
while (number != 0) {
digit = number % 10;
sum += digit;
number /= 10;
}
[Link]("Sum of digits = " + sum);
}
}
Sample Output
1 Enter a positive integer : 583
2 Sum of digits = 16
Explanation of Terms and Logic
Term or Statement Explanation
while A loop statement that repeatedly executes a block as long as the
specified condition remains true.
number != 0 Checks whether the number still contains digits to be processed.
digit = number % 10 Extracts the last digit of the number.
sum += digit A compound assignment equivalent to sum = sum + digit.
number /= 10 Removes the last digit. It is equivalent to number = number /
10.
1.5 Program 15: Reversing a Number
import [Link];
public class ReverseNumber {
6 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.5 Program 15: Reversing a Number 1 BASIC JAVA PROGRAMS – PART 2
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int number;
int digit;
int reverse = 0;
[Link]("Enter an integer: ");
number = [Link]();
while (number != 0) {
digit = number % 10;
reverse = reverse * 10 + digit;
number /= 10;
}
[Link]("Reversed number = " +
reverse);
}
}
Sample Output
1 Enter an integer : 4826
2 Reversed number = 6284
Explanation of Terms and Logic
Term or Statement Explanation
7 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.6 Program 16: Checking Whether a Number is a Palindrome
1 BASIC JAVA PROGRAMS – PART 2
reverse A variable used to construct and store the reversed number.
reverse * 10 Shifts the existing digits of the reversed number one place to-
wards the left.
reverse * 10 + digit Appends the extracted digit to the end of the reversed number.
1.6 Program 16: Checking Whether a Number is a Palindrome
import [Link];
public class PalindromeNumber {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int number;
int originalNumber;
int digit;
int reverse = 0;
[Link]("Enter an integer: ");
number = [Link]();
originalNumber = number;
while (number != 0) {
digit = number % 10;
reverse = reverse * 10 + digit;
number /= 10;
}
if (originalNumber == reverse) {
8 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.7 Program 17: Checking Whether a Number is Prime 1 BASIC JAVA PROGRAMS – PART 2
[Link]("Palindrome Number");
} else {
[Link]("Not a Palindrome
Number");
}
}
}
Sample Output
1 Enter an integer : 1221
2 Palindrome Number
Explanation of Terms and Logic
Term or Statement Explanation
Palindrome number A number that remains the same when its digits are written in
reverse order.
originalNumber Stores the original input because the value of number changes
during the reversal process.
originalNumber == Compares the original number with its reversed form.
reverse
1.7 Program 17: Checking Whether a Number is Prime
import [Link];
public class PrimeNumber {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
9 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.7 Program 17: Checking Whether a Number is Prime 1 BASIC JAVA PROGRAMS – PART 2
int number;
boolean isPrime = true;
[Link]("Enter an integer: ");
number = [Link]();
if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
[Link](number + " is a prime
number.");
} else {
[Link](number + " is not a prime
number.");
}
}
}
Sample Output
10 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.8 Program 18: Generating the Fibonacci Series 1 BASIC JAVA PROGRAMS – PART 2
1 Enter an integer : 17
2 17 is a prime number .
Explanation of Terms and Logic
Term or Statement Explanation
Prime number A positive integer greater than 1 that has exactly two factors: 1
and the number itself.
boolean A data type that stores either true or false.
isPrime A Boolean variable used to represent whether the entered number
is prime.
number <= 1 Identifies numbers that cannot be classified as prime.
i <= number / 2 Checks possible divisors from 2 up to half of the entered number.
number % i == 0 Determines whether i is an exact divisor of the number.
break Immediately terminates the nearest loop when a divisor is found.
if (isPrime) Executes the block when the Boolean variable contains the value
true.
1.8 Program 18: Generating the Fibonacci Series
import [Link];
public class FibonacciSeries {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int terms;
int first = 0;
int second = 1;
int next;
[Link]("Enter the number of terms: ");
11 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.8 Program 18: Generating the Fibonacci Series 1 BASIC JAVA PROGRAMS – PART 2
terms = [Link]();
[Link]("Fibonacci series: ");
for (int i = 1; i <= terms; i++) {
[Link](first + " ");
next = first + second;
first = second;
second = next;
}
}
}
Sample Output
1 Enter the number of terms: 8
2 Fibonacci series : 0 1 1 2 3 5 8 13
Explanation of Terms and Logic
Term or Statement Explanation
Fibonacci series A sequence in which each term is obtained by adding the two
preceding terms.
first Stores the current term of the Fibonacci series.
second Stores the term that follows the current term.
next Stores the sum of first and second.
next = first + Calculates the next term in the series.
second
first = second Moves the second value into the position of the first value.
second = next Updates the second value with the newly calculated term.
12 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.9 Program 19: Checking Whether a Number is an Armstrong
1 BASICNumber
JAVA PROGRAMS – PART 2
1.9 Program 19: Checking Whether a Number is an Armstrong Number
import [Link];
public class ArmstrongNumber {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int number;
int originalNumber;
int temporaryNumber;
int digit;
int numberOfDigits = 0;
int sum = 0;
[Link]("Enter a non-negative integer:
");
number = [Link]();
originalNumber = number;
temporaryNumber = number;
if (temporaryNumber == 0) {
numberOfDigits = 1;
}
while (temporaryNumber != 0) {
numberOfDigits++;
temporaryNumber /= 10;
13 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.9 Program 19: Checking Whether a Number is an Armstrong
1 BASICNumber
JAVA PROGRAMS – PART 2
temporaryNumber = number;
while (temporaryNumber != 0) {
digit = temporaryNumber % 10;
sum += (int) [Link](digit, numberOfDigits);
temporaryNumber /= 10;
}
if (sum == originalNumber) {
[Link]("Armstrong Number");
} else {
[Link]("Not an Armstrong
Number");
}
}
}
Sample Output
1 Enter a non - negative integer : 153
2 Armstrong Number
Explanation of Terms and Logic
Term or Statement Explanation
Armstrong number A number equal to the sum of its digits, with each digit raised to
the power of the total number of digits.
temporaryNumber Stores a copy of the number for digit counting and digit extrac-
tion.
14 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.10 Program 20: Reading and Displaying Array Elements
1 BASIC JAVA PROGRAMS – PART 2
numberOfDigits Stores the total number of digits in the entered number.
Math A predefined Java class containing mathematical methods.
[Link](a, b) Calculates a raised to the power b.
(int) An explicit type cast that converts the result returned by
[Link]() into an integer.
sum += (int) Adds the powered value of each digit to sum.
[Link](...)
1.10 Program 20: Reading and Displaying Array Elements
import [Link];
public class ArrayInputOutput {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int size;
[Link]("Enter the size of the array:
");
size = [Link]();
int[] numbers = new int[size];
[Link]("Enter the array elements:");
for (int i = 0; i < size; i++) {
numbers[i] = [Link]();
}
[Link]("Array elements are:");
15 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.10 Program 20: Reading and Displaying Array Elements
1 BASIC JAVA PROGRAMS – PART 2
for (int i = 0; i < size; i++) {
[Link](numbers[i] + " ");
}
}
}
Sample Output
1 Enter the size of the array: 5
2 Enter the array elements :
3 10
4 20
5 30
6 40
7 50
8 Array elements are:
9 10 20 30 40 50
Explanation of Terms and Logic
Term or Statement Explanation
Array A collection used to store multiple values of the same data type
under a single variable name.
int[] Declares an array capable of storing integer values.
numbers The name assigned to the integer array.
new int[size] Creates an integer array containing the specified number of ele-
ments.
i = 0 Starts array access from index zero because Java array indexing
begins at zero.
i < size Prevents access beyond the valid range of the array.
numbers[i] Refers to the array element located at index i.
16 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.11 Program 21: Finding the Sum and Average of Array1 Elements
BASIC JAVA PROGRAMS – PART 2
1.11 Program 21: Finding the Sum and Average of Array Elements
import [Link];
public class ArraySumAverage {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int size;
int sum = 0;
double average;
[Link]("Enter the size of the array:
");
size = [Link]();
int[] numbers = new int[size];
[Link]("Enter the array elements:");
for (int i = 0; i < size; i++) {
numbers[i] = [Link]();
sum += numbers[i];
}
average = (double) sum / size;
[Link]("Sum = " + sum);
[Link]("Average = " + average);
17 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.12 Program 22: Finding the Largest Element in an Array
1 BASIC JAVA PROGRAMS – PART 2
}
}
Sample Output
1 Enter the size of the array: 5
2 Enter the array elements :
3 10
4 20
5 30
6 40
7 50
8 Sum = 150
9 Average = 30.0
Explanation of Terms and Logic
Term or Statement Explanation
sum += numbers[i] Adds each array element to the cumulative sum.
average A variable used to store the arithmetic mean of the array ele-
ments.
(double) sum Converts the integer value of sum into a decimal value before
division.
(double) sum / size Performs floating-point division and produces a decimal average.
1.12 Program 22: Finding the Largest Element in an Array
import [Link];
public class LargestArrayElement {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
18 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.12 Program 22: Finding the Largest Element in an Array
1 BASIC JAVA PROGRAMS – PART 2
int size;
[Link]("Enter the size of the array:
");
size = [Link]();
int[] numbers = new int[size];
[Link]("Enter the array elements:");
for (int i = 0; i < size; i++) {
numbers[i] = [Link]();
}
int largest = numbers[0];
for (int i = 1; i < size; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
[Link]("Largest element = " +
largest);
}
}
Sample Output
19 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.13 Program 23: Searching for an Element Using Linear
1 Search
BASIC JAVA PROGRAMS – PART 2
1 Enter the size of the array: 5
2 Enter the array elements :
3 18
4 42
5 11
6 75
7 36
8 Largest element = 75
Explanation of Terms and Logic
Term or Statement Explanation
int largest = Assumes the first array element as the largest initial value.
numbers[0]
int i = 1 Begins comparison from the second array element because the
first element has already been assigned to largest.
numbers[i] > largest Checks whether the current array element is greater than the
stored largest value.
largest = numbers[i] Updates the largest value when a greater element is found.
1.13 Program 23: Searching for an Element Using Linear Search
import [Link];
public class LinearSearch {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int size;
int searchElement;
int position = -1;
20 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.13 Program 23: Searching for an Element Using Linear
1 Search
BASIC JAVA PROGRAMS – PART 2
[Link]("Enter the size of the array:
");
size = [Link]();
int[] numbers = new int[size];
[Link]("Enter the array elements:");
for (int i = 0; i < size; i++) {
numbers[i] = [Link]();
}
[Link]("Enter the element to search:
");
searchElement = [Link]();
for (int i = 0; i < size; i++) {
if (numbers[i] == searchElement) {
position = i;
break;
}
}
if (position != -1) {
[Link](
"Element found at position " + (position + 1)
);
} else {
[Link]("Element not found.");
21 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.14 Program 24: Finding the Square of a Number Using
1 a BASIC
MethodJAVA PROGRAMS – PART 2
}
}
}
Sample Output
1 Enter the size of the array: 5
2 Enter the array elements :
3 12
4 25
5 38
6 47
7 59
8 Enter the element to search : 38
9 Element found at position 3
Explanation of Terms and Logic
Term or Statement Explanation
Linear search A searching method that examines array elements sequentially
from the beginning.
searchElement Stores the value that must be located in the array.
position = -1 Uses −1 as an initial value to indicate that the element has not
yet been found.
numbers[i] == Compares the current array element with the required element.
searchElement
position = i Stores the array index at which the element is found.
position != -1 Confirms that a matching element was found.
position + 1 Converts the zero-based array index into a human-readable po-
sition beginning from 1.
1.14 Program 24: Finding the Square of a Number Using a Method
import [Link];
22 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.14 Program 24: Finding the Square of a Number Using
1 a BASIC
MethodJAVA PROGRAMS – PART 2
public class SquareUsingMethod {
public static int findSquare(int number) {
int result = number * number;
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int number;
int square;
[Link]("Enter an integer: ");
number = [Link]();
square = findSquare(number);
[Link]("Square = " + square);
}
}
Sample Output
1 Enter an integer : 8
2 Square = 64
Explanation of Terms and Logic
23 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)
1.14 Program 24: Finding the Square of a Number Using
1 a BASIC
MethodJAVA PROGRAMS – PART 2
Term or Statement Explanation
Method A named block of code designed to perform a particular opera-
tion.
findSquare The user-defined method name used to calculate the square of a
number.
int findSquare(...) Indicates that the method returns an integer value.
int number A formal parameter that receives the value passed during the
method call.
return result Sends the calculated value back to the statement that called the
method.
findSquare(number) Calls the method and passes the entered number as an argument.
square = Stores the value returned by the method in the variable square.
findSquare(number)
“‘
24 Dr. Mohamed Yousuff (AP/CI/SCOPE, VIT)