Basic programming course: Lesson #6 Functions.

in #devjr-s20w65 days ago

Function result = multiply(n1, n2).png

Edited By Canva

Tell us about your experience with programming, was it your first time? Did you find it complicated? What was your favorite part of the course?

I remember very well my beginnings in programming and honestly it was not the first time I ventured into it since I had already acquired some experience in this field during my career as a computer science teacher and also through my personal projects, however each new introduction to a programming language or method brings its share of discoveries and challenges even for someone who has a certain mastery of computer science.

To be honest I must admit that I did not find programming particularly complicated but on the other hand that does not mean that everything was easy for me because there were times when certain concepts required in-depth reflection especially when I tried to optimize certain solutions or integrate more advanced features by testing several execution cases. However what captivated me the most in this course was the possibility of applying abstract concepts to concrete situations and seeing them take shape in a tangible way.

Thank you @alejos7ven because I particularly enjoyed the part where I had to solve logic problems using conditional structures and loops because it allowed me to combine my passion for logic with my creativity by looking for different ways to arrive at a solution that is both elegant and efficient, which for me is the very essence of programming.

Add the functions to multiply and divide to the course calculator. Explain how you did it.

I will add the two functions of multiplication and division to this calculator for this I will follow the same model provided by the author and which used for the functions of addition and subtraction and here in detail the steps which I followed:

1. Add the multiplication function:

First of all I will define a function called multiply which will take two arguments which are n1 and n2 and will return their product, so the structure will be similar to that of the function sum.

Function result = multiply(n1, n2)
    Define result As Real
    result = n1 * n2
    Return result
EndFunction

2. Add the division function:

After I will also create a divide function but I will add a check to avoid division by zero which is a special case to solve that is to say if the user tries to divide by zero our function will display an error message and will not try to do the division.

Function result = divide(n1, n2)
    Define result As Real
    If n2 != 0 Then
        result = n1 / n2
    Else
        Print "Error: Division by zero is not allowed."
        result = 0 // Return a default value to avoid errors
    EndIf
    Return result
EndFunction

3. Modify the menu to include the new options:

Look that these changes then push me to add options for multiplication and division in the main menu so that the user can choose these operations.

Function opt = showMenu
Print "What do you want to do?";
Print "1. Sum.";
Print "2. Subtract.";
Print "3. Multiply."; // New option
Print "4. Divide."; // New option
Print "0. Exit.";
Read opt;
EndFunction

4. Update the algorithm logic:

And of course in the Switch structure, I will also add two new cases to handle multiplication and division by calling the corresponding functions.

Algorithm calc
    Define n1, n2 As Real
    Define opt As Integer
    Define exit As Logic

    exit = False

    Repeat
        opt = showMenu()

        Switch opt Do
            case 0:
                Clear Screen
                Print "Bye =)"
                exit = True
            
            case 1: // Addition
                n1 = askNum(n1)
                n2 = askNum(n2)
                result = sum(n1, n2)
                showResult(result)
                reset()
            
            case 2: // Soustraction
                n1 = askNum(n1)
                n2 = askNum(n2)
                result = subtract(n1, n2)
                showResult(result)
                reset()
            
            case 3: // Multiplication
                n1 = askNum(n1)
                n2 = askNum(n2)
                result = multiply(n1, n2)
                showResult(result)
                reset()
            
            case 4: // Division
                n1 = askNum(n1)
                n2 = askNum(n2)
                result = divide(n1, n2)
                showResult(result)
                reset()
            
            Default:
                Print "Invalid option."
                reset()
        EndSwitch
    Until exit = True
EndAlgorithm


>FINAL PROJECT: Create an ATM simulator.

Here is my pseudo-code version of the ATM simulation algorithm:

