(Extreme Noob here) Why wont this C code work? - c

Why won't this work, I'm very new to programming but I can't seem to figure out why this wont work correctly.
#include <stdio.h>
#include <math.h>
int main(){
int num1;
printf("Enter 1, 2, 3.");
scanf("%d", &num1);
if(num1 = 1)
printf("You entered one");
else if(num1 = 2)
printf("You entered two");
else if(num1 = 3)
printf("You entered three");
else
printf("Invalid");
}

In C it is valid to use assignment (int x = 5) within a conditional (if statement).
For example:
int x = 0;
if (x = 5)
{
}
This will evaluate to true (it returns 5 to the "if" and all non zero terms are true by convention) if the assignment could be done and the value != 0. Which, in this case, it can be done and returns 5.
You were likely looking for this:
int x = 0;
if (x == 5)
{
}
This will evaluate to false (0).
Remember: You use a single equal sign "=" to mean "assignment". Use a double equal sign "==" to mean "comparison".

Replace all the = with == and you should be fine (because = is used for assignment, while == is used to test for equality, which seems to be what you want to do)

In C, as in other many programming languages, the = operator means "assignment". When you do a = 3, that means "assign a with 3", which of course it's something that succeeds and returns true, that's why your program will always enter the first branch.
What you have to do is use the "equality testing" operator, ==, so that a == 3 returns true if and only if the value held by variable a is 3.

Your code having one mistake you have taken = instead of ==, in C = operator means assignment operator while== operator is used for comparision.
To clear about your doubts regarding operators read this link
http://www.tutorialspoint.com/cprogramming/c_operators.htm

And because you started with int main() just for compiler reasons put return 0; at the end of your program to be more correct.

It doesn't work because you need to change the = sign to ==. You use the equal sign sometimes when you declare a int or char. == is meaning equal to and you want to use that when your not declaring ints and chars.While != means not equal.You should also put a return 0; at the end of your program.

Related

Why is the output different in the short version of if condition when compared to its expanded version?

int a = 0;
a = 7 > 2 ? printf("6") : printf("4");
printf ("%d",a);
The ouput of this block is :
61
I tried the code in its expanded form
int a = 0 ;
if(7>2)
{
printf("6");
}
else
{
printf("4");
}
printf("%d",a);
Here I the output was:
60
I would like to get an explanation on why the output differs.
The first statement assigns the return value of printf to a. printf returns the number of bytes that were written. In this case that is 1. In the second expanded version, a is not assigned. Here is an actually equivalent version to the original:
int a = 0;
if(7>2)
{
a = printf("6");
}
else
{
a = printf("4");
}
printf("%d",a);
They are completely different.
To make them identical:
int a = 0 ;
if(7>2)
{
a = printf("6");
}
else
{
a = printf("4");
}
printf("%d",a);
cond?val1:val2 is the ternary operator. It is not supposed to be a control structure (like if, for or while). It is an operator. To build expression (things that have a value) rather than instruction (things that does things).
Frontier is fuzzier in C than in other languages, because instructions have a value (including void) and expression have potential side-effects.
But, well, you use cond?val1:val2 when you want to get the result. As you did, since you assigned the result to a.
And the result here is the result of printf("6"), that is 1, since printf returns the number of printed characters. Note that there is no real doubt, since even if 7 were smaller than 2, result would still have been 1. Since you print that result, it is normal to have a 1 printed after the 6.
(Just to be clear, even if I assume you know that already, what you did is print string "6" and then number 1, which is the result of 1st printf. Exactly as if you did
printf("%d",printf("6"));
which 1st prints "6", then pass the result to the outer printf to print what the inner printf returned, that is 1)
In your second code, you do nothing to change a's value, and you ignore the result of printf.
Your examples aren't equivalent. To be equivalent, the second one should say a=printf(... everywhere. After which a will get assigned the number of characters printed, 1.
The conditional operator (e1 ? e2 : e3) is not a "short version of if condition", although it has some similarities with an if ... else construct. The conditional operator yields a value (which you assign to a in your first example); an if ... else construct does not have a value.
So, your first example assigns a value to a, because it is written in the form of an assignment statement; that value is the 1 returned by the call to the printf function. To get similar behaviour in your second example, as others have said, you need to also assign the value returned by printf inside the if ... else blocks.
Alternatively, to make the first case work like the second, you can skip the assignment and use the conditional operation to determine the argument that is passed to the printf call:
int main(void)
{
int a = 0;
printf(7 > 2 ? "6" : "4");
printf("%d", a);
return 0;
}

How would a compiler interpret `if(!(a=10))`?

