Write a program find out smallest elements in this array number or index in c
Finding the smallest element in an array means determining the element in the array with the smallest value. This is a common operation in programming, especially when working with numerical data.
Program 01:smallest elements in this array number or index in c
#include
int main()
{
int a[5],ele,i,s,pos;
ele=sizeof(a)/sizeof(a[0]);
printf("sizeof the array is:%d\n",ele);
printf("enter an array elements:");
for(i=0;i<ele;i++)
scanf("%d",&a[i]);
printf("the array are:");
for(i=0;i<ele;i++)
printf(" %d",a[i]);
printf("\n");
s=a[0];// 10 20 30 40 50
for(i=1,pos;i<ele;i++)
if(a[i]<s)// 20>10
{
s=a[i];
pos++;
}
printf("The Smallest elemnts is:%d and That position:%d\n",s,pos);
}
Output:
size of the array is: 5
Enter an array elements: 50 20 10 30 40
The array is: 50 20 10 30 40
The Smallest element is: 10 and That position: 2
Program 02: Smallest elements in this array number or index in the c programming language
Here's an example program in C that finds the smallest element in an array, along with its index:
#include <stdio.h>
int main() {
int arr[] = {3, 5, 1, 7, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int min = arr[0];
int min_index = 0;
for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
min_index = i;
}
}
printf("The smallest element is %d at index %d\n", min, min_index);
return 0;
}
In this program, we first declare an integer array arr with 5 elements. We then calculate the length of the array n by dividing the size of the array by the size of its first element.
We then declare two integer variables min and min_index, both initialized to the first element of the array. We use a for loop to iterate over the elements of the array, starting from the second element. For each element, we check if it is less than the current minimum. If it is, we update the value of min to be the value of the current element, and update the value of min_index to be the current index.
After the loop finishes, we print out the value of the smallest element in the array min, along with its index min_index.
The output of this program will be:
The smallest element is 1 at index 2
Note that this program assumes that the array contains at least one element. If the array is empty, it will produce unexpected results. To handle this case, you could add a check at the beginning of the program to ensure that the array is not empty.