/*Write a program which will print all the pairs of prime numbers whose
sum equals the number entered by the user. */

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int maxNum;
    bool prime = true;
    cin >> maxNum;
    vector <int> primeSequence;

    for(int i = 1; i <= maxNum; i++)
    {
        for(int j = 2; j < i; j++)
        {
            if( i % j == 0 || i == 1)
            {
                prime = false;
            }
        }
        if(prime == true)
        {
            primeSequence.push_back(i);
            cout << primeSequence[i] << " is a prime\n";
        }
        prime = true;
    }
}

The code worked fine until I tried to implement vectors. I just printed i instead of primeSequence.
If I try to run it now, it just returns "random" numbers (some are even negative).

I never really worked with vectors, because arrays seemed sufficient so any help would be appreciated :)

Recommended Answers

All 2 Replies

That is because prime number i does not correspond to the index of the vector. Everytime you push a value into a vector, it takes the (n+1)th address. So, if your input is 10, i values 1, 2, 3, 5, and 7 are located at indices 0, 1, 2, 3 and 4 respectively. However, you're calling the elements at indices 1, 2, 3, 5 and 7, which you haven't assigned yet at the time each of them was called.

That makes sense. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.