Branch and repeat with control flow
Use conditions, loops, and boolean logic to direct a program.
- Write if/else, for, and while statements with clear conditions.
Use if, else if, and else to choose a path. A for loop is convenient when you know how to initialize, check, and update a counter. A while loop continues as long as its condition is true. Comparisons include ==, !=, <, and >=; && means logical AND and || means OR.
1using System;
2
3class Program
4{
5 static void Main()
6 {
7 for (int number = 1; number <= 3; number++)
8 {
9 string kind = number % 2 == 0 ? "even" : "odd";
10 Console.WriteLine($"{number} is {kind}");
11 }
12 }
13}1 is odd 2 is even 3 is odd
The conditional operator condition ? valueIfTrue : valueIfFalse is useful for choosing between two values. Prefer an if statement when each branch performs several actions, so the logic remains easy to read.
Key takeaways
Conditions select a path; loops repeat work.
Distinguish equality == from assignment =.
Check that loops have a clear exit condition.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write C#
Write C# 12 in the editor and run it against sample input. .NET 8 compiles and runs the code through Wandbox, a free public service; your source and test input are sent there.
Sum from one through n
Read an integer n and print the sum from 1 through n as Sum: N. Assume n is between 1 and 1000.
- Sum to 5
- Sum to 1
C# 12 code is compiled and run with .NET 8 on Wandbox, a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…