Addition of two numbers using function and without using function in c++


Addition of Two Numbers using function and without using function in c++


                Addition of two numbers in c++ is done using "+" (Addition operator). We will take two integers from user and add them. once added we will display the sum to the user. The program can be done by using function or by not using function, also the sum can be printed for n number of test cases. we will see all the methods below.

Addition of two numbers without using function

Logic

  1.  Take First Number
  2.  Take Second Number
  3.  Add them
  4.  Print the sum

Code

#include <iostream>
using namespace std;


int main() {

    cout<<"Enter two numbers "<<endl;

    int a;    

    cin>>a;

    int b;     

    cin>>b;

    int sum = a + b;   

    cout<<"sum = "<<sum; 

    return 0;

}


Addition of two numbers using function

Logic 

  1.  Define function add for calculating sum.
  2.  Take two integers as input.
  3.  Call function add.
  4.  Print the sum.

Code


#include <iostream>
using namespace std;

int add(int x, int y){

    int sum = x + y;

    cout<<"Sum = "<<sum<<endl;

    return 0;

}

int main() {

    cout<<"Enter two numbers "<<endl;

    int a,b;

    cin>>a>>b;

    add(a,b);

    return 0;

}


Addition of two numbers for n number of times

Logic

  1.  Define function add for calculating sum.
  2.  Take the number of test cases.
  3.  Repeat for n test cases using while loop
  4.  Take two integers as input.
  5.  Call function add.
  6.  Print the sum.

Code

#include <iostream>
using namespace std;

int add(int x, int y){

    int sum = x + y;

    cout<<"Sum = "<<sum<<endl;

    return 0;

}

int main() {

    cout<<"Enter the number of test cases "<<endl;

    int n;

    cin>>n;

    while(n--){

    cout<<"Enter two numbers "<<endl;

    int a,b;

    cin>>a>>b;

    add(a,b);

    }

    return 0;

}



Other Code Solutions

Post a Comment

0 Comments