# Programming Fundamentals/Conditions

This lesson introduces conditions, including if-then-else, case/switch, and structured exception handling. Conditions are statements that are created by the programmer which evaluates actions in the program and evaluates if it's true or false. If-then-else statement allows conditional execution based on the evaluation of an expression. Case/Switch statement type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map. This can be used to create pathways in a program which can allow efficiency and a better system of evaluation.

## Objectives and Skills

Objectives and skills for this lesson include:
* Understand structured programming concepts
* Understand sequence, selection/condition, and iteration/loop control structures
* Understand if-then-else and case/switch statements
* Understand structured exception handling concepts
* Use conditional code to implement program functionality

## Readings

* Pressbooks: Programming Fundamentals
* Wikipedia: Structured programming
* Wikipedia: Conditional (computer programming)
* Wikipedia: Exception handling

## Multimedia

* YouTube: The three basic structures—sequence, selection, and loop
* YouTube: Programming For Beginners - Relational Operators
* YouTube: Introduction to Programming - Control Flow
* Youtube: Programming Basics: Statements & Functions
* Youtube: Introduction to Conditional Statements

## Practice

* Conditions
* Nested Conditions
* Compound Conditions

## Examples

* Flowchart
* Pseudocode
* Block
* BASIC
* C
* C++
* C#
* Clojure
* COBOL
* Fortran
* Go
* Java
* JavaScript
* Lua
* Perl
* PHP
* PowerShell
* Python3
* Ruby
* Rust
* Swift
* VB.NET

## Activities

Complete the following activities using pseudocode, a flowcharting tool, or your selected programming language. Use separate functions for input, each type of processing, and output. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.
* Create a program to prompt the user for hours and rate per hour to compute gross pay (hours * rate). Include a calculation to give 1.5 times the hourly rate for any overtime (hours worked above 40 hours). For example, 50 hours worked at $10 per hour with overtime is $550.
* Create a program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in (M)onths, (D)ays, (H)ours, or (S)econds. Use if/else conditional statements to display their approximate age in the selected timeframe. Do not perform any unnecessary calculations.
* Review MathsIsFun: US Standard Lengths. Create a program that asks the user for a distance in miles, and then ask the user if they want the distance in US measurements (yards, feet, and inches) or in metric measurements (kilometers, meters, and centimeters). Use if/else conditional statements to determine their selection and then calculate and display the results.
* Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user what shape they would like to calculate the area for. Use if/else conditional statements to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
* Review Wikipedia: Aging in dogs. Create a program to prompt the user for the name of their dog and its age in human years. Calculate and display the age of their dog in dog years, assuming the first two years equal 10.5 years each, with subsequent years equaling four human years. Be sure to include the dog's name in the output, such as: Spike is 25.0 years old in dog years.
* Create a program that helps the user determine what sock size to order based on their shoe size: < 4 = extra small 4 to 6 = small 7 to 9 = medium 10 to 12 = large 13+ = extra large Use if/else conditional statements to determine their selection and then display the results. Round half-sizes up to the next whole size. One option for rounding is to add 0.5 and then convert to an integer.
* If your programming language supports it, update one or more of the programs above to replace the if/else conditional statements with case/select conditional statements.
* Review Wikipedia: Is functions. If your programming language supports it, update one or more of the programs above to include input validation for all numeric input.
* If your programming language supports it, extend one or more of the programs above by adding structured exception handling statements (try-catch, try-except, etc.) to handle any runtime errors caused by the user entering invalid values for the input.

## Lesson Summary

* Conditional statements are features of a programming language which perform different computations or actions depending on whether a programmer-specified Boolean condition evaluates to true or false. The basic attribute of a selection control structure is to select between two or more alternative paths. A question using Boolean logic controls which path is selected.
* The pseudocode structure of a conditional statement is:
* If the condition is true, the statements following the THEN are executed. Otherwise, the execution continues in the following branch – either in the ELSE block (which is usually optional), or if there is no ELSE branch, then after the END IF.
* By using ELSE IF/ELSEIF, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.
* Exception handling is the process of responding to the occurrence, during computation, of anomalous or exceptional events requiring special processing, often changing the normal flow of program execution.
* In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote a data structure storing information about an exceptional condition.
* One mechanism to transfer control, or raise an exception, is known as a throw.
* The scope for exception handlers starts with a "try" clause.
* An exception is said to be thrown and execution is transferred to a "catch" or "except" statement.
* Operator symbols and/or names can vary with different programming languages. Most programming languages use relational operators similar to the following:
Please, be careful as in many programming languages the ≠ is not used and the = symbol means assignment.
* Two-way selection structures may be nested inside other two-way selection structures, resulting in multi-way selection. The concept of nesting allows the mixing of the different categories of control structures.
* One of the most important concepts of programming is the ability to control a program so that different lines of code are executed or that some lines of code are executed many times. The mechanisms that allow us to control the flow of execution are called control structures.
* It is possible to establish more than one condition in one IF by using logical operators (AND, OR and NOT), these operations are used to make more open or strict decisions, depending on the programmer's needs.[source?]

## Key Terms
### Boolean expression

    A logical statement that is either "True" or "False". It is used to compare 2 variables as long as they are the same data type.

### branching

    An instruction in a computer program that can cause a computer to begin executing a different instruction sequence. This causes the program to deviate from its default behavior of executing instructions in order. This behavior is undesirable, and is therefore rarely used in modular structured programming.

### code block

    In computer programming, a block or code block is a lexical structure of source code which is grouped together. Blocks consist of one or more declarations and statements. Depending on the programming language, a code block can be signified by curly brackets "" or indentation.

### control structures

    The mechanisms used to control the code's flow of execution.

### if then else

    A two-way selection control structure. Questions with a Boolean true or false answer controls what the structure does. Simply put, the "if" part of the structure will do something if the question's answer is true, while the "else" part of the statement will do something if the question's answer is false.

### multiway selection

    Using control structures to be able to select from more than two choices. Nested control structures Placing one control structure inside of another.

### logical operator

    A logical operator is a symbol or word used to connect two or more expressions such that the value of the compound expression produced depends only on that of the original expressions and on the meaning of the operator. Common logical operators include AND, OR, and NOT. Python just uses the words and, or, and not. In many other languages && is used for AND, || is used for OR, and ! is used for not.[source?]

### relational operator

    An operator that defines or tests a relationship between 2 variables. They consist of: less than, less than or equal to, equal to, not equal to, more than, more than or equal to.

### selection

    A control structure where the program chooses between two or more options.

### sequence

    A control structure where the program executes the items in the order listed.

### spaghetti code

    A pejorative phrase for unstructured and difficult-to-maintain source code. Spaghetti code can be caused by several factors, such as volatile project requirements, lack of programming style rules, and insufficient ability or experience.

### structured programming

    A programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection (if/then/else) and repetition (while and for), block structures, and subroutines. Thus, preventing Spaghetti code as a result.

### truth table

    A table used to test Boolean logic. The table compares different combinations of a function's input values. It is also a common way to show logical relationships.

### truthy

    In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, 0n, "", null, undefined, and NaN).

## Assessments

* Quizlet: Flash Cards
* Quizlet: Flash Cards - Conditional Statements
* Quizlet: Quiz

## See Also

* Introduction to Programming/Control structures
* Programming Logic/Conditionals and Logic
* Wikipedia: Switch statement
* Medium: Introduction to Truth Tables & Boolean Algebra