How to access array values in C++?

Here is the simple program to find the multiples of 3. I can get the correct multiples of 3. But when I am trying to access a particular value. It’s throwing me garbage.

#include <iostream>

using namespace std;

int main()
{
    int n,i;
    
    std::cout <<" Enter number: "<< std::endl;
    std::cin >> n;
    int m3[n];
    
    for (i = 1; i < n; i++) {
        /* code */
        if(i % 3 == 0){
           m3[i]=i;
           cout<<m3[i];
           cout<<endl;
        }
         
    }
    cout<<endl;
           cout<<m3[1];
    
}

Output:
output

1 is not divisible by 3, so your for loop never put a value in m3[1]. The 32767 is junk data.

2 Likes

Thank you for answering @ArielLeslie
Hmm, that makes sense.

But how can I access by index and not by value? Let’s say I want value 3 which is at index 0 or value 6 which is at index 1.

Nothing valid sits at index 1. 3 is at index 3. 6 is at index 6, etc.

Try adding a loop to print every value in your array and you can see what we mean.

1 Like

Oh right, now I understood.

Thank You @JeremyLT and @ArielLeslie

1 Like