Back

Activity 2.5: Multiple Parameters, Scope, and Abstraction

divider

Activity 2.5

Multiple Parameters, Scope, and Abstraction

Key Concepts

Several Parameters of Different Types

Where a Variable Lives

Reaching Outward, and Why Parameters Are Safer

Abstraction as Being Allowed to Forget

Every Variable So Far Lived Everywhere

In Quarter 1, a variable declared near the top of your program could be used on any line below it. There was one program and one big space that every name lived in.

Methods change that. A variable declared inside a method belongs to that method, and the rest of the program cannot see it at all. Today is about where each name lives, which way names can be seen, and why that is a feature rather than an annoyance.

Three Parameters, Three Types

Activity 2.4's DrawBuilding took three ints. A method can take any mix of types, and each parameter is declared with its own type, separated by commas.

BoxCost prices a shipping box from its weight, how far it travels, and whether it is insured. Insurance is a yes or no, so it is a bool.

Three Parameters, Three Types

Demo
double BoxCost(double weight, int distance, bool insured)
{
double baseCost = weight * 0.5;
double miles = distance * 0.02;
double extra = 0;
if (insured)
{
extra = 3;
}
return baseCost + miles + extra;
}

Three Parameters, Three Types

The main program calls it twice, above the method. Predict both prices. The two calls differ only in the last argument.

Demo
Console.WriteLine($"Box A: {BoxCost(10, 250, true):F2}");
Console.WriteLine($"Box B: {BoxCost(10, 250, false):F2}");
Demo
Box A: 13.00
Box B: 10.00

Three Parameters, Three Types

Follow Box A through the body. Work out each number before it appears.

Value Trace
BoxCost(10, 250, true)
baseCost weight * 0.5 10 * 0.5 5.00
miles distance * 0.02 250 * 0.02 5.00
extra insured is true 3.00
returns 5.00 + 5.00 + 3.00 13.00

The two boxes differ by exactly 3.00, because insured is the only argument that changed and extra is the only thing it controls.

Position Still Decides Everything

Activity 2.2 showed that arguments are matched to parameters by position: first to first, second to second. That has not changed. Here is line 1 with the first and third arguments swapped. Will it build?

Demo
Console.WriteLine($"Box A: {BoxCost(true, 250, 10):F2}");
Demo
2-5-treasure-dive.cs(1,37): error CS1503: Argument 1: cannot convert from 'bool' to 'double'
2-5-treasure-dive.cs(1,48): error CS1503: Argument 3: cannot convert from 'int' to 'bool'

Position Still Decides Everything

true cannot go where a double belongs, so C# refuses. Different types protect you. Now swap the first two instead — a double and an int, both numbers. Will this one build?

Demo
Console.WriteLine($"Box A: {BoxCost(250, 10, true):F2}");
Demo
Box A: 128.20

It builds and charges 128.20 for a 13.00 box: a 250-pound box going 10 miles. Any number fits where a number goes, so C# has nothing to object to. Past three or four parameters, nobody remembers the order, and that is a real limit on how many a method should take.

A Variable Made Inside Stays Inside

BoxCost creates baseCost on its first line. Here the main program tries to print it after the call has finished. Predict what happens.

Demo
Console.WriteLine($"Box A: {BoxCost(10):F2}");
Console.WriteLine(baseCost);
double BoxCost(double weight)
{
double baseCost = weight * 0.5;
return baseCost;
}
Demo
2-5-treasure-dive.cs(2,19): error CS0103: The name 'baseCost' does not exist in the current context

A Variable Made Inside Stays Inside

CS0103: the name does not exist in the current context. Not “empty,” not “not set yet” — from line 2, there is no such name at all.

baseCost exists only inside BoxCost and only while it is running. It is created fresh on every call and thrown away when the call returns. If you need a value out of a method, that is what return is for.

It is the same error Activity 2.1 gave you for calling a method with the wrong capital letter. To the compiler, a name that lives somewhere else and a name that does not exist look exactly alike.

Scope Is Where a Name Means Something

The scope of a variable is the part of the program where its name can be used. A variable declared inside a method is local to that method: its scope is the method's braces and nothing more.

Parameters are local too. weight exists inside BoxCost and nowhere else, which is why Activity 2.2's methods could all use a parameter called name without colliding.

Looking Outward Works

Now the other direction. shipRate is declared in the main program, and BoxCost uses it without being given it as a parameter. Will it build?

Demo
double shipRate = 0.5;
Console.WriteLine(BoxCost(10));
double BoxCost(double weight)
{
return weight * shipRate;
}
Demo
5

Looking Outward Works

It prints 5. A method written inside your program can see the main program's variables, because the method sits inside the main program's space.

Inward: no. Outward: yes. The main program cannot see into a method, but a method can see out into the main program.

Outward Works for Changing, Too

A method that can see an outside variable can also change it. AddFee takes no parameters at all; it reaches out and adds 5 to the main program's total. Predict the number.

Demo
int total = 100;
AddFee();
Console.WriteLine(total);
void AddFee()
{
total = total + 5;
}
Demo
105

Outward Works for Changing, Too

105. The main program's total really did change, from inside a method, with nothing in the call to warn you. AddFee(); on its own line gives no hint that it touches total.

That is the danger of reaching outward to change things. In a long program, a value can change and the line that changed it can be anywhere. Keep that in mind for the next demo.

Same Name, Different Variable

Now AddFee takes a parameter, also called total. Predict both numbers.

Demo
int total = 100;
Console.WriteLine(AddFee(total));
Console.WriteLine(total);
int AddFee(int total)
{
total = total + 5;
return total;
}
Demo
105
100

Same Name, Different Variable

105, then 100. The parameter total is a new variable that was handed a copy of the main program's total. Adding 5 to the copy does nothing to the original.

Inside the method, the name total means the parameter, and the outer total is hidden for as long as the call runs. This is called shadowing: the inner name stands in front of the outer one.

A Parameter Is the Safer Door

Two ways for a method to work with the main program's data: reach out and change it, or take a copy as a parameter and return an answer.

The parameter version cannot damage its caller. You can pass a variable to any method without reading the method first, and your variable is still what it was afterward. The caller decides what to do with the returned value.

Reaching outward is not banned, and the Build uses it once so you can see it happen. But when you have the choice, pass it in and hand it back.

Abstraction Is Being Allowed to Forget

Once BoxCost works, you stop thinking about multiplying by 0.5 and 0.02. You think what does this box cost? and call it.

The College Board puts it this way: procedural abstraction “provides a name for a process and allows a procedure to be used only knowing what it does, not how it does it.”

Scope is what makes that safe. Because nothing inside BoxCost leaks out, you really can forget its insides: none of its variables can collide with yours.

A Program You Can Hold in Your Head Is One You Can Fix

Abstraction is one of the five Big Ideas on the AP exam, and managing complexity is the reason it matters.

A sixty-line program where every variable can be touched from everywhere has to be understood all at once. Split into methods with their own local variables, it can be understood one method at a time — and debugged one method at a time.

Today's Objectives

  • Writing a method with three parameters of different types
  • Explaining why a local variable cannot be seen from outside its method
  • Predicting what happens when a parameter shadows an outer variable
  • Describing abstraction as managing complexity

Key Terms

Scope
The part of a program where a name can be used.
Local variable
A variable declared inside a method, created on each call and gone when the call ends.
Shadowing
An inner name hiding an outer variable with the same spelling.
Abstraction
Hiding detail behind a name so you can use it without thinking about how it works.

'F' → Fullscreen

divider

Build

Today you go diving for sunken gold in a new program named 2-5-treasure-dive. Deeper water holds more gold but burns more air, and a lamp doubles what you find but costs air of its own. Your tank holds 100 air. By the end you will be planning dives to get the most gold out of one tank.

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 Much Gold?

  • Haul works out how much gold one dive brings back. It takes three parameters of three different jobs: how deep, how long, and whether you took the lamp. Every 10 m of depth is worth 1 gold a minute, and the lamp doubles the total.
  • Write the code below. Before you run it, work out all three amounts by hand and write them down. Then run it and compare.
  • Swap the first and third arguments on line 4 so it reads Haul(true, 5, 30), and run it. Write down the error code and what each error says. Put it back.
  • Now swap the first two arguments on line 3, so it reads Haul(5, 30, false). Write down what it prints, and explain where the number came from. Put it back.
