Sunday 28 December 2014

Write a c++ program to find the sum of two numbers using function.


#include<iostream>
using namespace std;
int sum(int a,int b)
{ return a+b;
}
int main()
{
int a=0,b=0;
cout<<"enter 1st no";
cin>>a;
cout<<"enter 2nd no";
cin>>b;
int c = sum(a,b);
}

Things to learn from this program :

Defining a Function:

function definition :

return_type function_name( parameter list )
{
body of the function
}

Declaring a Function:

return_type function_name(parameter list);

Calling a function :

function_name( [arg1, ... ] );

Function is to be defined outside main() function.
a and b are to be initialized to zero so that all previous values are deleted.


Another way of doing the program (if you want to do sum of known values):



#include<iostream>
using namespace std;
int sum(int a,int b){
return a+b;
}
int main()
{
int c= sum(10,20);
}

No comments:

Post a Comment

SAY HELLO!!