C/Language Basics/Operator Ternary

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Add function to the Ternary operator

#include <stdio.h>
int f1(int n);
int f2(void);
int main(void)
{
  int t;
  printf("Enter a number: ");
  scanf("%d", &t);
  /* print proper message */
  t ? f1( t ) + f2() : printf("No zero please.");
  printf("\n");
  return 0;
}
int f1(int n)
{
  printf("%d ", n);
  return 0;
}
int f2(void)
{
  printf("entered ");
  return 0;
}


Operator which accepts three value

#include <stdio.h>
int main(void)
{
  int isqrd, i;
  printf("Enter a number: ");
  scanf("%d", &i);
  isqrd = i>0 ? i*i : -(i*i);
  printf("%d squared is %d", i, isqrd);
  return 0;
}


Simple Ternary operator

#include <stdio.h>
int main(void)
{
  int i;
  printf("Enter a number: ");
  scanf("%d", &i);
  i = i > 0 ? 1: -1;
  printf("i =  %d", i);
  return 0;
}


Ternary (?) operator

#include <stdio.h>
void main()
{
  const double price = 3.50; 
  const double discount1 = 0.05;  /* Discount for more than 10 */
  const double discount2 = 0.1;   /* Discount for more than 20 */
  const double discount3 = 0.15;  /* Discount for more than 50 */
  double total = 0.0;
  int quantity = 0;
  printf("Enter the number that you want to buy:");     /* Prompt message */
  scanf(" %d", &quantity);                             /* Read the input */
  total = quantity * price * ( 1.0 - (quantity>50 ? discount3 :
       (quantity>20 ? discount2 : (quantity>10 ? discount1 : 0.0))));
  printf("The price for %d is $%.2lf\n", quantity, total); 
}


Ternary operator inside if else

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  int magic;
  int guess;
  magic = rand(); /* generate the magic number */
  printf("Guess the magic number: ");
  scanf("%d", &guess);
  if(guess == magic) {
    printf("** Right ** ");
    printf("%d is the magic number", magic);
  }
  else
    guess > magic ? printf("High") : printf("Low");
  return 0;
}


Use ternary operator in printf

#include <stdio.h>
int main(void)
{
  int x = 5, y = 10;
  printf("Max of %d and %d is: %d\n", x, y, (x>y ? x : y));
  return 0;
}


Write expression inside Ternary operator

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main(void)
{
  while(!kbhit()) 
      rand();
  rand() % 2 ? printf("H") : printf("T");
  return 0;
}