Saturday, April 19, 2025

C++ Printing Array Elements

It's easy to list/use elements from array in C++. We will use simple for loop to do that. Our starting point will be zero, and ending point will be total number of elements in an array.

This is case when we know how many elements will array store, or array is small enough to count them visually.

Of course, positions will be used here and abstract "x" will represent any of those elements while a loop is working until it reaches top level

#include <iostream>

using namespace std;

int main() {

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

    int x = 0;

    for (x; x < 5; x = x + 1) {
        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.284 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 .  ...