beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

If statement in C programming with example

By Chaitanya Singh | Filed Under: c-programming

When we need to execute a block of statements only when a given condition is true then we use if statement. In the next tutorial, we will learn C if..else, nested if..else and else..if.

C – If statement

Syntax of if statement:
The statements inside the body of “if” only execute if the given condition returns true. If the condition returns false then the statements inside “if” are skipped.

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

Flow Diagram of if statement

C-if-statement

Example of 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: The condition (x<y) specified in the “if” returns true for the value of x and y, so the statement inside the body of if is executed.

Example of multiple if statements

We can use multiple if statements to check more than one conditions.

#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;
}

In the above example the output depends on the user input.

Output:

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

Leave a Reply Cancel reply

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

C Programming Tutorial

  • Turbo C++ installation
  • First C Program
  • C - Keywords
  • Operator precedence
  • C - if statement
  • C - if..else
  • C - for loop
  • C - while loop
  • C - do while loop
  • C - continue
  • C - break statement
  • C - switch..case
  • C - goto statement
  • C - Arrays
  • 2 D array
  • C - String
  • C - functions
  • Function call by reference
  • Function call by value
  • Array to function
  • C - Structures
  • C - Pointers
  • Pointer to Pointer
  • Pointers to functions
  • C - function pointers
  • Pointer & Array
  • C - File I/O
  • C Programming Examples

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap