C Programming to find the largest and smallest number from an array.
In this programming tutorial, we are going to find out the smallest number from an array which has several other numbers as well by using C Programming.Video Tutorial:
First of all, we will assign an array named 'a[100]' and four other variables names 'n', 'i', 'large' and 'small' respectively.
int a[100], n, i, large, small;
Then our code will ask the user to the number of numbers that he/she want to add into the array.
printf("how many no. you want to enter : ");
Then by using the scanf function the user will put that number into the assigned variable.
scanf("%d", &n);
Then our code is going to display them, how many numbers the user should input going into the next step.
printf("enter %d numbers : ", n);
Then by using the for loop using the assigned variable 'i', we will put 'n' numbers into the array that's there, by using the scanf function.
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
Now, we will assign the variable 'large' equals to the first element of array 'a' i.e. '[0]', for further operations.
large=a[0];
Then again by using the for loop, we will first assign that first element as the largest and then with respect to that number, we will compare the other numbers present in the array, then by using 'if' statement we will assign the largest number if that condition is satisfied.
for(i=0; i<n; i++)
{
if(large<a[i])
large=a[i];
}
Then it will print the largest number present in the array 'a'.
printf("largest no. is %d\n", large);
Again, we will assign the variable 'small' equal to the first element of array 'a' i.e. '[0]', for further operations.
small=a[0];
Then again by using the for loop, we will first assign that first element as the smallest and then with respect to that number, we will compare the other numbers present in the array, then by using 'if' statement we will assign the smallest number if that condition is satisfied.
for(i=0; i<n; i++)
{
if(small>a[i])
small=a[i];
}
Then it will print the smallest number present in the array 'a'.
printf("smallest no. is %d\n", small);
0 Comments