Find greatest of three numbers

In this article, we will find the greatest of three numbers with C program with algorithm and example.
The program will read the numbers a user input.

Algorithm
Following are the steps to find the greatest of three numbers.

1. Read numbers.
2. Compare first number with second.
3. If num1 > num2
    A. Compare num1 with num3
    B. If num1 > num3
        num1 is the largest
       Else
        num3 is the largest
4. Else Compare num2 with num3
5. If num2 > num3
    num2 is the largest
    Else
    num3 is the largest

C Program
Below is the C program written as per above algorithm

// variables for storing numbers
int num1, num2, num3;
printf("Enter the values of num1, num2 and num3\n");
// read numbers
scanf("%d %d %d", &num1, &num2, &num3);
// compare first 2 numbers
if (num1 > num2) {
  if (num1 > num3) {
    printf("%d is the greatest among three \n", num1);
  } else {
    printf("%d is the greatest among three \n", num3);
  }
} else if (num2 > num3) {
    printf("%d is the greatest among three \n", num2);
} else {
    printf("%d is the greatest among three \n", num3);
}

Following is the output

Enter the values of num1, num2 and num3
23 41 67
67 is the greatest among three

Above code can also be written using C logical AND operator(&&), where we can combine two conditions instead of nesting if blocks as shown below.

// variables for storing numbers 
int num1, num2, num3; 
printf("Enter the values of num1, num2 and num3\n"); 
// read numbers scanf("%d %d %d", &num1, &num2, &num3); 
// compare first 2 numbers 
if (num1 >= num2 && num1 >= num3) { 
  printf("%d is the greatest among three \n", num1); 
} else if (num2 >= num1 && num2 >= num3) { 
  printf("%d is the greatest among three \n", num2); 
} else { 
  printf("%d is the greatest among three \n", num3); 
}

Hope the article was useful.