Topics List |
Basic Concepts |
Conditionals |
Conditional Statements ''If'' and ''Select Case'' |
Conditional statements are fundamental in programming as they allow us to make decisions based on certain conditions. In Kenzie, the syntax for conditional statements follows a pattern similar to Lua, with the use of _If _Then _Else _End_If for simple conditions and _Select _Case _Case_Else _End_Select for more complex branching.
Simple Conditional Statements (_If _Then _Else _End_If)The _If _Then _Else _End_If statement in Kenzie is used to execute a block of code if a specified condition is true, and another block of code if it is false. Here´s an example:
In this example, if the value of nombre is ''Robert'', it will print ''Hi Robert'' to the console. Otherwise, it will print ''Hello '' followed by the value of nombre and ''How are you.''. Complex Conditional Statements (_Select _Case _Case_Else _End_Select)The _Select _Case _Case_Else _End_Select statement in Kenzie is used when there are multiple conditions to be evaluated. It works like a switch-case statement in other languages. Here´s an example:
In this example, depending on the value of animal, it will print different sounds. If animal is ''Duck'', it prints ''Quack''. If animal is ''Cat'', it prints ''Meow''. Otherwise, it prints ''Moo''. Here are additional examples: Example: Determining Discount Based on Purchase Amount Suppose we have a program that determines the discount a customer receives based on their total purchase amount. We will use the following discount scale:
In this example, we first set the purchaseAmount variable to 250. We then use multiple _If statements to check the purchase amount against each discount threshold. Each _If statement is independent and will be evaluated regardless of the outcome of the previous _If statements. Example: Determining Day of the Week Suppose we have a program that determines the day of the week based on a numeric value representing the day (1 for Monday, 2 for Tuesday, and so on). We will use the _Select _Case statement to achieve this:
Example: Planning Meals for the Day In this example, we have variables day and meal, representing the day of the week and the mealtime (breakfast, lunch, or dinner), respectively. Depending on the day and mealtime, the program suggests a food item. The _Select statement is used to determine the food item based on the day and mealtime combination.
ConclusionConditional statements are essential for controlling the flow of a program based on certain conditions. In Kenzie, the _If _Then _Else _End_If and _Select _Case _Case_Else _End_Select statements provide powerful tools for implementing conditional logic in your code. Understanding how and when to use these statements is key to writing effective and flexible programs in Kenzie. |