Division of 2 Numbers: C


In this video tutorial you can learn the procedure followed in C programming to divide two numbers.

 
#include < stdio.h >

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

    printf("Enter 2 numbers for division\n");
    scanf("%d %d", &a, &b);

    c = a / b;

    printf("Division of %d and %d is %d\n", a, b, c);

    return 0;
}

Output:
Enter 2 numbers for division
10
5
Division of 10 and 5 is 2

You can write same program without using third variable to calculate division of 2 numbers, as below:

 
#include < stdio.h >

int main()
{
    int a, b;

    printf("Enter 2 numbers for division\n");
    scanf("%d %d", &a, &b);

    printf("Division of %d and %d is %d\n", a, b, (a/b));

    return 0;
}

Output:
Enter 2 numbers for division
10
5
Division of 10 and 5 is 2

Note: Instead of int you can take float variables too. That would help in taking both integer as well as real values from the user as input.

Division by 0

What if a user enters 0 for variable b. Any number divided by 0 will give undefined return. So lets handle the scenario using Decision Control Instruction In C: IF and inequality operator.

 
#include < stdio.h >

int main()
{
    int a, b;

    printf("Enter value for 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);

    if( b == 0 )
       printf("You can't divide a number by 0\n");

    return 0;
}

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

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

Output 3:
Enter value for a and b, for division (a/b)
0
5
Division of 0 and 5 is 0

In above program, != is inequality operator. It returns true(non-zero number) if the operands are not equal. == is equality operator. It returns true(non-zero number) if the operands are equal.

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

Division of Two Numbers: C Programming


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

YouTube Link: https://www.youtube.com/watch?v=QOhDxu0xbY8 [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 *