C: Ternary operator demonstration.


Demonstrating how a ternary statement works in C.

#include <stdio.h>
int main(int argc, char* argv[])
{
    int n = -1;     // Set to -1 for do while loop.
    
    printf("\nEnter number from 0-100: \n");    // prompt user for input.

    // Loops until user enters valid input:
    do {
        scanf(" %d", &n);
        n < 0 || n > 100 ? printf("Invalid number! Try again.\n") : printf("Valid!\n");
    } while(n < 0 || n > 100);

    // Detect whether number is less than or greater than 50:
    n > 50 ? printf("Number is greater than 50.\n") : printf("Number is less than 50.\n");

    return 0;
}

https://github.com/pereiradaniel/c_programs/blob/master/ternary/ternary.txt
==119== Memcheck, a memory error detector
==119== Copyright (C) 2002-2017, and GNU GPL'd, by Julian 
Seward et al.
==119== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==119== Command: ./ternary
==119== 

Enter number from 0-100: 
-1
Invalid number! Try again.
101
Invalid number! Try again.
25
Valid!
Number is less than 50.
==119== 
==119== HEAP SUMMARY:
==119==     in use at exit: 0 bytes in 0 blocks
==119==   total heap usage: 2 allocs, 2 frees, 2,048 bytes allocated
==119== 
==119== All heap blocks were freed -- no leaks are possible
==119== 
==119== For lists of detected and suppressed errors, rerun with: -s
==119== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==120== Memcheck, a memory error detector
==120== Copyright (C) 2002-2017, and GNU GPL'd, by Julian 
Seward et al.
==120== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==120== Command: ./ternary
==120==

Enter number from 0-100:
-5
Invalid number! Try again.
102
Invalid number! Try again.
75
Valid!
Number is greater than 50.
==120==
==120== HEAP SUMMARY:
==120==     in use at exit: 0 bytes in 0 blocks
==120==   total heap usage: 2 allocs, 2 frees, 2,048 bytes allocated
==120==
==120== All heap blocks were freed -- no leaks are possible
==120==
==120== For lists of detected and suppressed errors, rerun with: -s
==120== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Popular posts from this blog

C: Usage Of limits.h And float.h To Access Min And Max Constants.

C programming and relevancy