Addition Of Numbers Using Function


Explanation

A function can also receive values from the main() function through parameters. In this program, the user-defined function add() accepts two integer values, adds them, and displays the result. The same function is called multiple times with different values, which avoids writing the addition logic repeatedly.

How It Works?

  • Step 1: Include the required header files stdio.h and conio.h.
  • Step 2: Create a user-defined function add(int a, int b) that accepts two numbers.
  • Step 3: Add both numbers and store the result in the variable k.
  • Step 4: Display the total using the printf() function.
  • Step 5: Inside the main() function, call add() several times with different values.
  • Step 6: Each function call calculates and displays the addition of the given numbers.
  • Step 7: Stop the screen using getch().

Example Program


#include <stdio.h>
#include <conio.h>

void add(int a, int b)
{

    int k;

    k = a + b;

    printf("\n Total is %d", k);

}

int main()
{

    clrscr();

    add(20, 10);

    add(30, 20);

    add(40, 30);

    add(50, 40);

    add(60, 50);

    getch();

}

Output

Total is 30
Total is 50
Total is 70
Total is 90
Total is 110

Practice Exercises

Task 1: Write a C program using a function named add() to add two numbers. Call the function five times with different values and display the sum each time.

Goal: Learn how to pass arguments to a user-defined function and reuse the same function for multiple calculations.

💡 Hint: Create a function add(int a, int b). Inside the function, add the two numbers and print the result. Call the function multiple times from main() using different values.
💡 Show Solution

#include <stdio.h>
#include <conio.h>

void add(int a, int b)
{

    int total;

    total = a + b;

    printf("\n Total is %d", total);

}

int main()
{

    clrscr();

    add(5, 10);

    add(12, 18);

    add(20, 25);

    add(30, 40);

    add(50, 60);

    getch();

}

Output
Total is 15
Total is 30
Total is 45
Total is 70
Total is 110
Explanation: The program defines a user-defined function named add() that accepts two integer values as parameters. Whenever the function is called, it adds the two numbers and displays the result. The same function is reused five times with different arguments, demonstrating the advantage of functions in reducing code repetition.