Back

Activity 2.1: Methods: Defining and Calling

divider

Activity 2.1

Methods: Defining and Calling

Key Concepts

You Have Been Calling Methods All Along

Defining Is Not Running

Where the Program Goes During a Call

One Place for Each Idea

Quarter 1 Programs Say Everything Twice

Every program you wrote in Quarter 1 ran from the top line to the bottom line. When you wanted the same output twice, you typed it twice. Here is a launch log that shows its banner three times.

Read it and ask: what happens when the banner has to say FLIGHT CONTROL instead?

Quarter 1 Programs Say Everything Twice

Demo
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");
Console.WriteLine("Fuel loaded.");
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");
Console.WriteLine("Crew aboard.");
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");

Three copies means three places to edit, and nothing checks that you found all three. Miss one and the program still runs — it just shows two different banners, and nobody notices until a user does.

You Have Been Calling Methods Since Activity 1.1

Console.WriteLine, Console.ReadLine, int.Parse, Random.Shared.Next — every one of them is a method: a named block of code that somebody else wrote once, and that you run by writing its name followed by parentheses.

You never saw the code inside WriteLine, and you never needed to. Today you write methods of your own, so that a block like the banner exists in exactly one place and every other line just uses its name.

Give the Block a Name

A method definition has two parts. The first line, the header, gives the method its name. The lines between the braces, the body, are the code the name stands for.

Here is the banner, given the name PrintBanner. Predict what this program prints when you run it.

Give the Block a Name

Demo
void PrintBanner()
{
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");
}
Demo
2-1-mission-control.cs(1,6): warning CS8321: The local function 'PrintBanner' is declared but never used

Nothing prints. The program builds, runs, and ends having done nothing, and the compiler's warning says why: the method is declared — defined — but never used.

Defining Is Not Running

Defining a method teaches C# what a name means. It is a recipe written on a card: the card says how to make the dish, but writing it down does not cook anything.

Calling the method is what runs its body. A call is the method's name followed by () and a semicolon — exactly the way you have always written Console.WriteLine().

C# names a method written inside your main program a local function, which is why the warning says local function. For this course it is a method, and the compiler's word is just its own.

Read the Header Piece by Piece

void PrintBanner() has three parts:

  • void — this method does its job and hands nothing back. Activity 2.3 writes methods that do hand back a value, and they replace void with a type like int.
  • PrintBanner — the name. C# method names start with a capital letter, like WriteLine, and name what the method does.
  • () — empty today. Activity 2.2 puts something in them.

There is no semicolon after the header. The header and its braces are one piece; a semicolon would cut them apart.

Defined Once, Called Twice

Add two calls above the definition and one line of your own between them. The body exists once in the file. Predict how many banners appear.

Demo
PrintBanner();
Console.WriteLine("Systems nominal.");
PrintBanner();
void PrintBanner()
{
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");
}

Defined Once, Called Twice

Demo
PrintBanner();
Console.WriteLine("Systems nominal.");
PrintBanner();
void PrintBanner()
{
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");
}
Demo
=========================
MISSION CONTROL
=========================
Systems nominal.
=========================
MISSION CONTROL
=========================

Two banners from one body. Change the wording inside the braces and both banners change, because there is only one place for the wording to live.

A Call Is a Round Trip

Until today a program ran straight down the file. A call breaks that. When the program reaches a call, it jumps into the method, runs the whole body, and then comes back to the line right after the call.

The lines in this demo are numbered by the order they print, not the order they appear. Check that the numbers are right.

A Call Is a Round Trip

Demo
Console.WriteLine("1. Before the call");
SayHello();
Console.WriteLine("4. After the call");
void SayHello()
{
Console.WriteLine("2. Inside the method");
Console.WriteLine("3. Still inside");
}
Demo
1. Before the call
2. Inside the method
3. Still inside
4. After the call

Line 2 sends the program down to line 7. After line 8, the body is finished, so it returns to line 3 — the line right after the call — and carries on from there.

A Method Can Call a Method

A method body can hold any code you know, including a call to another method. Each call is its own round trip, and the inner one finishes before the outer one carries on.

Predict the order of the five letters before the next slide.

A Method Can Call a Method

Demo
Console.WriteLine("A");
Outer();
Console.WriteLine("E");
void Outer()
{
Console.WriteLine("B");
Inner();
Console.WriteLine("D");
}
void Inner()
{
Console.WriteLine("C");
}
Demo
A
B
C
D
E

