Lesson 7: Functions

Remember that a C++ program always start from the main function? In this lesson, you will learn about what a function is.

An add function

In the earlier, you learned to write a program to add two numbers.

//Program 7.1
int x = 0, y = 0;
int answer = 0;
std::cin >> x;
std::cin >> y;
answer = x + y;

Instead of adding the two numbers inside the main function, now I want to add them in a function. To do this, I need to declare a new function (computer doesn’t know about your new functions unless you declare them, like variables). The way to declare a function is this:

return_type function_name (data_type variable_name, ...)

For example, in the case of an add function, I would need to have two arguments so that I can add them. The two arguments will be declared inside the parenthesis. After adding, I need to return the answer to whatever variable that calls the function.

int add (int x, int y)

Above means that the add function takes in two inputs x and y of the integer type, and returns an integer type. Modify Program 7.1.

// Program 7.2
int add (int x, int y){ 
  return x + y; 
}

int main(int argc, const char * argv[]) {
 
 int x = 0, y = 0;
 int answer = 0;
 std::cin >> x;
 std::cin >> y;

 answer = add(x,y);
 
 std::cout << answer << std::endl;

 return 0;
}

You might ask why not just add the values inside the main function. If your program is large, having many operations inside your main function makes it unreadable. Breaking out the operations into functions make it easier for your program to be read and understand.

Other examples

A function may also return null type. This means that it does not return anything. To declare such type of functions, use the keyword void.

// Program 7.3
void sayHello () {
 std::cout << "Hello" << std::endl;
}

int main(int argc, const char * argv[]) {
 
 sayHello();
 
 return 0;
}

In Program 7.3, you see that the sayHello function does not need any input, and it does not return any type. If a function does not need any arguments, then use a pair of parenthesis ().

Challenge 1

Write a program to add, subtract, multiply and divide two integers. Break out each operation into its respective functions. Ask user to select an operation using 1,2,3 or 4, representing add, subtract, multiply and divide respectively. Also ask user to input two integers.

Output the answer to console.

Challenge 2

A classic programming exercise is called the FizzBuzz Test. The problem is stated below:

“Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.”

Write a program that perform the above test.

 

 

 

 

print