# Write Program to find smallest and largest element in an array

28 September 2022

Write Program to find smallest and largest element in an array

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

# Description

Get an array as input from the user and then find the smallest and largest element in the array.

Input

Enter the size of array: 5

Enter the elements:  10 20 5 40 30

Output

Smallest Number: 5

Largest Number: 40

C Program

#include<stdio.h>

void check(int arr[], int n)

{

int small, large;

small = large = arr[0];

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

if(arr[i] < small) small = arr[i];

if(arr[i] > large)

large = arr[i];

}

printf("Smallest Number: %d\n",small);

printf("Largest Number: %d", large);

}

int main()

{

int n;

printf("Enter the size of array: ");

scanf("%d",&n);

int arr[n];

printf("Enter the elements of array: ");

for(int i=0;i<n;i++)

scanf("%d",&arr[i]);

check(arr, n);

return 0;

}

C++ Program

#include<iostream>

using namespace std;

void check(int arr[], int n)

{

int small, large;

small = large = arr[0];

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

if(arr[i] < small) small = arr[i];

if(arr[i] > large)

large = arr[i];

}

cout<<"Smallest Number: "<<small<<"\n";

cout<<"Largest Number: "<<large<<"\n";

}

int main()

{

int n;

cout<<"Enter the size of array: ";

cin>>n;

int arr[n];

cout<<"Enter the elements of array: ";

for(int i=0;i<n;i++)

cin>>arr[i];

check(arr, n);

return 0;

}

Java Program

import java.util.Scanner;

public class Main

{

public static void main(String args[])

{

int n;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the size of the array: ");

n = sc.nextInt();

int[]arr = new int[n];

System.out.println("Enter the array elements: ");

for(int i = 0; i < n; i++)

{

arr[i] = sc.nextInt();

}

int large = arr[0], small=arr[0];

for(int i=0; i<arr.length; i++)

{

if(small > arr[i])

small = arr[i];

if(large < arr[i])

large = arr[i];

}

System.out.println("Smallest Number: "+small);

System.out.println("Largest Number: "+large);

}

}

Python Program

n = int(input("Enter size of array: "))

arr = []

print("Enter array elements: ")

for i in range(0,n):

temp = int(input())

arr.append(temp)

small = arr[0]

large = arr[0]

for i in range(len(arr)):

if arr[i] < small:

small = arr[i]

if arr[i] > large:

large = arr[i]

print ("Smallest Number: ",small)

print ("Largest Number: ",large)

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023