CPPForSchool.com: Variable, Operator & Expression Set 1: Assignment 9

9. Write a program to check whether the given number is positive or negative (using ? : ternary operator )

This assignment had my computer science senses tingling, in a very bad way.  For this particular assignment, I had to code a program that utilizes a ternary operator for determining if a number is positive or negative.  In concept this should be rather simple, but reading it hasn't been too easy.  From what I understood, ternary operators function much like a shorthand if/else statement.  Nevertheless, below is the source code and output.


Although there everything outputted as expected, there is a minor issue.  If the user decides to input a zero, regardless of the instruction, it will output incorrect information.

Example 1: "23 is a positive number."  <--Correct!




Example 2: "-123 is a negative number."  <--Correct!




Example 3: "0 is a negative number." <--Wrong!




Once again, I would like to point out that for this particular exercise, ternary operators are probably not the best approach.  Then again, this is merely an introduction to the concept so I shouldn't judge it so harshly.  Still, I feel that this was a poor execution as an introduction to the concept.


**********UPDATE*********
I am very excited to update this post.  After reviewing the code and watching a few more videos pertaining to ternary operators, I was finally able to correct the shortcomings of this exercise example solution.  Below is the updated source and output.  The program is now able to handle the entire scope of integers, including zero.



Example 3: "You've entered 0, please follow directions." <---Correct!



Comments

Popular posts from this blog

CPPForSchool.com: Array - Single Dimension Set 1 Assignment 6

CPPForSchool.com: Variable, Operator & Expression Set 1: Assignment 8