Programming Concepts and Database CSCI N201 Programming Concepts and Database 8 – Conditions Lingma Acheson linglu@iupui.edu Department of Computer and Information Science, IUPUI
Task: Ask the user to input a required integer, and compare the input to the required integer. If it’s the same, output “You entered the right integer!” If not the same, no output. E.g. Comp: Please enter integer 9: User: 9 Comp: “You entered the right integer!”
Algorithm Design Pseudocode – a mixture of natural language with programming language to help in algorithm design. Algorithm design: - Start a new program - Create a new variable n1 - Prompt for user input “Please enter integer 9:” and store the input to n1 - Change n1 to integer - If n1=9, output “You entered the right integer!” - End the program
Using Miracle http://www.cs.iupui.edu/~aharris/MirJS.html Begin the If branch (Conditional => If branch) Give the two numbers or values to compare Give the comparison operator == Equals != Not Equal <= Less than or equal to >= Greater than or equal to < Less than > Greater than End the If branch (Conditional => End structure)
If Statement Checks a condition Begins a block of code If condition is true, executes all codes in block If condition is false, skips code block
Refine the Algorithm Pseudocode: - Start a new program - Create a new variable n1 - Prompt for user input “Please enter integer 9:” and store the input to n1 - Change n1 to integer - If n1==9, output “You entered the right integer!” - End if - End the program Using Miracle!
Else Branch If the user input is not 9, output “You entered a wrong integer!” Pseudocode: - Start a new program - Create a new variable n1 - Prompt for user input “Please enter integer 9:” and store the input to n1 - Change n1 to integer - If n1==9 output “You entered the right integer!” else output “You entered a wrong integer!” - End if - End the program
Else Clause Else is a useful addition to If statements. Else allows you to set up another block of code to execute if the condition is false Using Miracle!
Lab Create a program to compare two user inputs and output the comparison result. Extra 20 credit: Create a program to take two integers, ask the user to enter “+”, “-”, “*”, or “/”. Perform the correspondent maths operation and output the result to the user.