Write a C Program which accepts two numbers from the user. Find the greater number from accepted values (numbers can be equal too).

This is one of the easiest programs which you will encounter while learning C programming language. In order to solve this problem, you must know the concept of comparison operators.

Tutorial πŸ“Ί

Watch tutorial and learn how to solve this problem. πŸ˜‰

Steps πŸͺœ

To find greater number from 2 numbers

  1. Accept 2 integer numbers from the user and store the values in n1 and n2.
  2. First, check if n1 > n2 returns true or not. If it returns true then it will display the message, “n1 is greater.” otherwise the control will move to else-if statement.
  3. If above condition is false then it will check if n2 > n1 returns true or not. If it returns true then it will display the message, “n2 is greater.” otherwise the control will move to else statement.
  4. Finally, if all above conditions are false then this (else) statement will be executed. A message will be displayed, “Both numbers are equal”.

Code πŸ’»

#include <stdio.h>
#include <conio.h>

void main() 
{
  int n1 = 0, n2 = 0;
  clrscr();
  printf("Please enter the number 1: ");
  scanf("%d", &n1);
  printf("Please enter the number 2: ");
  scanf("%d", &n2);
  if (n1 > n2)
    printf("n1 (%d) is greater.", n1);
  else if(n2 > n1)
    printf("n2 (%d) is greater.", n2);
  else
    printf("Both numbers are equal, n1 = %d and n2 = %d", n1, n2);
  getch();
}

Example 😍

Let’s assume, the user enters two numbers as 39 and 23.

First of all, it will check if n1 > n2 (39 > 23) which is true. Thus, it will display the message, “n1 (39) is greater.“.

Let’s take another example and this time user enters -4, and 8. First, it will check if n1 > n2 (-4 > 8) which is false so it will execute next else-if statement. Again, it will check if n2 > n1 (8 > -4) which is true.

Thus, it will display the message:

n2 (8) is greater.

Let’s take one more example where user enters both numbers same, 22. First, it will check if n1 > n2 which will return false. Next, it will check if n2 > n1, again it will return false. Finally, it will execute the else-part and display the message:

Both numbers are equal, n1 = 2 and n2 = 2

This is how we write C program to find the greater number from two numbers accepted from the user.
For more C programs, click here.


Popular Posts πŸ˜ƒ

Categorized in: