Written by Sai Sandeep Thota on March 29, 2013 in C > Programming

C Program to find Smallest Number in an Array

GET ALERTS:

Get our Latest updates delivered to your mailbox!

This program is used to find the smallest number present in an array. We are defining a function here called smallest. In this function we are declaring a integer variable small and initializing it to the first element of an array (Array count starts at 0). So we are using a for loop here and iterating over the loop by checking the condition if(a[i]<small) if the condition is met then the smallest number will be stored in the small variable. Then we are priting out the smallest number present in the array.

Example:
1. Let us consider an Array with 3 elements: 4, 3, 2.
2. Now we initialize the value of small=4.
3. By iterating using a for loop and a if condition in it. As we have 3 elements here for loop will iterate 3 times and compares the other values with 4, if any value which is less than 4 is found that value will be stored in the variable.

Coming to the main program, we are taking input from the user by asking number of elements he needs to enter and we are passing those values into the array and calling the function smallest to evaluate.

C Program to find Smallest Number in an Array

#include
#include

void smallest(int a[10], int n) {
	int small = a[0];
	int i;

	for(i=0;i<n;i++)
	{
		if(a[i]<small)
		{
			small = a[i];
		}
	}
	printf("\nSmallest Element in the Array is: %d",small);
}

void main() {

	int n, i, a[10];
	clrscr();
	printf("\nEnter Number of elements: ");
	scanf("%d",&n);
	printf("\nEnter %d elements into the Array: ",n);
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);
	printf("\nYou have entered values: ");
	for(i=0;i<n;i++)
		printf("%d\t",a[i]);

	smallest(a,n);
	getch();
}

Output:
smallest

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: