loop counter

I'm very new to c++.

Is there a way to count of the number of times a wile loop iterates? And capture the number in a variale??

1
2
3
4
5
6
7
8
// ...

int iterated; iterated = 0;
while()
{
        // ...
        iterated++;
}
prefer to initialize your variables when declaring them:
1
2
int iterated; iterated = 0;
int iterated = 0;
closed account (1CfG1hU5)
to make this example more interesting, making random number for i to reach

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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
 {

  int i = 0;    // declare integer and assigned to 0
  int n;

  srand(time(NULL));  // initialize random number generator

  n = rand() % 14+2;  // choose random number to place in n. high 14, no less than 2

  printf("i is 0 to begin, so add 1 to the value of n for total executions\n");
  printf("the value of n for i to reach is %d\n", n);

while (i <= n)
 {
    printf("loop executed value is %d\n", i);
    i++;  // increment loop 1 at a time
  }

    printf("while loop has executed %d times\n", i);


return 0;

}


i get 15 sometimes with rand(), should be a number from 2 to 14.
Last edited on
Thank you. That's all very helpful. Now to be a little more specific. I am starting with a user input (a whole number). The goal is to us a loop to decrement the input number by 10. What I want to out put is the final number of iterations ONLY.

Here is the code I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

#include <iostream>
using namespace std; 
          
int main()
{         
   int ticketsWon;
   int num; num = 0;

   //ask user to input number of tickets won
   cout << "Enter the number of tickets you won: ";
   cin >> ticketsWon;

   //if number entered is >= 10 subtract 10
   while(ticketsWon >= 10)
   {
        ticketsWon = ticketsWon - 10;
        cout << "Candy Bars = " << ++num << " \n";

   }
    
   return 0;
}


It's basically doing what I want, except it's printing every iteration. Like this:



flip2 ~/kingmat 81% ./arcade3
Enter the number of tickets you won: 100
Candy Bars = 1 
Candy Bars = 2 
Candy Bars = 3 
Candy Bars = 4 
Candy Bars = 5 
Candy Bars = 6 
Candy Bars = 7 
Candy Bars = 8 
Candy Bars = 9 
Candy Bars = 10 



What I want to print is JUST the last line. Thanks!
Topic archived. No new replies allowed.