For each of the variables in the following program indicate
For each of the variables in the following program, indicate the scope. Then determine what the program prints, without actually running the program.
R5.10 For each of the variables in the following program, indicate the scope. Then deter- mine what the program prints, without actually running the program 1 public class Sample 2 public static void main(String[] args) 4 5 6 7 8 9 10 int 1 10; int b = g(i); System.out.println(b i); public static int f(int i) 12 13 int n 0; while (n n ) n+; return n 1; 15 16 17 18 19 20 21 public static int g(int a) int b 0; for (int n = 0; nSolution
Hi, I have commented for all variables.
Please let me know in case of any issue.
public class Sample{
public static void main(String[] args){ // args : scope: within main method
int i = 10; // i: Local variable, with in main method
int b = g(i); // b: Local variable, with in main method
System.out.println(b+i);
}
public static int f(int i){ // i : Local to method f
int n = 0; // local to function f
while(n*n <= i){
n++;
}
return n-1;
}
public static int g(int a){ // a : local to g, scope inside g method
int b = 0; // local to function g
for(int n=0; n<a; n++){ // n : scope is within for loop
int i = f(n); // i : within for loop
b = b + i;
}
return b;
}
}
Output:
26
