C++ Programming/Exercises/Functions
From Wikibooks, the open-content textbooks collection
[edit] EXERCISE 1
Write a program with a function that takes two int parameters, adds them together, then returns the sum. The program should ask the user for two numbers, then call the function with the numbers as arguments, and tell the user the sum.
Solution
#include <iostream>
using namespace std;
int AddTwo (int addend1, int addend2) {
return addend1 + addend2;
}
int main () {
int number1, number2, sum;
cout << "Enter two integers:\n";
cin >> number1 >> number2;
sum = AddTwo(number1, number2);
cout << "\nThe sum is " << sum << ".";
return EXIT_SUCCESS;
}
The solution in C.
#include <stdio.h>
int add(int, int);
int main()
{
int a, b, sum;
printf("A: ");
scanf("%d", &a);
printf("B: ");
scanf("%d", &b);
sum = add(a, b);
printf("The sum of %d and %d is %d.\n", a, b, sum);
return 0;
}
int add(int a, int b)
{
return a + b;
}
[edit] EXERCISE 2
Basically the same as exercise 1, but this time, the function that adds the numbers should be void, and takes a third, pass by reference parameter; then puts the sum in that.
Solution
#include <iostream>
using namespace std;
void AddTwo (int addend1, int addend2, int &sum) {
sum = addend1 + addend2;
}
int main () {
int number1, number2, sum;
cout << "Enter two integers:\n";
cin >> number1 >> number2;
AddTwo(number1, number2, sum);
cout << "\nThe sum is " << sum << ".";
return EXIT_SUCCESS;
}