C PROGRAM • DECISION MAKING

Find the Largest of Three Numbers

Track a current largest value and update it after comparing each remaining number.

Beginnerif statementComparisonRunning maximum

PROBLEM UNDERSTANDING

Input and expected output

Sample input
14 39 27
Sample output
Enter three integers: 14 39 27
Largest = 39

C PROGRAM

Complete program

largest-of-three.c
#include <stdio.h>

int main(void)
{
    int first, second, third, largest;
    printf("Enter three integers: " );
    scanf("%d %d %d", &first, &second, &third);

    largest = first;
    if (second > largest)
        largest = second;
    if (third > largest)
        largest = third;
    printf("Largest = %d\n", largest);
    return 0;
}

INTERACTIVE LEARNING

Debug this program line by line

Watch the active line, variables and output.

CURRENT STEP

Select Start to trace this program.

VARIABLES

ScopeNameValue
Not started

CALL STACK

main()

PROGRAM OUTPUT

Waiting to run…
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read three integers.
  2. Assume first is the largest.
  3. Replace largest when second is greater.
  4. Replace largest when third is greater.
  5. Print largest.

The variable largest stores the best value seen so far. Each independent if statement compares one remaining input with that current value.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Using else-if when independent comparisons are intended.

Check this

Forgetting to initialize largest before comparing values.