Saturday, April 19, 2025

C++ Arrays in Functions

We can use array as function argument. For example, function printElement() will have task printing specific element using positions/indexes.

Our function will take two parameters, first will be our array of integers, and second will be position of some element.

Of course, declaration of the function will be done before main() section of the program.

We are using genArr[] as generic/abstract name for any real array we pass, and integer posOfElem will represent any position of an element we need, because we can use this function multiple times, on multiple different arrays.

Our real array "numbers" with real values is in main() section. We have five elements total, and searching for value at position four, in this example: 

#include <iostream>

using namespace std;

void printElement(int genArr[], int posOfElem) {
    cout << "Element of array: " << genArr[posOfElem] << endl;
}

int main() {

    int numbers[5] = {23, 34, 56, 5000, 2};

    printElement(numbers, 4);

    return 0;

}

 Result:

Element of array: 2

Process returned 0 (0x0)   execution time : 0.137 s
Press any key to continue.

An absolutely same approach when we are working with arrays that store other data types.

In this example we have array of characters, so our first parameter for function will be generic array g[], and second parameter integer "x" will represent position of some element we care about when function is called.

Don't forget single quotes around elements, because we are working with individual characters and not strings (words).

Run this code: 

#include <iostream>

using namespace std;

void printElement(char g[], int x) {
    cout << "Element of array: " << g[x] << endl;
}

int main() {

    char simbols[3] = {'A', 'C', 'D'};

    printElement(simbols, 1);

    return 0;

}

Result:

Element of array: C

Process returned 0 (0x0)   execution time : 0.157 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...