Find Greatest of Two or Three Numbers: C, Python, and Java
If-else, ternary, and built-in approaches to finding the max of 2 or 3 numbers in C, Python, and Java, with N-numbers loop and edge cases.
Finding the maximum of two or three numbers is among the first programs freshers are asked to code on a whiteboard, and the edge cases catch more candidates than the happy path does.
Equal values. Negative integers. Three numbers where two share the maximum. These inputs separate a prepared candidate from one who only tested 5 and 10.
This article covers the if-else approach, the ternary operator, and language-native built-in functions in C, Python, and Java. It also covers the loop-based generalisation for N numbers and the six test cases worth running before considering the problem complete.
Greatest of Two Numbers
If-Else
The if-else approach uses three branches: greater, lesser, and equal. Missing the equal branch is the most common slip under interview time pressure.
In C:
#include <stdio.h>
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
if (a > b) {
printf("Greatest: %d\n", a);
} else if (b > a) {
printf("Greatest: %d\n", b);
} else {
printf("Both numbers are equal: %d\n", a);
}
return 0;
}
In Python:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a > b:
print("Greatest:", a)
elif b > a:
print("Greatest:", b)
else:
print("Both numbers are equal:", a)
In Java:
import java.util.Scanner;
public class MaxTwo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
if (a > b) {
System.out.println("Greatest: " + a);
} else if (b > a) {
System.out.println("Greatest: " + b);
} else {
System.out.println("Both numbers are equal: " + a);
}
}
}
The equal-values branch is the one most candidates drop under speed-write conditions. Inputs like 5 5 or -3 -3 fall through the first two conditions and produce no output if the else clause is missing.
Ternary Operator
The expression (a > b) ? a : b returns a when a > b is true, and b otherwise. One line, same logic.
In C and Java (same syntax):
int greatest = (a > b) ? a : b;
In Python (conditional expression):
greatest = a if a > b else b
The ternary does not naturally produce a separate “both equal” message. If the problem requires printing that message on a tie, the if-else chain is cleaner.
Greatest of Three Numbers
If-Else with Logical AND
The three-number case adds one layer of comparison. The critical detail: use >= (greater-than-or-equal), not strict >.
In C:
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
if (a >= b && a >= c) {
printf("Greatest: %d\n", a);
} else if (b >= a && b >= c) {
printf("Greatest: %d\n", b);
} else {
printf("Greatest: %d\n", c);
}
return 0;
}
In Python:
a = int(input())
b = int(input())
c = int(input())
if a >= b and a >= c:
print("Greatest:", a)
elif b >= a and b >= c:
print("Greatest:", b)
else:
print("Greatest:", c)
In Java:
if (a >= b && a >= c) {
System.out.println("Greatest: " + a);
} else if (b >= a && b >= c) {
System.out.println("Greatest: " + b);
} else {
System.out.println("Greatest: " + c);
}
Why >= matters: with inputs 10 10 5, the condition a > b is false (both equal 10), so a strict-greater-than chain falls through. b > a is also false, so the final else prints c as the greatest, giving the wrong answer of 5. Using >=, the first condition a >= b && a >= c is true (10 >= 10 and 10 >= 5), so a is correctly returned.
Ternary for Three Numbers
The nested ternary in C and Java:
int greatest = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
In Python:
greatest = a if (a > b and a > c) else (b if b > c else c)
The logic: if a > b, then compare a and c to get the maximum; otherwise compare b and c. One level of nesting is readable. For whiteboard interviews, the if-else chain adds five seconds and removes all ambiguity.
Built-In Functions
All three languages provide a built-in that removes the need for manual comparison:
| Language | Function | Example |
|---|---|---|
| Python | max(a, b) or max(a, b, c) | max(10, 20) returns 20 |
| Java | Math.max(a, b) | Math.max(10, 20) returns 20 |
| C++ | std::max(a, b) from <algorithm> | std::max(10, 20) returns 20 |
| C | No standard max() in C99; use ternary or define a macro |
Python’s built-in max() also accepts an iterable: max([3, 1, 4, 1, 5, 9]) returns 9. The C++ standard library’s std::max handles pairs; for three values, use std::max({a, b, c}) with an initialiser list. Java’s Math.max() accepts exactly two arguments; chain two calls for three values: Math.max(a, Math.max(b, c)).
For a coding interview, knowing the built-in exists is expected. Being able to implement the comparison without the built-in is what examiners test. Prepare both.
N Numbers: Loop-Based Running Max
When the input is an array or list of arbitrary length, the comparison loop scales cleanly.
Algorithm:
- Set
running_maxto the first element. - Iterate through the remaining elements.
- Update
running_maxwhenever the current element is> running_max. - Return
running_maxafter the loop ends.
In C:
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int arr[n], running_max;
for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
running_max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > running_max) running_max = arr[i];
}
printf("Greatest: %d\n", running_max);
return 0;
}
In Python:
nums = list(map(int, input().split()))
running_max = nums[0]
for x in nums[1:]:
if x > running_max:
running_max = x
print("Greatest:", running_max)
In Java:
int[] arr = {5, 12, 3, 99, 47};
int runningMax = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > runningMax) runningMax = arr[i];
}
System.out.println("Greatest: " + runningMax);
This generalises directly to the find smallest and largest element in an array problem, where a single pass tracks both a running_min and a running_max. Time complexity: O(n) since the loop visits each element once. Space complexity: O(1) since only the running maximum is stored alongside the input array.
Test Cases and Edge Cases
Run these before marking any solution ready:
(5, 5): equal values. Output should name both equal, or return either value.(-5, -10): both negative. Greatest is-5because-5 > -10.(0, -1): zero vs. negative. Zero is greater.(10, 10, 5): two tied at the maximum. Either tied value is a correct answer.(-2, -5, -10): all negative. Greatest is-2.(100, 100, 100): all equal. Any value is correct.
The data structures interview guide applies the same edge-case logic to array search and sort problems. Listing edge cases before writing the first line of code is a habit that transfers across every problem type.
Practice pairing this conditional logic with a palindrome check or a flower-stick arrangement problem to build fluency switching between numeric comparison and index-based thinking.
The running-max loop from the N-numbers section maps directly to the argmax step in classification models: the network scores all output nodes and returns the index of the highest activation. TinkerLLM lets you inspect that selection step in real models, starting at ₹299, without needing a local Python environment.
Primary sources
Frequently asked questions
Is this type of program asked in TCS NQT or Cognizant GenC coding rounds?
Yes. Basic conditional-logic programs appear in the easy tier of service-sector coding rounds. The typical variant adds a constraint: handle negative inputs or report when two values are tied.
Can nested ternary operators be used for three numbers in Java?
Yes. Java supports nested ternaries. The expression (a > b) ? (a > c ? a : c) : (b > c ? b : c) returns the maximum of three integers. Most style guides cap nesting at two levels for readability.
Does the if-else approach handle negative numbers correctly?
Yes. The comparisons work for any integer range including negatives. For example, max(-5, -10) returns -5 because -5 > -10 evaluates to true.
What happens when all three numbers are equal in an if-else chain?
The first condition (num1 >= num2 && num1 >= num3) evaluates to true, so num1 is printed. Any value is correct since all three are identical.
How do I find the maximum of N numbers in Python?
Pass a list to the built-in max() function: max([3, 7, 1, 9, 4]) returns 9. For a manual loop, initialise a variable to the first element, then update it whenever a larger element is found.
Is using Python's max() function acceptable in placement coding tests?
It depends on the platform. Many online judges allow built-in functions. Interviewers testing conditional logic will ask for a manual implementation, so know both approaches.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)