Reputation: 1141
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.
Upvotes: 0
Views: 57
Reputation: 11
int res=0; //initializing res with 0
for(int j=0;j<n;j++){
res=res+p[j]*10;
}
Upvotes: 1
Reputation: 799
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]
}
Upvotes: 1
Reputation: 36
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
Upvotes: 1