I have a homework assignment in which I believe the professor has made a typo, typing if(!(a=10)) instead of if(!(a==10)). However, when asked if this was typo, she told me to "assume that the equations are correct and give your answer." Specifically, the assignment is to describe the behavior of the program:
#include <stdio.h>
int main() {
int a = 100;
while (1) {
if (!(a=10)) {
break;
}
}
return 0;
}
If the offensive code read (!(a==10)) then the program would enter the if loop, reach the break and exit both loops, which makes sense for a beginner-level course in C programming.
However, if, truly, the code is meant to read (!(a=10)) then I don't know what the compiler will interpret that to mean. I do know that the code compiles, and when you run it in UNIX, it just allows you to input whatever you want using the keyboard, like say the number "7", and then you press enter and it moves to a new line, and you can enter "dog", and move to a new line, and on and on and it never exits back to the command line. So (1) how would the compiler interpret (!(a=10))? And (2) why does the program allow you to just continue to input entries forever?
Thanks!
For the first question,
What's the meaning of if( !(a=10) ){break;},
It's equivalent to
a = 10; if(!a) {break;}
For a value of 10 !a will be 0 and it never breaks the while loop.
In this particular example, if you assign if(!(a=0)), then it will exit the loop;
For the second question, there is no code present in your example.
But first question's answer can be extended here as the loop never breaks it keeps on asking the input values.
From the C Standard (6.5.3.3 Unary arithmetic operators ΒΆ5)
5 The result of the logical negation operator ! is 0 if the value of
its operand compares unequal to 0, 1 if the value of its operand
compares equal to 0. The result has type int. The expression !E is
equivalent to (0==E).
So according to the quote the if statement
if (!(a=10)) {
is equivalent to
if ( ( a = 10 ) == 0 ) {
As the value of the assignment sub-expression, a = 10 is equal to 10 that is it is not equal to 0 then the condition of the if statement evaluates to logical false and the sub-statement of the if statement will not get the control and you will have an infinite while loop.
In fact, you can rewrite this while loop
while (1) {
if (!(a=10)) {
break;
}
}
the following way with the same effect
while ( ( a = 10 ) ) {}
or just
while ( ( a = 10 ) );
or more simply:
while ( a != 0 );
because what is important is that within the while loop the variable a does become equal to 0.
while (1) {
if (!(a=10)) {
break;
}
}
as !(a = 10) is always zero (false) it is equivalent of:
while (1) {
}

my binary search function doesn't work properly

1st of all, sorry my english, it's not my mother language.
Hello everyone, I'm having a problem with my binary search function. I need to make a recursive function(using C language) of binary search, using the boolean type, here it is:
bool binary_search(int x, int array[], int m, int n){
int middle=(m+n)/2;
if(m>n) return(0);
else if(x == array[middle]) return(1);
else if(x < array[middle]) return(binary_search(x, array, m, middle-1));
else return(binary_search(x, array, middle+1, n));
}
here is the call in the main function:
printf("type the element to search: \n"); scanf("%d", &x);
if(binary_search(x, A, 0,dim-1)) printf("Found!\n");
else printf("Not found!\n");
The problem is, it always return "not found" even if the element is not in the array. I tried to change the logic inside the if command, but it just made all results become "found". If anyone can help, I'll be glad.
UPDATED: I changed the "=" problem, but the output still wrong, I printed the output of the function, and it's always zero
The following line has a serious problem:
else if(x = array[middle]) return(1);
Instead of comparing x to array[middle], you are assigning the value of array[middle] to x. Provided this value is nonzero, it will always evaluate to true, and so your function will always return at that point. You should use ==, which compares for equality, instead of =, which means assignment.
This is an extremely common error among beginning C programmers, so you may wonder why A = B is even an expression at all in C, rather than a statement like in Python. The (ex post facto?) rationale is that it is sometimes very convenient to be able to assign a variable inside an expression. Consider:
char *error;
if ((error = do_something()) != NULL) {
printf("error: %s\n", error);
// ...
}
You are using assignment = rather than the test for equality ==. The resulting expression is probably non-zero so the if compares as true.
Ok did u check if u give sorted array as an input to your binary search function? if it is not then using binary search will not give you the correct answer.
I founded the error:
I generate random numbers in a function("random_numbers()"), and the "dim" variable is inside that function, so, the dim inside the main() is 0. so the return value of the search will always be 0. I'm feeling a little bit stupid, but thanks all for the help. Sorry by the newbie error.

Passing an array through "isalpha" through a loop

I've been at this for quite some time now and the existing answers offer little to no help. I am new to programming and am trying to write a sub-part of my program which tries to check whether any given input is constituted solely of alphabets.
For this, the idea I have in mind is to pass an entire array through the isalpha function by using a loop which passes each character at a time. The idea makes logical sense but I am having syntactic trouble implementing it. I will greatly appreciate any help!
Below is my code-
printf("Please type the message which needs to be encrypted: ");
string p = GetString();
for (int i = 0, n = strlen(p); i < n; i++)
{
if(isalpha(**<what I'm putting here is creating the problem, I think>**) = true)
{
printf("%c", p[i]);
}
}
You should modify your code as this (assuming you have the string type defined yourself):
printf("Please type the message which needs to be encrypted: ");
string p = GetString();
for (int i = 0, n = strlen(p); i < n; i++)
{
if(isalpha(p[i]) == true) // HERE IS THE ERROR, YOU HAD =, NOT ==
{
printf("%c", p[i]);
}
}
Operator = is for assignment and operator == is for comparison!
So what was happening? The assignment resulted in true, no matter what p[i] was.
As Quentin mentioned:
if(isalpha(p[i]) == true)
could be more elegant and error prune if written like this:
if(isalpha(p[i]))
Here is an example in C:
/* isalpha example */
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int i = 0;
char str[] = "C++";
while (str[i]) // strings in C are ended with a null terminator. When we meet
// the null terminator, while's condition will get false.
{
if (isalpha(str[i])) // check every character of str
printf ("character %c is alphabetic\n",str[i]);
else
printf ("character %c is not alphabetic\n",str[i]);
i++;
}
return 0;
}
Source
Ref of isalpha().
C does not have a string type.
Tip: Next time post your code as it is!
Aslo, as Alter noticed, it would be nice to use:
isalpha((unsigned char)str[i])
and in your code
isalpha((unsigned char)p[i])
for safety reasons.
Your example is here.
I.e. parameter of isalpha() is i-th character of string p. The only question is how to access to i-th character. Usually you can use []. I.e. just use following code: isalpha(p[i]) (I see that you already use [] in call of printf).
Also isalpha(p[i]) = true is wrong condition. It looks like you planned to check isalpha(p[i]) == true (you can skip == true).
Late but:
both other answers say omitting == true is desirable, but don't say it is necessary for portability.
The C core-language operators == != < <= > >= && || which return a 'logical' value use an int value of 1 for true and 0 for false. In C99 and up with stdbool.h and by common convention before that true is 1 and false is 0, so e.g. if( (a < b) == true ) will work correctly, although it is redundant and many (including me) consider it poor style. Language elements that test a logical value, namely if(c) while(c) for(;c;) and the operands to && || and the left operand to ?: consider any value that compares equal to 0 to be false, and any other value to be true.
The character-classification routines in ctype.h as well as some other standard-library routines like feof(f) and ferror(f) are specified to return some nonzero int for true and 0 (an int) for false, and on many implementations the nonzero value used for true is not (always) 1. In those cases isalpha(whatever) == true might result in testing say 4 == 1 and fail even when whatever is an alphabetic character. OTOH isalpha(...) != false or isalpha(...) != 0 does work correctly if you really want to write something explicit.

assignment works as a condition

Consider the following Code,
int i;
while(i=0)
printf("Hello");
Now Generally speaking i=0 is an assignment and not a condition for while to check.
But the GCC compiler lets it go with a warning and even evaluates it correctly (does not execute the print statement).
Why? I usually would do with parenthesis for the truth value but my juniors feel that I am wrong and there is no real reason for the parenthesis in this!
EDIT: Zeroing down on the 'actual' doubt, Please consider the following test case
int callme(){
return 0;
}
int main(int argc,char*argv[]){
int c;
while(c = callme()){
printf("Calling...\n");
}
return 0;
}
The expression i = 0 does 2 things:
Has the side effect of storing o in i
Yields the value 0
I usually would do with parenthesis for the truth value but my juniors
feel that i am wrong and there is no real reason for the parenthesis
in this
It's usually a hint to the compiler meaning "I actually want this, I didn't forget a =, shut up".
For your specific case there's no reason to write if (i = 0): you already know what if (0) does. But it's pretty useful when used as:
if ((i = some_function()))
...
i=0 is always an assignment (unless you have it as part of int i = 0; where it is an initialization). But any non-void expression may appear inside the condition of a while loop and if it evaluates to non-zero, the body of the loop will be executed, and if it is zero, the body of the loop will not be executed.
The notation:
while (i = 0)
printf("Hello\n");
is always equivalent to:
i = 0;
There is very little justification for writing the loop at all.
People do write other expressions:
while (c = getchar())
...process EOF or a non-null character...
But that's usually a bug. It is more likely that you should be writing:
while ((c = getchar()) != EOF)
...process a character - possibly null...
or even:
while ((c = getchar()) != EOF && c != '\0')
...process a non-null character...
The first getchar() loop gets a warning from GCC; the latter two do not because of the the explicit test of the value from the assignment.
The people who write a condition like this:
while ((c = getchar()))
really annoy me. It avoids the warning from GCC, but it is not (IMNSHO) a good way of coding.
When you use an assignment operator such as
a=0;
You assign the value to 'a', and still return the number 0.
To test your question, I tried these lines of codes:
int a;
printf("%d", a=0);
and these lines displayed 0.
Then, I tested another set of codes:
int b;
printf("%d", b=15);
Here, the lines displayed 15.
So, if you do:
while(a=0)
{
printf("zero");
}
The (a=0) statement would return false, thus not displaying anything.
But if you do:
while(a=15)
{
printf("fifteen");
}
The "fifteen" will be displayed endlessly, because the statement (a=15) will return a non zero value, or 15, which is not false, not zero, thus it is true. :)
As cnicutar has told above the assignment also yields the value zero.
Some additional info:
It is a common coding mistake for people to omit an extra '=' whereby the comparison becomes an assignment.
An easy way to avoid this is to write the comparison as below, in which case even if a '=' is missed compiler will give an error
while(0 == i)
{
prinf("Hello");
}

Resources