Programming Fundamentals/Conditions

From Wikiversity
Jump to navigation Jump to search
Flowchart Conditions
Flowchart 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.[1] 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.[2] This can be used to create pathways in a program which can allow efficiency and a better system of evaluation.

Objectives and Skills[edit | edit source]

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[edit | edit source]

  1. Pressbooks: Programming Fundamentals
  2. Wikipedia: Structured programming
  3. Wikipedia: Conditional (computer programming)
  4. Wikipedia: Exception handling

Multimedia[edit | edit source]

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

Practice[edit | edit source]

Examples[edit | edit source]

Activities[edit | edit source]

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.

  1. 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).[3] For example, 50 hours worked at $10 per hour with overtime is $550.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.[4]
  7. 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.
  8. 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.
  9. 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[edit | edit source]

  • 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.[5] 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.[6]
  • The pseudocode structure of a conditional statement is:[7]
IF (Boolean condition) THEN
  • 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.[8]
  • 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.[9]
  • 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.[10]
  • 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.[11]
  • One mechanism to transfer control, or raise an exception, is known as a throw.[12]
  • The scope for exception handlers starts with a "try" clause.[13]
  • An exception is said to be thrown and execution is transferred to a "catch" or "except" statement.[14][15]
  • Operator symbols and/or names can vary with different programming languages. Most programming languages use relational operators similar to the following:[16]
Operator	Meaning
<	        less than
>	        greater than
<=	        less than or equal to
>=	        greater than or equal to
==	        equality (equal to)
!= or <>	inequality (not equal to)

Please, be careful as in many programming languages the ≠ is not used and the = symbol means assignment.[17]

  • 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.[18]
  • 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.[19]
  • 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[edit | edit source]

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.[20]
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.[21]
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.[22]
control structures
The mechanisms used to control the code's flow of execution.[23]
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.[24]
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.[25]
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.[26]
A control structure where the program chooses between two or more options.[27]
A control structure where the program executes the items in the order listed.[28]
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.[29]
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.[30]
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.[31]
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).[32]

Assessments[edit | edit source]

See Also[edit | edit source]

References[edit | edit source]

  1. Actian: If Then Else Statements
  2. Wikipedia: Switch statement
  3. PythonLearn: Conditional Execution
  4. Wikibooks: Programming Fundamentals/Practice: Conditions
  5. Wikipedia: Conditional (computer programming)
  6. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweig)
  7. Wikipedia: Conditional (computer programming)
  8. Wikipedia: Conditional (computer programming)
  9. Wikipedia: Conditional (computer programming)
  10. Wikipedia: Exception handling
  11. Wikipedia: Exception handling
  12. Wikipedia: Exception handling
  13. Wikipedia: Exception handling
  14. Wikipedia: Exception handling
  15. Handling Exceptions
  17. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweig)
  18. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweig)
  20. Wikipedia: Boolean expression
  21. Wikipedia: Branch (computer science)
  22. Wikipedia: Block (programming)
  26. Wikipedia: Relational operator
  29. Wikipedia: Spaghetti code
  30. Wikipedia: Structured programming
  31. Wikipedia: Truth table