To find the highest of three values, compare the numbers with if...else conditions. The same idea can later be extended to arrays and functions.
#include <stdio.h>
int main(void) {
int a = 12;
int b = 25;
int c = 18;
int highest;
if (a >= b && a >= c) {
highest = a;
} else if (b >= a && b >= c) {
highest = b;
} else {
highest = c;
}
printf("Highest = %d\n", highest);
return 0;
}
#include <stdio.h>
int main(void) {
int a;
int b;
int c;
printf("Enter three integers: ");
if (scanf("%d %d %d", &a, &b, &c) != 3) {
printf("Invalid input.\n");
return 1;
}
int highest = a;
if (b > highest) {
highest = b;
}
if (c > highest) {
highest = c;
}
printf("Highest = %d\n", highest);
return 0;
}
This second style starts with one candidate and updates it when a larger value is found. It scales naturally to an array.
#include <stdio.h>
int main(void) {
int values[] = {7, 21, -5, 42, 18};
size_t count = sizeof values / sizeof values[0];
int highest = values[0];
for (size_t i = 1; i < count; i++) {
if (values[i] > highest) {
highest = values[i];
}
}
printf("Highest = %d\n", highest);
return 0;
}
#include <stdio.h>
float find_max(const float values[], size_t count) {
float maximum = values[0];
for (size_t i = 1; i < count; i++) {
if (values[i] > maximum) {
maximum = values[i];
}
}
return maximum;
}
int main(void) {
float values[] = {3.5f, 8.2f, 4.1f, 9.7f};
size_t count = sizeof values / sizeof values[0];
printf("Highest = %.2f\n", find_max(values, count));
return 0;
}
#include <stdio.h>
#define MAX_VALUES 100
int main(void) {
int count;
int values[MAX_VALUES];
printf("Enter number of elements (1-%d): ", MAX_VALUES);
if (scanf("%d", &count) != 1 ||
count < 1 || count > MAX_VALUES) {
printf("Invalid size.\n");
return 1;
}
for (int i = 0; i < count; i++) {
printf("Enter number %d: ", i + 1);
if (scanf("%d", &values[i]) != 1) {
printf("Invalid input.\n");
return 1;
}
}
int maximum = values[0];
for (int i = 1; i < count; i++) {
if (values[i] > maximum) maximum = values[i];
}
printf("Highest = %d\n", maximum);
return 0;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
22-03-2022 | |
| Thanks so much for this detailed c program, it's a good journey | |