Cover Image for Add two Numbers using Function in C++

Add two Numbers using Function in C++

To add two numbers using a function in C++, you can create a simple function that takes two parameters (the numbers to be added) and returns their sum. Here’s an example:

#include <iostream>

// Function to add two numbers
int addNumbers(int num1, int num2) {
    return num1 + num2;

int main() {
    int number1, number2;

    // Get user input for the first number
    std::cout << "Enter the first number: ";
    std::cin >> number1;

    // Get user input for the second number
    std::cout << "Enter the second number: ";
    std::cin >> number2;

    // Call the addNumbers function and store the result
    int sum = addNumbers(number1, number2);

    // Display the result
    std::cout << "Sum: " << sum << std::endl;

    return 0;

In this program:

  • We define a function called addNumbers that takes two integer parameters (num1 and num2) and returns their sum using the + operator.
  • In the main function, we declare two integer variables, number1 and number2, to store the user’s input.
  • We use std::cin to get input from the user for both number1 and number2.
  • We call the addNumbers function with number1 and number2 as arguments and store the result in the variable sum.
  • Finally, we use std::cout to display the sum.

When you run this program, it will prompt you to enter two numbers, and then it will calculate and display their sum.


The Tech Thunder

The Tech Thunder

The Tech Thunder