Subprograms



In C++, a subprogram (also known as a function) is a block of code that performs a specific task and can be called whenever needed in a program. Functions help structure and organize code, making it easier to understand, maintain, and reuse.


Example:

Given two natural numbers n and m. Determine the sum of the reversed digits of n and m.

#include < iostream >
using namespace std;

int reverse(int x)
{
    int r = 0;
    do
    {
        r = 10 * r + x % 10;
        x /= 10;
    }
    while(x != 0);
    return r;
}

int main(){
    int n , m;
    cin >> n >> m;
    cout << reverse(n) + reverse(m);
    return 0;
}


Function Header

The function has a header: int reverse(int x), from which we deduce that:



Function Body

The function has a block of statements, the function body, delimited by braces {}, which specifies the operations to obtain the result. Furthermore:


Void Functions

Functions with a return type of void in C++ are functions that do not return any value. These functions are used to perform actions or operations that do not require an explicit result. Usually, void functions are used to manipulate data, display information on the screen, or perform other auxiliary actions within a program.


Characteristics of void Functions:


Example:

#include < iostream >
using namespace std;

// Function that displays a greeting message
void greet()
{
    cout << "Hello! Welcome!" << endl;
}

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

In this example, the greet function displays a message on the screen and does not return any value.


Color Contrast

Text Size

Text Spacing

Reading Aids


In this section you can generate a summary of the page content using AI! Feel free to use the button below whenever you are in a hurry and don't have time to learn everything!


Summary

In this section you can ask our expert robot anything related to the questions you encountered during the lessons! Feel free to use the button below whenever you need additional explanations!


Chatbot