Simple function that sums up 2 numbers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Simple function that sums up 2 numbers

Creating a function after main () executes but called inside main () block of code and also declaring its name before main () starts executing.

20th Nov 2016, 3:08 AM
Mielu
Mielu - avatar
2 Answers
+ 1
/* we'll create a simple function that adds up the sum of 2 inputs from user but we will create it after main () executes yet we will call it within main () block of code. that is in fact our goal here :) for that to work properly we also need to declare its name before main () statrs executing. here we go :) */ #include <iostream> using namespace std; int myFunction (); /* notice the semicolon at the end of myFunction (), remeber that always when you code like this -> (execute main () and then create your functions) */ // now the program tarts xecuting int main() { return myFunction (); // simple statement :) } // and now we create our function that adds up 2 numbers from user input here below int myFunction () { int a, b, sum; cout << "Please enter a number: " << endl; cin >> a; cout << "Please enter another number: " << endl; cin >> b; sum = a + b; cout << "The sum of your numbers is: " << sum << endl; } /* remember, its just a simple function and does not check if your input is really a number or not, if you leave empty or input anything else than numbers you will get either error messages or numbers that might be some address */
20th Nov 2016, 3:09 AM
Mielu
Mielu - avatar
+ 1
#include <iostream> using namespace std; int sum(int a, int b) { return a + b; } int main() { int a, b; cout << "Enter 2 numbers: "; cin >> a >> b; cout << "Sum is " << sum(a, b); return 0; }
20th Nov 2016, 1:46 PM
Cohen Creber
Cohen Creber - avatar