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:

  1. Include header file:

C

#include <stdio.h>
  1. Declare variables:

C

int num1, num2, max;
  1. Get input from the user:

C

printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
  1. Apply logic using if-else:

C

if (num1 > num2) {
    max = num1;
} else {
    max = num2;
}
  1. 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.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button