Basic programming course: Lesson #5 Control structures. Part 2. Cycles. [ESP-ENG]

in devjr-s20w5 •  last month 

prt2.png

Edited By Canva

Explain the cycles in detail. What are they and how are they used? What is the difference between the While and Do-While cycle?

When I program I often find myself having to repeat instructions until a condition is met. Loops, or cycles, are important tools that allow me to execute the same code several times without having to rewrite it each time. They make it easier for me to automate tasks, manage data and control the functioning of my programs.

One loop I use frequently is the while loop. It runs code as long as a condition is true. Before starting, I set up the necessary variables. The loop then checks the condition, and if it's true, the code runs. After that, I update the variables so the loop will eventually stop. It keeps running until the condition becomes false.

For example, if I want to display numbers from 1 to 5 using the while loop, the algorithmic syntax would look like this:

i ← 1
While i ≤ 5 Do
    Print "Number is: ", i
    i ← i + 1
EndWhile

In this example, I start with i at 1. The loop checks if i is less than or equal to 5. If the condition is true, the program prints the number and adds 1 to i. This continues until i reaches 6, when the loop stops.

Another useful loop is the repeat-until loop, which guarantees that the code runs at least once before checking the condition. Similar to a do-while loop in other programming languages, the code runs first, then the condition is checked. If the condition is false, the loop repeats; if it's true, the loop stops.

For instance, if I want to write a program that asks the user to enter a positive number, I can ensure the prompt shows up at least once and repeats until the user gives a valid input. The algorithm would look like this:

Repeat
    Print "Enter a positive number: "
    Read n
Until n > 0

In this scenario, the program prompts the user to enter a positive number. Regardless of the initial input the code inside the cycle executes at least once. The cycle continues to prompt the user until the condition n > 0 is true.

The for loop is very useful when I know exactly how many times I want the code to run. This loop lets me set a range, and it automatically handles starting, stopping, and updating the counter. It’s great for tasks like printing a list of numbers or iterating over elements in an array.

For instance, if I want to display the numbers from 1 to 5, I can use the "for" cycle as follows:

For i from 1 to 5 Do
    Print "Number is: ", i
EndFor

In this example, the cycle initializes i to 1 and increments it by 1 in each iteration until it reaches 5. The code inside the cycle prints the current value of i.

Difference Between While and Do-While Loops

It is important to understand the differences between these cycles. With a while loop the condition is checked before running the code. If the condition is false from the start the code may never run. With a repeat-until loop the code runs first, then the condition is checked which ensures that the code runs at least once.

Investigate how the Switch-case structure is used and give us an example.

I often find myself having to make decisions in my code based on the value of a variable. In this case the Switch-case structure is very helpful. It allows me to execute different blocks of code depending on the value of a variable, which makes my programs simpler and easier to read.

The Switch-case structure compares the variable to several possible values (called "cases") and executes the code that matches. If no cases match, a default block of code can be executed.

How the Switch-case Structure is Used

When I have a variable that can have multiple values ​​and I want to perform different actions depending on each value, I use the Switch-case structure. This makes my code simpler and avoids using multiple if-else conditions, making it easier to read and maintain.

Here is the basic syntax of the Switch-case structure in algorithms:

Switch variable Do
    Case value1:
        // Code to execute when variable equals value1
    Case value2:
        // Code to execute when variable equals value2
    ...
    Case valueN:
        // Code to execute when variable equals valueN
    Default:
        // Code to execute if variable doesn't match any case
EndSwitch

Real-life Example

Let's imagine that I write a program that determines the day of the week based on a number entered by the user. The user enters a number from 1 to 7, and the program shows the corresponding day. Using the Switch-case framework I can implement this as follows:

Print "Enter a number from 1 to 7 to select a day of the week:"
Read dayNumber

Switch dayNumber Do
    Case 1:
        Print "The day is Monday."
    Case 2:
        Print "The day is Tuesday."
    Case 3:
        Print "The day is Wednesday."
    Case 4:
        Print "The day is Thursday."
    Case 5:
        Print "The day is Friday."
    Case 6:
        Print "The day is Saturday."
    Case 7:
        Print "The day is Sunday."
    Default:
        Print "Invalid number. Please enter a number from 1 to 7."
EndSwitch

In this example, I ask the user to enter a number between 1 and 7, then store that value in the dayNumber variable. I then use the Switch-case struct to compare dayNumber to each case. If dayNumber matches one of the cases, the corresponding day is displayed. If no case matches, the Default case runs and the program displays an error message.

Benefits of Using Switch-case

The Switch-case structure makes my code more readable by clearly outlining each possible value and the corresponding action. It can be more efficient than multiple if-else-if statements especially when dealing with many possible values. Adding or modifying cases is straightforward which helps when updating the code in the future.

Another Practical Example

Imagine I'm developing a simple calculator that performs basic arithmetic operations based on the user's choice. Here's how I might use the Switch-case structure:

Print "Select an operation:"
Print "1: Addition"
Print "2: Subtraction"
Print "3: Multiplication"
Print "4: Division"
Read choice

Print "Enter the first number:"
Read num1
Print "Enter the second number:"
Read num2

Switch choice Do
    Case 1:
        result ← num1 + num2
        Print "The result of addition is: ", result
    Case 2:
        result ← num1 - num2
        Print "The result of subtraction is: ", result
    Case 3:
        result ← num1 * num2
        Print "The result of multiplication is: ", result
    Case 4:
        If num2 ≠ 0 Then
            result ← num1 / num2
            Print "The result of division is: ", result
        Else
            Print "Error: Cannot divide by zero."
        EndIf
    Default:
        Print "Invalid choice. Please select a valid operation."
