C++ Program Add Two Numbers using Class and Function
Source Code:
#include <iostream> using namespace std; class Add{ public: /* Two variables that we are going to * add. If you want to add float or double * variables instead, just change the data * type. for example: float num1, num2; */ int num1, num2; /* This function ask the user for two numbers. * The numbers that user enter are stored into * num1 and num2 variables so that we can add * them later. */ void ask(){ cout<<"Enter first number: "; cin>>num1; cout<<"Enter second number: "; cin>>num2; } /* This function adds the numbers that are passed * to it through arguments. I have used parameter names * as n1 and n2 but you can choose any parameter name. * This function returns the result. */ int sum(int n1, int n2){ return n1+n2; } //This function displays the addition result void show(){ cout<<sum(num1, num2); } }; int main(){ //Creating object of class Add Add obj; //asking for input obj.ask(); //Displaying the output obj.show(); return 0; }
Post a Comment