Quick vector problem help

closed account (N0M9z8AR)
Create a vector and fill it with random numbers from 1 to 100 until the new value is a multiple of 19. Print out the values and how numbers in the vector.

Can someone explain to me how I go about doing this problem. I tried doing it but it not correct.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 #include<iostream>
#include<cstdlib>
#include<time.h>
#include<vector>

using namespace std;

int main()
{
    srand(time(NULL));
    vector<int> nums;
    int sum=0, counter=0;


    while(sum % 19 == 0){

        nums.push_back(rand()%100+1);
        sum += nums[counter];
        counter++;
}

    for(int i=0; i<nums.size(); i++)
    {
        cout<<nums[i]<<" ";
    }
    cout<<"\n\n";
    cout<<"#'s in vector: "<<counter;
    return 0;
}
You want to execute the loop until the new value is a multiple of 19. You're executing the loop while the sum of the numbers is a multiple of 19.

1
2
3
4
5
6
    int num;  // No need for sum
    do 
    {  num = rand()%100+1;
       nums.push_back(num);
        counter++;
    } while (num%19 != 0);

First of all your problem statement says "...the new value is a multiple of 19." and you are checking if sum is multiple of 19.

Secondly you are checking if sum % 19 == 0
First time the mod is zero (zero mode anything is zero?!)

When first number is generated the mod is non zero, hence the condition sum % 19 == 0) becomes false and the while loop ends.

If you want to check if the sum is multiple of 19 or not then try this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <vector>

using namespace std;

int main() {
  srand(time(NULL));
  vector<int> nums;
  int sum = 0, counter = 0;

  do {

    nums.push_back(rand() % 100 + 1);
    sum += nums[counter];

    counter++;
  } while ((sum % 19) != 0);

  for (auto &num : nums) {
    cout << num << " ";
  }
  cout << "\n\n";
  cout << "#'s in vector: " << counter << "\n";
  return 0;
}


Note the change to while loop. The change to for loop is not necessary for it to work buts neater to look at. Its called range-based loop.

Also, the C++ way to generate and use random numbers is to use the <random> header, more here http://www.cplusplus.com/reference/random/
Topic archived. No new replies allowed.