How Do Booleans Control Program Behavior?
So far, every line executes in order. But what if we want the program’s state to determine which code runs? What if we want code to repeat?
Booleans let us control which code executes. A boolean expression determines whether a scope runs or skips. This is called control flow: the path execution takes through your program.
We’ll explore two forms of control flow: branching with if statements, and repeating with loops.
Branching with if
Here’s the simplest form of control flow:
bool ready = true;
if (ready)
{
Console.WriteLine("Go!");
}
Console.WriteLine("Done");When this program runs, it displays:
Go!
Done
But if we change the first line to bool ready = false;, the output becomes just:
Done
The if statement checks a condition. If the condition evaluates to true, the scope inside the curly braces executes. If the condition evaluates to false, that scope is skipped entirely.
The translation: “If ready evaluates to true, execute the scope.”
The scope contains: “Display the string ‘Go!’ to the console.”
Notice what’s inside the parentheses: ready. This is a boolean expression. We evaluate it to get a value, either true or false. That value determines whether we execute the scope.
Any boolean expression works as a condition. We could write:
if (active && enabled)
{
Console.WriteLine("System running");
}The translation: “If active and enabled evaluates to true, execute the scope.”
The scope contains: “Display the string ‘System running’ to the console.”
The compound expression active && enabled evaluates to a single boolean value. That value controls the branch.
Try it yourself.
Translate this code to English:
if (finished)
{
Console.WriteLine("Complete!");
}Write your answer before revealing ours.
Reveal answer
“If finished evaluates to true, execute the scope.”
The scope contains: “Display the string ‘Complete!’ to the console.”
If your answer differed, note what you missed before continuing.
Scope
Look at this code:
if (true)
{
bool inside = true;
}
Console.WriteLine(inside);This code fails. The compiler reports an error: inside does not exist.
But we just created it. What happened?
The curly braces create a boundary. Variables declared inside that boundary exist only within it. When execution leaves the closing }, those variables are gone. The binding disappears.
This region, bounded by { and }, is called a scope.
A scope is a region of code bounded by { and }. Variables declared inside a scope exist only within that scope.
Here’s how to visualize it:
┌─────────────────────────────────────────┐
│ Outer scope │
│ │
│ if (true) │
│ ┌─────────────────────────────────┐ │
│ │ Inner scope │ │
│ │ │ │
│ │ bool inside = true; │ │
│ │ ← inside exists here │ │
│ │ │ │
│ └─────────────────────────────────┘ │
│ │
│ ← inside does NOT exist here │
│ │
│ Console.WriteLine(inside); // Error! │
│ │
└─────────────────────────────────────────┘
The variable inside is born when we enter the inner scope and dies when we leave it. Outside that scope, it doesn’t exist.
How do we fix this? Declare the variable in the outer scope:
bool inside = false;
if (true)
{
inside = true;
}
Console.WriteLine(inside);Now inside is declared in the outer scope. It exists before the if statement and continues to exist after. The code inside the if scope can see variables from the outer scope, so inside = true; works. It rebinds a variable that already exists.
This version displays true.
The rule: variables are visible in the scope where they’re declared and in any scopes nested inside. They’re not visible outside.
Try it yourself.
What does this code display?
bool x = false;
if (true)
{
x = true;
bool y = true;
}
Console.WriteLine(x);Write your answer before revealing ours.
Reveal answer
It displays true.
The variable x is declared in the outer scope, so it’s visible inside the if scope. The line x = true; rebinds it. After the if scope ends, x still exists and still holds true.
The variable y is declared inside the if scope. It exists only there. After the closing }, y is gone. We don’t try to use y outside its scope, so no error occurs.
If your answer differed, note what you missed before continuing.
Try it yourself.
This code has an error. Find it and fix it.
if (true)
{
bool result = true;
}
if (result)
{
Console.WriteLine("Success");
}Write your answer before revealing ours.
Reveal answer
The error: result is declared inside the first if scope, so it doesn’t exist outside. The second if statement tries to use result, but it’s gone.
The fix: declare result before the first if.
bool result = false;
if (true)
{
result = true;
}
if (result)
{
Console.WriteLine("Success");
}Now result is declared in the outer scope. Both if statements can see it.
If your answer differed, note what you missed before continuing.
How if Executes
Now that you understand scope, let’s look more carefully at how an if statement executes.
bool ready = true;
if (ready)
{
Console.WriteLine("Go!");
}
Console.WriteLine("Done");Let’s break down if (ready) { ... } token by token:
if (ready)— evaluate ready; if true, execute the scope; if false, skip the scope{ ... }— the scope to execute when the condition is true
Let’s trace through with a state table:
With ready = true:
| after line | ready | displayed |
|---|---|---|
| 1 | true | — |
| 3: evaluate condition | true | — |
| 3: condition is true, execute scope | true | — |
| 5 | true | ”Go!“ |
| 8 | true | ”Go!\nDone” |
With ready = false:
| after line | ready | displayed |
|---|---|---|
| 1 | false | — |
| 3: evaluate condition | false | — |
| 3: condition is false, skip body | false | — |
| 8 | false | ”Done” |
The state table shows exactly what happens: when ready is false, line 5 never executes.
Here’s a flowchart showing the two possible paths:
flowchart TD A[evaluate condition] --> B{true?} B -->|yes| C[execute scope] B -->|no| D[skip scope] C --> E[continue after if] D --> E
Execution flows down. At the diamond, we check the condition. If true, we take the left path and execute the scope. If false, we take the right path around it. Both paths rejoin and continue.
Try it yourself.
Write C# code for this description:
“Create a boolean variable named active and bind true to it. If active evaluates to true, execute a scope that displays the string ‘Running’ to the console.”
Write your answer before revealing ours.
Reveal answer
bool active = true;
if (active)
{
Console.WriteLine("Running");
}If your answer differed, note what you missed before continuing.
if-else
What if we want to do one thing when true, and a different thing when false?
bool loggedIn = false;
if (loggedIn)
{
Console.WriteLine("Welcome back!");
}
else
{
Console.WriteLine("Please log in.");
}This displays: Please log in.
If we change loggedIn to true, it displays: Welcome back!
The else provides an alternative path. When the condition evaluates to false, instead of skipping to the code after the if, we execute the else scope.
The translation: “If loggedIn evaluates to true, execute the first scope. Otherwise, execute the second scope.”
The first scope contains: “Display the string ‘Welcome back!’ to the console.”
The second scope contains: “Display the string ‘Please log in.’ to the console.”
The word “otherwise” captures what else means: we execute one scope or the other, never both and never neither. Exactly one scope executes.
Try it yourself.
Translate this code to English:
if (valid)
{
Console.WriteLine("Accepted");
}
else
{
Console.WriteLine("Rejected");
}Write your answer before revealing ours.
Reveal answer
“If valid evaluates to true, execute the first scope. Otherwise, execute the second scope.”
The first scope contains: “Display the string ‘Accepted’ to the console.”
The second scope contains: “Display the string ‘Rejected’ to the console.”
If your answer differed, note what you missed before continuing.
How if-else Executes
Let’s look more carefully at what happens when an if-else runs.
Let’s break down if (condition) { ... } else { ... } token by token:
if (condition)— evaluate the condition; if true, execute the first scope; if false, skip to else{ ... }— the first scope to execute when the condition is trueelse { ... }— the second scope to execute when the condition is false
This is mutual exclusion. You execute one scope or the other, and the condition determines which.
With loggedIn = false:
| after line | loggedIn | branch taken | displayed |
|---|---|---|---|
| 1 | false | — | — |
| 3: condition is false | false | else | — |
| (if skipped) | false | — | — |
| 9 | false | else | ”Please log in.” |
With loggedIn = true:
| after line | loggedIn | branch taken | displayed |
|---|---|---|---|
| 1 | true | — | — |
| 3: condition is true | true | if | — |
| 5 | true | if | ”Welcome back!” |
| (else skipped) | true | — | “Welcome back!” |
Exactly one branch executes. Never both.
flowchart TD A[evaluate condition] --> B{true?} B -->|yes| C[execute first scope] B -->|no| D[execute second scope] C --> E[continue after if-else] D --> E
Two paths diverge based on a single condition, and you execute exactly one. Both paths rejoin after the scope completes.
Try it yourself.
Write C# code for this description:
“If enabled evaluates to true, execute a scope that displays ‘ON’ to the console. Otherwise, execute a scope that displays ‘OFF’ to the console.”
Write your answer before revealing ours.
Reveal answer
if (enabled)
{
Console.WriteLine("ON");
}
else
{
Console.WriteLine("OFF");
}If your answer differed, note what you missed before continuing.
if-else if-else
Sometimes there are more than two possibilities. We can chain conditions:
bool isAdmin = false;
bool isMember = true;
if (isAdmin)
{
Console.WriteLine("Full access");
}
else if (isMember)
{
Console.WriteLine("Member access");
}
else
{
Console.WriteLine("Guest access");
}This displays: Member access
The conditions are checked in order. The first one that evaluates to true wins. Its scope executes, and we skip all remaining branches.
The translation: “If isAdmin evaluates to true, execute the first scope. Otherwise, if isMember evaluates to true, execute the second scope. Otherwise, execute the third scope.”
The first scope contains: “Display the string ‘Full access’ to the console.”
The second scope contains: “Display the string ‘Member access’ to the console.”
The third scope contains: “Display the string ‘Guest access’ to the console.”
Try it yourself.
Translate this code to English:
if (priority)
{
Console.WriteLine("Urgent");
}
else if (normal)
{
Console.WriteLine("Standard");
}
else
{
Console.WriteLine("Low");
}Write your answer before revealing ours.
Reveal answer
“If priority evaluates to true, execute the first scope. Otherwise, if normal evaluates to true, execute the second scope. Otherwise, execute the third scope.”
The first scope contains: “Display the string ‘Urgent’ to the console.”
The second scope contains: “Display the string ‘Standard’ to the console.”
The third scope contains: “Display the string ‘Low’ to the console.”
If your answer differed, note what you missed before continuing.
How if-else if-else Executes
Let’s trace through different initial states to see how this chain works.
| isAdmin | isMember | Which scope? | Output |
|---|---|---|---|
| true | true | First | ”Full access” |
| true | false | First | ”Full access” |
| false | true | Second | ”Member access” |
| false | false | Third | ”Guest access” |
Notice the first row: both conditions are true, but we only see “Full access.” Once we find a true condition, we execute that scope and skip the rest. The second condition is never even checked.
The final else is a catch-all. If no condition is true, we execute the else scope. Without it, we might skip all branches entirely.
flowchart TD A[evaluate first condition] --> B{true?} B -->|yes| C[execute first scope] B -->|no| D[evaluate second condition] D --> E{true?} E -->|yes| F[execute second scope] E -->|no| G[execute else scope] C --> H[continue] F --> H G --> H
This is still mutual exclusion. Exactly one scope executes.
Try it yourself.
What does this code display?
bool a = false;
bool b = false;
bool c = true;
if (a)
{
Console.WriteLine("A");
}
else if (b)
{
Console.WriteLine("B");
}
else if (c)
{
Console.WriteLine("C");
}
else
{
Console.WriteLine("None");
}Write your answer before revealing ours.
Reveal answer
It displays C.
We check a: false. Skip to else if. We check b: false. Skip to else if. We check c: true. Execute that scope. Display “C”. Skip the final else.
If your answer differed, note what you missed before continuing.
Try it yourself.
Write C# code for this description:
“If high evaluates to true, execute a scope that displays ‘High’ to the console. Otherwise, if medium evaluates to true, execute a scope that displays ‘Medium’ to the console. Otherwise, execute a scope that displays ‘Low’ to the console.”
Write your answer before revealing ours.
Reveal answer
if (high)
{
Console.WriteLine("High");
}
else if (medium)
{
Console.WriteLine("Medium");
}
else
{
Console.WriteLine("Low");
}If your answer differed, note what you missed before continuing.
Nested Conditionals
An if statement can contain another if statement. This is nesting.
bool hasPermission = true;
bool hasQuota = false;
if (hasPermission)
{
if (hasQuota)
{
Console.WriteLine("Access granted");
}
else
{
Console.WriteLine("Over quota");
}
}
else
{
Console.WriteLine("Access denied");
}This displays: Over quota
Let’s trace through to see why:
| step | action |
|---|---|
| 1 | Bind true to hasPermission |
| 2 | Bind false to hasQuota |
| 3 | Evaluate hasPermission → true, enter outer scope |
| 4 | Evaluate hasQuota → false, take the inner else |
| 5 | Display “Over quota” |
Each if creates its own scope, and scopes can be nested inside other scopes. The inner if only runs if we entered the outer if first. This lets us check conditions in sequence: first hasPermission, then (only if that passed) hasQuota.
Try it yourself.
Translate this code to English:
if (loggedIn)
{
if (isAdmin)
{
Console.WriteLine("Admin panel");
}
}Write your answer before revealing ours.
Reveal answer
“If loggedIn evaluates to true, execute the scope.”
The scope contains: “If isAdmin evaluates to true, execute the scope.”
That inner scope contains: “Display the string ‘Admin panel’ to the console.”
If your answer differed, note what you missed before continuing.
Nesting vs Compound Conditions
When should you nest versus use compound conditions? Compare:
// Nested version
if (hasKey)
{
if (doorUnlocked)
{
Console.WriteLine("Enter");
}
}
// Compound version
if (hasKey && doorUnlocked)
{
Console.WriteLine("Enter");
}For simple cases like this, the compound version is cleaner. Both require hasKey and doorUnlocked to be true.
But nesting gives you more control. The nested version lets you put different else branches at different levels:
if (hasKey)
{
if (doorUnlocked)
{
Console.WriteLine("Enter");
}
else
{
Console.WriteLine("Door is locked");
}
}
else
{
Console.WriteLine("You need a key");
}The compound version can’t express this structure. You’d need separate if statements.
Rule of thumb: use compound conditions when you just need everything to be true. Use nesting when different false cases need different responses.
Try it yourself.
Rewrite this nested conditional as a single if statement with a compound condition:
if (loggedIn)
{
if (verified)
{
Console.WriteLine("Welcome");
}
}Write your answer before revealing ours.
Reveal answer
if (loggedIn && verified)
{
Console.WriteLine("Welcome");
}Both versions display “Welcome” only when loggedIn and verified are both true. The compound version is simpler when you don’t need separate else branches.
If your answer differed, note what you missed before continuing.
Try it yourself.
Write code for this description:
“If loggedIn evaluates to true, execute a scope that checks if admin also evaluates to true. If both are true, display ‘Admin panel’ to the console.”
Write your answer before revealing ours.
Reveal answer
if (loggedIn)
{
if (admin)
{
Console.WriteLine("Admin panel");
}
}Or using compound condition:
if (loggedIn && admin)
{
Console.WriteLine("Admin panel");
}Both versions work. The compound condition is more concise.
If your answer differed, note what you missed before continuing.
Try it yourself.
This code has nested conditionals. Should they be rewritten as a compound condition with &&? Why or why not?
if (fileExists)
{
if (fileSize > 1000)
{
Console.WriteLine("Large file");
}
}Write your answer before revealing ours.
Reveal answer
Either form can be correct in C#. But I’d keep it nested here.
In C#, && short-circuits: it only evaluates the right side if the left side is true. So if fileSize > 1000 is a safe expression to evaluate whenever it runs, then this is fine:
if (fileExists && fileSize > 1000)
{
Console.WriteLine("Large file");
}Nesting is still useful when you want different responses for different failures (no file vs small file), or when the second check only makes sense conceptually after the first. Nesting makes that dependency explicit.
If your answer differed, note what you missed before continuing.
So far we’ve only branched on variables we created ourselves. But real programs respond to user input. To do that, we need to work with text.
Strings for User Input
When someone types at a keyboard, they produce text. We need to store that text.
A string is text in quotation marks.
Examples: "hello", "yes", "42"
You can create string variables:
string message = "Hello";And compare them:
bool match = message == "Hello"; // trueThat’s all you need for now. In Chapter 4, we’ll explore strings fully. For this section, strings let us work with user input and display messages.
Displaying Messages
We’ve used Console.WriteLine to display values. It works with strings too:
Console.WriteLine("Hello!");The translation: “Display the string ‘Hello!’ to the console.”
One useful signature to keep in mind is: WriteLine: (string) → void
Same pattern we saw before. It takes a string value, displays it, and produces nothing in return.
Reading Input
Now for input:
string answer = Console.ReadLine();The translation: “Call ReadLine and bind the result to a string variable named answer.”
One useful signature to keep in mind is: ReadLine: () → string
The () means ReadLine takes no input. It waits for the user to type something and press Enter. Then it produces that text as a string value. We bind that value to a variable.
Try it yourself.
Translate this code to English:
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();Write your answer before revealing ours.
Reveal answer
First statement: “Display the string ‘Enter your name:’ to the console.”
Second statement: “Call ReadLine and bind the result to a string variable named name.”
If your answer differed, note what you missed before continuing.
Branching on Input
Now we can branch based on what the user typed:
Console.WriteLine("Continue? (yes/no)");
string answer = Console.ReadLine();
if (answer == "yes")
{
Console.WriteLine("Continuing...");
}
else
{
Console.WriteLine("Stopping.");
}The expression answer == "yes" compares two strings. It evaluates to true if they match, false otherwise. This is a boolean expression, so we can use it as a condition.
The translation for answer == "yes": “answer equals the string ‘yes’”
This program’s behavior depends on what the user types. If you type “yes” and press Enter, you’ll see “Continuing…” If you type anything else, you’ll see “Stopping.”
Try it yourself.
Write a program that:
- Displays “Enter password:” to the console
- Reads input and binds it to a string variable named password
- If password equals the string “secret”, displays “Access granted”
- Otherwise, displays “Access denied”
Write your answer before revealing ours.
Reveal answer
Console.WriteLine("Enter password:");
string password = Console.ReadLine();
if (password == "secret")
{
Console.WriteLine("Access granted");
}
else
{
Console.WriteLine("Access denied");
}If your answer differed, note what you missed before continuing.
Loops with while
What if the user types the wrong password? We could tell them to try again. But our program ends after one check.
We could add more if statements:
Console.WriteLine("Enter password:");
string password = Console.ReadLine();
if (password != "secret")
{
Console.WriteLine("Wrong password. Try again:");
password = Console.ReadLine();
}
if (password != "secret")
{
Console.WriteLine("Wrong password. Try again:");
password = Console.ReadLine();
}
// How many times do we copy this?This is tedious and limited. What if they get it wrong three times? Ten times? We’d need endless copies of the same code.
What we want is a way to say: keep asking until they get it right.
Console.WriteLine("Enter password:");
string password = Console.ReadLine();
while (password != "secret")
{
Console.WriteLine("Wrong password. Try again:");
password = Console.ReadLine();
}
Console.WriteLine("Access granted");The while statement has the same structure as if: a condition in parentheses and a scope in curly braces. The difference is in behavior. Instead of executing the scope once (or not at all), while executes repeatedly, as long as the condition remains true.
The translation: “While password != ‘secret’ evaluates to true, execute the scope.”
Try it yourself.
Translate this code to English:
while (waiting)
{
Console.WriteLine("Still waiting...");
}Write your answer before revealing ours.
Reveal answer
“While waiting evaluates to true, execute the scope.”
The scope contains: “Display the string ‘Still waiting…’ to the console.”
If your answer differed, note what you missed before continuing.
How while Executes
Let’s look more carefully at what happens when a while loop runs.
Let’s break down while (condition) { ... } token by token:
while (condition)— evaluate the condition; if true, execute the scope; if false, skip to after the loop{ ... }— the scope to execute when the condition is true; after executing, check the condition again
The key difference from if is that after executing the scope, we check the condition again, repeating until it evaluates to false.
Let’s trace through with specific input. The user types “wrong”, then “also wrong”, then “secret”:
| step | password | condition | action |
|---|---|---|---|
| 1 | — | — | Display prompt |
| 2 | ”wrong” | — | Read input, bind to password |
| 3 | ”wrong" | "wrong” != “secret” → true | Check condition, enter loop body |
| 4 | ”wrong” | — | Display “Wrong password…“ |
| 5 | ”also wrong” | — | Read input, rebind password |
| 6 | ”also wrong" | "also wrong” != “secret” → true | Check condition again, enter loop body |
| 7 | ”also wrong” | — | Display “Wrong password…“ |
| 8 | ”secret” | — | Read input, rebind password |
| 9 | ”secret" | "secret” != “secret” → false | Check condition again, exit loop |
| 10 | ”secret” | — | Display “Access granted” |
The loop ran twice. Each time, we checked the condition, found it true, entered the scope, and came back to check again. On the third check, the condition was false, so we exited.
flowchart TD A[evaluate condition] --> B{true?} B -->|yes| C[execute scope] B -->|no| D[continue] C --> A
The arrow looping back is the key difference from if. We keep circling until the condition is false.
This structure, where we repeatedly execute a scope while a condition holds, is called a loop.
A loop is a control structure that repeatedly executes a scope while a condition evaluates to true.
Try it yourself.
Write C# code for this description:
“Create a string variable named command and bind an empty string to it. While command does not equal the string ‘exit’, execute a scope that displays ‘Enter command:’ to the console, then calls ReadLine and binds the result to command.”
Write your answer before revealing ours.
Reveal answer
string command = "";
while (command != "exit")
{
Console.WriteLine("Enter command:");
command = Console.ReadLine();
}If your answer differed, note what you missed before continuing.
Finding Problems in Loops
Try it yourself.
This code has a serious problem. What will happen when you run it?
bool running = true;
while (running)
{
Console.WriteLine("Working...");
}
Console.WriteLine("Done");Think about it before revealing the answer.
Write your answer before revealing ours.
Reveal answer
The code never stops. It runs forever.
The variable running is never changed inside the loop. It stays true forever. The condition never becomes false. The program never reaches “Done”.
The loop displays “Working…” endlessly. Your program appears stuck (it never reaches the code after the loop).
If your answer differed, note what you missed before continuing.
Infinite Loops
The problem above is called an infinite loop. The loop never ends because the condition never becomes false.
Every while loop must have a way for the condition to become false. If nothing in the loop changes state, the loop runs forever.
Compare these:
// This loop terminates
string input = "";
while (input != "quit")
{
Console.WriteLine("Enter command:");
input = Console.ReadLine(); // State changes here
}
// This loop runs forever
string input = "";
while (input != "quit")
{
Console.WriteLine("Enter command:");
// Forgot to read new input! State never changes.
}The first loop reads new input each iteration. Eventually the user types “quit”, and the loop exits.
The second loop displays “Enter command:” forever. The variable input stays empty because we never rebind it.
Key insight: Something in the loop body must eventually change state to make the condition false. Otherwise, the loop never ends.
When your program seems frozen, check your loops: does something inside change state? Can the condition become false?
Remember the earlier while-translation exercise? That code had this same problem:
while (waiting)
{
Console.WriteLine("Still waiting...");
}What’s wrong with it? The variable waiting is never changed inside the loop. If it starts as true, it stays true. The condition never becomes false. The loop runs forever.
In our password example, the loop body reads new input and rebinds password. Eventually the user types “secret”, the condition becomes false, and the loop exits. That’s why it works.
Try it yourself.
Fix the infinite loop from earlier. Modify the code so it has a way to stop.
bool running = true;
while (running)
{
Console.WriteLine("Working...");
}
Console.WriteLine("Done");Write your answer before revealing ours.
Reveal answer
The variable running is never changed inside the loop. It stays true forever.
One fix: add a way to stop. For example, check user input:
bool running = true;
while (running)
{
Console.WriteLine("Working... Type 'stop' to end:");
string input = Console.ReadLine();
if (input == "stop")
{
running = false;
}
}
Console.WriteLine("Done");Now the user can type “stop” to make running false, which ends the loop.
If your answer differed, note what you missed before continuing.
Review
Before continuing to Functions, test yourself on what you’ve learned. Use the protocol from Chapter 0: attempt each exercise from memory, then search this section to check your answers, then note what you missed.
Part 1: Definitions
Write the definitions from memory, then find them in this section to check.
- What is a scope?
- What is a loop?
- What is a string?
If any of your answers differed from the definitions in this section, note what you missed and write the corrected version.
Part 2: Translations
Translate each piece of code to English.
-
if (ready) { Console.WriteLine("Go"); } -
if (valid) { x = true; } else { x = false; } -
while (active) { Console.WriteLine("Running"); } -
string name = Console.ReadLine(); -
if (input == "yes") { confirmed = true; }
Check your translations against the patterns shown in this section.
Part 3: Writing Code
Write C# code for each description.
-
If done evaluates to true, execute a scope that displays “Finished” to the console.
-
If authorized evaluates to true, execute a scope that displays “Welcome” to the console. Otherwise, execute a scope that displays “Access denied” to the console.
-
While running evaluates to true, execute a scope that displays “Processing…” to the console.
-
Call ReadLine and bind the result to a string variable named response.
Check your code against the examples in this section.
Part 4: Execution Traces
Trace the execution of this code. Show which lines run and in what order.
bool x = true;
bool y = false;
if (x)
{
Console.WriteLine("A");
if (y)
{
Console.WriteLine("B");
}
else
{
Console.WriteLine("C");
}
}
else
{
Console.WriteLine("D");
}
Console.WriteLine("E");What does it display? Trace the execution step by step, then check your trace against the nested conditionals example earlier in this section.
Part 5: Loop Traces
Trace the execution of this code. Assume the user types “no”, then “no”, then “yes”.
Console.WriteLine("Ready?");
string answer = Console.ReadLine();
while (answer != "yes")
{
Console.WriteLine("Please type yes:");
answer = Console.ReadLine();
}
Console.WriteLine("Starting!");Create a table showing the value of answer and the output at each step. Check your trace against the password example in the “How while Executes” section.
Part 6: Complete Programs
Write complete programs for these specifications:
-
A program that asks “Play again? (yes/no)” and keeps asking until the user types “no”. When they type “no”, display “Goodbye!”
-
A program that asks for a username. If the username equals “admin”, ask for a password. If the password equals “12345”, display “Welcome, admin!” Otherwise display “Wrong password.” If the username wasn’t “admin”, display “Unknown user.”
Check your programs by tracing through them with different inputs.
You now know how to control which code runs based on state. You can branch with if, choose between alternatives with if-else, chain multiple conditions, and repeat code with while loops. In the next section, we’ll learn how to package our own computations into reusable functions.
Previous: Section 2 - Computation