cwhile-loopnegative-integer

Our professor asked us to make a C program that will display the cube of a number using a while loop


When I input a negative integer the output will not result to it's cube value. I'm confused what should I do? here is my code:

#include <stdio.h>
int main()
{
    
    int n, i, cube;
    printf("Enter an integer: ");
    scanf("%d",&n); 
        
    while (i<=n)
    {   
        cube = i*i*i;   
        i++;

    }
    printf("The cube of %d = %d\n ", n, cube);  

    return 0;
}

Solution

  • I would assume you'd want to compute the cube of a number by using a loop that iterates 3 times.

    int n, cube, i;
    printf("Enter an integer: ");
    scanf("%d",&n); 
    
    cube = 1;
    i = 0;
    while (i < 3)
    {
        cube = cube * n;
        i++;
    }
    
    printf("%d\n", cube);