Home > Back-end >  How do I apply a mathematical equation to each number in a for loop?
How do I apply a mathematical equation to each number in a for loop?

Time:08-21

I've done some searching around and tried some solutions I've found, but a lot of them result in the same problem I am having. I'd like to apply a mathematical equation to each number of a for loop. The problem I am having is that the equation only occurs on the last number in that for loop. For example:

for (int i = 3; i <= 5; i  )
{
    radius = i;
    area = (Math.PI * (radius * radius));
    System.out.println (radius)
}

My code is much more extensive than this, but this is the part I am having issues with. It prints:

3
4
5
Radius: 5
Area: 78.53981633974483

I tried using for each loop, while loop, putting the numbers in a variable to pull from, I'm kind of at my wits end on what to try myself without asking. I'd like the for loop to look like:

3
Radius: 3
Area: //... the area with radius 3...
4
Radius: 4
Area: //... the area with radius 4...
5
Radius: 5
Area: //...area with radius 5...

How would I go about going through each iteration of the for loop and apply the mathematical equation to it?

CodePudding user response:

You did not post the full code, but from your output one can guess you have something like this:

int radius = 0;
double area = 0.0;
for (int i = 3; i <= 5; i  )
{
    radius = i;
    area = (Math.PI * (radius * radius));
    System.out.println (radius)
}
System.out.println("Radius: "   radius);
System.out.println("Area: "   area);

With that your program loops over i = 3, 4, 5; for each i it calculates the area and prints the radius. Only when the loop is over it prints radius and area - and exactly that is what you see in the output.

Change your code as commented by Federico to look like this:

int radius = 0;
double area = 0.0;
for (int i = 3; i <= 5; i  )
{
    radius = i;
    area = (Math.PI * (radius * radius));
    System.out.println("Radius: "   radius);
    System.out.println("Area: "   area);
}

Then it will loop over the same values, and for each perform the calculation and print the result.

CodePudding user response:

Assuming you are using java 8, take advantage of it.

IntStream
    .range(3, 6)
    .forEach(radius -> {
        float area = (float) (Math.PI * (radius * radius));
        System.out.println("Radius: "   radius);
        System.out.println("Area: "   area);
    });
  • Related