✍️ Practice (For)
1. Sum of Evens
Ask the user for a limit, then add up every even number from 2 to that limit.
👀Hints
Pseudocode
- Ask the user for the limit
- Set the sum to 0
- For each even number from 2 up to the limit:
- Add the number to the sum
- Show the sum
💡Solution
Console.Write("Enter a limit: ");
int limit = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 2; i <= limit; i += 2)
{
sum += i;
}
Console.WriteLine("Sum of even numbers: " + sum);
2. Charge your Phone
A phone starts at 100% battery and loses 20% each hour:
int batteryLevel = 100;
for (int hour = 0; hour < 4; hour++)
{
batteryLevel -= 20;
}
Console.WriteLine($"Battery left: {batteryLevel}%");
Fill in a trace table showing hour and batteryLevel for each pass, then predict what the program prints.
hour | hour < 4 | batteryLevel after the pass |
|---|---|---|
👀Hints
The first row is:
hour | hour < 4 | batteryLevel after the pass |
|---|---|---|
| 0 | true | 80 |
| 1 | ||
| 2 | ||
| 3 | ||
| 4 |
💡Solution
hour | hour < 4 | batteryLevel after the pass |
|---|---|---|
| 0 | true | 80 |
| 1 | true | 60 |
| 2 | true | 40 |
| 3 | true | 20 |
| 4 | false | loop ends |
Final value: 20
3. Limit Sum
Loop through a range of numbers from 1 to 100. Keep a running total sum of these numbers. As soon as the total sum exceeds 50, stop the loop and print the total sum and the last number added.
💡Solution
int totalSum = 0;
for (int num = 1; num <= 100; num++)
{
totalSum += num;
if (totalSum > 50)
{
Console.WriteLine($"The sum exceeded 50 at number {num}. Total sum is {totalSum}.");
break;
}
}
4. Clock
Display every minute of every hour in a day.
0:00
0:01
0:02
…
23:58
23:59
👀Hints
Save yourself a lot of typing by using 2 loops!
Pseudocode
- for each hour of a total hours:
- for each minute or total minutes:
- print hour:minute
- for each minute or total minutes:
💡Solution
for (int hour = 0; hour < 24; hour++)
{
for (int minute = 0; minute < 60; minute++)
{
Console.WriteLine($"{hour}:{minute}");
}
}
5. Triangle
Write a program to display a cute right angle triangle as shown below:
*
**
***
****
👀Hints
Pseudocode
- set total rows to 4
- for each row from 1 to total rows:
- for each column from 1 to row: print "*"
- print a new line
💡Solution
const int Rows = 4;
for (int i=1; i<=Rows; i++) // Rows
{
for (int j=1; j<=i; j++) // Columns
{
Console.Write("*");
}
Console.WriteLine(); // or Console.Write("\n");
}