I am writing a program that prints products of a number, (for example, 2 can be 1 * 4, 2 * 2, 4 * 1 and counter shows (3) numbers), I need to have a counter that counts how many numbers were printed. I can't use (i) as a counter as it counts everything.
for(i=1; i<=number; i++)
{
if(number%i==0)
cout<<i<<"*"<<number/i<<"="<<number<<endl;
}
return 0;
Just add another variable and expand the body of the if-statement right?
int count = 0;
for(i=1; i<=number; i++)
{
if(number%i==0) {
cout<<i<<"*"<<number/i<<"="<<number<<endl;
count++;
}
}
cout << "Printed " << count << " times" << endl;
return 0;
Because i
is declared outside of the loop, gets initialized to 1, and is already incremented by 1 each iteration, you can just print it out after.
int i;
for(i=1; i<=number; i++)
{
if(number%i==0)
cout<<i<<"*"<<number/i<<"="<<number<<endl;
}
cout << "Looped " << i << " times\n";
return 0;
Just note i
must be declared outside the loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.