What are Functions?
Swipe to show menu
Functions are fundamental building blocks in programming. They are reusable blocks of code designed to perform a specific task. Functions help make code more organized, readable, and easier to maintain. By using functions, you can break a large, complex program into smaller, manageable subroutines.
main.cpp
1234int main() // `main` is the name of a function { return 0; }
The name main is already reserved by the C++ language. Therefore, when declaring a function with this name, the compiler will generate an error.
Creating a function involves several key steps to ensure it performs a specific task and integrates seamlessly into your program. A function consists of a return type, a name, parameters (if needed), and a body where the logic resides.
get_bank_name.h
123456// Returns the name of the bank std::string get_bank_name() // Function declaration with return type and name { std::string bank_name = "Future Savings Bank"; // Store bank name return bank_name; // Return it to the caller }
After creating a function, the next step is to call it. Calling a function executes the code inside it and allows you to use its result (if it returns a value).
main.cpp
1234567891011121314#include <iostream> #include <string> // Function to return the name of the bank std::string get_bank_name() { std::string bank_name = "Future Savings Bank"; return bank_name; // Return the name of the bank } int main() { std::cout << "Name of the bank: " << get_bank_name() << std::endl; }
Converting currencies is a common real-life task, especially in global transactions or travel. By creating a function, we can simplify this process, making the conversion reusable and efficient.
main.cpp
123456789101112131415#include <iostream> // Function to convert USD to Euros double convert_usd_to_eur(double usd_amount) { const double exchange_rate = 0.91; double euros = usd_amount * exchange_rate; return euros; } int main() { double usd = 100.0; // Amount in USD std::cout << usd << " USD = " << convert_usd_to_eur(usd) << " EUR" << std::endl; }
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat