if else statement in C


In our previous video tutorial we saw how to use the decision control instruction if. In this tutorial we shall see how we can use if else statement in division of 2 numbers example.

We illustrate the use of if else statement in this video tutorial with the help of a division of 2 numbers example program.

Division of 2 Numbers: if else construct in C

Single statement in both if and else block

 
#include < stdio.h >

int main()
{
    int a, b;

    printf("Enter value of a and b for division (a/b)\n");
    scanf("%d%d", &a, &b);

    if( b != 0)
        printf("Division of %d and %d is %d\n", a, b, a/b);
    else
        printf("You can't divide a number by 0\n");

    return 0;
}

Output 1:
Enter value of a and b for division (a/b)
10
2
Division of 10 and 2 is 5

Output 2:
Enter value of a and b for division (a/b)
50
0
You can’t divide a number by 0

Note: When condition for if is true, if block gets executed. When condition in if is false, else block code gets executed.

Multiple statements in both if and else block

 
#include < stdio.h >

int main()
{
    int a, b, c;

    printf("Enter value of a and b for division (a/b)\n");
    scanf("%d%d", &a, &b);

    if( b != 0)
    {
        c = a / b;
        printf("Division of %d and %d is %d\n", a, b, c);        
    }
    else
    {
       printf("You can't divide a number by 0\n");
       printf("Please run the program once again and give proper value\n");
    }


    return 0;
}

Output 1:
Enter value of a and b for division (a/b)
10
2
Division of 10 and 2 is 5

Output 2:
Enter value of a and b for division (a/b)
50
0
You can’t divide a number by 0
Please run the program once again and give proper value

In above example we are enclosing if and else block code in curly braces as both if and else has multiple lines of code or block of code to be executed.

Scanf(): For user input

In above c program we are asking user to enter the values for variable a and b. You can know more about scanf() method/function in this video tutorial: Using Scanf in C Program

if else Construct in C: Division of 2 numbers logic


[youtube https://www.youtube.com/watch?v=WLLJn3hcFa0]

YouTube Link: https://www.youtube.com/watch?v=WLLJn3hcFa0 [Watch the Video In Full Screen.]


This video was produced as building block for our simple calculator application.

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

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