Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does 'total' not exist in the current context?

I am trying to print n to the power of p without using Math.Pow().
Here is the pseudocode:

get two integers n , p from the user

using a for-loop calculate the power function n ** p without using Math.Pow() method.
output the result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using a while loop repeat the calculations
output the result

using a do-while loop repeat the calculation
output the result.

I have tried declaring the variables in numerous ways, and return total in the for loop.

using System;


public class Powers
{
    
    public static void Main()
    {

        Console.WriteLine("Enter the base integer here:");
        int n = int.Parse(Console.ReadLine());

        Console.WriteLine("Enter exponent here:");
        int p = int.Parse(Console.ReadLine());

        for (int total = 1, counter = 1; counter <= p; ++counter)
        {
            
            total = total * n;          
        }

        Console.Write($"{n} to the {p} power is {total}");
    }
}

>Solution :

Variables defined in the for clause exist only inside of the for loop. If you want it to survive the loop, you have to define it outside:

        int total = 1;
        for (int counter = 1; counter <= p; ++counter)
        {
            total = total * n;          
        }

        Console.Write($"{n} to the {p} power is {total}");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading