Reputation: 53
How can I return value in a for loop ? For example if I have a loop that give me 3 numbers: 1,2,3... How can I return the value of the last number (here it is 3)?
public class Cod {
public static void main(String[] args) {
exp();
}
public static int exp() {
int x=10;
for (int i=1; i<=3;i++) {
x=x*10;
int y=x/10;
System.out.println(y);
return y;
}
}
}
Upvotes: 1
Views: 38690
Reputation: 15552
I am not sure if you want to loop or break after a certain condition in a loop
To break you can do
public static int exp() {
int x=10;
int y = 0;
for (int i=1; i<=3;i++) {
x=x*10;
y=x/10;
System.out.println(y);
break;
}
}
This will break straight away so it will only loop once. The value of y is accessible at this point.
If you want the value of the counter variable then declare this outside the loop
int i = 1;
for (i = 1; i<=3;i++) {
x=x*10;
y=x/10;
...
}
System.out.println(i + "");
Then the value of i is accessible outside the loop.
EDIT: after comment
to get the value of y do
public static int exp() {
int x=10;
int y = 0;
for (int i=1; i<=3;i++) {
x *= 10;
y = y + (x/10);
}
System.out.println("y value after loop is "+ y);
}
or if y is not to be added to
public static int exp() {
int x=10;
for (int i=1; i<=3;i++) {
x *= 10;
}
int y = x/10;
System.out.println("y value after loop is "+ y);
}
Upvotes: 0
Reputation: 73625
If I understood what you are trying to do, here is your example modified:
public class Cod {
public static void main(String[] args) {
System.out.println(exp());
}
public static int exp() {
int x=10;
for (int i=1; i<=3;i++) {
x=x*10;
}
int y=x/10;
return y;
}
}
I don't understand why you do x/10
- instead you could just loop one less round.
Upvotes: 0
Reputation: 726509
The easiest thing is to wait for the loop to finish, and then return the last value that it has produced.
The only valid reason why you need to wait for the loop to calculate all three results is that the calculation is dependent upon the value calculated by the prior iteration of the loop. In this case, here is how you can do it:
int res = 0;
for (int i = 0 ; i != 3 ; i++) {
res = calculateResult(i, res);
}
return res;
In case when you can calculate the value of the last iteration directly without running the previos iterations, there is no reason to run the loop at all.
Upvotes: 5