0

My prompt and validation works already. The program compiled. But when I run it and enter a valid height, it does nothing. It seems like my loops don't execute. Now I have changed a few things to improve but get the compilation error that my counter i is undefined even though I declare it in the for statement. And since the number of spaces I need is defined by the counted, spaces does not get declared either. What is wrong? Here is that part of the code

for (int i=0;i==height; i++)

    /* final number of spaces and hashs to target */
    int spaces=i;
    int hashs=height -i;
        {
          for (int j=0;j==spaces;j++)
            {    printf(" "); }
        for (int k=0;k==hashs;k++)   
             {  printf("#");    }
            printf("#\n");
        }
1

Your for loop won't run because of your condition statement.

So within your for loop, initialising i to 0 (with int i = 0)is setting a counter for your loop.

On each iteration of the loop, 'i' will increase by one (By using i++)

The middle part of your for loop is a test condition; the loop will run while this condition is true. In your case your test condition is 'i == height', which is saying 'while i is equal to height' run the loop, however i is 0, and therefore not equal to height so will not run.

4
  • Claire, you're exactly right, but your explanation is very muddy. Can you please edit your answer and be more clear about the test clause and the effect of initializing i=0?
    – Cliff B
    Jun 9 '16 at 7:27
  • oh i misunderstood the for loop, I thought the middle part is the end point of the loop, not the condition (I thought I am saying start from i = 0 and end at i = height, for example.
    – AnGo
    Jun 9 '16 at 8:17
  • Claire, thanks, it is working now!!! So silly, I spent 8 hours testing things and all it was was that I didn't know I had to put condition rather than the end point into the for loop :-(. My pyramid is upside down at the moment because I thought the way the computer executes, it will build the base of the pyramid first, then go up, not the other way round, but this should be easy to fix now. So glad it is finally (almost) done. Thanks for your help.
    – AnGo
    Jun 9 '16 at 8:28
  • Glad it worked for you! It's an easy error when your learning, hope you understand loops better now. I have attempted to clarify my answer more for others who may have the same problem; hoping I haven't made it worse!
    – Claire
    Jun 9 '16 at 12:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .