2. Minimum and Maximum.

 2. Find the Minimum and Maximum element of the Array. 


Problem link :- Minimum and Maximum element of the Array.
        We are going to solve all this problems using functions. And in C and C++ we cannot return more than one variable from a function. So I have called function by reference(call by reference / call by address).
        But geeks for geeks used structure to return 2 variables simultaneously (indirect).


C code

//Find the maximum element in an array
#include<stdio.h>

void min_max(int arr[], int *min, int *max, int n)
{
    int i;

    if(n == 1)
    {
        *min = arr[0];
        *max = arr[0];
    }
    if(arr[0] < arr[1])
    {
        *min = arr[0];
        *max = arr[1];
    }
    else
    {
        *min = arr[1];
        *max = arr[0];
    }
    for(i=2; i<n; i++)
    {
        if(arr[i] > *max)
            *max = arr[i];
        else if(arr[i] < *min)
            *min = arr[i];
    }
}

void main()
{
    int arr1[30];
    int n;
    int i;
    int max, min;

    printf("Enter the size of the array\n");
    scanf("%d",&n);
    printf("Enter the elements of the array\n");
    for(i=0; i<n; i++)
        scanf("%d",&arr1[i]);

    min_max(arr1, &min, &max, n);

    printf("\n\nMaximum element : %d\n",max);
    printf("Minimum element : %d\n\n",min);
}

Java code

//Max and Min
package programs;

import java.util.*;

public class Array__2
{

	static class pair
	{
		int min;
		int max;
	}
	
	static void print_array(int arr[], int n)
	{
		int i;
		for(i=0; i<n; i++)
			System.out.print(arr[i] + " ");
	}
	
	static pair get_minmax(int arr[], int n)
	{
		pair minmax = new pair();
		
		if(n == 1){
			minmax.min = arr[0];
			minmax.max = arr[0];
			return minmax;
		}
		if(arr[0] > arr[1]){
			minmax.min = arr[1];
			minmax.max = arr[0];
		}else{
			minmax.min = arr[0];
			minmax.max = arr[1];
		}
		
		for(int i=2; i<n; i++)
		{
			if(arr[i] > minmax.max )
				minmax.max = arr[i];
			if(arr[i] < minmax.min)
				minmax.min = arr[i];
		}
		return minmax;
	}
	
	public static void main(String[] args)
	{
		int array[] = new int[30];
		int n, i;
		pair ans = new pair();
		
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the size of the array :");
		n = s.nextInt();
		
		System.out.println("Enter the elements of the array :");
		for(i=0; i<n; i++)
			array[i] = s.nextInt();
		System.out.println("Given Array :");
		print_array(array, n);
		
		ans = get_minmax(array, n);
		System.out.println("\nMinimum : " + ans.min + "\nMaximum : " + ans.max);
	}

}

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree