+ 1

Can someone please explain how the if block works without using == inside a loop ?

int main(){ int n, m; scanf("%d %d", &n, &m); int *a = malloc(sizeof(int) * n); for(int a_i = 0; a_i < n; a_i++){ scanf("%d",&a[a_i]); } int *b = malloc(sizeof(int) * m); for(int b_i = 0; b_i < m; b_i++){ scanf("%d",&b[b_i]); } int count = 0; for(int x=1; x<=100; x++){ int flag = 1; for(int a_i = 0; a_i < n; a_i++){ for(int b_i = 0; b_i < m; b_i++){ if(x % a[a_i] || b[b_i] % x) flag = 0; } } if(flag) count++; } printf("%d", count); return 0; } Here, can anyone please ...does if loop check x%a[i]==0 and flag==1 ....if yes, why?

18th Jan 2022, 6:11 PM
Dreamer
4 Answers
+ 5
The x % a[a_i] will be true if the expression evaluates to anything other than zero (basically if there is a remainder.) The same is true for the expression to the right of the Or || If the first expression evaluates to true the expression on the right side of the Or will not be looked at. if(flag) is equivalent to if(flag) !=0
18th Jan 2022, 6:21 PM
Paul K Sadler
Paul K Sadler - avatar
+ 3
You are about asking this? if(x % a[a_i] || b[b_i] % x) flag = 0; If yes, then if any of ( x%a[a_i] or b[b_i]%x ) is true then it will flag set to 0. It is false only when both results false like if (0 || 0 ) x%a[i] is true if value is anything ,other than 0 ( 1,2,...-1, -5..) Also b[I]%x is true if reminder is non-zero
18th Jan 2022, 6:28 PM
Jayakrishna 🇼🇳
+ 2
To your question: does if loop check x%a[i]==0 and flag==1 ....if yes, why? No, it is not checking if flag==1 at if(x % a[a_i] || b[b_i] % x) flag = 0; here you are only doing checks on x mod a[a_i] or b[b_i] mod x. Now anything that does not equal 0 is true in an if statement conditional. Per C Standard: C11 6.8.4.1p2: "In both forms, the first substatement [of an `if` statement] is executed if the [controlling] expression compares unequal to 0 at if(flag) count++; it is checking to see if flag is anything other than 0. Your code is not however checking them at the same time.
18th Jan 2022, 9:18 PM
William Owens
William Owens - avatar
+ 1
Here is the c standard: 6.8.4.1 The if statement Constraints 1 The controlling expression of an if statement shall have scalar type. Semantics 2 In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0. If the first substatement is reached via a label, the second substatement is not executed. 3 An else is associated with the lexically nearest preceding if that is allowed by the syntax. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
18th Jan 2022, 9:23 PM
William Owens
William Owens - avatar