Back

Activity 2.3: Return Values

divider

Activity 2.3

Return Values

Key Concepts

Printing Is Not Handing Back

The Return Type Is a Promise

A Call Becomes Its Value

return Leaves Immediately

Every Method So Far Talked Only to the Screen

Activities 2.1 and 2.2 wrote void methods. Each one did its job by printing, and the main program never got anything back. That is fine for a banner. It is useless for a price.

Here is a method that works out the price with 8% tax, two times. Then try to add the two taxed prices together.

Every Method So Far Talked Only to the Screen

Demo
AddTax(20);
AddTax(35);
void AddTax(double price)
{
Console.WriteLine(price * 1.08);
}
Demo
21.6
37.800000000000004

The two numbers are on the screen, and nowhere else. The main program cannot add them, store them, or even format that long second one, because AddTax never gave them to it. Once a value is printed, the program is finished with it.

Hand the Value Back Instead

Two changes turn it into a method that answers a question. The word return in the body sends a value back to the line that made the call. And the header's void becomes double, the type of value it sends back.

The call can then sit on the right of an =, exactly like a number would. Predict what this prints.

Hand the Value Back Instead

Demo
double total = AddTax(20);
Console.WriteLine($"Total: {total}");
double AddTax(double price)
{
return price * 1.08;
}
Demo
Total: 21.6

AddTax printed nothing. It worked out 21.6 and handed it back, line 1 stored it in total, and line 2 — the main program, which now owns the value — decided to show it.

The Type Before the Name Is a Promise

void AddTax promises nothing back. double AddTax promises a double back, every single time it is called. Any type you know can go there: int, string, bool.

C# holds you to the promise. A double method with no return will not build, and neither will storing the result of a void one. You will make both errors on purpose in Task 1.

Nothing Comes Back From void

Here is the printing method from the first demo, with its result stored as if it handed something back. Predict what C# does with line 1.

Demo
double total = AddTax(20);
void AddTax(double price)
{
Console.WriteLine(price * 1.08);
}

Nothing Comes Back From void

Demo
double total = AddTax(20);
void AddTax(double price)
{
Console.WriteLine(price * 1.08);
}
Demo
2-3-dragon-duel.cs(1,16): error CS0029: Cannot implicitly convert type 'void' to 'double'
The build failed. Fix the build errors and run again.

It refuses to build. The message has the same number, CS0029, as Activity 1.5's int level = "24";: a value of the wrong type going into a variable. Here the “value” is void — nothing at all — and nothing cannot go into a double.

A Call Becomes Its Value

Wherever you write a call to a method that returns, C# runs the method and puts the returned value in the call's place. So a call can go anywhere a number can — including in the middle of arithmetic.

Predict both lines, and remember Activity 1.9's :F2.

A Call Becomes Its Value

Demo
double cart = AddTax(20) + AddTax(35);
Console.WriteLine(cart);
Console.WriteLine($"{cart:F2}");
double AddTax(double price)
{
return price * 1.08;
}
Demo
59.400000000000006
59.40

AddTax(20) became 21.6, AddTax(35) became 37.8-and-a-bit, and line 1 added them. The long first line is Activity 1.9's round-off again, and because the main program now owns the number, :F2 can tidy it — something the first demo could never do.

A Returned Value Nobody Catches Disappears

A call to a returning method can also stand alone on its line, like a void call. Predict what this prints — and whether C# complains.

Demo
AddTax(20);
Console.WriteLine("Done.");
double AddTax(double price)
{
return price * 1.08;
}

A Returned Value Nobody Catches Disappears

Demo
AddTax(20);
Console.WriteLine("Done.");
double AddTax(double price)
{
return price * 1.08;
}
Demo
Done.

No error, no warning, and no 21.6. The method ran and handed the value back, and line 1 did nothing with it, so it was thrown away. Returning is not printing: if you want to see a returned value, the line that catches it has to show it.

return Leaves the Method Immediately

return does two things at once: it sends the value back, and it ends the method on the spot. Nothing after it in that body runs.

Predict whether Tax added. ever prints.

Demo
Console.WriteLine(AddTax(20));
double AddTax(double price)
{
return price * 1.08;
Console.WriteLine("Tax added.");
}

return Leaves the Method Immediately

Demo
Console.WriteLine(AddTax(20));
double AddTax(double price)
{
return price * 1.08;
Console.WriteLine("Tax added.");
}
Demo
2-3-dragon-duel.cs(6,5): warning CS0162: Unreachable code detected
21.6

It never prints, and C# warns you before the program even starts: line 6 is unreachable, because every way into the body leaves at line 5. A warning still lets the program run — it is C# saying “this line is pointless.”

Leaving Early Can Make the Decision

Because return leaves at once, a method can check one thing, return if it matches, and only reach the next check if it did not. No else is needed: getting past the first if already means it was false.

