Basic programming course: Lesson #6 Functions. [ESP-ENG]

in devjr-s20w6 •  last month 

Hello Steemians, welcome to my post, and stay safe as you read through this post.

1000193591.png


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? (2 points)

My first time programming was both challenging and exciting to me which at first I thought I wouldn't be able to cope with because my field of study is outside computer science. Initially, at beginning I found it a bit complicated to understand almost all the concepts such as functions, loops, and others, I got disappointed at first for not understanding them, but as I put effort into practicing them, they started making sense to me.

My favorite part of the course was Operations which talks about Arithmetic operations, and Control structures. Part 1. Conditionals. Like cracking my brain mathematically which by doing so makes me reason big and beyond my imagination. Seeing the results of my work and effort which I used my brain to quote usually makes me feel happy. Indeed there are joys in learning and understanding programming which I have derived from this challenge.


Add the functions to multiply and divide to the course calculator. Explain how you did it. (3 points)

To add multiplication and division functions to the calculator in the provided pseudocode, we will need to follow the exact structure as the sum and subtract functions which below is how it can be done.

Create the Multiply Function

This is the function that will take two parameters, multiply them, and then return the result.

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

Create the Divide Function

This is the function that will take two parameters, divide them, and then return the result. The division must be zero.

Function result = divide(n1, n2)
    Define result As Real;
    If n2 ≠ 0 Then
        result = n1 / n2;
    Else
        Print "Error: Division by zero.";
        result = 0;
    EndIf
EndFunction

Modify the Menu to include options for multiplication and division:

Here Is to apply addition options in the showMenu function to include multiply and divide.

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

Update the Main algorithm to handle the new operations

At this point, In the calc algorithm, add new cases for multiplication and division.

Algorithm calc
    Define n1, n2 As Real;
    Define opt As an Integer;
    Define exit As Logic;
    
    exit = False;
    
    Repeat
        opt = showMenu();
        
        Switch opt Do
            case 0:
                Clear Screen;
                Print "Bye =)";
                exit = True;
            case 1:
                n1 = askNum(n1);
                n2 = askNum(n2);
                result = sum(n1, n2);
                showResult(result);
                reset();
            case 2:
                n1 = askNum(n1);
                n2 = askNum(n2);
                result = subtract(n1, n2);
                showResult(result);
                reset();
            case 3:
                n1 = askNum(n1);
                n2 = askNum(n2);
                result = multiply(n1, n2);
                showResult(result);
                reset();
            case 4:
                n1 = askNum(n1);
                n2 = askNum(n2);
                result = divide(n1, n2);
                showResult(result);
                reset();
            Default:
                Print "Invalid option.";
                reset();
        EndSwitch
    While !exit
EndAlgorithm

Interpretation:

  • Multiply Function: This is the function that is used to multiply two numbers and return the result.

  • Divide Function: This is the function that divides two numbers and checks for division by zero to stop errors.

  • Menu Update: This includes the option for multiplication and division in the user menu.

  • Algorithm Update: This adds cases for multiplication and division to take care of user inputs for these operations, which is similar to how sum and subtraction are managed.


FINAL PROJECT: Create an ATM simulator. It must initially request an access pin to the user, this pin is 12345678. Once the pin is successfully validated, it must show a menu that allows: 1. view balance, 2. deposit money, 3. withdraw money, 4. exit. The cashier should not allow more balance to be withdrawn than is possessed. Use all the structures you learned and functions. (5 points)

Here I will be using Python programming language to create an ATM simulator, since I always find errors each time I use pseudocode.

# ATM Simulator in Python

# Define PIN and initial balance
PIN = 12345678
balance = 0.00

# Function to input and validate the PIN
def input_pin():
    user_pin = int(input("Please enter your PIN: "))
    return user_pin

# Function to display the menu and get user choice
def show_menu():
    print("\nATM Menu:")
    print("1. View Balance")
    print("2. Deposit Money")
    print("3. Withdraw Money")
    print("4. Exit")
    choice = int(input("Choose an option: "))
    return choice

# Function to view the current balance
def view_balance():
    global balance
    print(f"Your current balance is: ${balance:.2f}")

# Function to deposit money into the account
def deposit_money():
    global balance
    deposit_amount = float(input("Enter the amount to deposit: "))
    balance += deposit_amount
    print(f"${deposit_amount:.2f} has been deposited. Your new balance is: ${balance:.2f}")

# Function to withdraw money from the account
def withdraw_money():
    global balance
    withdraw_amount = float(input("Enter the amount to withdraw: "))
    if withdraw_amount <= balance:
        balance -= withdraw_amount
        print(f"You have withdrawn ${withdraw_amount:.2f}. Your new balance is: ${balance:.2f}")
    Else:
        print("Insufficient funds! Your balance is: ${:.2f}".format(balance))

# Main ATM algorithm
def atm():
    global balance
    user_pin = input_pin()

    if user_pin == PIN:
        exit_program = False
        while not exit_program:
            choice = show_menu()

            if choice == 1:
                view_balance()

            elif choice == 2:
                deposit_money()

            elif choice == 3:
                withdraw_money()

            elif choice == 4:
                print("Thank you for using the ATM!")
                exit_program = True

            else:
                print("Invalid option. Please try again.")
    else:
        print("Incorrect PIN. Access Denied.")

# Run the ATM simulator
atm()

1000193576.jpg

Interpretation:

Global Variables:

  • PIN: This holds the correct PIN value
    • balance: This stores the user's account balance (initialized at 0.00).

Functions:

  • input_pin(): This prompts the user to input their PIN and returns it.

  • show_menu(): This displays the menu options and returns the user`s choice.

  • view_balance(): This displays the current account balance of the user.

  • deposit_moneh(): This prompts the user for a deposit amount, adds it to the balance and then displays the updated balance.

  • withdraw_money(): This prompts the user for a withdrawal amount and checks if the balance is sufficient. If it is sufficient, it deducts the amount; if it is not it displays an insufficient funds message.

atm() Function:

  • This handles the main logic: prompts for the PIN, shows the menu, and calls the appropriate function based on the user's input. The loop will continue until the user chooses to exit.

I am inviting: @kuoba01, @simonnwigwe, and @ruthjoe

Cc:-
@alejos7ven

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:  
Loading...

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

TEAM 7

Congratulations!

THE QUEST TEAM has supported your post. We support quality posts, good comments anywhere, and any tags


postbanner.JPG

Curated by : @sduttaskitchen