Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Find Smallest Element in Java

Find Smallest Element in Java

Sure! Here's how you can find the smallest element in an array in Java:


Java Program to Find the Smallest Element in an Array

import java.util.Scanner;public class SmallestElement {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        System.out.print("Enter the number of elements: ");        int n = scanner.nextInt();  // Size of array        int[] numbers = new int[n];        System.out.println("Enter " + n + " numbers:");        // Input array elements        for (int i = 0; i < n; i++) {            numbers[i] = scanner.nextInt();        }        int smallest = numbers[0];  // Assume first element is the smallest        // Check for the smallest element        for (int i = 1; i < n; i++) {            if (numbers[i] < smallest) {                smallest = numbers[i];            }        }        System.out.println("Smallest element is: " + smallest);        scanner.close();    }}

Explanation:

  • Assume the first element is the smallest.

  • Compare it with every other element.

  • Update smallest whenever a smaller number is found.


Sample Output:

Enter the number of elements: 5Enter 5 numbers:72941Smallest element is: 1

Would you also like me to show a version where we sort the array first and then pick the smallest? ?
(That's another smart way!) ?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql