find largest and smallest number using array and its position.
Answers
public class LargestSmallest
{
public static void main(String[] args)
{
int a[] = new int[] { 23, 34, 13, 64, 72, 90, 10, 15, 9, 27 };
int min = a[0]; // assume first elements as smallest number
int max = a[0]; // assume first elements as largest number
for (int i = 1; i < a.length; i++) // iterate for loop from arrays 1st index (second element)
{
if (a[i] > max)
{
max = a[i];
}
if (a[i] < min)
{
min = a[i];
}
}
System.out.println("Largest Number in a given array is : " + max);
System.out.println("Smallest Number in a given array is : " + min);
}
}
Output:
Largest Number in a given array is : 90
Smallest Number in a given array is : 9
Related example
Java program to find largest number in an array
Java program to find second largest number in an array
Java program to find largest and smallest number in an array
Java program to find largest and second largest number in an array
Java program to find second smallest number in an array
Java program to find index of max value in array java
Java program to find index of smallest element in array java
Related Post
Comments
Yamini Chinni
Good it is very easy to understand
yaminkumar
Nice there are very used on .
Nishant Kumar
NNNNNNNNNNNNNNNice there are very used onnnnnnnnnnnnnn
Name
Post your comment here
java training in chennai
Answer:
#include<iostream>
using namespace std;
int main(){
int n, sum=0;
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
while(sum<n-1){
for(int i=0; i<n-1; i++){
if(arr[i]>arr[i+1]){
int temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
sum++;
}
cout<<"the largest element of the given array is "<<arr[n-1]<<endl;
cout<<"the samllest element of the given array is "<<arr[0]<<endl;
return 0;
}
Step-by-step explanation:
easy c++ solution for this question.