Saturday, April 19, 2025

C++ Number of Elements

In this example we will find number of elements in an array so we don't need to count them manually.

Solution is a little bit weird because we get size of whole array and than divide it by size of an individual element (in bytes).

Please note, when calculating array size we are not using an integer as data type, but size_t data type in combination with sizeof() function: 

#include <iostream>

using namespace std;

int main() {

    int numbers[] = {45, 234, 5000, 0, 567};

    size_t n = sizeof(numbers) / sizeof(numbers[0]);

    for (size_t x = 0; x < n; x++) {

        cout << "Element at position: " << x << " -> " << numbers[x] << endl;

    }

    return 0;

}

Result:

Element at position: 0 -> 45
Element at position: 1 -> 234
Element at position: 2 -> 5000
Element at position: 3 -> 0
Element at position: 4 -> 567

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

 We will use the same approach when working with individual characters

Don't forget to use single quotes for elements when data type is char:

#include <iostream>

using namespace std;

int main() {

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

    size_t n = sizeof(characters) / sizeof(characters[0]);

    for (size_t x = 0; x < n; x++) {

        cout << "Element at position: " << x << " -> " << characters[x] << endl;

    }

    return 0;

}

Result:

Element at position: 0 -> A
Element at position: 1 -> C
Element at position: 2 -> D

Process returned 0 (0x0)   execution time : 0.021 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 .  ...