c# · level 1 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Big programs are small pieces working as a team.
Real programs are built from small parts. An array holds the data. A loop walks through it. A function answers one small question, and an if decides what to do with each answer.
IsTasty returns a bool, so its answer slots straight into an if. It is so short that it fits on one line. C# goes by the brackets and semicolons, not by the line breaks.
When something goes wrong, you : find the bug, fix it, run again. Every programmer does this every day. Small functions help, because you can test each one on its own.
using System;
int[] ratings = { 9, 3, 8, 5 };
foreach (int rating in ratings)
{
if (IsTasty(rating))
{
Console.WriteLine($"{rating} out of 10. Yum!");
}
}
bool IsTasty(int score) { return score >= 7; } Test each function on its own first, then put the pieces together.
guess first
Every piece at once. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
int[] goals = { 1, 2, 3 };
int total = 0;
foreach (int goal in goals)
{
total = total + Twice(goal);
}
Console.WriteLine(total);
int Twice(int number) { return number * 2; }
your turn
Your turn. Plan a trip to the snack shop.
Put three snack prices in the array, as whole numbers, then type how much money you have in the last blank. Make sure you can afford at least one snack!
output
press run to see what happens
fix it
Only one Paris counts as right. Debug it!
output
press run to see what happens
- Only one guess counts as right. What is different about the other two?
==compares text letter by letter, capitals included. Change the answer to small letters before comparing.- On line 12, change
answer ==toanswer.ToLower() ==, then run.
nailed it
you put all the pieces together. :D
- Small functions, each with one job, build big programs.
- Arrays hold data, loops walk through it, and
ifdecides. - To debug, find the bug, fix it, then run again.
new words in your collection
- debug
This lesson isn’t saved. A free account remembers every lesson you finish.