Why is the output in 5th line =0 instead of (-10)? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is the output in 5th line =0 instead of (-10)?

int main() { int a[]={1,2,3,4,5}; for(int i =0;i<=4;i++){ a[4]=a[4]-a[i]; cout <<a[4]<<endl; } cout <<"\n\n\n"<<a[4]%a[1]; return 0; }// Outputs 4 2 -1 -5 0 0

7th Jul 2017, 1:28 PM
Kushagra Agarwal
Kushagra Agarwal - avatar
3 Answers
+ 3
--------------------- ITERATION: 0: PROBLEM: (5) - (1) RESULT: 4 --------------------- ITERATION: 1: PROBLEM: (4) - (2) RESULT: 2 --------------------- ITERATION: 2: PROBLEM: (2) - (3) RESULT: -1 --------------------- ITERATION: 3: PROBLEM: (-1) - (4) RESULT: -5 --------------------- ITERATION: 4: PROBLEM: (-5) - (-5) RESULT: 0 https://code.sololearn.com/cr8tPjk10PrX/#cpp
7th Jul 2017, 2:29 PM
AgentSmith
+ 2
@Soman He is talking about the last iteration of the loop, not the modulo stuff after the loop. It's 0 instead of -10 because -5 - (-5) is 0 since the negative signs cancel each other out.
7th Jul 2017, 2:33 PM
AgentSmith
- 1
% returns you reminder from division. Use / operator.
7th Jul 2017, 2:24 PM
soman