Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write a C program to find out the largest and smallest number in a series
In C programming, finding the largest and smallest numbers in a series is a fundamental problem that can be solved using conditional statements or arrays. This involves comparing each number with the current maximum and minimum values to determine the extremes.
Syntax
if (number > max)
max = number;
if (number < min)
min = number;
Method 1: Using Four Variables
This approach reads four numbers from the user and compares them to find the largest and smallest −
#include <stdio.h>
int main() {
int minno, maxno, p, q, r, s;
printf("Enter any four numbers: ");
scanf("%d %d %d %d", &p, &q, &r, &s);
minno = maxno = p; // Initialize with first number
if (minno > q) // Check 2nd number
minno = q;
if (maxno < q)
maxno = q;
if (minno > r) // Check 3rd number
minno = r;
if (maxno < r)
maxno = r;
if (minno > s) // Check 4th number
minno = s;
if (maxno < s)
maxno = s;
printf("Largest number: %d<br>", maxno);
printf("Smallest number: %d<br>", minno);
return 0;
}
Enter any four numbers: 34 78 23 12 Largest number: 78 Smallest number: 12
Method 2: Using Arrays
This approach uses an array to store multiple numbers and finds the extremes using a loop −
#include <stdio.h>
int main() {
int a[50], i, num, large, small;
printf("Enter the number of elements: ");
scanf("%d", &num);
printf("Input the array elements:<br>");
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
large = small = a[0]; // Initialize with first element
for (i = 1; i < num; i++) {
if (a[i] > large)
large = a[i];
if (a[i] < small)
small = a[i];
}
printf("Smallest number: %d<br>", small);
printf("Largest number: %d<br>", large);
return 0;
}
Enter the number of elements: 6 Input the array elements: 45 23 67 12 89 34 Smallest number: 12 Largest number: 89
Key Points
- Always initialize the min and max variables with the first number or array element.
- Use separate
ifstatements for minimum and maximum checks to handle all cases correctly. - The array method is more scalable for handling large datasets.
Conclusion
Finding largest and smallest numbers involves simple comparison logic using conditional statements. The array approach is more efficient for handling multiple numbers, while direct variable comparison works well for a fixed count of numbers.
Advertisements
