Five basic problem solving with solution in java
Q1:Find the maximum element in an array.
public class Test2 {
public static int findMaxElement(int[] arr) {
if (arr.length == 0) {
System.out.println("Array is empty.");
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
public static int findMinElement(int[] arr) {
if (arr.length == 0) {
System.out.println("Array is empty.");
}
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
public static void main(String[] args) {
int[] arr = {5, 8, 2, 10, 3,34,5,20,1};
int maxElement = findMaxElement(arr);
int minElement = findMinElement(arr);
System.out.println("Maximum element in the array: " + maxElement);
System.out.println("Minimum element in the array: " + minElement);
}
}
Output:
Maximum element in the array: 34
Minimum element in the array: 1
Q2: Calculate the sum of all elements in an array.
public class Test2 {
public static int calculateSum(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
public static void main(String[] args) {
int[] arr = {5, 8, 2, 10, 3,34,5,20,1};
int total = calculateSum(arr);
System.out.println("sum elements in the array: " + total);
}
}
Output:
sum elements in the array: 88
Q3: Print the first N numbers in the Fibonacci series.
public class Test2 {
public static void printFibonacciSeries(int n) {
int[] fibSeries = new int[n];
fibSeries[0] = 0;
fibSeries[1] = 1;
for (int i = 2; i < n; i++) {
fibSeries[i] = fibSeries[i - 1] + fibSeries[i - 2];
}
System.out.println("Fibonacci series:");
for (int i = 0; i < n; i++) {
System.out.print(fibSeries[i] + " ");
}
}
public static void main(String[] args) {
int n = 10;
printFibonacciSeries(n);
}
}
Output:
Fibonacci series:
0 1 1 2 3 5 8 13 21 34
Q4: Calculate the factorial of a given number.
public class Test2 {
public static int calculateFactorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Number cannot be negative.");
}
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
return factorial;
}
public static void main(String[] args) {
int n = 5;
int factorial = calculateFactorial(n);
System.out.println("Factorial of " + n + ": " + factorial);
}
}
Output:
Factorial of 5: 120
Q5: Print a pattern of stars.
public class Test2 {
public static void printPattern(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
public static void main(String[] args) {
int n = 5;
printPattern(n);
}
}
Output:
*
**
***
****
*****
Channel: @java_tuorial0101 By: Abdulbari AL-Mamari