C (programming language)
C Program to Find Maximum Between Two Numbers Using
Understanding the Problem
- The goal is to write a C program that takes two numbers as input and determines the larger of the two.
- We’ll explore different approaches to achieve this:
- Using if-else statements
- Using conditional operators
- Using a function
Method 1: Using if-else Statements
Steps:
- Include header file:
C
#include <stdio.h>
- Declare variables:
C
int num1, num2, max;
- Get input from the user:
C
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
- Apply logic using if-else:
C
if (num1 > num2) {
max = num1;
} else {
max = num2;
}
- Print the result:
C
printf("The maximum number is: %d", max);
Method 2: Using Conditional Operators
Code:
C
#include <stdio.h>
int main() {
int num1, num2, max;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
max = (num1 > num2) ? num1 : num2; // Conditional operator
printf("The maximum number is: %d", max);
return 0;
}
Method 3: Using a Function
Code:
C
#include <stdio.h>
int findMax(int num1, int num2) {
if (num1 > num2) {
return num1;
} else {
return num2;
}
}
int main() {
int num1, num2, max;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
max = findMax(num1, num2); // Call the function
printf("The maximum number is: %d", max);
return 0;
}
Key Points:
- All three methods provide correct results.
- Choose the method based on code readability and preferences.
- Functions promote code reusability and modularity.
- Conditional operators offer a concise way to write conditional expressions.
- Always test your code with various inputs to ensure its correctness.