Using the Ternary Operator in C to Compare Two Values


The #include<stdio.h> is a preprocessor command that includes the contents of the standard input-output library in the program.

The int main() function is the starting point of the program execution. Inside the main function, two integers a and b are declared. printf() and scanf() are used to get input and display output respectively.

The ternary operator a==b?printf("Given 2 values are equal:%d",a):printf("Given two values are not equal:%d,%d",a,b); is used to check if the two integers entered by the user are equal or not.

If the values of a and b are equal, the first part of the ternary operator, printf("Given 2 values are equal:%d",a), will execute, else the second part of the ternary operator printf("Given two values are not equal:%d,%d",a,b) will execute.

Finally, the return 0 statement is used to indicate the successful execution of the program. The return value of 0 is a convention used to indicate that the program has executed correctly.

Source Code

#include<stdio.h>
int main()
{
    int a,b;
    printf("\nEnter the First value:");
    scanf("%d",&a);
    printf("\nEnter the Second value:");
    scanf("%d",&b);
    a==b?printf("Given 2 values are equal:%d",a):printf("Given two values are not equal:%d,%d",a,b);
    return 0;
}
To download raw file Click Here

Output

Enter the First value: 5
Enter the Second value: 5
Given two values are equal: 5

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C