Basic programming course: Lesson #6 Functions

in devjr-s20w6 •  last month  (edited)


1000348620.jpg
Functions


Hello everyone!

I welcome you to this week's engagement challenge. So excited to make this. So far, I am equally living a hand of applaud so Mr @alejos7ven For taking out his time to train us on the basics of programming. It's been quite a remarkable season with lots of fun and caring exercises.

Notwithstanding, I equally want to thank the Steemit team For granting us this week full of lessons which help us impact us in several ways, first time not only is steemit use For engagement purposes, but it can greatly be used as an educational platform. This season proves that all.

Getting back to work, We are going to learn something new about programming algorithms today, which is on functions. Without taking much time, I will begin the exercises and discuss more about functions and practical work which is due to this task.


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?


It's been a great time learning programming. I had a lot of experience throughout these exercises as I was able to catch up with some basic tactics in programming which I didn't know before. I must mention I was having no idea about pseint or pseudo code. But through this lessons, I was ever to get to know them.

Before I have been learning some basics in programming through the online platform w3schools.com. On there, I was practicing three languages which are HTML, CSS and JavaScript. But then with these lessons, I have been able to learn more of algorithm using c++, python and improve my knowledge in pseudo code.

Well, I did find some little difficulties Using pseudo codes, As initially I would have problems but then since The programming language was in Spanish, and sometimes the program indicate errors which are so unable to identify since It is in Spanish. With time, I was able to learn the basics structure of the command, and so far, I have been able to translate and know exactly what each command stands for. There I will say no more problems.

Talking about my favorite part of the lesson, I will say it was less than five which discuss on control structures. Using the for loop, while loop and do while loop. I was able to carry out this exercise with ease, Since after reading the main post I understood it so well and then carrying out some research too. I was able to finalize my ideology about control structures. I bet I still have a lot to learn but for now I got the basics on this lessons.


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


Original code.

Function opt = showMenu
    Print "What do you want to do?";
    Print "1. Sum.";
    Print "2. Subtract.";
    Print "0. Exit.";
    Read opt;
EndFunction

Function n = askNum(n)
    Print "Enter a number:";
    Read n;
EndFunction

Function showResult(r)
    Print "The result is " r;
EndFunction

Function reset
    Print "Press any key to continue.";
    Wait Key;
    Clear Screen;
EndFunction

Function  result = sum (n1, n2)
    Define result As Real;
    result = n1 + n2; 
EndFunction

Function  result = subtract (n1, n2)
    Define result As Real;
    result = n1 - n2; 
EndFunction

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:
                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();
            Default:
                Print "Invalid option."; 
                reset();
        EndSwitch
        
    While !exit
EndAlgorithm

Updated code with multiplication and division

Function opt = showMenu
    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

Function n = askNum(n)
    Print "Enter a number:";
    Read n;
EndFunction

Function showResult(r)
    Print "The result is " r;
EndFunction

Function reset
    Print "Press any key to continue.";
    Wait Key;
    Clear Screen;
EndFunction

Function result = sum(n1, n2)
    Define result As Real;
    result = n1 + n2; 
EndFunction

Function result = subtract(n1, n2)
    Define result As Real;
    result = n1 - n2; 
EndFunction

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

Function result = divide(n1, n2)
    Define result As Real;
    If n2 != 0 Then
        result = n1 / n2;
    Else
        Print "Cannot divide by zero!";
        result = 0;  
// Optional: Return a default value or handle differently.
    EndIf
EndFunction

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

Changes Integrated:

1• Menu:

I Added options 3 for multiplication and 4 for division in the showMenu function. You can see the difference by comparing the 2 set of codes.

2• Functions:

I equally Defined the new multiply and divide functions to perform multiplication and division, respectively. Observing again we can see it under the add and substrate section.

3• Switch:

The switch options was modified by adding cases for multiplication and division:

  • Case 3 opt the multiply function.

  • Case 4 opt the divide function and checks for division by zero. If n2 is zero, a message will display "`cannot be divided by zero"

The code now performs four operations: sum, subtraction, multiplication, and division, and follows the same flow as your original submission.

Here's a display using pseudo code.

