You are here:

C++/Looping through integers...

Advertisement


Question
I am a puzzle enthusiast and many a times I have come across puzzles where I have to loop through digits e.g.
Find a 9-digit number with all digits unique that satisfies a certain condition. At times I resort to C++ programming to cut my effort short but usually I have to loop through all numbers which can be very taxing on the system. What I wish to learn is how to use a for..next loop where we can leave out the digit already used in a prev. loop. Example in pseudo-code(say I want to find a 3 digit number with all digits different):
for i=1 to 9
 for j= 1 to 9
    for k = 1 to 9
       number=100*i + 10*j + k
       //here I wish that while looping j, it should not use value that i has taken and while looping through k, it should not take values that i & j have been given
    next k
  next j
next i

//other code

Thanks a lot.  

Answer
One way I solve problems is to write down what I want to do in English and then convert that to code.  We can do that here:

//here I wish that while looping j, it should not use value that i has taken and while looping through k, it should not take values that i & j have been given

if (j != i && k != i && k != j)
 // do something

this if is execute for j and k provided j is not what i is and k is not what i and j is.

I think this is what you were wanting.  If not, please show by examples.

Bill

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Bill A

Expertise

I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.

Experience

I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Publications
Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

Education/Credentials
BS Computer Engineering

©2016 About.com. All rights reserved.