C Operator priority at CLA certification exam - c

Currently, I'm taking C language certification course at cppinstitute.org.
In one of it's quizzes there is a question as below to recognize output.
int i = 1,j= 1;
int w1,w2;
w1 = (i>0) && (j<0) || (i<0) &&(j>0);
w2 = (i<=0) || (j>=0) && (i>=0) || (j<=0);
printf("%d",w1 == w2);
I think the program should print 0 to the screen, but the quiz accepts printing 1 as the answer.
Am I correct?if not ,where I'm wrong?
Thanks in advance!I'm a beginner.

Here, && higher precedence than || operator.
So,
w1 = (i>0) && (j<0) || (i<0) &&(j>0);
= 1 && 0 || 0 && 1;
= 0 || 0
= 0
And
w2 = (i<=0) || (j>=0) && (i>=0) || (j<=0);
= 0 || 1 && 1 || 0
= 0 || 1 || 0
= 1 || 0
= 1
So, w1 == w2 become false. So, correct output is 0.

Related

Laravel Check All Multiple Requests Boolean Variable's value to True

I made an if condition for checking request boolean in laravel controller method update, it worked but the line seems too long and i want make the code in short line. And this is my code that i wrote:
if( $request->jamlak == 1
&& $request->kontrak == 1
&& $request->jamuk == 1
&& $request->sprin_pc == 1
&& $request->pc == 1
&& $request->izin_bekal == 1
&& $request->sprin_komisi == 1
&& $request->bek == 1
&& $request->komisi == 1
&& $request->bagudang== 1
&& $request->pem_gudang == 1
&& $request->bast == 1
&& $request->lpp == 1
&& $request->pemerataan == 1){
$validatedData['is_complete'] = 1;
}
else {
$validatedData['is_complete'] = 0;
}
Task::where('id', $task->id)
->update($validatedData);
return redirect('/admin/tasks')->with('success', 'New post has been updated!');
So about this code i want to make $validatedData['is_complete'] turns to be 1(true) after it checks all of requests 1 True, Is there any chance to make it way more efficient line?

`else if` condition not properly working in my program in c

I am new and I don't know to to resolve this error.
When I give inputs for the third else if statement condition it gives the output as salary =0.
Can anyone explain why this happening?
I want to get the answer as :the salary of the candidate = 7000
but the output shows as : the salary of the candidate = 0
/******************* calculating the salary *********************/
/***** bitwise operator ***********/
#include <stdio.h>
int main()
{
char gen;
int qual, y_o_s, sal = 0 ;
printf ( "Enter Gender, Years of Service and Qualifications ( 0 = G, 1 = PG ):\n" );
printf("enter the gen, y_o_s, qual, \n");
scanf("%c\n%d\n%d", &gen, &y_o_s, &qual);
if (gen == 'M' && y_o_s >= 10 && qual == 1)
sal = 15000;
else if ((gen == 'M' && y_o_s >= 10 && qual == 0) ||
(gen = 'M' && y_o_s < 10 && qual == 1))
sal = 10000;
else if (gen == 'M' && y_o_s < 10 && qual == 0)
sal = 7000;
else if (gen == 'F' && y_o_s >= 10 && qual == 1)
sal= 12000;
else if (gen == 'F' && y_o_s >= 10 && qual == 0)
sal = 9000;
else if (gen == 'F' && y_o_s < 10 && qual == 1)
sal = 10000;
else if (gen == 'F' && y_o_s >= 10 && qual == 0)
sal = 6000;
printf("the salary of the candidat = %d\n", sal);
return 0;
}
I want to get the answer as :the salary of the candidate = 7000
but the output shows as : the salary of the candidate = 0.
Alter your if-else-if ladder like :
#define POST_GRAD 1
#define SEX_MALE 'M'
if (SEX_MALE == gen) {
if (POST_GRAD == qual) {
sal = (y_o_s >= 10) ? 15000 : 10000;
} else { // undergrad
sal = (y_o_s >= 10) ? 10000 : 7000;
}
} else { // not Male
if (POST_GRAD == qual) {
sal = (y_o_s >= 10) ? 12000 : 10000;
} else { // undergrad
sal = (y_o_s >= 10) ? 9000 : 6000;
}
}
It's easier to follow. Notice, that constants like POST_GRAD are on the left side comparator ==, it helps compiler catch unintended typos like = for comparisons.
Also, you may want those salaries at one place like :
#define MALE_PG_EXP_SAL 15000
#define MALE_UG_EXP_SAL 10000
// and so on
#define FEMALE_UG_EXP_SAL 9000
#define FEMALE_UG_INEXP_SAL 6000
When they change, you can find them at one place to modify.
PS: I wouldn't want to work at this place.
You are assigning a value to gen
else if ((gen == 'M' && y_o_s >= 10 && qual == 0) ||
(gen = 'M' && y_o_s < 10 && qual == 1))
^
So when you get to your next line gen is no longer what you expect.
else if (gen == 'M' && y_o_s < 10 && qual == 0)
^^
And then improve the code with SparKots suggestions.

