Second smallest element in array (C Programming)
The following program I scribbled, for finding the second smallest number in an integer array in C program.
The logic? Simple and childish !!!
The c program:
The logic? Simple and childish !!!
- Get the length
- Get the array contents
- Find the smallest number in the array with a for loop
- Again loop through the elements to find number which is smaller than the rest of the elements but greater than the smallest element you just found.
- There !! you found the second smallest number !!!
The c program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include<stdio.h> int main() { int xArray[10]; int Length; int smallInt; int i,j,l; int xSecodSmall; printf("Enter the number of elements min(1) max(2):\t"); Length=11; scanf("%d",&Length); while (Length > 10 | Length < 2) { printf("\nEnter a number within 2 and 10:\t"); scanf("%d",&Length); } for (i = 0; i < Length; i++) { printf("\nNumber %d\t",(i+1)); scanf("%d",&xArray[i]); } smallInt = xArray[0]; for (j = 0; j < Length; j++) { if (smallInt > xArray[j]) { smallInt = xArray[j]; } } printf("\nSmallest integer: %d",smallInt); xSecodSmall = xArray[0]; for (l = 0; l < Length; l++) { if (xArray[l] < xSecodSmall & xArray [l] > smallInt) { xSecodSmall = xArray[l]; } else if(xArray[l] == xSecodSmall & l == 0 ) { xSecodSmall = xArray[1]; } } printf("\nSecond smallest integer: %d",xSecodSmall); return 0; } |
Comments
Post a Comment