rewrite using ternary operator if (a<b) { c=(a+b); else c=(a-b); }
Answers
Answer: if and else in C
From here, the real coding part begins. Gear up to travel to the next part of coding. This will be a lot of fun.
Many times, we need to first see the condition and then make a decision.
As an example, consider that a chocolate costs 10 rupees. So, if you have 10 rupees or more, you can buy the chocolate.
if and else in c
But how do we represent this scenario in C?
This type of decision taking is done by using if statement in C.
if statement
Let's consider an example.
#include <stdio.h>
{
int a = 5;
int b = 5;
if (a==b)
{
printf ( a and b are equal\n);
}
return 0;
}
Output :
if (a==b) → a==b is the condition. Conditions are written inside '()'. Here, condition is true (will return 1). Since the condition is true, statements inside if will be executed. {} after if represents the body of if. Whatever is written inside '{}' is part of if.
So, the flow is that first the condition of if is checked and if it is true then statement(s) inside if are executed.
Hope it helped
:)
c = a < b ? a + b : a - b;
Basic syntax for a ternary operator is:
- variable = Condition ? Expression 2 : Expression 3
- The above statement means- If condition is true then execute Expression 1 else execute expression 2 and store the result in the variable.
- Hence the answer becomes- c = a < b ? a + b : a - b;
- c = if condition (a<b) ? then a + b : else a - b ;