When we are starting in programming, in some moment we'll encounter with conditionals. Conditionals are expressions that tell the program what to do in certain conditions. Theses statements are essential in programming, not only for beginners, but for every developer who wants to create a solution in their software.
First, to completely understand the use of conditionals we can connect it to the real life. In our daily routines why use conditionals to take decisions. For example, if I had a job interview but I'm running late, I'd say, "If I go by foot, I might not arrive at time, but if I take the subway I'll arrive just at time." Notice that I use if to show that I'm taking about a condition and what will happen if that condition is met. Well, the same is for programming.
- Second of all, before showing you code examples I'd like to briefly explain you the Truth Table. This table helps us to know when conditions combinations are true or false, it means when the final condition will be met or not. Here is a basic truth table.
Table created using designcap |
Next, one more step before putting all this into code. There are some symbols to identify each operation. Programming languages uses the following.
AND is represented by &.
OR is represented by |.
NOT is represented by !.
Finally, let's apply all this knowledge to some code examples.
To use AND, we'll solve the next problem. "If the student is older than 18 and his class is business, print 'Congrats, you can apply for the job' or else print 'Sorry you must be older than 18 and be in the business class'"
To use OR, we'll solve the next problem. "If the student is older than 18 or has a dog, print 'Congrats, you can be a dog sitter' or else print 'Sorry you must be older than 18 or have a dog'"
To use NOT, we'll solve the next problem. "If the student career is related with medicine , print 'Congrats, you can apply for being a doctor' or else print 'Sorry you have to be studying medicine'"
To conclude, we use conditionals in order to execute certain code segments. These statements are very helpful when we want to create a solution. Programming languages have symbols to represent each condition type and also some keywords are similar like if and else. You also understood the truth table and how to use conditionals in real code exercises.
Comments
Post a Comment