![]() |
|
#1
|
|||
|
|||
Help using nested for loopsProgram Help Using nested for loops
-------------------------------------------------------------------------------- I'm having trouble with this program the objective is to Prompt the for a int. from 0-999, then split the int into three digits, then output the three digits from 000 through number entered using 3 nested for loops. i.e integer entered: 3 ; 000,001,002,003. I can get the second and last digits to work but I can't figure out what if statement(s) I need to use, so the program will work. Here is what I have so far: CPP / C++ / C Code:
Last edited by JdS : 04-Oct-2004 at 10:07.
Reason: Please insert your example C/C++ codes between [c] and [/c] tags
|
|||
|
#2
|
|||
|
|||
|
Quote:
Well, I would have done this with one loop, but if your assignment explicitly specified three loops, I would say that you have "almost" got it. First of all: you seem to have correctly split the number into its hundreds, tens, and units digits. For debug purposes I would temporarily put an output statement to confirm this, but you can probably tell that you have this part OK. Now, when you say your program doesn't quite work, I know that you have tried it. What did you get? Well if you enter any number from 1 to 9, it is perfect, right? What if you enter, say, 14. What did you get? I got 000 001 002 003 004 010 011 012 013 014 Now, what's happening here? In your program for this example the inner loop counter only goes from 0 through 4, so no numbers with units digit greater than 4 are printed. Not quite what you had in mind. Look at the action: The outer loop goes through all numbers whose hundreds digit is 0, then all numbers whose hundreds digit is 1, etc. For each value of outer loop counter, the middle loop prints all numbers whose tens digit is 0, then all numbers whose tens digit is 1, etc. For each value of outer loop counter and middle loop counter, the inner loop prints all numbers in the sequence. So, in this case, with k == 0 and i == 0, you want the inner loop to go from 0 through 9, when k == 0 and i == 1, you want the inner loop to go from 0 to e (the units digit). So, in general, the inner loop has two possible limits: The inner loop (which has the output statement) goes from 0 through 9 in all cases except when k == c and i == d. But when k == c and i == d you want the inner loop to go from 0 through e. You can make an if(){}else{} statement that sets the proper upper limit for the inner loop, based on current values of k and i. Now, back up a little, and perform the same magic on the other loop(s) that need fixing. Regards, Dave |
Recent GIDBlog
Not selected for officer school by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| looped loops | Marjolein | C++ Forum | 28 | 06-Jul-2004 08:55 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The