Functions in C++

What are functions?

Functions help break down your code into reusable blocks, making it more organized and readable.

Why Use Functions?

Basic Function Example

This function prints a message:


#include <iostream>
using namespace std;

void sayHello() {
    cout << "Hello, welcome to C++!" << endl;
}

int main() {
    sayHello(); // Calling the function
    return 0;
}
            

Function with Parameters

Functions can take inputs (parameters) and use them:


#include <iostream>
using namespace std;

void greet(string name) {
    cout << "Hello, " << name << "!" << endl;
}

int main() {
    greet("Alice"); // Output: Hello, Alice!
    greet("Bob");   // Output: Hello, Bob!
    return 0;
}
            

Function with Return Value

Functions can also return values:


#include <iostream>
using namespace std;

int add(int a, int b) {
    return a + b;
}

int main() {
    int sum = add(5, 3);
    cout << "Sum: " << sum << endl; // Output: Sum: 8
    return 0;
}