Oskar Mikael
Oskar Mikael

Reputation: 326

C# for loop skips one step

I'm trying to loop through numbers and calculate the volume of a sphere.

The user inputs a number and then it loops through the volumes of the numbers until it reaches the user's number.

However the loop skips the calculation of the first number.

Here's my current code

 public static float Calculation(float i)
    {
        //Calculation
        float result = (float)(4 * Math.PI * Math.Pow(i, 3) / 3);
        //Return the result
        return result;
    }
    static void Main(string[] args)
    {
        //Declare the result variable in the main method
        float result = 0;

        //Ask the user to input a number
        Console.WriteLine("Please input a number:");
        int radius = int.Parse(Console.ReadLine());

        //For loop, that runs until i is lesser than or equals to the radius that the user input
        for(int i = 0; i <= radius; i++)
        {
            Console.WriteLine($"The Sphere's volume with radius {i} is {result}\n");

            //Setting the result by calling the Calculation method and setting the radius to the current i value in the loop
            result = Calculation(i);
        }
        Console.ReadLine();

    }

The output is:

The Sphere's volume with radius 0 is 0

The Sphere's volume with radius 1 is 0

The Sphere's volume with radius 2 is 4,1887903

The Sphere's volume with radius 3 is 33,510323

The Sphere's volume with radius 4 is 113,097336

The Sphere's volume with radius 5 is 268,08258

The Sphere's volume with radius 6 is 523,59875

The Sphere's volume with radius 7 is 904,7787

The Sphere's volume with radius 8 is 1436,755

The Sphere's volume with radius 9 is 2144,6606

The Sphere's volume with radius 10 is 3053,6282

Upvotes: 1

Views: 268

Answers (1)

Jack Dane
Jack Dane

Reputation: 402

Change your for loop to this:

    //For loop, that runs until i is lesser than or equals to the radius that the user input
    for(int i = 0; i <= radius; i++)
    {
        //Setting the result by calling the Calculation method and setting the radius to the current i value in the loop
        result = Calculation(i);

        Console.WriteLine($"The Sphere's volume with radius {i} is {result}\n");
    }

You would want to calculate the result first and then print.

Thanks,

Upvotes: 1

Related Questions