Write C program to enter two numbers. Find the smallest out of two numbers using conditional operator.

C program to find smallest out of two numbers is a good example of how to use conditional operator in C language.

Conditional operator is a ternary operator which means it works with three operands. The advantage of using conditional or ternary operator is that it improves the performance and reduces the lines of code.

Tutorial πŸ“Ί

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

Steps πŸͺœ

To find out the smallest number

  1. Display a message to the user and accept two numbers. Store these values in two variables n1 and n2. We will use the conditional or ternary operator to find the solution, as mentioned in the problem statement.
  2. Next, we will use the ternary operator to find out which number is the smallest one. That’s it. 😎

Flow Chart 🌻

flow charts - Find the smallest number out of two

Code πŸ’»

#include <stdio.h>

int main()
{
  int n1 = 0, n2 = 0;
  printf("Please enter two numbers:\n");
  scanf("%d%d", &n1, &n2);
  // Find the smallest out of two values using conditional operator:
  n1 < n2 ? printf("\n\n%d is the smallest number.", n1) : printf("\n\n%d is the smallest number.", n2);
  return 0;
}

Examples 😍

Let’s assume, the user enters two numbers as 23 and 31. First, it will check which one is the smallest, since 23 is the smallest one, so it will execute the first printf() statement which will display the appropriate message.

The output will be like:

23 is the smallest number.

Let’s take another example, where the user enters two numbers as -76 and -91. Again, it will check for the smallest one, since -91 is the smallest number, so it will execute the first printf() statement and will display the appropriate message.

The output will be like:

-91 is the smallest number.

This is how we find out the smallest number out of two numbers using conditional or ternary operator in C language. 😎
For more C programs, click here.

Categorized in: