Select Page

 C Program to Find out the Second smallest number in an array-In this topic we will explain that procedure of finding the second smallest element using for loop. 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 is written in three unique manners:

  • 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[size-2]

 

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("\nSecond smallest number :%d ",A[size - 2]);
return 0;
}

 

OUTPUT

Using While 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 : ");
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("\nSecond smallest number :%d ",A[size - 2]);
return 0;
}

 

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 smallest number :%d\n\n ",A[size - 2]);
return 0;
}