0

*How 14 and 20 came on the output can anyone explain?*

//*How 14 and 20 came on the output can anyone explain?* #include <stdio.h> main() { int i, j, k, x = 0; for (i = 0; i < 5; ++i) { for (j = 0; j < i; ++j) { k = (i + j - 1); if (k % 2 == 0) x += k; else if (k % 3 == 0) x += k - 2; printf("%d\n", x); } } printf("\nx = %d", x); } /*output: 0 0 2 4 5 9 10 14 14 20 x = 20Press any key to continue . . */

3rd Jan 2022, 4:51 PM
Rafid
Rafid - avatar
4 Answers
+ 1
To further understand what is going on.. let make some minor adjustment to the code as below: #include <stdio.h> int main() { int i, j, k, x = 0; for (i = 0; i < 5; ++i) { for (j = 0; j < i; ++j) { k = (i + j - 1); if (k % 2 == 0) x += k; else if (k % 3 == 0) x += k - 2; printf("i=%d j=%d k=%d x=%d\n", i, j, k,x); } } printf("\nx = %d", x); } so we will get output such as below: i=1 j=0 k=0 x=0 i=2 j=0 k=1 x=0 i=2 j=1 k=2 x=2 i=3 j=0 k=2 x=4 i=3 j=1 k=3 x=5 i=3 j=2 k=4 x=9 i=4 j=0 k=3 x=10 i=4 j=1 k=4 x=14 i=4 j=2 k=5 x=14 i=4 j=3 k=6 x=20 x = 20 So, I assume you want to know how the 2 last output come to be. The reason is, at i=4 and j=2, our k is 5 which means that there is no adjustment made to x because both if and else if statement return false. let k = 5, k % 2 == 0 will return false k % 3 == 0 will return false Then in the next iteration when i=4, j=3, our x become 20 because it pass if statement. let k = 6, k % 2 == 0 will return true k % 3 == 0 will return true since we wrote our code using if and else if instead of 2 separate if statement, it simply ignore the else if k%3 since the k%2 is already true. That is why it return 20 (14 + k where k is 6)
3rd Jan 2022, 5:17 PM
Shahrull Fytri
Shahrull Fytri - avatar
+ 1
Let look back at the part of code that responsible to adjust the value of x ``` if (k % 2 == 0) x += k; else if (k % 3 == 0) x += k - 2; ``` As you can see, if k%2==0, then our x will increase as much as k but if k%3==0, x will increase as much as k-2. But since k=5, both k%2==0 and k%3==0 is false. Which mean that there is no changes make to x. Since, 5%2 = 1 5%3 = 2 Therefore k%2==0 is false and k%3==0 is also false That is why 14 appear twice. Because there is no changes to x when k=5
3rd Jan 2022, 6:19 PM
Shahrull Fytri
Shahrull Fytri - avatar
0
I am really appreciate your precious answer. Thanks a lot! Can you please explain how 14 came twice on the output. I am confused about it. Since, when i=4, j=1, K=4, x=10+4=14 ( Totally clear ) But, when i=4, j=2, k=5, x= ? both of the condition is false here so what will be the output here? and how?
3rd Jan 2022, 5:55 PM
Rafid
Rafid - avatar
0
Oh now I am fully clear about the following code. Once again thanks for giving your precious time to solve my question.
3rd Jan 2022, 6:21 PM
Rafid
Rafid - avatar