Thursday, 26 December 2019

Use of Functions in programming languages

For example:

an Account has account_no, balance;
if person has withdrawn some amount then balance = balance - amount;
after withdraw if we want to print the account_no and balance

you have to write print account_no, balance

again if we deposit amount

balance = balance + amount;

you have to write print account_no, balance

again and again we have to print account_no and balance after every withdrawal and deposit

so we can put display() and write account_no and balance in that method display()
and call display() inside withdraw() and deposit()
int acno,bal;
void withdraw(int amt)
{
        bal=bal-amt;
}
void deposit(int amt)
{
        bal=bal-amt;
}
void display()
{
      printf("acc number = %d and Balance = %d", acno, bal);
}
int main()
{
       printf("Press 1. for withdraw 2. for deposit 3. display 4. exit");
       int choice;
       scanf("%d",&choice);
       switch(choice)
      {
             case 1:
                          printf("enter amount to withdraw");
                          int amt;
                          scanf("%d",&amt);
                          withdraw(amt);
                          display();
                          break;
           case 2:
                          printf("enter amount to deposit");
                          int amt;
                          scanf("%d",&amt);
                          deposit(amt);
                          display();
                          break;
           case 3:
                       display();
                       break;
           case 4: exit(0);
     }
}


No comments:

Post a Comment