Write a java program to store n numbers an array and find the smallest number among them (using array )
anger
Certainly! Here's a Java program that allows you to store `n` numbers in an array and find the smallest number among them:
```java
import java.util.Scanner;
public class SmallestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] numbers = new int[n];
System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
int smallest = numbers[0];
for (int i = 1; i < n; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
System.out.println("The smallest number is: " + smallest);
}
}
```
To explain how this program works:
1. First, we import the `Scanner` class from the `java.util` package so that we can read input from the user.
2. We create a `Scanner` object to read the user's input.
3. We prompt the user to enter the number of elements (i.e., the size of the array) and store it in the variable `n`.
4. We create an integer array `numbers` of size `n` to store the user's input.
5. We then loop `n` times to read the numbers from the user and store them in the `numbers` array.
6. Next, we initialize the `smallest` variable with the first element of the array (`numbers[0]`).
7. We then loop over the remaining elements of the array (`numbers[1]` to `numbers[n-1]`) and compare each element with the current value of `smallest`. If an element is smaller than `smallest`, we update `smallest` to hold that value.
8. Finally, we print the value of `smallest`, which represents the smallest number in the array.
That's it! By running this program, you can store `n` numbers in an array and find the smallest number among them.