programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Problems calculating 2^n with For loop

Greenhorn
Posts: 2
I am trying to calculate 2^n with a for loop and am having some difficulties. My program uses a loop to generate numbers 1-20 which are then used to be n.
So if n = 3 (2^3) it should calculate 2*2*2, if n = 5 (2^5) it should calculate 2*2*2*2*2. But it does not do that, not sure what it does. It's the method all the way on the bottom that is giving me a hard time. Can someone help?

Sheriff
Posts: 11343

Silke Sewell wrote:...not sure what it does. It's the method all the way on the bottom...

Welcome to the ranch!

To see what your method is actually doing, add some println statements. For example...

This should show you where it's going wrong.

Ranch Hand
Posts: 44
Hi Silke,

Welcome to Java Ranch

In the exponent method

why have you assigned also verify your loop within exponent which executes n+1 times.

Regards,
Antany.

Silke Sewell
Greenhorn
Posts: 2

marc weber wrote:

Silke Sewell wrote:...not sure what it does. It's the method all the way on the bottom...

Welcome to the ranch!

To see what your method is actually doing, add some println statements. For example...

This should show you where it's going wrong.

Thank you I have been trying to figure out a way to debug in JGrasp this helped. I got it fixed.

marc weber
Sheriff
Posts: 11343
Since these are powers of 2, a nice exercise would be to code this using bit shifting instead of a for loop.

Bartender
Posts: 1776
45
by the way, this too looks wrong to me:

isnt it same as :

I am not looking at the logic though, its just an observation.