This method hands back a string. Predict the three letters.

Leaving Early Can Make the Decision

Demo
Console.WriteLine(Grade(95));
Console.WriteLine(Grade(85));
Console.WriteLine(Grade(40));
string Grade(int score)
{
if (score >= 90)
{
return "A";
}
if (score >= 80)
{
return "B";
}
return "C";
}
Demo
A
B
C

For 85, the test on line 7 is false, so the program skips to line 12, which is true, and line 14 returns "B". For 40 both tests fail and the last line catches it. The order of the checks matters — Task 5 shows what happens when it is wrong.

Printing or Returning: Pick One Job

Printing puts a value on the screen. People can read it; the program cannot use it.

Returning hands a value back to the program. The program can store it, do arithmetic with it, or pass it on; the screen sees nothing until some line decides to show it.

A method that works something out should usually return it and let the main program decide what to show. That is what makes it reusable — a taxed price that only prints can only ever be printed.

Today's Objectives

  • Writing a method with a return type and a return statement
  • Explaining the difference between printing and returning
  • Using a returned value in a variable, in arithmetic, and in another call
  • Using early return to make a decision

Key Terms

Return value
The value a method hands back to the line that called it.
Return type
The type in front of a method's name — double, int, string— or void when nothing comes back.
return
Sends a value back and ends the method immediately.
Unreachable code
A line that can never run, such as one right after a return.

'F' → Fullscreen

divider

Build

Today you fight a dragon in a new program named 2-3-dragon-duel. A knight and a dragon trade blows until one of them falls, and every number in the fight — each hit, each roll of the dice, each potion — is worked out by a method that hands its answer back. The dragon is stronger than you. By the end, you will need a plan to beat it.

How to read the code blocks. Each task's code block shows your whole program, from line 1, as it should look when that task is finished.

The green lines marked with a + are the ones you add or change for that task — everything else is already in your file. Do not type the + sign.


Task 1: How Hard Does It Hit?

  • Damage takes an attack and a defense and returns how much damage gets through: the attack minus the defense. A blow too weak to get through still does 1, so the first if returns early.
  • Write the code below and run it. Before you run it, work out both numbers by hand and write them down.
  • Delete the line return attack - defense; and run it. Write down the error code and what it said. Put the line back.
  • Now change int to void in the header of Damage and run it. Write down the error on line 4, and what the error on line 14 says about return. Then change it back to int.
2-3-dragon-duel
int knightAttack = 8;
int dragonDefense = 3;
int hit = Damage(knightAttack, dragonDefense);
Console.WriteLine($"The knight hits the dragon for {hit}.");
int scratch = Damage(2, dragonDefense);
Console.WriteLine($"A pebble hits the dragon for {scratch}.");
int Damage(int attack, int defense)
{
if (attack <= defense)
{
return 1;
}
return attack - defense;
}

Task 2: How Is It Doing?

  • Status turns a number of hit points into a word the player can read at a glance. It returns a string, and it checks from the bottom up with early returns.
  • Add Status below Damage, and the four test lines to the main program. Before you run it, write down the word you expect for each of the four. Then run it and compare.
  • The four test values are one from each band — that is on purpose. Then try Status(40) and Status(15), the two boundaries, and write down which band each one landed in.
2-3-dragon-duel
int knightAttack = 8;
int dragonDefense = 3;
int hit = Damage(knightAttack, dragonDefense);
Console.WriteLine($"The knight hits the dragon for {hit}.");
int scratch = Damage(2, dragonDefense);
Console.WriteLine($"A pebble hits the dragon for {scratch}.");
Console.WriteLine($"At 60 HP: {Status(60)}");
Console.WriteLine($"At 30 HP: {Status(30)}");
Console.WriteLine($"At 10 HP: {Status(10)}");
Console.WriteLine($"At 0 HP: {Status(0)}");
int Damage(int attack, int defense)
{
if (attack <= defense)
{
return 1;
}
return attack - defense;
}
string Status(int hp)
{
if (hp <= 0)
{
return "defeated";
}
if (hp < 15)
{
return "barely standing";
}
if (hp < 40)
{
return "wounded";
}
return "steady";
}

Task 3: The Fight

  • Replace the main program with the fight shown below, and add Roll at the bottom. Roll(6) returns a random number from 1 to 6, like a die — Activity 1.15's Next with its + 1.
  • Look at line 14: knightAttack + Roll(6) is worked out first, and that sum is the argument to Damage. A call inside a call, inside arithmetic.
  • Run it and press Enter to swing until the fight ends. Play twice, and write down how each fight ended and how much HP the dragon had left.
