gigibot
gigibot

Reputation: 3

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;
}

Upvotes: -4

Views: 1666

Answers (3)

stark
stark

Reputation: 13189

You just want the cube of 1 number?

i = 0;
cube = 1;
while (i<3)
{ 
    cube *= n;
    i++;
}

Upvotes: 0

0___________
0___________

Reputation: 67476

  1. Loop is wrong.
  2. Your loop invokes undefined behaviour as i is not initialized.

You simply need:

long long cube(int n)
{
    return n * n * n;
}

int main(void)
{
    int x = -21;
    while(x++ < 40)
        printf("n=%d n^3 = %lld\n", x, cube(x));

}

Or if you need to use while loop:

long long cube(int n)
{
    long long result = 1;
    int power = 3;
    while(power--) result *= n;
    return result;
    
}

Or full of whiles and no multiplication.

long long cube(int n)
{
    long long result = 0;
    unsigned tempval = abs(n);
    while(tempval--) result += n;
    tempval = abs(n);
    n = result;
    while(--tempval) result += n;
    return result;
    
}

Upvotes: 0

selbie
selbie

Reputation: 104474

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);

Upvotes: 1

Related Questions