EndSwitch

In this example, I present a menu of operations to the user and read their choice. I then prompt the user to enter two numbers. Using the Switch-case structure, I execute the corresponding arithmetic operation based on the user's choice. If the user selects an invalid option, the Default case handles it by displaying an error message.

Comparison with If-Else-If Statements

While I could use multiple if-else-if statements to achieve the same result, the Switch-case structure is more concise and easier to read when dealing with numerous discrete values.

Using If-Else-If Statements:

If dayNumber = 1 Then
    Print "The day is Monday."
ElseIf dayNumber = 2 Then
    Print "The day is Tuesday."
...
Else
    Print "Invalid number. Please enter a number from 1 to 7."
EndIf

This approach becomes cumbersome as the number of conditions increases. The Switch-case structure simplifies the code and reduces the likelihood of errors.

When to Use Switch-case

I use the Switch-case structure when I have a variable that can take on a finite set of values and need to execute different code blocks based on the variable's value. It helps keep my code clear and maintainable.

Explanation what the code does

The algorithm provided, named switchcase demonstrates how the Switch-case structure is used within a program. Here's a detailed explanation of what the code does:

The algorithm begins by defining several variables: op, n, ns, and a as integers and exit as a logical (boolean) variable. The variable exit is initialized to False, and a is set to 0. These initializations set up the necessary conditions for the program to operate correctly.

The program enters a Repeat...Until cycle that continues until exit becomes True. Inside this cycle the program presents a menu to the user, processes the user's input and performs actions based on that input.

First, the program displays options to the user by printing a menu with three choices:

Print "Select an option:";
Print "1. Sum numbers.";
Print "2. Show results.";
Print "3. End program.";

The user is then prompted to enter their choice, which is read into the variable op:

Read op;

The program uses a Switch op Do structure to handle the user's choice:

Switch op Do
    case 1:
        // Code for summing numbers
    case 2:
        // Code for showing results
    case 3:
        // Code for ending the program
    Default:
        // Code for handling invalid options
EndSwitch

In Case 1 (Sum Numbers), the program asks how many numbers the user wants to sum and reads the input into n:

Print "How much nums do you want to sum?";
Read n;

It then enters a For cycle from i = 1 to n:

For i from 1 to n Do
    Print "Enter a number: ";
    Read ns;
    a = a + ns;
EndFor

Inside the cycle, the user is prompted to enter a number, and each entered number ns is added to the accumulator a. After the cycle, the program notifies the user that the operation is completed:

Print "Completed! Press any button to continue";
Wait Key;
Clear Screen;

In Case 2 (Show Results), the program displays the current total sum stored in a:

Print "This is the current result: ", a;
Print "Press any button to continue.";
Wait Key;
Clear Screen;

In Case 3 (End Program), the program clears the screen, prints a goodbye message, and sets exit to True to terminate the cycle:

Clear Screen;
Print "Bye =)";
exit = True;

(Note: In the code provided, case 3 is written as caso 3, which might be a typo or a language-specific term.)

If the user enters an option other than 1, 2, or 3, the program handles it in the Default case, treating it as an invalid option:

Print "Invalid option.";
Print "Press any button to continue";
Wait Key;
Clear Screen;

After executing the appropriate case, the cycle repeats until exit becomes True:

Until exit

When the user selects option 3, exit is set to True, and the Repeat...Until cycle terminates, ending the program gracefully.

Error Handling:

The program includes a Default case in the Switch-case structure to handle invalid menu selections gracefully. When an invalid option is entered, the program informs the user and returns to the menu, ensuring that the program remains robust and user-friendly.

Write a program in pseudo-code that asks the user for a number greater than 10 (Do-While), then add all the numbers with an accumulator (While) Example: The user enters 15. The program adds up to 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15.

Algorithm SumNumbers
    Declare n, sum, i as Integer

    Repeat
        Print "Enter a number greater than 10: "
        Read n
    Until n > 10

    sum ← 0
    i ← 1

    While i ≤ n Do
        sum ← sum + i
        i ← i + 1
    EndWhile

    Print "The sum of numbers from 1 to ", n, " is: ", sum
EndAlgorithm

In this program, I start by declaring the necessary variables: n for the number entered by the user, sum to accumulate the sum and i as a counter for the cycle. The Repeat...Until cycle ensures that the user enters a number greater than 10. After initializing sum to 0 and i to 1 I use a While cycle to add each number from 1 up to n. In each iteration I add the value of i to sum and increment i by 1. Once the cycle is finished I display the result by indicating the sum of numbers from 1 to n.

For example, if the user enters 15, the program will calculate the sum 1 + 2 + 3 + ... + 15 which equals 120. The program will then display: "The sum of numbers from 1 to 15 is: 120".


Thank you very much for reading, it's time to invite my friends @pelon53, @lhorgic, @mohammadfaisal to participate in this contest.

Best Regards,
@kouba01

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Upvoted. Thank You for sending some of your rewards to @null. It will make Steem stronger.


💯⚜2️⃣0️⃣2️⃣4️⃣ This is a manual curation from the @tipu Curation Project

@tipu curate

This post has been upvoted/supported by Team 5 via @httr4life. Our team supports content that adds to the community.

image.png

Loading...