absolute value of a number in c program using ternary operator and also using branching

Through this program we will calculate the absolute value of a digit. Absolute value is whether we give negative or positive input the program will always return positive value.


#include<stdio.h>
int main(){

    int number;
    printf("Enter Number value: \n");
    scanf("%d",&number);

    int abs;

    //abs= (number<0)? (-number): number;

    if(number<0){
        abs=(-number);
    }
    else
        abs=number;
        
    printf("The absulate Value: %d\n",abs);

return 0;
}

Output

Enter Number value:
-7
The absulate Value: 7


In this program first I have taken a Number variable. And took input from user inside that Number variable. After that, I printed the program in such a way that regardless of whether the user inputs negative or positive, the program will always print the positive value.

We have tried to solve this program in two ways. The first is through ternary operator. And finally in a similiar way we solved using if & else condition.You can use any one. Although in this program the problem is solved with ternary operator and commented out.

Post a Comment

Previous Post Next Post