HELP PLEASE counting random numbers until it reaches 58

I had to write a code for range [40,200] and random numbers should have printed until it printed 58. The code is right and it does that. However, the second part is to print how many integers did it print until it reached 58. and I do not know how to do it, can you help me please and tell me what code should I use for that? I searched all over the internet,however I could not find it. Help me please, I am beginner and I want to study how to do it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
#include<time.h>
using namespace std;
int main()
{
        int x;
    do {
    
        x=rand()%161+40;
        cout<<x<<endl;
    
    }
    while (x!=58);
    
    return 0;


}
Last edited on
What if you had a counter and you would increase it by one on each iteration?
so should I declare int counter; and than how to increase it by one with each iteration? should I write x+counter? or how ? I do not know much in c++, I only had 2 lessons and I am trying and trying and I like it, but I do not know much :)) Can you help me please and tell me how can I do it?
It is not about writing homework I should know how it works..
Yeah it's actually pretty easy to do that, just declare an int counter and initialize it to zero

int counter=0;

For every iteration you add 1 to the counter.

counter=counter+1; or counter++; for short.
1. #include <cstdlib>

2. Seed the pseudo-random number generator, once, at the start.
http://en.cppreference.com/w/cpp/numeric/random/srand

3. Each time through the loop, increment a counter.

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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std ;

int main()
{
    // seed the random number generator
    srand( time(0) ) ;

    // initialize a counter to zero
    int cnt = 0 ;

    int x ;

    do {

        // increment the counter
        ++cnt ;

        x=rand()%161+40;
        cout << cnt << ". " << x << '\n' ;

    }
    while (x!=58);
}
Thank youu!!!!! I get everything now!!! thank you thank you!! :)
Topic archived. No new replies allowed.