Menu
Coddy logo textTech

Parameters

Part of the Fundamentals section of Coddy's C++ journey — lesson 52 of 74.

An argument in a function is a value that you pass into the function when you call it. To add arguments to a function we write them inside the parenthesis ():

return_type method_name(data_type arg1, data_type arg2, ...) {
	// code
}

We can name the arguments as we want and we can write as many arguments as we need, as long as the names follow standard variable naming rules: they must start with a letter or underscore, and can only contain letters, digits, and underscores — no special characters like /, &, or !.

To call a function and pass arguments to it we write:

method_name(value1, value2, value3, ...);

Passing too many arguments to a function that is expecting less arguments will cause the program to fail

Example of usage:

void isEven(int number) {
	if (number % 2 == 0) {
		std::cout << number << " is even" << std::endl;
	} else {
		std::cout << number << " is odd" << std::endl;
	}
}
int main() {
    for (int i = 15; i < 34; i++) {
	    isEven(i);
	}
	for (int i = 153; i < 219; i++) {
	    isEven(i);
	}
    return 0;
}

Here we have a function called isEven that accepts one argument called number and prints whether the number is even or odd.

Then we call the function twice: once for all the numbers between 15 and 34, and second time for all numbers between 153 and 219.

challenge icon

Challenge

Easy

Write a program that gets two int numbers as input. The input numbers are the arguments of the function. 

Create a function that gets two arguments, calculates the product of them, and prints it. Name the function however you like.

Call the function with these input numbers.

Note! In your code, write the function before it's call/execution statements.

Cheat sheet

Function arguments are values passed into a function when calling it. Define arguments inside parentheses with their data types:

return_type function_name(data_type arg1, data_type arg2, ...) {
    // code
}

Call a function by passing values as arguments:

function_name(value1, value2, value3, ...);

Example function with one argument:

void isEven(int number) {
    if (number % 2 == 0) {
        std::cout << number << " is even" << std::endl;
    } else {
        std::cout << number << " is odd" << std::endl;
    }
}

int main() {
    isEven(15);  // calling function with argument
    return 0;
}

Note: Passing too many arguments to a function will cause the program to fail.

Try it yourself

#include <iostream>

// Function declaration


int main() {
    int a, b;
    std::cin >> a >> b;
    // Call the function with a and b as arguments
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals