Simple for loop question I've been having a hard time with for loop, can somebody help me out here?? I want to make the following pattern *** ** * I'm using the following code, but not getting anywhere close. Can someone just tell me whats wrong with my code?? int n = 4; for (int r = 1; r <=n; r++) { int temp = n; temp--; for(int c = temp; c >=1; c--){ printf("*"); } printf("\n"); }
Without knowing what's going wrong, int temp = n; is the most suspicious line. Free advice: be consistent with your brackets. If you start with them on their own line, make them all on their own line. Your code will be MUCH easier to read. Having one for loop incrementing and one decrementing is pretty much guaranteed to be confusing when reading the code.
So I should have both incrementing or both decrementing at a given time??
If possible. Sometimes you can't, but in this case, I think it may be contributing to your difficulties. Frequently, when a loop doesn't work right, you have to mentally do the loop and keep track of the value of the variables and if the variables are going different directions it's not as much fun.
I can do it by keeping both rows and columns incrementing, but what I wanna know is why is this approach incorrect.. as for first row starting from no of columns = 4 each column no should be decreasing after each row is incremented right? I'm sorry if this confuses you.. But just try to tell me why for(c = n;c>=1;c--) nested inside the row for loop isn't decreasing in number after each iteration??
And when is n decrementing?
after each iteration of the column loop, you said you were getting confused with temp, so I placed n instead of it. Sorry if it confused you further but yeh temp = n is decreased after each iteration of column loop.
I'm not confused. Pay attention to what is happening when. I'm assuming you're getting the same number of astericks in each line. I can see that happening in your code. Timing is everything.
Yes Yes!! Thats exactly whats happening. Please elucidate sensei!!
Since I can figure out your problem by reading your code, you may want to go back and look at your code with my original reply in mind. We're supposed to assist/teach, not provide the answers, so we have to be a bit vague with our answers.
I'm not really looking for an answer of that sort.. besides had it been a homework problem of some kind there are already answers for it online... besides like I said i can do it by using two incrementing loops.. I feel like my logic is right but can't seem to understand if I'm wrong then where exactly I'm wrong.. So if you'll be kind enough... please enlighten this grasshopper with your wisdom smith sensei.. :P
Every time that int temp = n; temp will equal 4. n is a constant. You want c in the inner loop for(int c = temp; c >=1; c--) to start at decrementing values. Maybe: for( int c = --n; c > -1; c-- )
Join our real-time social learning platform and learn together with your friends!