C++ examining conditions

Discussion in 'Scripting & Programming' started by Mof, Aug 18, 2008.

  1. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Glad you saw it in the end! :biggrin
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  2. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    If (a = 0) then 'I'm false' is returned. hbroomhall explains it perfectly.
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  3. Mof

    Mof Megabyte Poster

    526
    2
    49

    so are you saying (a = 0) has been assigned because its inclosed in parentheses there for making boolean true so returns the if statement.

    PS if im wrong dont give me the answer just tell me to try again mabe with a hint
     
    WIP: C++ and A+
  4. jayford

    jayford Bit Poster

    22
    0
    14
    Hi Guys

    been following this silently for a while but had to jump in here as I am just wondering if Mathematix has got things mixed up slighly.

    I have absolutly NO expertise in C++, infact I am just learning c#, but from my understanding

    as this statement if(a=0) is true, meaning "has zero been assigned to a", which it has (or appears to be) in the "if statement", then should not the output be "I'm true" and not "I'm false" .

    The reason why I am thinking that there may be a mix up is that in the second version of the problem a was initialised to 1. Whereas in the first version of the problem a was initialised to 0.

    If I am wrong I offer my apologies, not trying to be big headed, but as I am a noob I just want to make sure I understand what is going on :cry: ( ....hoping the sniffling elicites a reduction of any harsh rebutals for poking noses where the noses knows nowt :biggrin )
     
    Certifications: HND Computing, procrastination+
    WIP: MCITP Developer, Bsc Info & Comp
  5. hbroomhall

    hbroomhall Petabyte Poster Gold Member

    6,624
    117
    224
    I'll try and explain (sorry Mof!).

    The statement a = 0, like all assignments, has a side-effect that the value used for the initialization is the value of the assignment as well.

    Take the line a = b = 1; b is initialized to 1. And the 'value' of 'b = 1' is also one. So it now looks like a = 1, so a is initialized to 1.

    So when you say a = 0 in the example above a is initialized to 0, and the assignment, i.e. 'a = 0' is also zero.
    So 'if (a = 0)' becomes 'if (0)'. And '0' is interpreted by the language as 'false'.
    Now the 'if' statement tests the contents of the parentheses for truth. Here it will be false, so the false branch will be taken.

    Hence the way it works above.

    And the best way to learn is to try it! Just as I did yesterday evening to make sure I had got it right!

    Harry.
     
    Certifications: ECDL A+ Network+ i-Net+
    WIP: Server+
  6. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Harry answered! :D
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  7. Mof

    Mof Megabyte Poster

    526
    2
    49
    alright I was wrong
     
    WIP: C++ and A+
  8. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    A perfectly reasonable question. Recall that in programming 'false' is zero and 'true' is any other non-zero number. The following three program demonstrates this concept.

    Code:
    #include <stdio.h>
    
    int main()
    {
    	int a;
    
    	if(a = 0)			// this is false because '0' is 'logical false'.
    		printf("I'm true.\n");
    	else
    		printf("I'm false.\n");
    
    	if(a = -1)			// this is true because '-1' is 'logical true', as is any negative number.
    		printf("I'm true.\n");
    	else
    		printf("I'm false.\n");
    
    	if(a = 1)			// this is true because '1' is 'logical true', as is any positive number.
    		printf("I'm true.\n");
    	else
    		printf("I'm false.\n");
    
    	return 0;
    }
    
    I've removed the initial initialisation because it has no real relevance and confuses the stiuation.
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  9. Mof

    Mof Megabyte Poster

    526
    2
    49

    Ah Ha
    I can now see where I was going wrong:rolleyes: I was working to the theory if = (true) and else =(false).
    so if(a = 0) 0 is false so take the false branch which is as we all now Know is "I am True".

    I ran the code last night and was flummexed by the "I am true" report, thanks for being patient with me:).
     
    WIP: C++ and A+
  10. jayford

    jayford Bit Poster

    22
    0
    14
    :idea: Ahhhhh the penny has dropped. At the fringes of my consiousness I can remember having dipped my toes into C++ and the concept of "0" being being "false" and all else true does makes sense.

    I think I shall refrain from commenting on coding matters until I can consider my skill level an instance of the class "uber programmer" (hope I used that reference correctly:))

    Mathematix I owe you an apology but also thanks as I thought that my understanding of what was happening was correct :oops:
     
    Certifications: HND Computing, procrastination+
    WIP: MCITP Developer, Bsc Info & Comp
  11. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    No need to apologise, jayford. Every question is a valid question, as far as I'm concerned. I'm just glad that there are people out there who wish to understand rather than just 'do' with a half-understanding.

    Feel free to fire away with any questions you have - no matter how small! :biggrin
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  12. Mof

    Mof Megabyte Poster

    526
    2
    49
    just wanted to check Im on the right track and can finaly move on.

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    int a,b,max;
    a=1,b=2;
    cout << "Variable a value is:";
    cout << ((a!=1) ? "not one,":"one,"); // the equation in the inner parentheses is equated first 
                                          //and the logical not reverses the true in to a false so when the conditional operator examans this
                                          // it will take the false branch (one)
    
    cout << ((a%2!=0) ?"odd" : "even");
    cout << endl << "Variable b value is:";
    cout << ((b!=1) ? "not one," : "even");
    
    max = (a > b) ? a:b;
    cout << endl << "Greater value is:" << max << endl;
    return 0;
    }
     
    WIP: C++ and A+
  13. hbroomhall

    hbroomhall Petabyte Poster Gold Member

    6,624
    117
    224
    Er - I'm not sure what the question is....

    Harry.
     
    Certifications: ECDL A+ Network+ i-Net+
    WIP: Server+
  14. dmarsh
    Honorary Member 500 Likes Award

    dmarsh Petabyte Poster

    4,305
    503
    259
    As harry says, whats the question ? :D

    Theres a number of minor issues but you appear to have the gist of it.

    Code:
    cout << ((a!=1) ? "not one,":"one,"); // the equation in the inner parentheses is equated first 
                                          //and the logical not reverses the true in to a false so when the conditional operator examans this
                                          // it will take the false branch (one)
    Poor explantion, 'logical not' is a unary operator to get the logical/boolean negation of a value. Not equal is a binary relational operator that evaluates to a 'boolean' integer value, there is a difference !

    See here :-
    http://www.sunilb.com/c-programming/c-tutorial-operators-in-c
    http://en.wikipedia.org/wiki/Operators_in_C_and_C&#37;2B+

    As you can see there are many operators and there are various precedence rules that control evaluation.

    On top of this you have the usual implicit casts and promotion, a bool type was introduced into C++ but apparently logical operators still operate on integers, the bools are 'promoted' first. Logical and Relational operators can only ever return integer 0 or 1. You also have short cut functionality built into the logical AND and logical OR operators.

    You seem to have understood the ternary if operator, however in reality this is not used that much as a verbose 'if ... else' statement is more readable.

    Code:
    cout << ((b!=1) ? "not one," : "even");
    This is obviously incorrect, just because somethings 'not one' does not make it even, theres an large set of both positive and negative odd integer numbers the int can contain. In fact it states that one is even which is the easiest way to show that the statement is false.

    Otherwise keep up the good work ! :D
     
  15. Mof

    Mof Megabyte Poster

    526
    2
    49
    sorry for not explaining my question very well it was getting late when I posted it. I was just confirming what I had commented was right before moving onto the next step in this book.

    this is how they write code in the book im reading, I know 0 = false and any other number = isTrue I would go on but it seems to be getting busy here so better go for now.:)
     
    WIP: C++ and A+
  16. dmarsh
    Honorary Member 500 Likes Award

    dmarsh Petabyte Poster

    4,305
    503
    259
    Get another book if thats true ! Draw a venn diagram, 'not one' and 'even', the sets intersect totally, meaning there is inclusion of the 'even' set by the 'not one' set. Not one includes all numbers except one, both odd and even, so its a superset of the set of all even numbers. The logic is all wrong whichever way you look at it ! :D
     
  17. Mof

    Mof Megabyte Poster

    526
    2
    49
    true


    I will after this one. It teaches the basic but not much else, im not complaining as you have to start somewhere,

    thanks for the link on Venn diagrams its good to learn something new every day and this will help me when i get a bit further down the line. Im still finding the whole programming experience very interesting and I know I have a long way to go.:D
     
    WIP: C++ and A+
  18. dmarsh
    Honorary Member 500 Likes Award

    dmarsh Petabyte Poster

    4,305
    503
    259
    No problem Mof ! I expect it was a cut and paste bug or typo but thought I should point it out anyway.

    Basic books are fine, just try to avoid books that teach with bad examples, you want to get used to seeing as much correct code as possible.

    C/C++ programmers tend to get really caught up in syntax, this can be to the detriment of learning other areas of software development. I'd try not to get too bogged down in the details if you can. Ternary if statements are really just a nice to have abbreviation feature, they could be put in a reference section at the back of the book in my mind.

    Try and write programs that do things that are useful like :- read from the console, write to a file, generate a fibonanci sequence, convert celcius to fahrenheit.

    Later maybe create a sorting routine, a basic calculator or telephone directory. After that maybe a video rental system or hotel room booking system.

    That way you can practice the basics while still feeling you are producing something useful that actually does something ! :D
     
  19. Mof

    Mof Megabyte Poster

    526
    2
    49
    Thats a very good idear and will follow that up. My aim when Ive got past the basic stage was to try and write a programme that will take a given size (ie 30x20) and when a differant size (ie A4) is input will work out how many A4s I can get out of the 30 x 20. But must learn the basics first.:biggrin

    this book does finish with us writing a random number selector for Lottery numbers.
     
    WIP: C++ and A+
  20. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Sorry I've disappeared for so long. Just got back from just short of two weeks in Florida to see family, and of course, Disney World! Had a great itme, but anyway.

    The advice quoted above from dmarsh is about as good as it gets. The way that you were learning before was slow and some of the techniques you were supposed to be picking up weren't quite sinking in. I hope you listen to his advice. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.

Share This Page

Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.