C Programming Tutorial

C Programming Tutorial

C If Else Statement

Hello Everyone, In this article, we will cover the “if else statement” in C Programming, a fundamental control structure that allows you to make decisions in your code. Here we will cover, basic syntax of if else, how to use “if-else” statements with the help of examples to help you understand and implement this essential feature in your programs. Whether you’re new to C or have some experience, this guide will help you to understand C If Else Statement effectively. Let’s get started.

An if-else statement is a control flow statement used in programming languages that allows the program to execute different blocks of code depending on certain conditions.

Basic syntax of an if-else statement:

if (condition) {
    // block of code to be executed if the condition is true
} else {
    // block of code to be executed if the condition is false
}

Example to demonstrate the use of if-else statement in Python:

# A program to check if a number is even or odd

number = 10

if number % 2 == 0:
    print("The number is even")
else:
    print("The number is odd")

In this example, the program checks if the variable number is divisible by 2 using the modulo operator (%). If the result is 0, the number is even and the first block of code is executed. If the result is not 0, the number is odd and the second block of code is executed. The output of this program would be: “The number is even

C program that uses an if-else statement to check if a number is positive or negative:

#include <stdio.h>
int main() {
    int number;

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

    if (number >= 0) {
        printf("%d is a positive number\\n", number);
    } else {
        printf("%d is a negative number\\n", number);
    }

    return 0;
}

In this program, the user is prompted to enter a number, which is stored in the number variable using the scanf function. Then, an if-else statement is used to check if the number is greater than or equal to 0. If it is, the program prints that the number is positive. If not, the program prints that the number is negative.

You can compile and run this program on a C compiler to test it out.

The output of the program would look like if the user enters the number 7:

Enter a number: 7
7 is a positive number

And here’s an example of what the output would look like if the user enters the number -2:

Enter a number: -2
-2 is a negative number
Share This Article