All articles
c

A program to explain COMPOUND IF

Share this article

Share on LinkedIn Share on X (formerly Twitter)

C Programming Language 016

Compound if statements allow you to test multiple conditions in a single decision-making structure. They're essential for creating more sophisticated program logic.

What is a Compound if?

A compound if statement combines multiple conditions using logical operators like && (AND) and || (OR) to make complex decisions.

Basic Syntax

if (condition1 && condition2) {
    // Execute when BOTH conditions are true
}
 
if (condition1 || condition2) {
    // Execute when AT LEAST ONE condition is true
}

Practical Examples

Example 1: Age and Citizenship Check

#include <stdio.h>
 
int main() {
    int age;
    char citizen;
 
    printf("Enter your age: ");
    scanf("%d", &age);
 
    printf("Are you a citizen? (y/n): ");
    scanf(" %c", &citizen);
 
    // Compound if using AND operator
    if (age >= 18 && citizen == 'y') {
        printf("You're eligible to vote!\n");
    } else {
        printf("You're not eligible to vote.\n");
    }
 
    return 0;
}

Example 2: Grade Calculator

#include <stdio.h>
 
int main() {
    int score;
 
    printf("Enter your score (0-100): ");
    scanf("%d", &score);
 
    // Compound if using OR operator
    if (score >= 90) {
        printf("Grade: A\n");
    } else if (score >= 80 || score >= 70) {
        printf("Grade: B or C\n");
    } else {
        printf("Grade: D or F\n");
    }
 
    return 0;
}

Example 3: Login Validation

#include <stdio.h>
#include <string.h>
 
int main() {
    char username[20], password[20];
 
    printf("Username: ");
    scanf("%s", username);
 
    printf("Password: ");
    scanf("%s", password);
 
    // Multiple conditions with AND
    if (strcmp(username, "admin") == 0 &&
        strcmp(password, "secret") == 0) {
        printf("Login successful!\n");
    } else {
        printf("Invalid credentials.\n");
    }
 
    return 0;
}

Key Points to Remember

  1. && (AND): All conditions must be true
  2. || (OR): At least one condition must be true
  3. Precedence: && has higher precedence than ||
  4. Parentheses: Use () to group conditions for clarity

Common Use Cases

  • User authentication
  • Range checking (e.g., if (age >= 18 && age <= 65))
  • Input validation
  • Game logic
  • Database queries

Practice Exercise

Write a program that determines if a person qualifies for a loan based on:

  • Credit score ≥ 650 AND
  • Annual income ≥ $30,000 OR existing account balance ≥ $10,000

Compound if statements are powerful tools that make your programs more intelligent by allowing them to make decisions based on multiple criteria simultaneously.


Comments