If Statement In C programming





An "if statement" is a fundamental control flow statement in programming languages. It allows a program to make decisions based on whether a certain condition is true or false. The basic syntax of an if statement typically looks like this:

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

In above if statement syntax:

  1. "condition" is an expression that evaluates to either true or false.
  2. If the condition evaluates to true, the code block inside the curly braces {} is executed.
  3. If the condition evaluates to false, the code block is skipped, and execution continues after the if statement.


A program that will cheack number is positive or negative using only if statement.

#include <stdio.h>

int main() {
    int x;

    printf("Enter the value of x: ");
    scanf("%d", &x);

    if (x < 0) {
        printf("Negative Number.\n");
    }

    if (x >= 0) {
        printf("Positive Number.\n");
    }

    return 0;
}
output:
Enter the value of x: 5
Positive Number.
Enter the value of x: -5
Negative Number.



Here's an another example of a C program that uses only if statements to determine the largest of three numbers:

#include <stdio.h>

int main() {
    int num1, num2, num3;

    printf("Enter three numbers: \n");
    scanf("%d %d %d", &num1, &num2, &num3);

    if (num1 > num2 && num1 > num3) {
        printf("%d is the largest number.\n", num1);
    }

    if (num2 > num1 && num2 > num3) {
        printf("%d is the largest number.\n", num2);
    }

    if (num3 > num1 && num3 > num2) {
        printf("%d is the largest number.\n", num3);
    }

    return 0;
}
Output:
Enter three numbers:
11
22
33
33 is the largest number.        
Enter three numbers:
11
33
22
33 is the largest number.        
Enter three numbers:
33
22
11
33 is the largest number.       

In this program, the user is prompted to enter three numbers. The program then uses a series of if statements to compare the numbers and determine the largest among them. Each if statement checks if one number is greater than the other two, and if so, it prints that number as the largest.

Note that using only if statements can result in multiple conditions being true, which is why each condition is checked independently. In this case, if more than one number is the largest, all of them will be printed.

You can run this program by compiling and executing it. Enter three numbers, and the program will output the largest among them using only if statements.