Counting the Number of Loops in a program

I was wondering if you can count the number of times you loop a segment.

for example:
int x = 4;

while (x<6) {
cout<<"Hello World! \n";
}

could I count the number of times (using some function in the c++ language) that the program looped?
Last edited on
closed account (iG3b7k9E)
You could use the for loop to make your code loop a certain number of times.
x will always be smaller than 6. You loop for as long as your program runs :P
I don't quite understand the question. Just use a variable to keep track of the number of loops:
1
2
3
4
5
6
7
int count = 0;
while(condition)
{
++count;
//Code
}
std::cout<<count;

Or like Random said, use a for loop. Although if you declare the 'counter' inside the 'for' syntax then it won't live past the for loop's scope.
The variable idea sounds good. I'll give it a try and see if it works.
Thanks
Hello World will be displayed 10 times
1
2
3
4
5
int i;
for(i=0;i<10;i++)
{
cout<<"Hello World!\tNumber of Loops: "<<i+1<<endl;
}
Topic archived. No new replies allowed.