[Solved] How are variables involved in a for loop’s body if they are not defined? [closed]


In your for loop, the variable result Is created outside of the for loops scope. Essentially, you are just changing the result variable that has already been created. If you attempted to create a new variable within the for loop such as “newResult = base * result”, it would fail if you attempted to use it outside of the for loop. Here is a simple example that optimizes your code:

//Start getting the proper variables in your MAIN method. 
Scanner reader = new Scanner(System.in);//create scanner here. 
System.out.println("Enter a base number: ");
int base = reader.nextInt();
System.out.println("Enter an exponent: ");
int power = reader.nextInt();
out.println(exponent(base, power));

Then you could optimize the exponent method like so:

public static int exponent(int base, int power) {
    double r = Math.pow(base, power);
    int result = (int)r;
    return result;

}

Now, for your specific question, lets imagine changing the for loop in your example to this below, this is the important point:

for(int i = 1; i <= power; i++)
{
   int newResult = base * result;
}
System.out.println("Result: " + base + " ^ " + power + " = " + newResult);

That code above would generate an error because you are trying to access a variable outside of the scope it was created in. However, since result is passed to the method in your example as a parameter, it is considered to be accessible by the for loop that is created later within the scope of the method. Essentially, the result variable that you already defined will simply reference a new value inside of your for loop. If we attempted to create a new result variable in the for loop such as newResult, you would not be able to reference it outside of the scope of that for-loop.

4

solved How are variables involved in a for loop’s body if they are not defined? [closed]