0

I have an array like this.

int p[] = new int[n];

which is actually like this.

//p[2,3,4,5,6];

Now I am multiplying each elemnt by 10 and want to store that value and letter wamt sum of that. my for loop.

int res ;
for(int i=0; i<n ;i++){
    res = p[i]* 10;
}

Now my question is in second iteration result is loosing the previous hold value. how to fix that.

Debanik Dawn
  • 797
  • 5
  • 28
shanky singh
  • 1,121
  • 2
  • 12
  • 24
  • 3
    If `res` is the sum, shouldn't the assignment be `res += p[i]* 10;` (`res = res + p[i]* 10;`) – Carcigenicate Aug 19 '17 at 18:04
  • 1
    `res += p[i]* 10;` instead of `res = p[i]* 10;`. Otherwise `res` is only going to hold the value in the current iteration since res can only store one int at a time. [Check out this question for more info](https://stackoverflow.com/questions/7456462/what-does-the-operator-do-in-java/7456548) – Tom O. Aug 19 '17 at 18:06
  • If you want to store that value back, then it is like p[i] = p[i]*10; res += p[i]; – Girish007 Aug 19 '17 at 18:25

3 Answers3

1

With each iteration your res variable is being overwritten with a new value. Try this:

int res=0; //initializing this to 0 is important!
for(int i=0; i<n ;i++){
    res += p[i]* 10; //increment res by the 10 times p[i] 
}
Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72
Debanik Dawn
  • 797
  • 5
  • 28
1

well there are two ways: way 1: make an array of results and have each block of the array save all the results, but this way is only for a case in which you need to use the single values later. way 2: in this case the way you should go with is to write this line of code inside the for loop:

res += p[i]* 10;

and return or print (whatever you need) res

GuyL
  • 36
  • 2
1
int res=0; //initializing res with 0
for(int j=0;j<n;j++){
res=res+p[j]*10;
}
A.YULGHUN
  • 11
  • 2