Select Page

Find out the Second Highest number from  an array

C Program to Find out the Second Highest number in an array-In this topic we will explain that procedure of finding the second Highest number using  loops. Firstly, we will use two for loop one is outer for loop which is responsible for row and the second one is inner for loop which is responsible for the column.

The following program source code  is implemented using three unique manner

  • For Loop
  • While Loop
  • Do..While Loop

Follow the Algorithm

Step 1: Declare four variable size, r, c, temp and an array named A[10].

step 2: The size of array and element of an array will given by the user as long as r<size.

step 3: initialize r=0 and  enter the element  till the end of size-1

step 4: outer loop:

            r=0

step 5:  loop will be performed as long as  r<size

step 6: inner loop:

              c=r+1

step 7: loop will perform as long as  r<size

step 7.1: check if (A[r]<A[c]) is true then 

                      temp = A[r];
                     A[r] = A[c];
                     A[c] = temp;        

step 8: j=j+1

step 9: End inner loop

step 10: i=i+1

step 11: End of outer loop

step 12: print the second smallest number using A[1]

 

Source Code using For Loop

int main ()
{
    int A[10], size, r, c, temp;
    printf("Enter the size of an array : ");
    scanf("%d",&size);
    printf("Enter elements of array : ");
    for (r = 0; r < size; r++)
        scanf("%d",&A[r]);
    for (r = 0; r<size; r++)
    {
        for (c = r + 1; c < size; c++)
        {
            if (A[r] < A[c])
            {
                temp = A[r];
                A[r] = A[c];
                A[c] = temp;
            }
        }
    }
    printf("Second Highest number :%d",A[1]);
    return 0;
}

output

Source Code using While Loop

int main ()
{
 int A[10], size, r, c, temp;
 printf("\\n\\tEnter the size of an array : ");
 scanf("%d",&size);
 printf("\\tEnter elements of array : ");
 r=0;
  while( r< size )
  {
    scanf("%d",&A[r]);
r++; } r=0; while( r<size ) { c=r+1; while( c<size) { if (A[r] < A[c]) { temp = A[r]; A[r] = A[c]; A[c] = temp; } c++; } r++; } printf("\\n\\tSecond Highest number :%d \\n\\n",A[1]); return 0; }

Output after using While loop

Source Code using do..While Loop

int main ()
{
 int A[10], size, r, c, temp;
 printf("\\n\\tEnter the size of an array : ");
 scanf("%d",&size);
 printf("\\tEnter elements of array : ");
 r=0;
  do
  {
    scanf("%d",&A[r]);
r++; }while( r< size ); r=0;
do
{
c=r+1;
do
{
if (A[r] < A[c])
{
temp = A[r];
A[r] = A[c];
A[c] = temp;
}
c++;
} while( c<size );
r++;
} while( r<size);
printf("\\n\\tSecond Highest number :%d \\n\\n",A[1]); return 0; }

Output after using do..While loop