I want the loop to exit when both strncmp() and check() return 0, meaning they both found a match. The problem is, when check() returns 0 and strncmp() does not return 0 the loop is exiting.
while (strncmp(buf, match, 3) != 0 && check(buf[3]) != 0)
{
}
I have checked the values in buf and match and they do not match when it exits. buf[3] does match when it exits.
You are using && so you're saying both strncmp(buf, match, 3) and check(buf[3]) != 0 must be met in order for the loop to continue. To get the result you specified you should use ||
This loop runs as long as
buf and match differ somewhere in the first 3 characters, AND
check(buf[3]) is nonzero
Is that what you want? In other words, the loop exits when either
buf and match share the same three initial characters OR
check(buf[3]) is zero
I want the loop to exit when both strncmp() and check() return 0
Then you can rewrite the loop to be very easy to verify against your requirement:
for(;;) {
...
if (strncmp(buf, match, 3) == 0 && check(buf[3]) == 0)
break;
...
}
Now place the negated condition in the controlling expression of the loop:
while (! (strncmp(buf, match, 3) == 0 && check(buf[3]) == 0) ) {
...
}
If you are somewhat into computer science, you realize that not(A and B) is--per de Morgan's Laws--equivalent to (not A) or (not B). This finally yields:
while (strncmp(buf, match, 3) != 0 || check(buf[3]) != 0) {
}
So your error was using && instead of || for the logical operator.
u can try this ...
int c,d;
while ((c=strncmp(buf, match, 3) != 0) && (d=check(buf[3]) != 0))
{}
Description:
strncmp() will return a value that have to store in a var..if u don't do then how it will compare with 0..same as also check().
Related
int leavesEven(tree t)
{
if(t == NULL) return 1;
if(t->left == NULL && t->right == NULL)
return t->value % 2 == 0;
return leavesEven(t->left) && leavesEven(t->right);
}
I was given this code as a solution to this task:
For a given tree t, write a function that returns 1 if all values (of the leaves) are even, else return 0.
I dont get this line: return t->value % 2 == 0;
I thought it returns 0 only if value of t modulo 2 equals 0. But this makes no sense, because 0 means that the number was even, so why would I want to return 0, which means that there was an odd number found in the tree??
In C a "true" value is any non-0 value.
The result of comparisons are 0 for false, and 1 for true.
So 2 % 2 == 0 evaluates to 1, since it is true.
I need to use boolen expressions instead of using terms such as: c: b? A, switch, else ... if. and using for / while-do / while as if is also not allowed.
My question is when receiving a name, based on its value we decide what to print. For example, if the name is shorter than 6 letters we print "player A is sent", if the letters sum (in ascii values) is more than 20 we send player B and stuff like that. In addition, if we can send more than one player, we will choose to send the largest lexicographic player (playerC < playerB < playerA.)
what I tried to do is something like this
bool sum = AsciiSum(name)>=20;
bool len = NameLength(name)<6;
...
so the rest should be that
if(sum)
printf("%c\n" ,'playerA');
else if (len)
printf("%c\n" ,'playerB');
else
printf("%c\n" ,'no player was sent');
But as I said , I cant use if and else or similar conditions. Will be grateful for any help in that last part.
One way of doing this would be to reroute your input through a custom print function which return a boolean value. That was, you could then just use the AND (&&) operator to call it.
Example code:
bool printMessage(char* string)
{
printf("%s", string);
return true;
}
bool sum = AsciiSum(name)>=20 && printMessage("playerA");
bool len = NameLength(name)<6 && printMessage("playerB");
// ... etc
Why does this work? The AND operator will only allow the next condition to be checked if the first one was true. Since your condition is that sum must be true in order to print the message, this is a way to call the method to print without directly using any if/else statements
Edit: An even better way, as suggested by Johnny Mopp is to use stdio puts(), which returns an integer (that's what a boolean is functionally).
bool sum = AsciiSum(name)>=20 && puts("playerA");
bool len = NameLength(name)<6 && puts("playerB");
With this, you don't even have to create a printMessage function, though you should stay with whichever feels more comfortable to work with.
Given an output function that always returns true :
bool print( const char* msg )
{
puts( msg ) ;
return true ;
}
You can then exploit short-circuit evaluation thus:
bool sum = AsciiSum(name)>=20;
bool len = NameLength(name)<6;
(sum && print("playerA")) ||
(len && print("playerB")) ||
print("no player was sent") ;
Testing all combinations thus:
bool sum = false, len = false ;
(sum && print("playerA")) || (len && print("playerB")) || print("no player was sent") ;
sum = false, len = true ;
(sum && print("playerA")) || (len && print("playerB")) || print("no player was sent") ;
sum = true, len = false ;
(sum && print("playerA")) || (len && print("playerB")) || print("no player was sent") ;
sum = true, len = true ;
(sum && print("playerA")) || (len && print("playerB")) || print("no player was sent") ;
correctly outputs:
no player was sent
playerB
playerA
playerA
Your compiler may issue a diagnostic regarding the result of the expression being unused; that can be supressed by a dummy assignment:
bool dummy = (sum && print("playerA")) ||
(len && print("playerB")) ||
print("no player was sent") ;
or by casting the whole expression to void:
(void)((sum && print("playerA")) ||
(len && print("playerB")) ||
print("no player was sent")) ;
The only requirement of the output function is that it returns a non-zero value to short-circuit the ||, to that end printf() will work if the message is not an empty string, and avoid the need to define a specific output function.:
(void)((sum && printf("playerA\n")) ||
(len && printf("playerB\n")) ||
printf("no player was sent\n")) ;
puts() however only guarantees to return a non-negative value on success, which includes zero, so should not be used.
Okay I need help with translating sentences to condition statements in C.
For example, if I want my input to be from 1 to 35 (inclusive), and only want odd integer inputs, how would I go about making a conditional statements?
Is it:
int n;
while(1){
printf("What is the value for n you wish to use (please use an odd number?: ");
scanf("%d", &n);
if(n%2=0 && n<=35 && n>=1)
if(n<1)
break;
}
if (n%2=0 && n<=35 && n>=1)
is (almost) the condition for even numbers, those exactly divisible by 2. Note that the equality operator is ==. For odd, you want
if (n%2==1 && n<=35 && n>=1)
With this, you do not need any more if statements.
This n%2=0 should be (for odd numbers) n%2 == 1
And if you want to break on a number not matching your conditions, use something like this in the loop:
if(!((n%2 == 1) && (n<=35) && (n>=1)))
break;
}
Now if you want to break from a loops if any one of following condition get satisfies
The number must be above 1
The number must be below 35
The number must be odd
Then you can write:
if(n%2==1 || n>=35 || n<=1) break;
First, let's define the tests for 1 to 35 inclusive. C supports short circuiting, we should test the simple things -
if (n > 0 && n < 36) /* <---- 1 to 35 */
if (n >= 1 && n <= 35) /* <---- 1 to 35 */
or
#define MIN 1
#define MAX 35
if (n >= MIN && n <= MAX) /* MIN to MAX */
However, your code is incorrect. The second if will ever evaluate to true since the first requires n>=1
if(n%2=0 && n<=35 && n>=1)
if(n<1)
break;
I believe you wanted
if (n > 35 || n < 1) {
break;
}
A test for even should just continue (and not end the loop), or you could test for odd and just display those,
if (n % 2 == 0) continue;
or
if (n % 2 != 0) printf("%i\n", n);
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.
I have the below code to choose sin or cos to be integrated,
while( x !=1 || y !=(1||0) ){
printf("Sin (1) or Cos (0)?\n");
x = scanf("%d",&y);
_flushall();
if(y==1){
printf("Sin set\n");
}
else if(y==0){
printf("Cos set\n");
}
}
However the
y!= (1||0)
never evaluates to true for y == 0 , can someone explain what's wrong here? Thanks.
You need (y != 1 && y != 0) (or similar, it depends on what you really mean to express there). The || operator is being applied to the operands 1 and 0. Put another way, y != (1 || 0) means "Do (1 || 0) then do y != result".
You are attempting to effectively code directly Boolean algebra, and C doesn't accept it in the manner you've provided.
while( x !=1 || y !=(1||0) )
should be
while( (x!=1) || ( (y!=1) || (y!=0) ) )
Never underestimate the value of using excess parentheses in C. The optimizer will likely optimize the code to be more efficient anyways.
The part of code that generates this error evaluates as follows:
LHS (left hand side), RHS (right hand side)
LHS = y
!= (1||0) [definition given]
!= (1) [b/c (1||0) = (1)]
y != (0||1)
is equivalent to
y != 1
since 0||1 is 1. You'll need two comparisons if you want y != 0 or y != 1.