Week 6 Lab
Sign in to lab!
Q&A on Material
- Defining and calling simple functions
- While loops
Exercises
Walk through these exercises and complete them as a group (if time allows).
Function Tracing
#include <iostream>
using namespace std;
double withdraw(double balance, double amount);
double deposit(double balance, double amount);
bool isOverdrawn(double balance);
int main()
{
double balance = 100.0;
// deposit two paychecks and try to withdraw
balance = deposit(balance, 500.0);
if ( !isOverdrawn(withdraw(deposit(balance, 700.0), 400.0)) )
{
balance = withdraw(deposit(balance, 700.0), 400.0);
}
return 0;
}
double withdraw(double balance, double amount) {
balance -= amount;
return balance;
}
double deposit(double balance, double amount) {
balance += amount;
return balance;
}
bool isOverdrawn(double balance) {
return balance < 0.0;
}
While Loop Tracing
Determine the output of this program by tracing its execution manually.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x = 0;
int y = 1;
while (!((x % 5 == 0) && (y % 64 == 0)))
{
x++;
y *= 2;
}
cout << x << " " << y << endl;
return 0;
}
Function Coding
Loop Exercises
Walk through these exercises and complete them as a group (if time allows).
HW help
Q&A regarding the current homework.
Want to Learn More (Individual Study)
Coding Practices
We hope that as you learn the basics of programming you can also start to learn good coding practices to make your code more readable and well-organized. Below are some helpful links to improving your coding of conditionals that also involve functions. Take some time to read over them and see if you can improve any of your code either from last week’s or this week’s lab.
- Extract variable
- Split temporary variable
- Extract Method
- Decompose Conditional
- Consolidate If Statements
- Consolidate Duplicate Fragments
Idioms Related to Iterative Statements
Take a look at the idioms related to basic loop (iterative) statements:
Open-ended Help
Any students with questions may stay after to get help. Please ask questions! Anyone else may leave at this stage.