Ana içeriğe geç
eLearner.app
Modül 3 · Ders 1 ders 2Kurstaki 7/18~10 min
Modül dersleri (1/2)

Temel işlevler

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

Egzersiz#cpp.m3.l1.e1
Denemeler: 0Yükleniyor…

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.

Düzenleyici yükleniyor…
İpucu göster

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

3 denemeden sonra çözüm mevcut

Egzersiz#cpp.m3.l1.e2
Denemeler: 0Yükleniyor…

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.

Düzenleyici yükleniyor…
İpucu göster

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

3 denemeden sonra çözüm mevcut