-1

So I have created an array that holds all the positive integers between 1 and a user inputed number,'n'. I have stored all of them in my array vector<int> numbers. The problem is accessing them. My plan is to loop through each element of the array and check if that specific element is divisible or not. The problem is that I cannot get the program to divide and instead, I am prompted with an error message when I run it. The message says the entire program is not responding. Debugging wise, there are not any errors.

I think there is something wrong with the

 for (int i=1; i<numbers.size()-1; i++)
        {
            for (int b=0; b<=num; b++)
            {
                if (numbers[i] % b == 0)
                    cout << b << ", " ;
            }

        }

but I am not sure what. Here is the whole program.

#include <iostream>
#include <vector>

using namespace std;

int store (int num);

vector<int> numbers;

int main()
{
    int num;
    cout << "Enter a number: " << endl;
    cin >> num;

    store(num);
}

int store (int num)
{
    for (int a=1; a<=num; a++)
    {
        numbers.push_back(a);
    }


    for (int i=1; i<numbers.size()-1; i++)
    {
        for (int b=0; b<=num; b++)
        {
            if (numbers[i] % b == 0)
                cout << b << ", " ;
        }

    }
}
user3344400
  • 69
  • 1
  • 1
  • 3

1 Answers1

2

You start with b = 0, this leads to a Module 0 calculation which will result in an error. Also, you should start with i = 0 for the vector elements.

You can find more about this here: Can't Mod Zero?

Community
  • 1
  • 1
Roxxorfreak
  • 380
  • 2
  • 10
  • that solves the "not working" issue but it does give me the divisors. Instead its giving me a bunch of related integers. This is what command prompt looks like: Enter a number: 12 1, 1, 2, 1, 3, 1, 2, 4, 1, 5, 1, 2, 3, 6, 1, 7, 1, 2, 4, 8, 1, 3, 9, 1, 2, 5, 10 , 1, 11, Process returned 0 (0x0) execution time : 1.041 s Press any key to continue. – user3344400 Feb 23 '14 at 21:48
  • Seems to be correct. Divisors of 1: 1, of 2: 1,2, of 3: 1,3, of 4: 1,2,4,... of 11: 1,11. What were you expecting? – Lutz Lehmann Feb 23 '14 at 21:50
  • ahhhhhhhh misinterpreted the results. Thank you. – user3344400 Feb 23 '14 at 22:01