5
u/PhyllaciousArmadillo Dec 24 '21
#include<stdio.h>
int main()
{
int x;
printf(”Please enter the x number:/n”);
scanf(”%d”, &x);
if(x<=1)
{
printf(”Infant”);
}
//else if(1<x<13) <-----This evaluates differently than you think it does. Regardless of that, you don't have to evaluate “1<x” because, if this were true, it would have stopped at the first if statement and printed “Infant”.
else if(x<13) //better way to write it
{
printf(”Child”);
}
// else if(13<=x<20) <----Same idea, x<13 is already evaluated by the else if above. So if x is less than 13, your program won't even look at this statement.
else if(x<20) //better way
{
printf(”Teenager”);
}
// else if(x>=20) <----- This works, however, being the last statement and encompassing every other value, the better way to write it would be to simply use an else statement.
else //implies every remaining value
{
printf(”Adult”);
}
return 0; // always return a value, unless it's a void function.To address it always printing child, I threw out a little hint in my edit. The statement 1<x<13 is evaluated left to right as in (1<x)<13. First, you're asking if 1<x. If x is greater than 1, this evaluates to True which is 1 as a boolean value.
So, when x is greater than 1
1<x == 1
Which means
(1<x)<13 == 1<13 == true
When x is less than 1, t it evaluates to False or boolean 0
1<x == 0
So
(1<x)<13 == 0<13 == true
So both are true and will therefore be accepted and will print “Child” no matter what the input is.
If you do need to make an evaluation like this, you should use the AND operator. Like such
x>1 && x<13
1
20
10
u/szkuwa Dec 23 '21
Reddit suggested I should look at this but damn… is r/codinghelp an alias for „do it for me because i dont give a shit”?
3
3
u/DoomGoober Dec 24 '21
To be fair, this is a pretty interesting subtle bug introduced by the specifics of C.
In many languages, the expression 1 < x < 3 won't compile as 1 < x evaluates to boolean and boolean < 3 is invalid.
However, in C it is valid because 1 < x evaluates to int or BOOLEAN or whatever the heck C uses which properly casts to int and makes the < 3 evaluate to true always.
Yes, OP seems hostile to people helping and this clearly is just a homework assignment that's not working but the original question is a very good one.
-1
7
u/Alsalvad0r Dec 23 '21
I think you need something more like else if(1<x && x<13) As it is the compiler is just reading the first conditional expression so any number greater than 1 will result true and thus will be child, you need the and operator to add an additional condition
1
u/PhyllaciousArmadillo Dec 24 '21
It compares the first statement 1<x to the final <13. Ie. (1<x)<13. The comparison gives a boolean value, 0(false) or 1(true). So no matter what the input is, the final comparison will always be true. Because 1 and 0 are both less than 13.
If x is less than 1,
1<x == 0for false, then0<13 == 1for true.If x is greater than 1,
1<x == 1for true, then1<13 == 1for true again.
3
u/verytiredrightnow Dec 23 '21
Change 1<x<13 to x<13 and 13<=x<20 to x<20
11
Dec 23 '21
I think the same thing but an explanation is in order:
There's no need to check that X is above 1 in the second check because you've already done that check in the first.
if X <= 1 (infant)
else if X <= 13 (child)
else if X <= 20 (teen)
else (adult)
4
3
2
Dec 23 '21
Well something that is not an issue but my ocd. In line 5 I'm assuming you're taking input in next line so it should be \n. It's optional though
2
u/kamemebymo Dec 23 '21
In addition to the other comments, in the first printf you wrote /n where it should have been \n
2
u/DMoney12344 Dec 23 '21
That you want to learn how to code but apperantly dont know how to take a proper screenshot..
2
Dec 23 '21
Makes me seriously question OP ability to code... Common mate... There's a button on the keyboard literally to screenshot. /Sad
1
u/istarian Dec 24 '21
For what it’s worth Print Screen only copies the image to the clipboard, at least in Windows land. You have to press Win+PrintScreen to have it saved directly to a file.
5
2
1
Dec 23 '21
To do a range, as mentioned, you need to do "AND" (&&) to pick "x is above 1 AND x is below 13"
And when doing range checks... no need to recheck since you are going in order. No need to do "between 1 and 13" because you already know the age is above 1.
https://www.mycompiler.io/view/BqJbDHp
change the input and click run to see the results. 15 prints teenager.
Fork the code and change the input, click run.
And for future questions... use something like the above or text sharing programs. Pictures of code is bad form :)
1
u/Musicrafter Dec 23 '21
You don't even have to specify the lower bounds on any of your "else" ranges at all. It wouldn't have reached that "else" condition in the first place if the number were less than the lower bound, because it would be covered by the previous condition.
1
u/Beastly_Priest Dec 23 '21
Is it only pulling in one character? From reading your other comments, it sounds like you are only getting single digit values (thus child).
2
1
u/RazerNinjas Dec 23 '21
You cannot do something like 1 < x < 3 what ends up happening is that it evaluates. 1 < x as true which in C is 1 if true then it does 1 < 3 which is false. Same with 1 < x is false is 0 and 0 < 3. Keep in mind that boolean operators in C always return 1 or 0 you need to chain with && or || operators
1
Dec 23 '21
Last condition should be else because else condition is the final one in the if else series
1
u/istarian Dec 24 '21 edited Dec 24 '21
You could leave it off if there is no significance to it.
In OP’s case the first IF is true for any number less than or equal to 1. So if you are -200 years old, guess what? You’re an Infant!
1
u/kalashnikovBaby Dec 23 '21
Is a return value necessary for main?
3
u/PhyllaciousArmadillo Dec 24 '21
No, but you should for non-void functions, or it's technically “undefined behavior”.
1
u/static-geek Dec 23 '21
Am I the only one bothered by the fact that Adult condition isn't first so that it and the subsequent elseifs would all be >= instead with else Infant at the end?
1
1
1
u/arm1997 Dec 24 '21
Whenever you declare a function, and you give it a return type which you will have to return to execute the function, also, you don't need to write the if in the last condition
1
u/istarian Dec 24 '21
As has been pointed out elsewhere in this thread, it’s not explicitly required for main. It’s still best practice though.
1
u/istarian Dec 24 '21 edited Dec 24 '21
You need to be careful any time you do something like this:
13<=x<=20 The evaluation of that may not produce the intended result and it’s hard to read.
True and False have numeric equivalents in C… As a result 13 could be less than equal to X and result in True (or 1) which would then be less than or equal to 20. This would be a problem if x was 30.
It’s better to do separate checks like this:
else if( x >= 13 && x < 20) Also, you can nest these kinds of statements. For example:
if( x <= 1 ) {
if( x < 13 ) {
}
else if( x < 20 ) {
}
else {
}
}1
u/atamicbomb Dec 24 '21
Would nesting statements like that be less efficient?
1
u/istarian Dec 24 '21
I didn’t write it all out properly, but I doubt the efficiency would change much for so simple a situation.
All it would do here is make it a little easier to read, because it would be obvious what checks exclude others. If the given age is a year old or younger then you’re basically done.
1
u/atamicbomb Dec 25 '21
It wouldn’t be much, but it compounds exponentially for each layer of inefficiency to a finished product.
Not critiquing your answer, just what to know if it is less efficient or if the compiler will generate the same code for both or something for me.
1
u/istarian Dec 25 '21
Efficiency or inefficiency can add up, but it does not necessarily compound exponentially. And if the amount for this is 0.001 units then even multiplyong it by 100 still doesn’t amount to that much.
The compiler is a mystical black box in a way, it can be hard to know exactly what it will do. In principle, there are tons of things that might happen, but the outcome should be equivalent.
One way to find out is to write code in different ways, but with equivalent function. You can then compile then and see what you got out.
One possibly step of optimizing code is to trim code paths that will never be executing and toss variables that will never be used.
1
u/atamicbomb Dec 25 '21
A difference of .001 isn’t common. You could be doing things in quadratic time when they could be done in logarithmic time. You could be reading from disk each time you do a common fetch instead of storing the first result in ram.
There’s a reason people claim that code inefficiency cancels out Mor’s law. It doesn’t, but optimized code is often orders of magnitude faster than poorly written code.
If the code uses two compare calls instead of 1, it’s half the speed
1
u/istarian Dec 25 '21
The point wasn’t the absolute value, but rather that magnitude matters. As someone with a BS in Comp. Sci. I am well aware of how algorithmic time complexity works.
Not all differences in code are as drastic as O(n) vs. O( n2 ).
The issue with two comparisons versus just one is that you don’t know what the cost of a single comparison is. If the base cost is small enough, then even a ten-fold increase is a tiny change. That’s part of why time complexity (big O) is an estimate.
1
1
1
1
0
1
u/Edthedaddy Dec 23 '21
Use switch and case instead of if statements.
1
u/atamicbomb Dec 25 '21
This appears to be a coding project. OP would receive a 0 for cheating if they did that. You’re only allowed to use what you’ve been tonight and they don’t teach switch.
To give you an idea of how infective coding classes are, half your grade in two schools I went to were written exams. For coding classes
1
u/average_asshole Dec 24 '21 edited Dec 24 '21
If the first condition doesnt run, thats the only time the second condition will run, that being said, we can assume x > 1.
Therefore, our second check should be:
Else if (x < 13)
The same logic goes for our third Else if condition, it will only run if the first two havent, so its greater than 13, and greater than 1.
Therefore, our third check should be:
Else if (x < 20)
Once again, the same logic follows, and we can assume that it must be greater than 20.
Knowing this, the fourth check should be changed to simply 'else'
For example:
Else { // code here // }
Programming is all about math and logic, sometimes it helps to walk away and come back. Youre learning a new language and a new way of thinking, it's tough.
Try drawing the problem out and writing it down, try explaining how it works to people around you, that can help a lot in finding issues.
In this case its just kind of thinking about the logic and the way Else if works. Remember that the chained Else ifs will only ever check if the preceding conditions are false.
As a side note, c++ is a strongly typed language. Your main function has a return type of int
Int main() ^ This is the return type
Therefore you should return 0; at the end of the function
1
u/atamicbomb Dec 24 '21
I don’t know why you got downvoted. I thought you explanation was great
2
u/average_asshole Dec 25 '21
Thanks mang, i had a controversial comment on another post so its probably a memory leak from that.
0
Dec 23 '21
In your first else if every number is evaluating true that it is greater than 1 so it prints child use parentheses and <or> operator
What language are you using?
1
0
-2
u/Similar-Concert4100 Dec 23 '21
Just use if, no need to use else if
1
u/IntroductionBright72 Dec 23 '21
But if there's multiple conditions we kinda need to use the else if🤔
1
u/Similar-Concert4100 Dec 24 '21
Else if looks to see if multiple conditions are true, here only one condition should be true. Each should be an if statement, no else if
1
u/vigbiorn Dec 24 '21
This is pretty much the direct opposite.
A series of ifs will all be evaluated, in order, regardless of the value. An else-if series like this executes until the first true condition is found.
You would use a series of ifs to find multiple conditions being true.
-1
Dec 23 '21
You can have multiple ifs statements instead of else if
2
u/PhyllaciousArmadillo Dec 23 '21
Then it evaluates all of them instead of just the one that's true...
1
-3
0
Dec 23 '21
[deleted]
6
u/W-recker Dec 23 '21
In this instance it does not change the functionality, but there is certainly a functional difference between else / else if statements which is important to understand.
With an Else statement, you can be assured that at least one section of the code will be hit. When you implement only else if statements as in the above code, you could reach the last else if statement, having not met any of the conditions, and drop out the bottom of the logic without having actually done anything at all. (Something which would be picked up upon in an IDE, for example in a method with a return type)
So yes, its much better to finish with an else.
-20
0
0
Dec 23 '21
[deleted]
2
u/istarian Dec 24 '21
I agree that it would be useful to do so in this context, but for a program this simple it’s obvious.
0
-1
Dec 23 '21
[removed] — view removed comment
3
u/KuntaStillSingle Dec 23 '21
You do need to reference the x, in C everything is pass by value, so you need to pass a pointer to it if you want to modify it inside a function, which is what scanf needs to do.
Also you mistyped, 1<x && x <13 is what you meant
-15
75
u/terroroferror Dec 23 '21 edited Dec 23 '21
Change following lines
Line #12 - (1 < x && x < 13)
Line #16 - (13 <= x && x < 20)
Keep only `else` on line #20
Edit: also add statement `return 0;` before line #24