Lompati ke konten utama
eLearner.app
Modul 3 · Pelajaran 1 dari 27/18 dalam kursus~10 min
Pelajaran modul (1/2)

Fungsi dasar

Functions allow organizing code into reusable logical blocks, reducing duplication and improving readability.

In C++, every function must declare the type of value it returns, its name, and the types of the parameters it accepts.

Defining a Function

Here is an example of a simple function that sums two integers:

Code
#include <iostream>

// Function definition
int add(int a, int b) {
    return a + b; // Returns the sum
}

int main() {
    int result = add(3, 4); // Function call
    std::cout << "Result: " << result << std::endl;
    return 0;
}

Structure and Signature

  • Return Type: the type of the value returned with the return statement (e.g. int, double, bool). If the function does not return any value, the special type void is used.
  • Name: the identifier to call the function (using camelCase style in accordance with R2).
  • Parameters: the list of input variables enclosed in parentheses (), each preceded by its type.

Declaration vs Definition

To place functions below the main function, you first declare the prototype (the signature without the body):

Code
#include <iostream>

// Prototype (Declaration)
int multiply(int a, int b);

int main() {
    std::cout << multiply(3, 5); // Valid
    return 0;
}

// Definition
int multiply(int a, int b) {
    return a * b;
}

Try it yourself

Latihan#cpp.m3.l1.e1
Upaya: 0Memuat…

Define a function named square that takes an integer n and returns its square (n * n). Call it inside main to calculate the square of 5 and print it using std::cout.

Memuat editor…
Tunjukkan petunjuk

The signature of the function is `int square(int n)`. Remember to place the function definition before `main`.

Solusi tersedia setelah 3 upaya

Latihan#cpp.m3.l1.e2
Upaya: 0Memuat…

Define a boolean function named isEven that takes an integer n and returns true if the number is even (using % 2 == 0), otherwise false. Call it in main with 4 and print it.

Memuat editor…
Tunjukkan petunjuk

The function must return a `bool`type. Use`n % 2 == 0`.

Solusi tersedia setelah 3 upaya