Monday, April 28, 2025

C Program - Find Greatest of Three Numbers using If Statement

This code is a program to find the largest number among three given numbers. It starts by declaring three integer variables named num1, num2, and num3.

Then the program prompts the user to input the values for these variables using printf() and scanf() statements.

After that, the program checks for three conditions using if-else statements to determine which number is the largest.

#include <stdio.h>

int main() {

  int num1, num2, num3;

  printf("Enter first number: ");
  scanf("%d", &num1);

  printf("Enter second number: ");
  scanf("%d", &num2);

  printf("Enter third number: ");
  scanf("%d", &num3);

  if (num1 == num2 && num2 == num3){
    printf("Same numbers. \n");
  }
  else if (num1 >= num2 && num1 >= num3)
    printf("%d is the largest number. \n", num1);

  else if (num2 >= num1 && num2 >= num3)
    printf("%d is the largest number. \n", num2);

  else if (num3 >= num1 && num3 >= num2)
    printf("%d is the largest number. \n", num3);

  return 0;
}

Result: 

Enter first number: 10
Enter second number: 20
Enter third number: 30
30 is the largest number.

Process returned 0 (0x0)   execution time : 3.214 s
Press any key to continue.
  • If all three numbers are equal, the program prints "Same numbers.".
  • If num1 is greater than or equal to num2 and num1 is greater than or equal to num3, the program prints "num1 is the largest number.".
  • If num2 is greater than or equal to num1 and num2 is greater than or equal to num3, the program prints "num2 is the largest number.".
  • If num3 is greater than or equal to num1 and num3 is greater than or equal to num2, the program prints "num3 is the largest number.".

Finally, the program returns 0 to indicate successful execution.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...