In the last section I mentioned βall the things functions are good for.β About this time, you might be wondering what exactly those things are. Here are some of the reasons functions are useful:
#include <iostream>
using namespace std;
int main() {
int x = 4;
x = x * 2;
x = x / 2;
x = x + 2;
x = x - 2;
cout << x << endl;
x = 13;
x = x * 2;
x = x / 2;
x = x + 2;
x = x - 2;
cout << x << endl;
x = 100;
x = x * 2;
x = x / 2;
x = x + 2;
x = x - 2;
cout << x << endl;
x = 22;
x = x * 2;
x = x / 2;
x = x + 2;
x = x - 2;
cout << x << endl;
x = 220;
x = x * 2;
x = x / 2;
x = x + 2;
x = x - 2;
cout << x << endl;
x = 0;
x = x * 2;
x = x / 2;
x = x + 2;
x = x - 2;
cout << x << endl;
x = 1000;
x = x * 2;
x = x / 2;
x = x + 2;
x = x - 2;
cout << x << endl;
x = 254;
x = x * 2;
x = x / 2;
x = x + 2;
x = x - 2;
cout << x << endl;
}
..you would reduce it to the 21 lines of code below, making it easier to read, debug, and use the function many times with rewriting it each time.
#include <iostream>
using namespace std;
void all_operators(int x) {
x = x * 2;
x = x / 2;
x = x + 2;
x = x - 2;
cout << x << endl;
}
int main() {
all_operators(4);
all_operators(13);
all_operators(100);
all_operators(22);
all_operators(220);
all_operators(0);
all_operators(1000);
all_operators(254);
}
While some functions do calculate values, the python idea of a function is slightly different from the mathematical idea of a function in that not all functions calculate values. Consider, for example, the turtle functions in this section. They made the turtle draw a specific shape, rather than calculating a value.