C

With An Example Of An If Statement In C Programming

The if statement is used when we need to execute a block of statements only when a given condition is true. In the following tutorial, we’ll go over C if..else, nested if..else, and else..if.

If statement in C

If statement syntax:
The statements contained within the body of “if” are only executed if the given condition is true. If the condition returns false, the statements contained within “if” are skipped.

if (condition)
{
     //Block of C statements here
     //These statements will only execute if the condition is true
}

An example of an if statement

#include <stdio.h>
int main()
{
    int x = 20;
    int y = 22;
    if (x<y)
    {
        printf("Variable x is less than y");
    }
    return 0;
}

Output:

Variable x is less than y

Explanation: Because the condition (xy) specified in the “if” returns true for the values x and y, the statement within the body of if is executed.

A multiple if statement example

To check multiple conditions, we can use multiple if statements.

#include <stdio.h>
int main()
{
    int x, y;
    printf("enter the value of x:");
    scanf("%d", &x);
    printf("enter the value of y:");
    scanf("%d", &y);
    if (x>y)
    {
	printf("x is greater than y\n");
    }
    if (x<y)
    {
	printf("x is less than y\n");
    }
    if (x==y)
    {
	printf("x is equal to y\n");
    }
    printf("End of Program");
    return 0;
}

The output in the preceding example is determined by the user input.

Output:

enter the value of x:20
enter the value of y:20
x is equal to y
End of Program

Related Articles

Leave a Reply

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

Back to top button