Friday 9 April 2021

Some basic C programs using Conditional Operator

Conditional operator simply returns one value when the condition is true and returns another value if the condition is false. It also knows as a ternary operator.

Syntax of a ternary operator

  (condition) ? Expression: Expression;

Example

(a>0)?1:0; evaluates to true so 1.

Now understand the ternary operator with the help of some basic problem.

Problem 1

Write a C program to check the numbers are positive or negative.

#include <stdio.h>

 

int main()

{

    int a, c;

    printf("Enter the number ");

    scanf("%d", &a);

    c = (a>0) ? printf("positive number ") : printf("Negative number ");

    // (a > 0) ? printf("positive number") : printf("Negative number");

}

Understanding the above code:

    Declared two integer type variables which are a and c.

    Input is taken in variable ‘a’ by  ‘scanf( )’ function.

    Integer type variable c is used to store the decision based upon the condition by the compiler.

Output








Using this in the above code

 (a > 0) ? printf("positive number") : printf("Negative number");








With both the code output is similar. 


Problem 2

Write a C program to determine the greatest number between the three numbers.

#include <stdio.h>

 

int main()

{

    int a, b, c, big;

    printf("a=");

    scanf("%d", &a);

    printf("b=");

    scanf("%d", &b);

    printf("c=");

    scanf("%d", &c);

    big = a > b ? (a > c ? a : c) : (b > c ? b : c);

    printf("Greatest number %d\n", big);

}

Output






No comments:

Post a Comment