Pages

Program to find Smallest and Biggest Number with it's position in C

In this example we track the smallest and biggest number in an array with it's position. The main logic behind it is first we consider the first element as small and big number in the array, then we compare it with each successive element of the array. If we found smaller or greater than the current number than we copy the number and position to the current number and position.

Source Code:
// program to find smallest & biggest no with its position for given N numbers
#include <stdio.h>
#include <conio.h>

int main()

{
    int i, n, smallest = 0, biggest = 0, smallpos = 0, bigpos = 0;
    int arrNum[100];  // no of integers that can be entered
    printf("Program to find Smallest & Biggest number with Position");
    printf("\n--------------------------------------------------------\n");
      // prompt how many no. that can be entered
    printf("Enter the total numbers:");
    scanf("%d", &n);

    // check for the size of array
    if(n < 1 || n > 100)
    {
       
         printf("Error: Enter a number between 1 - 100 !");
        scanf("%d", &n);
    }
    //accept input
    for ( i = 0; i < n; i++)
    {
        printf("\n Enter No [%d]: ", i+1);
        scanf("%d", &arrNum[i]);
    }
    // assume the position an number
    smallest = biggest = arrNum[0];
    smallpos = bigpos = 0; // declare pos of the small n big no.
 
    for(i = 0; i < n; i++) // check each integer with the 1st no
    {
         //find smallest than current number
         if (smallest > arrNum[i])
          {
                       smallpos = i;
                       smallest = arrNum[i];
          }
          //find greater than current number
          if (biggest < arrNum[i])
          {
                      bigpos = i;
                      biggest = arrNum[i];
          }
    }

    printf("\nNumber List: ");
    for(i = 0; i < n; i++)
        printf("%d \t", arrNum[i]);

    printf("\nSmallest Number: %d \t Position: %d", smallest, smallpos+1);
    printf("\nBiggest Number: %d \t Position: %d", biggest, bigpos+1);
 
    getch();
    return 0;
}      


Output:      

@msucil

Phasellus facilisis convallis metus, ut imperdiet augue auctor nec. Duis at velit id augue lobortis porta. Sed varius, enim accumsan aliquam tincidunt, tortor urna vulputate quam, eget finibus urna est in augue.

No comments:

Post a Comment