2-3-dragon-duel
int knightHp = 50;
int dragonHp = 80;
int knightAttack = 8;
int knightDefense = 5;
int dragonAttack = 9;
int dragonDefense = 3;
Console.WriteLine("A dragon blocks the mountain pass. Press Enter to swing your sword.");
while (knightHp > 0 && dragonHp > 0)
{
Console.ReadLine();
int hit = Damage(knightAttack + Roll(6), dragonDefense);
dragonHp = dragonHp - hit;
Console.WriteLine($"You hit the dragon for {hit}. Dragon: {dragonHp} HP, {Status(dragonHp)}.");
if (dragonHp > 0)
{
int bite = Damage(dragonAttack + Roll(6), knightDefense);
knightHp = knightHp - bite;
Console.WriteLine($"The dragon bites you for {bite}. Knight: {knightHp} HP, {Status(knightHp)}.");
}
}
if (knightHp > 0)
{
Console.WriteLine("The dragon is defeated. The pass is open!");
}
else
{
Console.WriteLine("The knight falls. The dragon keeps the pass.");
}
int Damage(int attack, int defense)
{
if (attack <= defense)
{
return 1;
}
return attack - defense;
}
string Status(int hp)
{
if (hp <= 0)
{
return "defeated";
}
if (hp < 15)
{
return "barely standing";
}
if (hp < 40)
{
return "wounded";
}
return "steady";
}
int Roll(int sides)
{
return Random.Shared.Next(1, sides + 1);
}

Task 4: Potions

  • The knight now carries three potions. Each turn, choose to attack or to drink one. Make the changes to the main program shown below.
  • Replace the comments at the bottom with Heal. It takes the knight's HP, the amount a potion heals, and the knight's maximum HP, and returns the new HP: the HP plus the amount, but never more than the maximum. A potion at 45 HP gives 50, not 60.
  • Play until you beat the dragon, and write down the knight's HP at the end. Then write one sentence on when it is worth drinking a potion. Drinking all three at the start almost never wins.
2-3-dragon-duel
int knightHp = 50;
int dragonHp = 80;
int knightAttack = 8;
int knightDefense = 5;
int dragonAttack = 9;
int dragonDefense = 3;
int potions = 3;
Console.WriteLine("A dragon blocks the mountain pass.");
while (knightHp > 0 && dragonHp > 0)
{
Console.Write($"Attack (1) or drink a potion (2)? Potions left: {potions}. ");
int choice = int.Parse(Console.ReadLine());
if (choice == 2 && potions > 0)
{
knightHp = Heal(knightHp, 15, 50);
potions = potions - 1;
Console.WriteLine($"You drink a potion. Knight: {knightHp} HP, {Status(knightHp)}.");
}
else
{
int hit = Damage(knightAttack + Roll(6), dragonDefense);
dragonHp = dragonHp - hit;
Console.WriteLine($"You hit the dragon for {hit}. Dragon: {dragonHp} HP, {Status(dragonHp)}.");
}
if (dragonHp > 0)
{
int bite = Damage(dragonAttack + Roll(6), knightDefense);
knightHp = knightHp - bite;
Console.WriteLine($"The dragon bites you for {bite}. Knight: {knightHp} HP, {Status(knightHp)}.");
}
}
if (knightHp > 0)
{
Console.WriteLine("The dragon is defeated. The pass is open!");
}
else
{
Console.WriteLine("The knight falls. The dragon keeps the pass.");
}
int Damage(int attack, int defense)
{
if (attack <= defense)
{
return 1;
}
return attack - defense;
}
string Status(int hp)
{
if (hp <= 0)
{
return "defeated";
}
if (hp < 15)
{
return "barely standing";
}
if (hp < 40)
{
return "wounded";
}
return "steady";
}
int Roll(int sides)
{
return Random.Shared.Next(1, sides + 1);
}
// Write a method named Heal here. It takes the knight's hp, the amount
// a potion heals, and the knight's maxHp, and returns the new hp --
// hp plus the amount, but never more than maxHp.

Task 5: Break It on Purpose

Three changes, one at a time. Write down exactly what happens, and put each one back before the next.

  1. In Status, delete the last line, return "steady";.
  2. In Damage, add Console.WriteLine("Ouch."); on a new line right after return attack - defense;, still inside the braces. Then play a few turns.
  3. In Status, swap the hp < 15 block and the hp < 40 block, so 40 is checked first. Play until the knight drops below 15 HP, and read the word.

One will not build, one builds with a warning, and one builds cleanly and gives a wrong answer. Say which is which. For the error, say which HP values would take the path through Status that has no return. For the wrong answer, say which HP values get the wrong word and why the rest are still right.

There is no code block for this task. When it is over, your program is exactly what it was at the end of Task 4.


