Solution to Self Check
Concept Questions
Q1: What is the difference between cohesion and coupling?
- Cohesion describes the relationship of the code within a function
- Coupling describes the relationship between functions.
Q2: Why is high cohesion desirable in a function?
A function that is highly cohesive is dedicated to a clear single objective. Every line of code is working towards the completion of that objective. It makes the function precise and understandable.
Q3: What is meant by the term loose coupling?
A function is loosely coupled if they are not dependent on each other. That is, each function can work on their own without needing to be paired to another function.
Walkthrough:
output of program:
This is a nifty program.
First final: 7
It is a program that shows how the runtimestack works!
Second final: 13
Programming
Programming 1:
double metricHeight(int feet, int inches)
{
double totalInches = feet * 12 + inches;
double result = totalInches * 2.54;
return result;
}
Programming 2:
int sum3Digits(int threeDigitNumber)
{
int digit1;
int digit2;
int digit3;
//left most digit.. example 923/100 = 9
digit1 = threeDigitNumber/100;
//middle digit... example 923/10 = 92. 92%10 = 2
digit2 = (threeDigitNumber/10) % 10;
//last digit ... example 923%10 = 3
digit3 = threeDigitNumber%10;
return digit1 + digit2 + digit3;
}
Programming 3:
double buy3GetOneFree(double unitPrice, int numUnits)
{
int fourFullUnits;
int leftOvers;
double totalPrice;
//every 4 units is charged as if 3 units were bought.
//because division is truncated, only get number
//of 4 full units in this calculation. Example if there were 9 units,
//this would be 9/4 = 2.
fourFullUnits = numUnits/4;
//this is the number of units that are essentially not part of the sale
leftOvers = numUnits%4;
totalPrice = unitPrice*3*fourFullUnits + leftOvers*unitPrice;
return totalPrice;
}