#include <stdio.h>
int main() {
int arr[50], n, i, j, temp;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(i=0; i<n; i++) {
scanf("%d", &arr[i]);
}
// Sort the array in ascending order
for(i=0; i<n; i++) {
for(j=i+1; j<n; j++) {
if(arr[i]>arr[j]) {
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
// Find the second smallest element
for(i=0; i<n; i++) {
if(arr[i] != arr[0]) {
printf("The second smallest element is: %d\n", arr[i]);
break;
}
}
return 0;
}
In this program, we first ask the user to input the number of elements in the array and then we take the input of the elements. We then sort the array in ascending order using a simple bubble sort algorithm. Finally, we find the second smallest element by looping through the array and checking for the element which is not equal to the first element of the array (which is the smallest element).
Note: This program assumes that there are at least two distinct elements in the array. If all elements are the same, it will output an incorrect result.
Given below is a sample program to find the second smallest number in an array.
#include <stdio.h>
int main()
{
int arr[] = {4, 2, 1, 5, 3};
int n = 5;
int smallest = arr[0]; //Stores first element in smallest
int second_smallest = arr[0]; //Stores first element in second smallest
for (int i = 1; i < n; i++) {
if (arr[i] < smallest) {
second_smallest = smallest;
smallest = arr[i];
}
else if (arr[i] < second_smallest && arr[i] != smallest) {
second_smallest = arr[i];
}
}
printf("The second smallest element in the array is: %d", second_smallest);
return 0;
}
#OUTPUT - The second smallest element in the array is: 2
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In this program, we first ask the user to input the number of elements in the array and then we take the input of the elements. We then sort the array in ascending order using a simple bubble sort algorithm. Finally, we find the second smallest element by looping through the array and checking for the element which is not equal to the first element of the array (which is the smallest element).
Note: This program assumes that there are at least two distinct elements in the array. If all elements are the same, it will output an incorrect result.
Given below is a sample program to find the second smallest number in an array.