Connect Four Check Winner

So to change my question. It refuses to recognize that there are four twos in a row. It recognizes that there are four ones in a row but that happens after the four twos. Why is this happening?
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 1 1 1 1 0 0
1 2 2 2 2 0 0
int checkFour(int a, int b, int c, int d){
if (a == b == c == d){
return 1;
}
else{
return 0;
}
return 0;
}
//check for the horizontal win
int checkHorizontal(){
for(int i=0; i < rows; i++){
for(int j=0; j < column - 3; j++){
if ((board[i][j] != 0) && (board[i][j+1] != 0) && (board[i][j+2]!= 0) && (board[i][j+3] != 0)){
if (checkFour(board[i][j],board[i][j+1],board[i][j+2],board[i][j+3]) == 1){
printf("Game Over\n");
exit(0);
}
}
}
}
}
What am I doing wrong?
if (a == b == c == d){ does not work the way you might think. The result of a comparison in C is a boolean value of 0 or 1. Given that == operator has left-to-right associativity, your statement can be re-written as:
if ((((a == b) == c) == d)
This appears to give correct results when they are all 1. This is because it ends up comparing the values (1) to the result of the comparison operation, also (1).
(((a == b) == c) == d) a == b -> 1
((1 == c) == d) 1 == c -> 1
(1 == d) 1 == d -> 1
The correct way is to use logical AND.
if (a == b && a == c && a == d)
All three comparisons need to evaluate to true for the entire statement to be true.
Note that there are other combinations that work. Ex:
if (a == b && b == c && c == d)
By the way, you can shorten the entire function to
int checkFour(int a, int b, int c, int d){
return a == b && b == c && c == d;
}
The problem is that you misunderstood the mechanism of C. the code if (a == b == c == d) wouldn't take if abcd are all values equal then return 1. because C computes from left to right(same priority), so it would compute a == b first, the result is 1 or 0, then take this result to compare with c, the second result also is 1 or 0, finally take second result to compare with d and the final result is come out.
The right code is like this:
if ((a == b) && (d == c) && (b == c))
return 1;
else
return 0;

Why does this following program print "Yes" instead of "No"?

Why does this following program print "Yes" instead of "No"?
None of the variables is initialized to 2.
bool hello = 0;
int a = 1;
int b = 3;
int c = 4;
int d = 5;
if (a || b || c || d == 2) {
hello = 1;
}
if (hello == 1) {
printf("Yes");
}
if (hello == 0) {
printf("No");
}
return 0;
}
The statement
if (a || b || c || d == 2)
is equivalent to:
if (a != 0 || b != 0 || c != 0 || d == 2)
The equality comparison does not automatically distribute across all the variables. If you want to do that, you need to perform all the comparisons explicitly:
if (a == 2 || b == 2 || c ==2 || d == 2)
The expression (a || b || c || d == 2) evalutates to true because it treats a, b, c as booleans, and any non-zero integer is true.
You have given logical operator in the expression It means that if non zero value came then the expression is true. Then hello=1 is set and in next f statement it prints YES
You just meet the short circuit behavior of logical expressions OR.
The order of evaluation of logical OR || is left to right.
So in the following expression:
left || right
if left = true then right will never going to be executed (short circuit). In your code exactly same happened.
As you know, any non zero value treated as true in C, hence, a which is 1 is true. So, take a look:
if (a || b || c || d == 2)
if (true || bla bla bla) //rights are not even checked!
if (true)
hello = 1;
Tada! So the program print "Yes"!
None of the variables is initialized to 2.
Yes of course! But your if condition is not going to check that. To do so, try this:
if (a == 2 || b == 2 || c ==2 || d == 2) {
//...
because if judge num is not zero , if think this is true. so your code
if (a || b || c || d == 2)
like
if ( true || true || true || false)
the result is true, programe print "YES"

What is the order in a for loop? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I'm trying to solve Problem 5 of project euler and I the answer I keep getting is wrong:
#include <stdio.h>
main()
{
int num;
int x = 0;
for (num = 20; x == 0; num++)
{
if ((num%1) == 0 && (num%2) == 0 && (num%3) == 0 && (num%4) == 0 && (num%5) == 0 && (num%6) == 0 && (num%7) == 0 && (num%8) == 0 && (num%9) == 0 && (num%10) == 0 && (num%11) == 0 && (num%12) == 0 && (num%13) == 0 && (num%14) == 0 && (num%15) == 0 && (num%16) == 0 && (num%17) == 0 && (num%18) == 0 && (num%19) == 0 && (num%20) == 0)
x = 1;
}
printf("%d %d", num, x);
}
My program keeps printing out 232792561 (I am aware that I'm printing x, this is simply for troubleshooting purposes).
The verbatim output I'm getting is: 232792561 1.
I did some research and I found that the correct answer to the problem is 232792560.
I am now beginning to believe that the problem lies in the for loop.
What does the loop do first, the iteration (num++) or the test (x == 0)?
A for loop can be converted to an equivalent while loop:
for (num = 20; x == 0; num++) {
// do stuff
}
is the same as
num = 20;
while (x == 0) {
// do stuff, then
num++;
}
So first the condition is checked, then the loop body is executed, then the increment.
(And yes, as others suggested, if you break; out of the loop when you need, you'll need the correct result, since break; immediately jumps out of the loop, thus the incrementing statement isn't executed for the last time.)
After the loop body has been executed (if at all, because first the initialisation code is run, then the condition checked to see whether the body is entered),
first the update code is run
then the condition is checked.
So after you set x to 1, num is incremented once more.
Instead of setting x to 1 to end the loop, you could simply break;, that would exit the loop without running the update code.
Your loop is needlessly complex and can be simplified using the while loop construct if you prefer. You can also get rid of the unnecessary variable x
int main() {
int num = 20;
while (!((num%1) == 0 && (num%2) == 0 && (num%3) == 0 && (num%4) == 0 && (num%5) == 0 && (num%6) == 0 && (num%7) == 0 && (num%8) == 0 && (num%9) == 0 && (num%10) == 0 && (num%11) == 0 && (num%12) == 0 && (num%13) == 0 && (num%14) == 0 && (num%15) == 0 && (num%16) == 0 && (num%17) == 0 && (num%18) == 0 && (num%19) == 0 && (num%20) == 0))
{
++num;
}
printf("%d\n", num);
return 0;
}
To answer why your for loop was giving incorrect answer:
Although you were setting x = 1 for the correct value of num, you were checking the condition of the for loop ONLY in the next iteration of the loop (i.e. after the num++ statement is executed), and hence your value of num was offset by 1.
As many people suggested, you could use the break statement to terminate the for loop execution so that the value of num is what you want it to be when the control reaches outside the loop.
Step 1: Initialization (num = 20)
Step 2: Test
Step 3: Iteration
Step 4: Test
Step 5: Iteration
and so on.
If I were you, I would choose while loop with condition as yours (I mean the long one inside for loop) with body of incrementing.

Resources