Introduction
Functions help us organize code into small, reusable pieces. They make programs easier to read, write, and fix.
Functions help us organize code into small, reusable pieces. They make programs easier to read, write, and fix.
return_type function_name(parameter_list) {
// code to do the task
return value; // if needed
}The return_type tells what kind of result the function gives back.
The parameter_list is where you put inputs the function needs.
void sayHello() { std::cout << "Hello!" << std::endl; }
int add(int a, int b) { return a + b; }
This program uses a function add to add two numbers. It shows how functions help reuse code and keep main simple.
#include <iostream> // Function to add two numbers int add(int x, int y) { return x + y; } int main() { int result = add(5, 3); std::cout << "5 + 3 = " << result << std::endl; return 0; }
Functions help avoid repeating the same code many times.
They make programs easier to test and fix.
Good function names explain what the function does.
Functions break big tasks into smaller parts.
They let you reuse code easily.
Functions make programs clearer and easier to manage.
add that returns an integer and takes two integers as parameters in C++?#include <iostream>
int square(int x) {
return x * x;
}
int main() {
int result = square(4);
std::cout << result;
return 0;
}square returns the input multiplied by itself.result is 16 and printed.#include <iostream>
int multiply(int a, int b) {
int product = a * b;
}
int main() {
std::cout << multiply(3, 5);
return 0;
}return product; inside the function fixes the error.main()?Pass the test and this pattern moves unknown