Home > Enterprise >  My code exceeds the amount of times i want it to loop
My code exceeds the amount of times i want it to loop

Time:11-16

i wrote a c code in c to display the square cubed of 50, the loop works but it stops at 150 instead of 100. what did i do wrong?

#include<conio.h>
#include<stdlib.h>
#include<stdio.h>

int main()
{
    int n=50;
    int i=0; //column names Number Square and Cube 
    printf("Number\tSquare\tCube\n");
    printf("____________________________\n");

    while (i<=100)
    {
        printf("%d\t%d\t%d\n", n, n * n, n * n * n);
        i  ;
        n  ;
    }
    return 0;
}

CodePudding user response:

You run the loop 100 times, so n increases from 50 to 150

CodePudding user response:

You said

i want to display the square and cubed of numbers from 50-100, its doing 50-150 instead

So one solution is to change your while loop condition so that it stops after n reaches 100:

while (n<=100)

After you make this change and verify that your program produces the correct output, you may notice that you no longer need the i variable at all.

  • Related