C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Function to add two numbers

Introduction

In C programming, functions are used to divide a large program into smaller, manageable parts.
This program demonstrates how to add two numbers using a user-defined function.
The addition logic is placed inside a separate function named add(), which improves modularity and code reusability.

 

C Program: Function to add two numbers

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

C

#include <stdio.h>

 

// Function declaration

int add(int a, int b);

 

int main() {

    int num1, num2, sum;

 

    // Taking input from user

    printf("Enter first number: ");

    scanf("%d", &num1);

    printf("Enter second number: ");

    scanf("%d", &num2);

 

    // Function call

    sum = add(num1, num2);

 

    // Display result

    printf("Sum of %d and %d is: %d\n", num1, num2, sum);

 

    return 0;

}

 

// Function definition

int add(int a, int b) {

    return a + b;

}

Output

 
OUTPUT :
Enter first number: 10
Enter second number: 20
Sum of 10 and 20 is: 30

Description

  1. Function Declaration:
    int add(int a, int b); tells the compiler that there is a function named add which takes two integers and returns an integer.
  2. Function Definition:
    The function add(int a, int b) performs the addition of two integers and returns the result.
  3. Function Call:
    The main() function calls add(num1, num2) and stores the result in sum.
  4. Output Display:
    The result is printed on the screen using printf().

 

C Program: Function to add two numbers

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

In this program, we will create a void function that takes two numbers as arguments, adds them, and directly prints the result.

C

#include <stdio.h>

 

// Function declaration

void addNumbers(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

    addNumbers(num1, num2);

 

    return 0;

}

 

// Function definition

void addNumbers(int a, int b) {

    int sum = a + b;

    printf("Sum of %d and %d is: %d\n", a, b, sum);

}

Output

 
OUTPUT :
Enter first number: 15
Enter second number: 25
Sum of 10 and 20 is: 40

Description

  1. Function Declaration:
    void addNumbers(int a, int b); tells the compiler that the function does not return a value.
  2. Function Definition:
    The function calculates the sum and prints it directly inside the function body.
  3. Function Call:
    The main() function calls addNumbers(num1, num2) after reading user input.
  4. No Return Value:
    The function performs the task (printing) without returning any result to the caller.