C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Function to subtract two numbers

Introduction

In C programming, using functions helps organize and reuse code.
This program demonstrates how to subtract two numbers using a user-defined function that accepts arguments and returns the result to the main function.

 

C Program: Function to subtract two numbers

Method 1: The function with int return type (With Arguments, With Return)

C

#include <stdio.h>

 

// Function declaration

int subtract(int a, int b);

 

int main() {

    int num1, num2, result;

 

    // Taking input from user

    printf("Enter first number: ");

    scanf("%d", &num1);

    printf("Enter second number: ");

    scanf("%d", &num2);

 

    // Function call

    result = subtract(num1, num2);

 

    // Display result

    printf("Difference between %d and %d is: %d\n", num1, num2, result);

 

    return 0;

}

 

// Function definition

int subtract(int a, int b) {

    return a - b;

}

Output

 
OUTPUT :
Enter first number: 25
Enter second number: 10
Difference between 25 and 10 is: 15

Description

  1. Function Declaration:
    int subtract(int a, int b); tells the compiler that the function accepts two integers and returns an integer.
  2. Function Definition:
    The function computes the difference between a and b using a - b.
  3. Function Call:
    main() calls the function and stores the returned result in the variable result.
  4. Output Display:
    The result is printed using printf().

 

C Program: Function to subtract two numbers

Method 2: The function with void return type (With Arguments, No Return)

C

#include <stdio.h>

 

// Function declaration

void subtractNumbers(int a, int b);

 

int main() {

    int num1, num2;

 

    // Taking input from user

    printf("Enter first number: ");

    scanf("%d", &num1);

    printf("Enter second number: ");

    scanf("%d", &num2);

 

    // Function call

    subtractNumbers(num1, num2);

 

    return 0;

}

 

// Function definition

void subtractNumbers(int a, int b) {

    int difference = a - b;

    printf("Difference between %d and %d is: %d\n", a, b, difference);

}

Output

 
OUTPUT :
Enter first number: 50
Enter second number: 20
Difference between 50 and 20 is: 30

Description

  1. Function Declaration:
    void subtractNumbers(int a, int b); — defines a function that takes two integer arguments but returns no value.
  2. Function Definition:
    Performs subtraction (a - b) and directly displays the result.
  3. Function Call:
    The main() function passes user inputs (num1, num2) to subtractNumbers().
  4. No Return Statement:
    Since the function is of type void, it does not return any value to main().