-
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
-
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).
-
You mean something like:
Code:
int cnt = 0;
for (int i = -10; i <= 10; i++)
{
cnt++;
}
cout << "Loop 4 executes " << cnt << " times.";
}
-
Thanks for the help
Thanks for your help.
Brian
-
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
-
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;
-
edit: I guess I answered his question about the same time Magos did... sorry;)
-
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