C If … Else

1. What is if...else?

  • The if...else statement allows your program to execute certain code only if a condition is true, and optionally another block if the condition is false.

  • Syntax:

if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}

2. Simple if Statement

#include <stdio.h>

int main() {
int num = 10;

if (num > 0) {
printf("Number is positive.\n");
}

return 0;
}

Output:

Number is positive.

The code inside {} executes only if the condition is true.


3. if...else Statement

#include <stdio.h>

int main() {
int num = -5;

if (num > 0) {
printf("Number is positive.\n");
} else {
printf("Number is not positive.\n");
}

return 0;
}

Output:

Number is not positive.

4. if...else if...else Statement

  • Used when you have multiple conditions.

#include <stdio.h>

int main() {
int num = 0;

if (num > 0) {
printf("Number is positive.\n");
} else if (num < 0) {
printf("Number is negative.\n");
} else {
printf("Number is zero.\n");
}

return 0;
}

Output:

Number is zero.

5. Nested if Statements

  • You can place one if inside another to check multiple conditions.

#include <stdio.h>

int main() {
int num = 15;

if (num > 0) {
if (num % 2 == 0) {
printf("Number is positive and even.\n");
} else {
printf("Number is positive and odd.\n");
}
}

return 0;
}

Output:

Number is positive and odd.

6. Key Points

  1. Conditions must evaluate to true (non-zero) or false (0).

  2. Use else if for multiple alternative conditions.

  3. Nested if allows checking complex scenarios.

  4. Curly braces {} are optional for single-line statements, but recommended for readability.


7. Combined Example

#include <stdio.h>

int main() {
int score = 85;

if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 75) {
printf("Grade: B\n");
} else if (score >= 50) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}

return 0;
}

Output:

Grade: B

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *