✍️ Practice Test 2
To study for Test 2, try out the problems on paper prior to checking the solution. Review your labs too!
Question 1
The code below contains syntax and logic errors. Find every error and correct them.
for(int i=42; i>=42; i++);
{
if (i == 50)
{
Console.WriteLine("wow so cool");
break;
}
if (i == "beans")
{
Console.WriteLine("???");
return;
}
}
💡Solution
The errors were:
- The
;after thefor - The condition
i >= 42is always true whileicounts up, so the loop only stops because of thebreak - The condition should describe when the loop ends (
i <= 50), which also makes thebreakunnecessary i == "beans"compares anintto astring, which won't compile- Using a
returnwithout any surrounding function is weird
The corrected code is:
const int Start = 42;
const int End = 50;
for (int i = Start; i <= End; i++)
{
if (i == End)
{
Console.WriteLine("wow so cool");
}
}
Question 2
The code below contains syntax and logic errors. Find every error and correct them.
static void WeirdFunction(int x; int y);
{
return "weird"
return "also weird"
}
WeirdFunction(2.0, 7, 40);
💡Solution
The errors were:
- Parameters should be separated by commas, not semicolons
(int x, int y). - The
;after the function is wrong - The function returns a
string, so its return type must bestring, notvoid return "weird"is missing its;return "also weird"can never run, since the function stops at the firstreturnso it should just be removed!- The call passes 3 arguments, but the function takes 2
- The call passes
2.0which is adoubleand can't be passed to anintparameter - The returned value is thrown away, it should be stored/used in some way
The corrected code is:
static string WeirdFunction(int x, int y)
{
return "weird";
}
string result = WeirdFunction(2, 7);
Console.WriteLine(result);
Question 3
What is the output of the following program? After each line runs, write down the current value of every variable.
static void Main(int x)
{
int p, q, r, y=2; // p=_________ q=_________ r=_________ y=_________ x=_________
q = x--; // p=_________ q=_________ r=_________ y=_________ x=_________
r = 3; // p=_________ q=_________ r=_________ y=_________ x=_________
p = r; // p=_________ q=_________ r=_________ y=_________ x=_________
p += x; // p=_________ q=_________ r=_________ y=_________ x=_________
Console.WriteLine("p=" + p + " q=" + q + " r=" + r + " x=" + x);
x = ++r; // p=_________ q=_________ r=_________ y=_________ x=_________
p = Compute(y); // p=_________ q=_________ r=_________ y=_________ x=_________
r += 5; // p=_________ q=_________ r=_________ y=_________ x=_________
Console.WriteLine("p=" + p + " q=" + q + " r=" + r + " x=" + x + " y=" + y);
}
static int Compute(int x)
{
int result; // result=_________ temp=_________ x=_________
int temp = 6; // result=_________ temp=_________ x=_________
x += 2; // result=_________ temp=_________ x=_________
result = x + temp; // result=_________ temp=_________ x=_________
Console.WriteLine("temp=" + temp + " y=" + x);
return result; // result=_________ temp=_________ x=_________
}
Main(10);
Write the exact text that each Console.WriteLine statement displays on the screen.
👀Hint
Some stuff to watch out for:
q = x--givesqthe old value ofx(10), then decreasesxto 9x = ++rincreasesrto 4 first, then gives that new value toxComputegets a copy ofy
💡Solution
The variables change as follows:
static void Main(int x)
{
int p, q, r, y=2; // p=– q=– r=– y=2 x=10
q = x--; // p=– q=10 r=– y=2 x=9
r = 3; // p=– q=10 r=3 y=2 x=9
p = r; // p=3 q=10 r=3 y=2 x=9
p += x; // p=12 q=10 r=3 y=2 x=9
Console.WriteLine("p=" + p + " q=" + q + " r=" + r + " x=" + x);
x = ++r; // p=12 q=10 r=4 y=2 x=4
p = Compute(y); // p=10 q=10 r=4 y=2 x=4
r += 5; // p=10 q=10 r=9 y=2 x=4
Console.WriteLine("p=" + p + " q=" + q + " r=" + r + " x=" + x + " y=" + y);
}
static int Compute(int x)
{
int result; // result=– temp=– x=2
int temp = 6; // result=– temp=6 x=2
x += 2; // result=– temp=6 x=4
result = x + temp; // result=10 temp=6 x=4
Console.WriteLine("temp=" + temp + " y=" + x);
return result; // result=10 temp=6 x=4
}
The output is:
p=12 q=10 r=3 x=9
temp=6 y=4
p=10 q=10 r=9 x=4 y=2
Question 4
Consider the following code where a user enters 10:
// initialize
int score = 0;
// user inputs 10
Console.Write("Enter a cool number: ");
int userInput = int.Parse(Console.ReadLine());
for (int num = 3; num < 6; num++)
{
score += userInput / num;
}
Trace the loop below by filling in one row per iteration. Leave any unneeded rows blank.
| iteration | score | userInput | num |
|---|---|---|---|
| start | 0 | 10 | - |
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 | |||
| 6 |
💡Solution
| iteration | score | userInput | num |
|---|---|---|---|
| start | 0 | 10 | - |
| 1 | 3 | 10 | 3 |
| 2 | 5 | 10 | 4 |
| 3 | 7 | 10 | 5 |
FYI the division drops the decimals cause int:
iteration 1: score = 0 + 10 / 3 = 0 + 3 = 3
iteration 2: score = 3 + 10 / 4 = 3 + 2 = 5
iteration 3: score = 5 + 10 / 5 = 5 + 2 = 7
Question 5
The program below checks whether a file will fit on a device. All sizes are in gigabytes (GB):
// Inputs
Console.Write("Total storage (GB): ");
double totalSpace = double.Parse(Console.ReadLine());
Console.Write("Storage already used (GB): ");
double usedSpace = double.Parse(Console.ReadLine());
Console.Write("Size of the file you want to download (GB): ");
double wantedSpace = double.Parse(Console.ReadLine());
// Calculations
double remainingSpace = totalSpace - usedSpace;
bool canStore = CanStoreData(wantedSpace, remainingSpace);
// Outputs
if(canStore)
{
Console.WriteLine("Enough space! Download Complete <3");
}
else
{
Console.WriteLine("Not enough space. Download FAILED >:[");
}
Write the missing function in C# below without changing anything in the above program:
💡Solution
static bool CanStoreData(double currentSize, double maxSize) {
return currentSize <= maxSize;
}
Question 6
Welcome to the American Student Debt Calculator 5000!
Most American college graduates leave school with student loans, and many don’t know how long repayment will take or how much of their money will go to interest. Your job is to write a program that tells them.
Background
- Federal undergraduate student loans have a fixed annual interest rate of 6.52%.
- A dependent undergraduate can borrow up to $27,000 in federal loans over four years.
Each month, interest is added to the balance and then the payment is subtracted:
Design a program that
- Asks the user how much they owe and how much they plan to pay each month
- Simulates repayment month by month until the debt is paid off
- Prints how long repayment takes (in years and months) and the total interest paid
👀Hint
You don't actually need functions or a for loop 👀
💡Solution
Turn your prior response into a short C# program
💡Solution
const double InterestRate = 6.52;
const int MonthsPerYear = 12;
// Inputs
Console.Write("How much do you owe? $");
double debt = double.Parse(Console.ReadLine());
Console.Write("How much will you pay each month? $");
double monthlyPayment = double.Parse(Console.ReadLine());
// Does the payment even cover interest?
double startingInterest = debt * (InterestRate / MonthsPerYear) / 100;
if (monthlyPayment <= startingInterest)
{
Console.WriteLine("Your payment doesn't even cover interest, so you will never pay this off in yer lifetime :^(");
// early return to prevent this continuing below (could also use an else statement instead)
return;
}
int months = 0;
double totalInterest = 0;
// While loop cause it'd be a very janky for loop
while (debt > 0)
{
double interest = debt * (InterestRate / MonthsPerYear) / 100;
totalInterest += interest;
debt = debt + interest - monthlyPayment;
months++;
}
int years = months / MonthsPerYear;
// OR months % MonthsPerYear if u are feeling fun
int leftoverMonths = months - (MonthsPerYear * years);
Console.WriteLine($"Debt paid off in {years} years and {leftoverMonths} months");
Console.WriteLine($"Total interest paid is ${totalInterest}");