C Program to Find Max and Min Using Pointers

The C program find the MAX and MIN using pointers in an array of integers is written using Dev-C++ version 4.9.9.2 installed on a 64-bit windows 7 operating system. The program receives an array of numbers as input and find the minimum number and a maximum number using pointers.

This program is intended for intermediate level learners familiar with the concept of pointers. If you are not familiar with pointer concepts, visit the link below to learn about pointers with example.

C Programming Tutorial – Pointers

You can also learn about implementing linear search and binary search algorithms, it will strengthen your concepts.

Learn implementation of Linear Search and Binary Search

Problem Definition

We want to write a program to find the MAX and MIN using pointers in an array of numbers. The program accept 10 numbers from user and store them in an array of integers.

We then use two pointers to locate the maximum and the minimum of the array. The pointer traverse through all the values of the array and compares it with value of max which is 0 at the beginning.

If the number in array greater than max current value, then make the new number as new max value, otherwise keep looking for another max. The same logic applies to minimum of array.

Flowchart – Find Max and Min using Pointers

To understand the logic of the program see the flowchart given below.

Flowchart - C Program to Find Max and Min using Pointers
Flowchart – C Program to Find Max and Min using Pointers

Program Source Code – Find MAX and MIN using Pointers

#include <stdio.h>

#include <stdlib.h>

int main()

{

    int i,j,temp,tempmin, max,min;

    max = temp = tempmin = 0;

    int arr[10];

    min = arr[0];

    printf("Enter number upto 10 numbern");

    for(i=0;i<=10;i++)

    {

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

    }

    int *ptr1, *ptr2;

    ptr1 = arr;

    ptr2 = arr;

    for(i=1;i<=10;i++)

    {

        if(max <= *ptr1)

        {

            temp = max;

            max = *ptr1;

            *ptr1 = temp;

        }

    ptr1++;

    }

    printf("MAX=%d\n",max);

// finding minimum

    for(j=1;j<=10;j++)

    {

        if(min >= *ptr2)

        {

            tempmin = *ptr2;

            *ptr2 = min;

            min = tempmin;

        }

        ptr2++;

    }

        printf("MIN=%d\n",min);

system("PAUSE");

return 0;

}

Output – Find MAX and MIN using Pointers

The output of the program is given below. The array stores the 10 numbers and MAX and MIN is found using pointers. The MAX value in example is 87 and MIN value is 5 after the program completes.

Output - C Program to Find Max and Min using Pointers
Output – C Program to Find Max and Min using Pointers
Advertisements