Challenge (Optional): Critical Hits

  • Write a method IsCritical that takes no parameters and returns a bool: true one time in ten. Its body is one return line that uses Roll.
  • When the knight attacks and IsCritical() is true, double the hit and print Critical hit! before the hit line.
  • A method that returns a bool can go straight into an if, the same way a returned number went into arithmetic. Play a few fights and check that crits happen, but not often.
divider

Same Idea, Exam Notation

The reference sheet writes a returning procedure with RETURN(expression) in its body, and captures the result with result ← procName(arg1, arg2, ...).

C#
double total = AddTax(20);
double AddTax(double price)
{
return price * 1.08;
}
Exam Notation
PROCEDURE addTax(price)
{
RETURN(price * 1.08)
}
total ← addTax(20)

1. RETURN Takes Parentheses

RETURN(price * 1.08), never RETURN price * 1.08. C#'s return has no parentheses, so this is the easiest notation detail in the quarter to get backward. It is capitalized, like every exam keyword.

2. No Return Type, No void

A returning procedure starts with PROCEDURE, exactly like one that only displays. The only way to tell them apart on the exam is to look inside for a RETURN. C# tells you in the header, with double or void.

3. RETURN Still Leaves Immediately

The reference sheet says RETURN may appear at any point in a procedure and causes an immediate return. Early returns work the same way on the exam as in your Status, and a line after a RETURN never runs there either — but no warning will point it out.

divider

Checkpoint

One real fight from the finished program, won with one potion left. Your rolls will be different.

Example Output
A dragon blocks the mountain pass.
Attack (1) or drink a potion (2)? Potions left: 3. 1 [Enter]
You hit the dragon for 8. Dragon: 72 HP, steady.
The dragon bites you for 8. Knight: 42 HP, steady.
Attack (1) or drink a potion (2)? Potions left: 3. 1 [Enter]
You hit the dragon for 11. Dragon: 61 HP, steady.
The dragon bites you for 5. Knight: 37 HP, wounded.
Attack (1) or drink a potion (2)? Potions left: 3. 1 [Enter]
You hit the dragon for 9. Dragon: 52 HP, steady.
The dragon bites you for 6. Knight: 31 HP, wounded.
Attack (1) or drink a potion (2)? Potions left: 3. 1 [Enter]
You hit the dragon for 6. Dragon: 46 HP, steady.
The dragon bites you for 9. Knight: 22 HP, wounded.
Attack (1) or drink a potion (2)? Potions left: 3. 1 [Enter]
You hit the dragon for 9. Dragon: 37 HP, wounded.
The dragon bites you for 5. Knight: 17 HP, wounded.
Attack (1) or drink a potion (2)? Potions left: 3. 2 [Enter]
You drink a potion. Knight: 32 HP, wounded.
The dragon bites you for 9. Knight: 23 HP, wounded.
Attack (1) or drink a potion (2)? Potions left: 2. 1 [Enter]
You hit the dragon for 11. Dragon: 26 HP, wounded.
The dragon bites you for 10. Knight: 13 HP, barely standing.
Attack (1) or drink a potion (2)? Potions left: 2. 1 [Enter]
You hit the dragon for 7. Dragon: 19 HP, wounded.
The dragon bites you for 7. Knight: 6 HP, barely standing.
Attack (1) or drink a potion (2)? Potions left: 2. 2 [Enter]
You drink a potion. Knight: 21 HP, wounded.
The dragon bites you for 7. Knight: 14 HP, barely standing.
Attack (1) or drink a potion (2)? Potions left: 1. 1 [Enter]
You hit the dragon for 9. Dragon: 10 HP, barely standing.
The dragon bites you for 8. Knight: 6 HP, barely standing.
Attack (1) or drink a potion (2)? Potions left: 1. 1 [Enter]
You hit the dragon for 10. Dragon: 0 HP, defeated.
The dragon is defeated. The pass is open!
  • No method prints; every line of output comes from the main program
  • Status gives the right word in all four bands, and you recorded where 40 and 15 land
  • Heal never takes the knight above 50 HP
  • You recorded both Task 1 errors, a win with the knight's final HP, your potion plan, and all three Task 5 results
divider

Reflection

Answer the following questions before submitting your work.

  1. Damage hands back a number instead of printing it. Name two things your duel does with that number that it could not do if Damage printed it instead.
  2. Deleting return "steady"; gave “not all code paths return a value.” Explain what a code path is, and which HP values would have taken the path with no return.
  3. Swapping two checks in Status gave the wrong word below 15 HP and the right word everywhere else. Explain why, and what that says about choosing values to test a method with.
divider

Submit

Submit four things to the dropbox:

  1. Your 2-3-dragon-duel program file.
  2. Both Task 1 errors and your hand calculation, your Task 2 predictions, your two Task 3 fights, and your Task 4 win with your potion plan.
  3. All three Task 5 results, with which is which.
  4. Your three reflection answers.

Activity Complete