# for loops in c++

• 10-15-2002
brianptodd
for loops in c++
I am writing a program using for loops and outputting the number of iterations in each loop. However, my program is outputting a line for every iteration of the loop, not just the total number of iterations.

Is there a way to count the number of iterations of a loop and output that total?

Attached is the program.

Brian
• 10-15-2002
Magos
Code:

```int Counter = 0; for(int i=0; i<10; i++) {   Counter++;   ... //Do whatever you want } cout << Counter;```
You could also print i+1, but that depends on which starting value i has. A general formula for this loop:

for(int i=a; i<b; i++)

would be: b-a times (assuming that the for loop completes, and is not breaked).
• 10-15-2002
Davros
You mean something like:

Code:

```int cnt = 0; for (int i = -10; i <= 10; i++) {   cnt++; } cout << "Loop 4 executes " << cnt << " times.";```
}
• 10-15-2002
brianptodd
Thanks for the help

Brian
• 10-15-2002
brianptodd
problems
In my program I am running 7 for loops, using counter for each one leaves me with each loop adding its iterations to the counter. Do I need to use a different name for each counter?

Brian
• 10-15-2002
Magos
Depends. If you print the result after each loop you can use the same. Just remember to nullify it (set it to 0) after every loop.
Code:

```int Counter = 0; for(...) {   Counter++; } cout << "Loop 1: " << Counter; Counter = 0; for(...) {   Counter++; } cout << "Loop 2: " << Counter; Counter = 0; for(...) {   Counter++; } cout << "Loop 3: " << Counter;```
• 10-15-2002
Gnoober
edit: I guess I answered his question about the same time Magos did... sorry;)
• 10-15-2002
brianptodd
thanks all
Thanks for your help again. I am just getting started so I'm sure most of my questions will be easily answered.

Brian