0

Alright, soo the task at hand is to compute 10^10 where the first 10 is an integer called "base" and the second 10 is an unsigned integer called "exponent".

int base = 10; unsigned int exponent = 10; int i = 1; long long result = 1;
while(i<=exponent){
result = result*base;
i++;
}
printf("X^y = %ld\n\n", result);

Now I've tried this with a for loop, while loop, recursive functions etc. And my "result" value is still 1410065400 for some reason? It should be just a one with a bunch of zeros. If anyone got a simple solution to this problem I would be very happy to hear it. And if this has been posted before (didn't find anything on here about it tho) then I would gladly accept the link to that solution.

bolov
  • 72,283
  • 15
  • 145
  • 224
Robin Svensson
  • 39
  • 1
  • 13
  • 2
    Save time, enable compiler warnings. Compiler should have complained about incorrect printf specifier with `printf("X^y = %ld\n\n", result);`. (Reconsider use of `"%ld"` with `long long`.) – chux - Reinstate Monica Feb 24 '18 at 13:01
  • OT and just to make sure: in C `^` is ***not*** the "power to"-operator. – alk Feb 24 '18 at 13:04
  • I'm aware that the ^ is not the "power to" operator, that is just for the mathematical expression when printing out. And I am using compiler warnings (and currently have zero warnings when I compile). – Robin Svensson Feb 24 '18 at 13:10
  • You might like to read about *length modifiers*, You can use the `printf` documentation for this. – alk Feb 24 '18 at 13:14
  • 1
    Or if you have an IDE, set a breakpoint at the printf and see what the internal value of result is. – Pam Feb 24 '18 at 13:15
  • 1
    @Pam: ... this is also possible without an IDE, using a stand alone debugger. – alk Feb 24 '18 at 13:16
  • I use Codeblocks with the standard debugger that's included. But I found what I was looking for now, and like I mentioned in my comment below I will start reading up on length modifiers & printf documentation. Thank you for all your answers/inputs. – Robin Svensson Feb 24 '18 at 13:22

1 Answers1

4

As sad in comment, your format specifier is wrong in printf function. It should be like:

printf("X^y = %lli\n", result);

lli is the correct format specifier. Result:

X^y = 10000000000

Integer values in C programming language are 32 bits and it can hold values that contains 10 digits but 10^10 is 11 digit so it overflows.

You can learn about more from this question:

What is the maximum value for an int32?

Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112
  • Oh, I guess I missunderstood what you were saying, my apologies. Our teacher taught us in engineering class to print it with %d but I get the feeling I should really read up upon that printf documentation after all. This worked, thank you. – Robin Svensson Feb 24 '18 at 13:18
  • @ChrisE: The *conversion specifiers* `i` and `d` do the same, both can be used to printf an `int`. So `%lld` would also do to printf a `long long int`. – alk Feb 25 '18 at 07:10