2-5-treasure-dive
Console.WriteLine("Treasure Dive: practice dives");
Console.WriteLine($"10 m for 10 minutes, no lamp: {Haul(10, 10, false)} gold");
Console.WriteLine($"30 m for 5 minutes, no lamp: {Haul(30, 5, false)} gold");
Console.WriteLine($"30 m for 5 minutes, lamp: {Haul(30, 5, true)} gold");
int Haul(int depth, int minutes, bool lamp)
{
int perMinute = depth / 10;
int coins = perMinute * minutes;
if (lamp)
{
coins = coins * 2;
}
return coins;
}

Task 2: Reach Inside and Fail

  • Haul worked out a variable called coins. Add line 5, which tries to print it from the main program.
  • Run it. Copy the error code, its line number, and its message exactly.
  • Then say in one sentence where coins actually lives, and when it exists. Delete line 5 before you move on.
2-5-treasure-dive
Console.WriteLine("Treasure Dive: practice dives");
Console.WriteLine($"10 m for 10 minutes, no lamp: {Haul(10, 10, false)} gold");
Console.WriteLine($"30 m for 5 minutes, no lamp: {Haul(30, 5, false)} gold");
Console.WriteLine($"30 m for 5 minutes, lamp: {Haul(30, 5, true)} gold");
Console.WriteLine(coins);
int Haul(int depth, int minutes, bool lamp)
{
int perMinute = depth / 10;
int coins = perMinute * minutes;
if (lamp)
{
coins = coins * 2;
}
return coins;
}

Task 3: Two Ways to Touch the Tank

  • Line 5 adds the tank: air, in the main program. Two new methods work with it in different ways.
  • AirAfter takes the air as a parameter named air, subtracts, and returns. Breathe takes only the amount used, and reaches outward to change the main program's air directly.
  • Add the new lines. Before you run it, write down the three numbers you expect. Then run it and compare. For each number you got wrong, say which variable you were thinking of.
2-5-treasure-dive
Console.WriteLine("Treasure Dive: practice dives");
Console.WriteLine($"10 m for 10 minutes, no lamp: {Haul(10, 10, false)} gold");
Console.WriteLine($"30 m for 5 minutes, no lamp: {Haul(30, 5, false)} gold");
Console.WriteLine($"30 m for 5 minutes, lamp: {Haul(30, 5, true)} gold");
int air = 100;
Console.WriteLine($"Practice check: {AirAfter(air, 30)} air would be left");
Console.WriteLine($"Air in the tank: {air}");
Breathe(30);
Console.WriteLine($"After a real dive: {air}");
int Haul(int depth, int minutes, bool lamp)
{
int perMinute = depth / 10;
int coins = perMinute * minutes;
if (lamp)
{
coins = coins * 2;
}
return coins;
}
int AirAfter(int air, int used)
{
air = air - used;
return air;
}
void Breathe(int used)
{
air = air - used;
}

Task 4: The Dive

  • Replace the main program with the game shown below, and delete AirAfter and Breathe. They are no longer called, and C# would warn that they are never used.
  • Replace the comments at the bottom with AirUsed, written yourself. It takes the same three parameters as Haul and returns the air a dive uses: each minute costs 1 air plus 1 more for every 10 m of depth, and the lamp adds 10 to the whole dive. A 10-minute dive at 30 m with the lamp uses 50; check yours gives that before playing.
  • The main program and AirUsed both have a variable called used. Write one sentence explaining why the two do not collide.
  • Play three games and write down your dives and your final gold for each. Then write one sentence on whether the lamp was worth it.
2-5-treasure-dive
int air = 100;
int gold = 0;
int dive = 1;
Console.WriteLine("Treasure Dive. Your tank holds 100 air.");
while (air > 0)
{
Console.Write($"Dive {dive}. How deep, 10 to 50 m? ");
int depth = int.Parse(Console.ReadLine());
Console.Write("How many minutes? ");
int minutes = int.Parse(Console.ReadLine());
Console.Write("Take the lamp? (true/false) ");
bool lamp = bool.Parse(Console.ReadLine());
int used = AirUsed(depth, minutes, lamp);
if (used > air)
{
Console.WriteLine($"That dive needs {used} air. You run out and drop the treasure.");
air = 0;
}
else
{
int found = Haul(depth, minutes, lamp);
air = air - used;
gold = gold + found;
Console.WriteLine($"Found {found} gold. Air left: {air}.");
}
dive = dive + 1;
}
Console.WriteLine($"You surface with {gold} gold.");
int Haul(int depth, int minutes, bool lamp)
{
int perMinute = depth / 10;
int coins = perMinute * minutes;
if (lamp)
{
coins = coins * 2;
}
return coins;
}
// AirUsed(depth, minutes, lamp) returns how much air a dive uses:
// every minute costs 1 air, plus 1 more for each 10 m of depth,
// so a minute at 30 m costs 4 air;
// and taking the lamp adds 10 air to the whole dive.
// Write it here, below Haul, in the same shape as Haul.

Challenge (Optional): The Perfect Tank

  • Staying between 10 and 50 m, find a plan that surfaces with 150 gold. Write down every dive in it and explain why it beats splitting the tank into smaller dives.
  • Nothing stops a player typing a depth of 90. Add a while loop after the depth question that asks again until the depth is between 10 and 50, the way Activity 1.17 re-asked for input.
divider

Same Idea, Exam Notation

The reference sheet writes a procedure with several parameters as PROCEDURE procName(parameter1, parameter2, ...), and says arg1 is assigned to parameter1, and so on — matched by position, exactly as in C#.

C#
double BoxCost(double weight, int distance)
{
return weight * 0.5 + distance * 0.02;
}
Exam Notation
PROCEDURE boxCost(weight, distance)
{
RETURN(weight * 0.5 + distance * 0.02)
}

1. Commas, and No Types

Parameters are separated by commas in both. The exam version has no types: no double, no int, no bool, and no return type in front of the name. So the exam can never catch a swapped argument the way CS1503 did today — every swap is the silent kind.

2. The Sheet Says Nothing About Scope

The reference sheet has no rule written down for where a name can be used, and no way to declare a variable other than assigning to it. That silence is worth knowing. An exam question about scope will describe it in words or show it in ordinary program code. Do not invent a notation for it.

divider

Checkpoint

One real game from the finished program, ending with 120 gold. Your dives will be different.

Example Output
Treasure Dive. Your tank holds 100 air.
Dive 1. How deep, 10 to 50 m? 50 [Enter]
How many minutes? 10 [Enter]
Take the lamp? (true/false) true [Enter]
Found 100 gold. Air left: 30.
Dive 2. How deep, 10 to 50 m? 20 [Enter]
How many minutes? 5 [Enter]
Take the lamp? (true/false) true [Enter]
Found 20 gold. Air left: 5.
Dive 3. How deep, 10 to 50 m? 10 [Enter]
How many minutes? 3 [Enter]
Take the lamp? (true/false) false [Enter]
That dive needs 6 air. You run out and drop the treasure.
You surface with 120 gold.
  • Haul and AirUsed each take three parameters, and AirUsed(30, 10, true) gives 50
  • AirAfter and Breathe are gone, and the program builds with no warnings
  • You recorded the Task 1 hand calculations, both swap results, the Task 2 error exactly, and your three Task 3 predictions
  • You recorded three games and your sentence about the lamp
divider

Reflection

Answer the following questions before submitting your work.

  1. In your own words: why can a method see variables declared in the main program, but the main program cannot see a method's variables?
  2. In Task 3, AirAfter left the tank at 100 and Breathe took it down to 70. Explain the difference, and say which one you would rather call without reading its code first.
  3. Name something in this course you now use without thinking about how it works. That is abstraction; say what it lets you ignore.
divider

Submit

Submit four things to the dropbox:

  1. Your 2-5-treasure-dive program file, with your AirUsed.
  2. Your Task 1 hand calculations and both swap results, and the Task 2 error exactly as it appeared.
  3. Your Task 3 predictions, your sentence about the two used variables, and your three games with the lamp sentence.
  4. Your three reflection answers.

Activity Complete