0
/*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 :)

2
Contributors
2
Replies
18
Views
2 Years
Discussion Span
Last Post by Entalist
1

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.