A, B, C, D, E — in alphabetical order, even though the file is not. Inner runs inside Outer's round trip, so D waits for C, and E waits for all of it.

The Parentheses Are the Call

PrintBanner on its own is just the name. PrintBanner() is the instruction to run it. Predict what happens if you leave the parentheses off.

Demo
PrintBanner;
void PrintBanner()
{
Console.WriteLine("MISSION CONTROL");
}

The Parentheses Are the Call

Demo
PrintBanner;
void PrintBanner()
{
Console.WriteLine("MISSION CONTROL");
}
Demo
2-1-mission-control.cs(1,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
The build failed. Fix the build errors and run again.

C# refuses to build it. A name alone is not an instruction — the error's list of things that can be a statement includes “call,” and without () this is not one. The fix is two characters.

Main Program First, Methods Below It

Every demo so far put the calls at the top and the definition underneath. C# reads all of a file's methods before it runs any line, so a call can sit above the method it calls.

The other order works too. This version defines first and calls after, and prints exactly what “Defined Once, Called Twice” printed.

Main Program First, Methods Below It

Demo
void PrintBanner()
{
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");
}
PrintBanner();
Console.WriteLine("Systems nominal.");
PrintBanner();

This course puts the main program at the top and every method below it. Read from line 1 and you see what the program does first; scroll down only when you want to know how a step works. Keep the main program together — never a method in the middle of it.

The Point Is One Place, Not Less Typing

A method does save typing, but that is the small reason. The real reason is that each idea gets one place to live.

A block copied five times is a bug waiting for someone to edit four copies out of five. A method edited once is right everywhere it is called, today and every time the program grows.

Repeated code is a warning sign. When you notice you are typing the same lines again, that is the moment to write a method.

Today's Objectives

  • Defining a method with void Name() and a body in braces
  • Calling a method by its name followed by ()
  • Explaining the difference between defining and calling
  • Tracing where the program goes during a call, and where it comes back to

Key Terms

Method
A named block of code that runs when it is called. C#'s word for it.
Procedure
The exam's word for the same thing. Other languages say function.
Define
Write the header and body. Nothing runs yet.
Call
Run a method by writing its name followed by ().
Flow of control
The order in which a program's lines actually run. A call jumps into the method and returns to the line right after it.

'F' → Fullscreen

divider

Build

Today you write the launch log for a rocket in a new program named 2-1-mission-control. It shows a banner between status messages, counts down, and closes the log — and every one of those jobs ends up as a method of its own.

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: Define It and Call It

  • Write the code below and run it. Line 1 is the call; lines 3 to 8 are the definition.
  • Delete line 1 and run it again. Write down what printed, and copy the warning code and the words after it. Then put line 1 back.
2-1-mission-control
PrintBanner();
void PrintBanner()
{
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");
}

Task 2: Three Calls, One Body

  • Add the five lines below the first call, so the banner appears three times with a status message after each one. Run it.
  • Now make every banner say FLIGHT CONTROL. Run it, check all three banners changed, and write down how many lines you edited. Then change it back to MISSION CONTROL.
2-1-mission-control
PrintBanner();
Console.WriteLine("Fuel loaded.");
PrintBanner();
Console.WriteLine("Crew aboard.");
PrintBanner();
Console.WriteLine("All systems go.");
void PrintBanner()
{
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");
}

Task 3: Follow the Round Trip

  • Add the Countdown method below PrintBanner, and the two new lines at the end of the main program. The body of a method can hold any code you know — this one is Activity 1.19's counting-down loop.
  • Before you run it, write down the last six lines you expect the program to print, in order. Then run it and compare.
  • Line 7 sends the program into Countdown, whose header is line 17. Write down the line number it comes back to when Countdown is finished.
2-1-mission-control
PrintBanner();
Console.WriteLine("Fuel loaded.");
PrintBanner();
Console.WriteLine("Crew aboard.");
PrintBanner();
Console.WriteLine("All systems go.");
Countdown();
Console.WriteLine("The rocket has cleared the tower.");
void PrintBanner()
{
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");
}
void Countdown()
{
for (int i = 3; i >= 1; i--)
{
Console.WriteLine($"T-minus {i}");
}
Console.WriteLine("LIFTOFF!");
}

Task 4: A Method of Your Own

  • Replace the two comments at the bottom with a method named PrintFooter. It prints a line of 25 dashes, then END OF LOG, then the dashes again.
  • Replace the comment on line 9 with a call to it, so the log ends with the footer. Write the definition and the call both — either one without the other is Task 1 again.
  • Run it and compare your output with the Checkpoint below. Centering END OF LOG is up to you.
2-1-mission-control
PrintBanner();
Console.WriteLine("Fuel loaded.");
PrintBanner();
Console.WriteLine("Crew aboard.");
PrintBanner();
Console.WriteLine("All systems go.");
Countdown();
Console.WriteLine("The rocket has cleared the tower.");
// Call PrintFooter here.
void PrintBanner()
{
Console.WriteLine("=========================");
Console.WriteLine(" MISSION CONTROL");
Console.WriteLine("=========================");
}
void Countdown()
{
for (int i = 3; i >= 1; i--)
{
Console.WriteLine($"T-minus {i}");
}
Console.WriteLine("LIFTOFF!");
}
// Write a method named PrintFooter here. It prints three lines:
// a line of 25 dashes, then END OF LOG, then the dashes again.

Task 5: Break It on Purpose

Three changes, one at a time. Each one stops the program from building. Write down the error code and the line number the message gives, then put the change back before the next one.

  1. On line 3, delete the parentheses so it says PrintBanner;.
  2. On line 1, change the capital P to a small one: printBanner();. Notice that lines 3 and 5 still use the capital.
  3. Add a semicolon to the end of the Countdown header, so it reads void Countdown();.

For each one, say in your own words what C# was objecting to — the message is written for programmers, and part of the job is translating it.

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): One Rule, One Place

  • PrintBanner prints the same line of = signs twice. Write a method named PrintRule that prints that line once, and call it twice from inside PrintBanner.
  • The output must not change at all. Check it line by line against your Task 4 output.
  • Now make the rule 30 characters long. Count how many lines you edited, and compare that with what it would have taken before the Challenge.
divider

Same Idea, Exam Notation

The exam calls a method a procedure, and the reference sheet writes it with the word PROCEDURE.

C#
PrintBanner();
void PrintBanner()
{
Console.WriteLine("MISSION CONTROL");
}
Exam Notation
PROCEDURE printBanner()
{
DISPLAY("MISSION CONTROL")
}
printBanner()

1. PROCEDURE Takes the Place of void

The exam has no void. Every procedure starts with the word PROCEDURE, whether or not it hands a value back — the difference shows up inside the body instead, which is Activity 2.3.

2. A Call Looks the Same in Both

printBanner() on the exam, PrintBanner(); in C#: the name, then parentheses. The exam has no semicolons, and its procedure names start with a small letter, the way the reference sheet writes procName. Either way, a call has to match the definition's name letter for letter — Task 5's number 2.

3. Three Words, One Idea

Procedure, method, and function all mean a named group of instructions. The College Board's own course description says the name depends on the language. Read any of the three on the exam as the thing you wrote today.

divider

Checkpoint

The finished program's output. Your footer may be centered differently.

Example Output
=========================
MISSION CONTROL
=========================
Fuel loaded.
=========================
MISSION CONTROL
=========================
Crew aboard.
=========================
MISSION CONTROL
=========================
All systems go.
T-minus 3
T-minus 2
T-minus 1
LIFTOFF!
The rocket has cleared the tower.
-------------------------
END OF LOG
-------------------------
  • PrintBanner's body appears once in the file, and the banner prints three times
  • Every method is defined below the main program, and every one is called
  • Your PrintFooter prints the last three lines
  • You recorded the Task 1 warning, the Task 2 edit count, your Task 3 prediction and return line, and all three Task 5 errors
divider

Reflection

Answer the following questions before submitting your work.

  1. Deleting the call in Task 1 printed nothing, and the warning said the method was declared but never used. Use that to explain the difference between defining a method and calling it.
  2. Task 2 asked how many lines you edited to change every banner. How many would it have been with the banner typed out three times, and why does one place matter more than the typing it saves?
  3. In Task 3, line 7 called Countdown. Describe where the program went when it reached that line, and where it went when Countdown was finished.
divider

Submit

Submit four things to the dropbox:

  1. Your 2-1-mission-control program file.
  2. Your Task 1 warning, Task 2 edit count, and Task 3 prediction and return line.
  3. All three Task 5 errors, each with its line and what it meant.
  4. Your three reflection answers.

Activity Complete