nest loop problem

S

sofin

Here is a routine to find all combination of 3 digits.
How to write a program where the number of digits is a variable?


int i,j,k;

for(i=0;i<10;++i)
{
for(j=0;j<10;++j)
{
for(k=0;k<10;++k)
{
// Print the digits
cout << i << j << k << endl;
}
}
}
 
D

Daniel Pitts

sofin said:
Here is a routine to find all combination of 3 digits.
How to write a program where the number of digits is a variable?


int i,j,k;

for(i=0;i<10;++i)
{
for(j=0;j<10;++j)
{
for(k=0;k<10;++k)
{
// Print the digits
cout << i << j << k << endl;
}
}
}

You wouldn't use loops, you would use an array of digits, and increment
the least significant digit until it is more than a digit, you would
then "carry" that value to the next digit, and so on.
 
R

Ron AF Greve

sofin said:
Here is a routine to find all combination of 3 digits.
How to write a program where the number of digits is a variable?


int i,j,k;

for(i=0;i<10;++i)
{
for(j=0;j<10;++j)
{
for(k=0;k<10;++k)
{
// Print the digits
cout << i << j << k << endl;
}
}
}

It is a bit late here but wouldn't this do the trick (think simple)

#include <iostream>
#include <iomanip>

using namespace std;
int main()
{

int NrOfDigits = 4; // or pass through atoi( argv[1] )

int Max = 1;

for( int Cnt = 0; Cnt < NrOfDigits; ++Cnt )
{
Max = Max * 10;
}

for( int Cnt = 0; Cnt < Max; ++Cnt )
{
cout << setw( NrOfDigits ) << setfill( '0' ) << Cnt << endl;
}

return 0;
}



Regards, Ron AF Greve

http://informationsuperhighway.eu
 
S

st.kpo15

I am Rocky from London.
int main()
{

int NrOfDigits = 4; // or pass through atoi( argv[1] )

int Max = 1;

for( int Cnt = 0; Cnt < NrOfDigits; ++Cnt )
{
Max = Max * 10;
}

for( int Cnt = 0; Cnt < Max; ++Cnt )
{
cout << setw( NrOfDigits ) << setfill( '0' ) << Cnt << endl;
}

return 0;

}
Alcoholism Information
<a href=http://www.alcoholisminformation.org>Alcoholism Information</a>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,897
Members
47,439
Latest member
shasuze

Latest Threads

Top