How can I simplify nested-if statements | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How can I simplify nested-if statements

Hello, I'm considering the way to simplify nested-if statements in a row, but I stuck in here. #include <stdio.h> int main() { float profit, clients, bonus; /* printf("Enter your profit and clients: \n"); scanf("%f %f", &profit, &clients); bonus = (profit > 500 & clients > 10) ? profit * clients : profit * clients * 0.3; printf("You'll get %.2f as your bonus \n", bonus); This is what I am working now.. but how can I put secone 'else' statement in the sentense? */ if (profit > 500) { if (clients > 10) { bonus = profit * clients; printf("You'll get %.2f as your bonus", bonus); } else { bonus = profit * clients * 0.3; printf("You'll get %.2f as your bonus", bonus); } } else { bonus = profit * clients * 0.1; printf("You'll get %.2f as your bonus", bonus); } return 0; }

23rd Nov 2019, 3:59 PM
Hyun Wook Jung
Hyun Wook Jung - avatar
4 Answers
+ 2
Jaya krishna as well as the bonus variable is same, which is being changed in every condition, so we can directly assign this complex ternary operation as a value to the bonus variable
23rd Nov 2019, 4:32 PM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
+ 1
bonus = (profit > 500) ? ((clients > 10) ? profit * clients : profit * clients * 0.3) : profit * clients * 0.1; printf("You'll get %.2f as your bonus \n", bonus);
23rd Nov 2019, 4:09 PM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
+ 1
(profit>500 ? (clients>10?(bonus=profit*clients) :(bonus=profit*clients*0.3) : (bonus=profit*client*0.1)) printf("You'll get %.2f as your bonus", bonus); Hyun Wook Jung oh same print statements so you write only once outside.. further you take out bonus and assingn as sami specified. i didnt noticed that all are calculating bonus only..
23rd Nov 2019, 4:14 PM
Jayakrishna 🇮🇳
+ 1
Sami Khan yes. I mentioned that also in editing. Of course i noticed that after seeing your post only.. I just followed converting nested ifelse to ternery.. And when i seen question, it is unanswered. But when i answer posted , u already posted the answer.. My typing less speed, you are too quick...
23rd Nov 2019, 4:59 PM
Jayakrishna 🇮🇳