Question
How do I remove Global variables in a C program to make the code have better abstraction and cohesion. Please help me understand through my
How do I remove Global variables in a C program to make the code have better abstraction and cohesion. Please help me understand through my example:
#include
int fifty = 0; int twenty = 0; int ten = 0; int five = 0;
void calculateChangeCoins(int change) {
if(change > 0) { if(change >= 50) { // if change is greater than 50 cents change -= 50; fifty++; } else if(change >= 20) { // if change is greater than 20 cents change -= 20; twenty++; } else if(change >= 10) { // if change is greater than 10 cents change -= 10; ten++; } else if(change >= 5) { // if change is greater than 5 cents change -= 5; five++; } else { printf(" Error : Invalid Change given!!!"); exit(0); } calculateChangeCoins(change); } }
void printTheChange() {
printf(" Change recived: "); if(fifty) // if 50 Cent coins are there in the change, print how many are there printf("Number of fifty cent coins: %d ", fifty); if(twenty) // if 20 Cent coins are there in the change, print how many are there printf("Number of twenty cent coins: %d ", twenty); if(ten) // if 10 Cent coins are there in the change, print how many are there printf("Number of ten cent coins: %d ", ten); if(five) // if 05 Cent coins are there in the change, print how many are there printf("Number of five cent coins: %d ", five); }
int readChange() { int change; // read the change printf("Enter the amount of money to be given back in chnage: "); scanf("%d%*c", &change); return change; }
int main() { int change = readChange(); calculateChangeCoins(change); // uses recusrion to calulate the correct change for the user printTheChange(); // uses printTheChange() function to output change values return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started