A function is one of the most useful code writing tools in programming!
We follow this syntax for creating functions.
dataType functionName () {
// statements of your function
}We can use functions to often simplify large blocks of code.
For example, we can write a function that displays a message in a console.
void hello () {
cout << "Hello, I'm Emu Ootori!";
}By calling this function in our main(), we execute the statement inside the hello() function.
void hello () {
cout << "Hello, I'm Emu Ootori!";
}
int main () {
hello(); // Outputs "Hello, I'm Emu Ootori!"
return 0;
}Function Arguments
A function can take in inputs as well.
These inputs that a function takes are called arguments.
Suppose that we want to display a number in the console using a function.
We can instead assign an argument num and initialize it as an integer like this.
void displayNum (int num) {
cout << num << endl;
}This way, if we do it like this, we can change the number we want to output as well.
int main () {
displayNum(2); // Outputs "2"
displayNum(5); // Outputs "5"
displayNum(20); // Outputs "20"
displayNum(69); // Outputs "69"
return 0;
}They can also take in multiple inputs.
We can have a function that adds two numbers.
void add (int num1, int num2) {
int sum = num1 + num2;
cout << "The sum of " << num1 << " and " << num2 << " is " << sum << endl;
}However, for each argument we add, we separate our inputs with a comma.
int main () {
add(1, 2); // Outputs "The sum of 1 and 2 is 3"
return 0;
}You can also other data types aside from int when assigning functions too.
void line (char lineCh) {
for (i = 1; i <= 80; i++) cout << lineCh;
}Note
When using strings as an argument in a function, make sure to use the
char*data type.void displayMessage (char* message) { cout << message << endl; }
line()