Loops in C#: For and While
שאלות 10
מפתח התשובות מוצג למורים מחוברים.
-
-
-
Choosing between for and while
Explain when a programmer should choose a for loop instead of a while loop in C#, and when a while loop is the better choice. Refer to how each loop handles its initialization, condition and iteration step.
Think about where the counter is set up and updated in each loop, and whether you know the number of repetitions before the loop starts. -
Spotting an infinite loop
The following C# code is intended to print the numbers 10 down to 1, but it does not behave as intended. int x = 10; while (x > 0) { Console.WriteLine(x); x++; } Explain why this loop never ends and how it should be corrected.
Consider the direction in which x changes on each iteration compared with the direction needed to make the condition x > 0 eventually false. -
Counting with nested for loops
Assume count is an int that starts at 0. What is the final value of count after the following C# code runs? for (int i = 0; i < 3; i++) { for (int j = 0; j < i; j++) { count++; } }
The inner loop runs a different number of times for each value of i. Work out how many times it runs when i is 0, 1 and 2. -
Writing a for loop that prints even numbers
Write a C# for loop that prints the even numbers from 2 to 20 inclusive, one number per line, using Console.WriteLine. Describe the initialization, condition and iteration step you used.
Start at the first even number and choose an increment that skips the odd numbers. Make sure the condition includes 20. -
-
-
Parts of a for loop
In a for loop, the ________________ part runs only once, before the first iteration. The ________________ is checked before every iteration, and the loop stops when it becomes false. The ________________ part, such as i++, runs at the end of each iteration.
terminatorconditioninitializationmodifiercounterdelimiteriteratorThe for loop header has three sections separated by semicolons; the first section sets up the loop variable. -
פרטים
- מקצועות
- c#
- קהל יעד
- תיכון · כיתות י׳–י״ב
- רמת קושי
- 6 מתוך 10
- שפה
- אנגלית
- מי יכול לראות
- כולם
- הושלם על ידי AI
- מה שמסומן בניצוץ נוסף על ידי AI.
- נוצר באמצעות AI
- Claude Haiku 5.5
- נוצר
תגובות