```Pseudo
Function pinIsValid = validatePin()
    Define userPin As Integer
    Define validPinCode As Integer
    validPinCode = 12345678
    Repeat
        Print "Enter your PIN"
        Read userPin
        If userPin = validPinCode Then
            pinIsValid = True
        Else
            Print "Invalid PIN Please try again"
            pinIsValid = False
        EndIf
    Until pinIsValid = True
EndFunction

Function showMenu()
    Print "ATM Menu"
    Print "1 View Account Balance"
    Print "2 Deposit Money"
    Print "3 Withdraw Money"
    Print "4 Exit"
    Print "Select an option"
    Read userChoice
    Return userChoice
EndFunction

Function viewBalance(accountBalance)
    Print "Your current balance is" accountBalance
EndFunction

Function depositMoney(accountBalance)
    Define depositAmount As Real
    Print "Enter the amount to deposit"
    Read depositAmount
    accountBalance = accountBalance + depositAmount
    Return accountBalance
EndFunction

Function accountBalance = withdrawMoney(accountBalance)
    Define withdrawalAmount As Real
    Print "Enter the amount to withdraw"
    Read withdrawalAmount
    If withdrawalAmount <= accountBalance Then
        accountBalance = accountBalance - withdrawalAmount
        Print "Withdrawal successful"
    Else
        Print "Insufficient funds"
    EndIf
    Return accountBalance
EndFunction

Algorithm atmSimulator
    Define accountBalance As Real
    Define exitProgram As Logic
    Define userChoice As Integer
    accountBalance = 0.0
    exitProgram = False

    validatePin()

    Repeat
        userChoice = showMenu()

        Switch userChoice Do
            case 1:
                viewBalance(accountBalance)
            case 2:
                accountBalance = depositMoney(accountBalance)
            case 3:
                accountBalance = withdrawMoney(accountBalance)
            case 4:
                Print "Thank you for using our ATM"
                exitProgram = True
            Default:
                Print "Invalid option Please try again"
        EndSwitch
    Until exitProgram = True
EndAlgorithm

In this code the first thing I implemented is a function called validatePin that allows me to check if the user is entering the correct PIN code, in this function I defined two variables named userPin containing the PIN code that the user will enter and the other is called validPinCode which is the correct PIN code that I set to 12345678. After I set up a loop repeat until which asks the user to enter his PIN code and compares what he entered with the correct code, then until the user has entered the correct code this function continues to ask him to try again and only once the correct code is entered does the loop stop and the function validates that the PIN code is correct.

Then I also implemented the showMenu function which has the role of displaying a main menu of the ATM and which presents the different banking operations available to the user such as the possibility of consulting the account balance, depositing money, withdrawing money or leaving the application permanently. After displaying the options the function reads the user's choice and returns this value so that I can use it later in the main algorithm.

Concerning the viewBalance function, it simply allows me to display the current account balance by taking the account balance (accountBalance) as a parameter and displays it to the user which gives a clear view of the money available in the account at any time.

Then, I create the depositMoney function which allows me to add money to the account balance. The user enters the amount he wants to deposit and I add it to the current balance and then I return the new balance to update the account balance when the user makes a deposit.

I continue with the withdrawMoney function which is a little more complex since it must check that the account balance is sufficient before authorizing a withdrawal, here the user must type the amount he wants to withdraw and if this amount is less than or equal to the account balance then the withdrawal is made, the balance is updated and a success message is displayed. On the other hand, if the user tries to withdraw more money than he has, the function displays an error message indicating that the funds are insufficient and the balance is not modified.

Finally in the main algorithm I will call atmSimulator starting by defining and initializing the necessary variables like accountBalance which represents the account balance, exitProgram whose role is to know if the user wants to exit the application and userChoice which stores the user's choice in the menu. The account balance is initialized to 0 and the program starts by calling the validatePin function to make sure the user enters the correct PIN before continuing.

After validating the PIN, I enter a loop that displays the main menu to the user using the showMenu function. Depending on the user's choice, different actions are performed. If the user chooses to view the balance, the viewBalance function is called, if the user chooses to deposit money, depositMoney is called, and to withdraw money, the withdrawMoney function is used. If the user decides to exit, the exitProgram variable is set to True, which ends the loop and terminates the program execution.

Execution Scenario

1.png

2.png

3.png

4.png

5.png


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

Best Regards,
@kouba01

Sort:  

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

Loading...