+ 2
Why we create functions in c/c++ languages?
explain me how functions work?
3 Answers
+ 1
Functions in C++ are very useful for multiple reasons.
For one, it allows us to create a single section of code that we can call and use throughout our program, such as a multiplication function or and average function or anything really. Functions are very powerful features in terms of what it gives to the coder.
Another reason is that instead of throwing all of our code into our main function, int main() for c++, we put sections into functions which allows us to easily debug code and port it over to other programs with the need for said function.
Creating a function in c++ goes as follows, it needs a return type, void/int/double/etc, it needs a name, like a variable name, and it needs parameters.
Here is a sample function:
void multiplication (int x, int y){
return x * y;
}
Calling this function in our main, or anywhere else, allows us to simply multiply two numbers together.
I would check up more on how functions work and their uses as this was a brief crash course (apologies for the lengthy message). There are plenty of awesome online resources for C++ help!
+ 1
void sum(a,b)
{
return x+y;
}
int main()
{
sum(2,3);
return 0;
}
that's it
+ 1
#include <iostream>
using namespace std;
int sum(int a,int b)
{
return a+b;
}
int main()
{
cout<<sum(2,3);
return 0;
}
harish tati -> first you didn't even initalize variable in sum function ,then your function is void and you have return value ,then inside sum function you call different variables to sum up...