1000348674.png1000348675.png
12
1000348676.png1000348673.png
34

1000348817.png1000348816.png
1000348820.png1000348819.png
--

1000348818.png


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


ATM Simulator.

#include <iostream>
#include <string>

using namespace std;

// Structure to store account information
struct Account {
    int accountNumber;
    double balance;
    string pin;
};

// Function to validate the PIN
bool validatePin(Account account, string inputPin) {
    return account.pin == inputPin;
}

// Function to display the menu
void displayMenu() {
    cout << "Welcome to the ATM\n";
    cout << "1. View Balance\n";
    cout << "2. Deposit Money\n";
    cout << "3. Withdraw Money\n";
    cout << "4. Exit\n";
}

// Function to view the balance
void viewBalance(Account account) {
    cout << "Your current balance is: $" << account.balance << endl;
}

// Function to deposit money
void depositMoney(Account& account) {
    double amount;
    cout << "Enter the amount to deposit: $";
    cin >> amount;
    account.balance += amount;
    cout << "Deposit successful. Your new balance is: $" << account.balance << endl;
}

// Function to withdraw money
void withdrawMoney(Account& account) {
    double amount;
    cout << "Enter the amount to withdraw: $";
    cin >> amount;

    if (amount > account.balance) {
        cout << "Insufficient funds.\n";
    } else {
        account.balance -= amount;
        cout << "Withdrawal successful. Your new balance is: $" << account.balance << endl;
    }
}

int main() {
    Account userAccount = {12345678, 1000.00, "12345678"}; // Sample account information

    string inputPin;
    bool isAuthenticated = false;

    while (!isAuthenticated) {
        cout << "Enter your PIN: ";
        cin >> inputPin;

        if (validatePin(userAccount, inputPin)) {
            isAuthenticated = true;
            cout << "PIN verified successfully.\n";
        } else {
            cout << "Invalid PIN. Please try again.\n";
        }
    }

    int choice;
    do {
        displayMenu();
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1:
                viewBalance(userAccount);
                break;
            case 2:
                depositMoney(userAccount);
                break;
            case 3:
                withdrawMoney(userAccount);
                break;
            case 4:
                cout << "Thank you for using the ATM.\n";
                break;
            default:
                cout << "Invalid choice. Please try again.\n";
        }
    } while (choice != 4);

    return 0;
}

Explanation of the Code:

Pseint would have been a used for this application but some parameters appear undefined. So I switched to c++ to save time.

1. PIN Validation:

The validatepin function demands the user for the PIN and it checks if it matches the correct value ("12345678") which is our default 8 digit pin. The command loops repeated 🔁 until the correct PIN is imputed.

2. ATM Menu:

The displaymenu function present the various options to the user which are:View Balance, Deposit Money, Withdraw Money, and Exit.

3. Viewing Balance:

This function displays the current balance to the user using the command viewbalance

4. Depositing Money:

The deposit function permits the user to enter a positive amount, which gets added to the the initial balance of the account.

5. Withdrawing Money:

The withdraw function allows the user to enter an amount to withdraw, but it makes sure that the user cannot withdraw more money than their account size. Greater than current balance.

6. Main ATM Loop:

This section of algorithm runs the ATM simulation. It loops the menu until the user chooses to exit. It responsible for:balance checking, deposits, and withdrawals while making sure the correct PIN has been imputed.

The algorithm cashier ensures that the user cannot withdraw more than their current balance and handles invalid input for deposits and withdrawals.

This program cycles or loops 🔁 back to the menu after each action, otherwise the user chooses to exit

Here's a program of the ATM .

1000348815.png1000348814.png

Conclusion, I will say it has been an amazing week of contest and I have learned a lot from this programming lessons. Just like it was mentioned in the main lesson, programming is based on practice. Practice makes perfect, And we should ensure to save our codes each time we write a program for reuse.

Thank you, Mr @alejos7ven for giving us this opportunity to learn And practice coding while having fun and earning as well. Overall thank you to the Steemit team.

Rounding up. I would like to invite some persons to participate with me in this amazing contest. @chant, @wirngo , @simonnwigwe and @fombae.


Cc: @alejos7ven



Best regards: @rafk.



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