If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Here is an example of a C program that finds the largest of three numbers using the "if-else" statement:
Copy code
#include <stdio.h>
int main() {
int num1, num2, num3;
printf("Enter three integers: ");
scanf("%d%d%d", &num1, &num2, &num3);
if (num1 > num2) {
if (num1 > num3) {
printf("%d is the largest number.", num1);
} else {
printf("%d is the largest number.", num3);
}
} else {
if (num2 > num3) {
printf("%d is the largest number.", num2);
} else {
printf("%d is the largest number.", num3);
}
}
return 0;
}
In this example, the program prompts the user to enter three integers, which are stored in the variables "num1", "num2", and "num3". The program then uses two nested if-else statements to check which of the three numbers is the largest. The first if-else statement compares "num1" and "num2". If "num1" is greater than "num2", the second if-else statement compares "num1" and "num3". If "num1" is also greater than "num3", "num1" is the largest number and the program prints "num1 is the largest number." If "num1" is not greater than "num3", "num3" is the largest number and the program prints "num3 is the largest number." If "num1" is not greater than "num2" in the first if-else statement, the second if-else statement compares "num2" and "num3". If "num2" is greater than "num3", "num2" is the largest number and the program prints "num2 is the largest number." If "num2" is not greater than "num3", "num3" is the largest number and the program prints "num3 is the largest number."
You can also use the ternary operator to find the largest of three numbers:
Copy code
int largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
printf("%d is the largest number.", largest);
This uses the ternary operator (also called the conditional operator) which is a shorthand for an if-else statement. It has the form condition ? expression_if_true : expression_if_false
and will return the value of expression_if_true
if condition
is true or expression_if_false
if condition
is false.
Comments: 0