Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ What are Functions? | Introduction to Functions
C++ Introduction (copy) 1769617216468njii0h

bookWhat are Functions?

メニューを表示するにはスワイプしてください

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

main.cpp

copy
1234
int main() // `main` is the name of a function { return 0; }
Note
Note

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

get_bank_name.h

copy
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

main.cpp

copy
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

main.cpp

copy
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; }
question mark

What is the main advantage of using functions in a program?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 5.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 5.  1
some-alt