Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

C if statements

Understanding the If Statement:

  • The if statement allows you to execute a block of code only if a specified condition is true.
  • The basic syntax of an if statement is:
C
if (condition) {
    // code to be executed if the condition is true
}
  • The condition is an expression that evaluates to either true or false.

Using Comparison Operators:

  • Comparison operators are used to compare values in conditions.
  • Common comparison operators in C include:
    • == (equal to)
    • != (not equal to)
    • < (less than)
    • > (greater than)
    • <= (less than or equal to)
    • = (greater than or equal to)

Using else statement:

  • The else statement allows you to specify an alternative block of code to execute if the condition in the if statement is false.
  • Example:
C
#include <stdio.h>

int main() {
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

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

    return 0;
}

Using Else If Statement:

  • The else if statement allows you to check multiple conditions sequentially.
  • Here’s an example that categorizes numbers into positive, negative, or zero:
C
#include <stdio.h>

int main() {
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

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

    return 0;
}

Nesting If Statements:

  • You can nest if statements within each other to create more complex conditions.
  • Here’s an example that checks if a number is positive, even, and divisible by 3:
C
#include <stdio.h>

int main() {
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    if (number > 0) {
        if (number % 2 == 0) {
            if (number % 3 == 0) {
                printf("The number is positive, even, and divisible by 3.\n");
            } else {
                printf("The number is positive and even, but not divisible by 3.\n");
            }
        } else {
            printf("The number is positive, but not even.\n");
        }
    } else {
        printf("The number is not positive.\n");
    }

    return 0;
}