Although this article discusses one of the fundamental topics, it is written for experienced professionals. The goal is to highlight the misconceptions that beginners in programming often have. For practicing developers, these issues have long been resolved, forgotten, or simply unnoticed. This article may be useful if you ever need to assist someone with this topic. Comparisons will be made with material from various programming books by authors such as Schildt, Stroustrup, and Okulov.
The topic of loops was chosen because it tends to filter out many people when learning programming.
This methodology is designed for weaker students. Strong students typically do not get stuck on this topic, and there is no need to invent special methods for them. A secondary goal of the article is to transform this methodology from a class that 'works for all students, but only with one instructor' to a class that 'works for all students and all instructors.' I do not claim absolute originality. If you already use a similar methodology for teaching this topic, please share how your approach differs. If you decide to implement it, let me know how it turned out. If a similar method is described in any book, please provide the title.
I have refined this methodology over four years, working individually with students of varying skill levels. In total, I have taught around fifty students and spent two thousand hours in lessons. Initially, students would get permanently stuck on this topic and drop out. After each student, the methodology and materials were adjusted. In the last year, students no longer get stuck on this topic, so I decided to share my findings.
Why so many words? Loops are elementary!
As I mentioned earlier, for practicing developers and strong students, the complexity of the concept of loops may be underestimated. For example, one can deliver a lengthy lecture, see nodding heads and intelligent eyes. However, when attempting to solve a task, confusion and inexplicable problems arise. After the lecture, students surely only have a partial understanding. The situation is exacerbated by the fact that students cannot articulate what exactly their misconceptions are.
Once, I realized that students perceive my examples as hieroglyphs. That is, as indivisible pieces of text where they need to add some 'magical' letter for it to work.
Sometimes I noticed that students think that solving a specific problem requires some other construct that I just haven't explained yet. However, solving it only required a slight modification of the example.
This led me to the idea that the main focus should be on the concept of refactoring repetitive code using loops. Once students grasp this idea, any syntax can be mastered through small exercises.
Who and why I teach
Since there are no entrance exams, classes can have both strong and very weak students. More details about my students can be found in the article
I aimed for programming to be accessible to everyone who wants to learn it.
My classes are individual, and each student pays for their lessons. It seems that students would optimize costs and demand the minimum. However, people attend face-to-face classes with a live teacher not just for knowledge, but for confidence in what they have learned, for a sense of progress, and for approval from an expert (the teacher). If students do not feel progress in their learning, they will leave. In general, classes can be structured so that students feel progress in the increase of familiar constructions. That is, we first study while in detail, then learn for, then do while, and we have our course ready for a thousand and one nights, where for two months we study only loops, leading to a student who dictates the standard library. However, to solve practical problems, one needs not only knowledge of the material but also independence in applying it and searching for new information. Therefore, for face-to-face courses, I believe it is correct to teach the minimum and encourage independent study of nuances and related topics. In the topic of loops, I consider the minimum to be the while construct. Understanding this principle allows one to independently master both for and do-while.
To ensure that weaker students grasp the material, it is not enough to just describe the syntax. It's important to provide plenty of simple yet diverse tasks and to outline examples in more detail. Ultimately, the speed of understanding is limited by the student's ability to transform expressions and identify patterns. For more perceptive students, most tasks will be tedious. When working with them, it is acceptable not to insist on solving 100% of the problems. You can view my material on . However, the repository is more like a grimoires of a wizard — no one but me will understand where everything is, and if you fail the review, it might drive you mad.
The methodology is focused on practice.
The theory is explained through solving problems. In introductory programming classes, where branching and loops are studied, it is simply not feasible to conduct a useful lecture on a single topic for an entire hour. 15-20 minutes is enough to explain the concept. The main difficulties arise during the practical assignments.
New teachers might cover operators, branching, loops, and arrays in a single lecture. However, students will face challenges in absorbing this information.
It is essential not only to present the material but also to ensure that the audience understands it.
The understanding of the topic is determined by how well the student performs in independent work.
If a student manages to solve a problem on the topic without the teacher's help, then the topic has been mastered. To facilitate self-checking, each problem is accompanied by a table with test scenarios. The tasks follow a clear sequence. It is not recommended to skip tasks. If the current problem is too complex, moving to the next will be pointless as it will be even harder. To help the student tackle the current challenging task, several techniques are explained using the first task as an example. Essentially, the entire content of the topic boils down to techniques for overcoming difficulties. Loops are more of a side effect.
The first task is always an example. The second task is slightly different and is performed 'independently' right after the first one under the teacher's supervision. All subsequent tasks aim to draw attention to various nuances that may cause misconceptions.
The explanation of the example consists of a dialogue where the student needs to invoke back propagation and cross-validation to ensure they've grasped the material presented.
I will be cliché and state that the first example on the topic is very important. When there is extensive material for independent work, missing the first example can be corrected. However, if there is nothing besides the example, the student is unlikely to grasp the topic.
While or for?
One of the contentious issues is the choice of construction for the example: while or for. Once, a practicing developer friend of mine, who had no teaching experience, tried to convince me for an hour that the for loop is the simplest to understand. His arguments boiled down to 'everything is clear and organized within it.' However, the root cause of the difficulties for true beginners lies in the very idea of loops, not in their syntax. If a person doesn't understand this idea, they will struggle with syntax. Once the idea is understood, problems with code formatting disappear on their own.
In my materials, the topic of loops follows the topic of branching. The external similarity of if and while allows for a direct analogy: 'when the condition in the header is true, the body executes.' The only difference with loops is that the body executes multiple times.
My second argument is that while requires less formatting than for. Less formatting means fewer silly mistakes with missing commas and parentheses. Newcomers do not yet possess the attention to detail needed to automatically avoid syntax errors.
The third argument is that in many good books, while is explained first.
If a student can easily transform expressions, then we can mention for in passing. The student can then choose what they prefer. However, if transformations are challenging, it's better not to distract them. Let them first resolve everything using while. Once the topic of loops is mastered, solutions can be rewritten to practice transforming while into for.
Post-condition loops are quite a rare beast. I don't spend any time on them at all. If a student has grasped the concepts of identifying patterns and transforming expressions, they can figure it out without my help.
When demonstrating the first example to strong students, I emphasize that in the first example, it is important to document not only the solution but also the entire chain of actions that led to the result. Lazy students may neglect the writing and only transfer the final algorithm to themselves. They need to be convinced that one day they will encounter a complex task. To solve it, they will need to go step by step as in this example. That is why it is important to document all stages. In subsequent tasks, only the final solution can be provided.
The main idea of automation is that we delegate routine tasks to the computer to perform instead of a human. One of the basic techniques is writing loops. It is used when the program has to perform several identical repetitive actions consecutively.
Explicit is better than implicit.
It may seem like a good idea in the first task about loops to output the same phrase several times. For example:
Hooray, it works!
Hooray, it works!
Hooray, it works!
Hooray, it works!
Hooray, it works!
Hooray, it works!
Hooray, it works!
Hooray, it works!
This option is poor because the output does not show the value of the counter. This is a problem for beginners. This issue should not be underestimated. Initially, this task was the first, while the task of outputting a series of numbers in ascending order was the second. Additional terms like "loop N times" and "loop from A to B" had to be introduced, which essentially mean the same thing. To avoid creating unnecessary entities, I decided to show only the example of outputting a series of numbers. Not many can learn to keep a counter in mind and model the program's behavior in their head without preparation. Some students encounter the concept of mental modeling for the first time precisely in the topic on loops.
After some practice, I give the task of repeating the same text as an independent exercise. If a visible counter is provided first and then an invisible one, students encounter fewer issues. Sometimes just the hint "don't print the counter to the screen" is enough.
How is it explained by others?
In most online educational materials, the syntax for loops is presented within the context of a 'lecture.' For example, on developer.mozilla.org (currently), the while loop is accompanied by several other constructs. However, only the constructs themselves are given in the form of templates. The results of their execution are described in words, while illustrations are absent. In my opinion, this style of presenting the topic diminishes the usefulness of such materials to zero. A student can rewrite the code and run it themselves, but a benchmark for comparison is still needed. How can one understand if the example has been rewritten correctly if there is nothing to compare the result against?
When only a template is provided without an example, it becomes even more challenging for the student. How can one know if the code fragments are arranged correctly in the template? One might try to write something, and then run it. But if there is no benchmark for comparing the result, then running it won't help either.
In the C++ course on Intuit, the syntax for loops is buried on the third page of lecture 4 on 'operators.' When explaining the syntax of loops, particular emphasis is placed on the term 'operator.' The term is presented as a set of facts such as 'a symbol; this is an operator,' '{} is a composite operator,' 'the loop body must be an operator.' I don't like this approach because it seems to obscure important relationships behind a single term. Analyzing the source code of a program into terms at such a level is necessary for compiler developers to implement language specifications, but it is not helpful for students in their initial learning. Beginners in programming rarely possess the diligence to pay such careful attention to the terms. Few people remember and understand new words the first time they encounter them. Practically no one can correctly apply a term that they have just learned. As a result, students often encounter numerous errors, such as 'I wrote while(a<7);{, and the program doesn't work.'
In my opinion, it's better to present the syntax of the construct initially with the brackets. The version without brackets should only be explained if the student has a specific question: 'why is it working here without brackets?'
In Okulov's book "Fundamentals of Programming" from 2012, the introduction to loops begins with the for template, followed by recommendations for its use, and then immediately moves into an experimental section of the lesson. As I understand it, the book was written for that small group of highly capable students who rarely attend my classes.
Popular books always present the results of code snippets. For instance, in Schildt's "Java 8: The Complete Reference" from 2015. First, a template is given, then a sample program, and right after that—the output result.
As an example, let's consider a while loop that performs a countdown, starting from 10, and outputs exactly 10 lines of "ticks":
After launching, this program outputs ten "ticks" as follows://Продемонстрировать применение оператора цикла while class While { public static void main(String args []) { int n = 10; while (n > 0) { System.out.println("такт " + n); n--; } } }This approach of presenting a template, a sample program, and the results of that program is also used in the book "JavaScript for Kids" and in the JavaScript course on w3schools.com. The webpage format even allows this example to be interactive.
step 10
step 9
step 8
step 7
step 6
step 5
step 4
step 3
step 2
step 1
In Bjarne Stroustrup's book "Principles and Practice Using C++" from 2016, the author goes even further. First, he explains what the expected result should be, and only after that—shows the program text. Moreover, they take not just a random program as an example, but provide a historical overview. This helps to draw attention to it: "Look, this is not just some useless text. You see something significant."
As an example of iteration, let's consider the first program executed on a stored-program machine (EDSAC). It was written by David Wheeler in the Computer Laboratory of Cambridge University (Cambridge University, England) on May 6, 1949. This program calculates and prints a simple list of squares.
Here, each line contains a number followed by a tab character (‘t’) and the square of that number. The version of this program in C++ looks like this:
0 0
1 1
2 4
3 9
4 16
...
98 9604
99 9801
Interestingly, the syntax pattern in this book is not described. Stroustrup emphasizes in the instructor's guide that he respects the intelligence of his students. Perhaps the ability to identify a pattern across several examples is deemed a manifestation of such intelligence.//Вычисляем и распечатываем таблицу квадратов чисел 0-99 int main() { int i = 0; // Начинаем с нуля while(i < 100){ cout << i << 't' << square(i) << 'n'; ++i; } }
As I explain myself) emphasizes that it respects the intelligence of its students. The ability to identify a pattern from several examples is considered a manifestation of such intelligence.
How I explain it myself
Stroustrup's approach: describe the outcome, then solve the problem, and finally conduct an independent analysis by the student—seems to be the most thoughtful. Therefore, I decided to base this on his method, but to discuss it using a less historical example—the task of generating a 'table of contents'. It creates a recognizable anchor, so I can later say, 'remember the task about the table of contents,' and the students will recall it specifically. In my example, I have tried to address two of the most common misconceptions. I will elaborate on them further.
In this task, we become familiar with techniques for solving complex problems. The initial solution should be primitive and straightforward. Then we can think about how to improve this solution.
Introduction
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Conclusion
In my observations, the 'template-example-result' approach, in various combinations, still leads students to perceive the loop as a hieroglyph. This was evident in their misunderstanding of why they needed to write a condition, how to choose between i++ and i--, and other seemingly obvious things. To avoid these misunderstandings, the explanation of loops should emphasize the meaning of repeating identical actions and only then—formatting them with the construction. Therefore, before presenting the syntax of the loop, one should solve the problem 'head-on.' A primitive solution for the table of contents task looks like this:
Console.WriteLine("Introduction");
Console.WriteLine("Chapter 1");
Console.WriteLine("Chapter 2");
Console.WriteLine("Chapter 3");
Console.WriteLine("Chapter 4");
Console.WriteLine("Chapter 5");
Console.WriteLine("Chapter 6");
Console.WriteLine("Chapter 7");
Console.WriteLine("Conclusion");
How can it be improved?
Replace repetitive actions with a loop.
What actions are repeated consecutively without changes?
There are none in this fragment. However, the commands outputting the word 'Chapter' with a number are very similar to each other.
Therefore, the next step is to find the difference between the fragments. This task makes it obvious, but later, there will be not just single commands repeating, but blocks of code consisting of 5 lines or more. One will have to search not just in the list of commands, but in branching or loop constructions.
In this example, the difference between the commands is in the number after the word 'Chapter.'
Once the difference is found, one must understand the pattern of change. Is the differing fragment a number? Does it constantly increase or decrease? How does the value of the number change between two commands in close proximity?
In this example, the number after the word "Chapter" increases by 1. The difference has been found, and a pattern has been identified. Now, we can replace the differing fragment with a variable.
You need to declare such a variable before the first of the repeating fragments. This variable is usually called i or j, or something more descriptive. Its initial value should be equal to the first value displayed on the screen. In this example, the first value is 1.
What initial value should be taken for outputting the series of numbers "100, 101, 102, 103, 104, 105"?
In this series, the first number is 100.
After each output command, the variable's value should be increased by 1. This unit is the step of change.
What step will be in the series of numbers "100, 102, 104, 106"?
In this series, the step is 2.
After replacing the differing fragment with a variable, the code will look like this:
Console.WriteLine("Introduction");
int i;
i = 0;
Console.WriteLine("Chapter " + i);
i = i + 1;
Console.WriteLine("Chapter " + i);
i = i + 1;
Console.WriteLine("Chapter " + i);
i = i + 1;
Console.WriteLine("Chapter " + i);
i = i + 1;
Console.WriteLine("Chapter " + i);
i = i + 1;
Console.WriteLine("Chapter " + i);
i = i + 1;
Console.WriteLine("Chapter " + i);
i = i + 1;
Console.WriteLine("Conclusion");
After applying the technique of "expressing the pattern as a variable", the code results in several groups of identical actions that follow one another. Now, repeating actions can be replaced with a loop.
The sequence for solving a problem where loops need to be used consists of the following stages:
- Solve "brute force" with multiple individual commands
- Find the pattern
- Express the pattern as a variable
- Format it as a loop
Next, new terms are introduced so that the student does not find themselves in a situation of "I understand everything, but I can't say it":
— counter — always a variable that is needed to track the number of steps in the loop. Usually an integer that is compared to a limit.
— counter step — a description of how the counter changes.
— limit — a number or variable with which the counter is compared to ensure the algorithm is finite. The counter's value changes to approach the limit.
— loop body — a set of commands that will be repeated. When it is said "the command is written inside the loop", it refers specifically to the body.
— loop iteration — a single execution of the loop body.
— loop condition — a logical expression that determines whether another iteration will be executed. (This might be confused with branching constructs)
Be prepared for the fact that at first, students may use terms incorrectly. This applies to both strong and weak students. Establishing a common language is an art in itself. To put it briefly: set the task 'highlight the code fragment with <term>' and use these terms correctly in conversation yourself.
After conversion with a loop, the fragment is:
Console.WriteLine("Introduction");
int i = 0;
while (i < 7) {
Console.WriteLine("Chapter " + i);
i = i + 1;
}
Console.WriteLine("Conclusion");The main misconception
One popular misconception among students is that they place actions inside a loop construct that should only be executed once. For instance, like this:
;
int i = 0;
while (i < 7) {
Console.WriteLine("Introduction")
Console.WriteLine("Chapter " + i);
i = i + 1;
Console.WriteLine("Conclusion");
}
Students frequently encounter this problem, both at the beginning and in more complex tasks.
The key hint in this case is:
How many times should the command be repeated: once or many?
The output commands for the words 'Introduction' and 'Conclusion', as well as the declaration and initialization of the variable i, do not resemble other repetitive actions. They are executed only once, so they should be written outside the loop body.
All three stages of the solution should remain in the code to refer to them in case of difficulties. The first two options can be commented out so they don't interfere.
The student's attention should be drawn to the following facts:
— In the loop condition, the counter is usually compared with a limit. The counter may change within the loop body, while the limit may not. To violate this rule requires sound reasoning.
— The commands for outputting the words 'Introduction' and 'Conclusion' are outside the loop body. We need to execute them once. 'Introduction' — before repeating actions, 'Conclusion' — after.
In the process of reinforcing this topic, mastering the next ones, and dealing with difficulties, it is helpful even for strong students to ask the question: 'How many times should this action be performed? Once or many?'.
Development of additional skills
While studying loops, students also practice the skill of diagnosing and solving problems. To perform diagnostics, a student needs to envision the desired outcome and compare it with the actual result. The actions to correct any differences depend on this comparison.
Since students at this stage still have a poor understanding of the 'desired' outcome, they can rely on test data. Typically, no one at this stage understands what might go wrong and how to tackle it. Therefore, I provide a written description of typical problems and several solutions. Choosing the most appropriate one is the student's task.
The written record is needed to ask questions like 'Was the expected result achieved?', 'What situation occurred?', 'Did the applied solution help?'.
- The number of actions is either one less or more than expected. Solutions include:
— increasing the initial value of the counter by 1.
— replacing the strict comparison operator (< or >) with a non-strict one (<= or >=).
— changing the limit value by 1. - Actions within the loop are executed without stopping, infinitely. Solutions include:
— adding a counter modification command if it is missing.
— correcting the counter modification command so its value approaches the limit.
— removing the limit modification command if it exists within the loop. - The number of actions in the loop is more than 1 less or more than expected. An action in the loop did not run at all. First, it's essential to determine the actual variable values right before entering the loop. Solutions include:
— changing the initial limit value.
— changing the initial value of the counter.
Usually, problem 3 is related to using the wrong variable or failing to reset the counter.
After this explanation, students may still have various misconceptions about how loops work.
To dispel the most common ones, I provide tasks:
- Where the limit, initial counter value, or step of the counter is input by the user.
- Where the counter value needs to be used in some arithmetic expression. Preferably with the counter in a sub-expression or in the denominator, so the difference is nonlinear.
- In which the counter value is not displayed on the screen during the loop process. For example, outputting the required number of identical text fragments or drawing a figure using turtle graphics.
- In which some repeating actions need to be performed first, and then others.
- In which other actions need to be performed before and after the repetitions.
For each task, you need to provide test data and the expected result.
To understand how quickly you can proceed, you need to read the conditions of these tasks and ask: "How do they differ from the example?", "What needs to be changed in the example to solve them?" If the student answers thoughtfully, then let them solve at least one in class, while the others can be done at home independently. If the solution is successful, then you can start explaining conditions within loops.
If there are difficulties with independent solution, then everything needs to be worked out in class. To ensure that the problem-solving does not resemble drawing an owl, I recommend starting by solving the problem non-generally. That is, in such a way that the solution passes the first test without using a loop structure. Then you can apply transformations to achieve generality in the solution.
Loops and branches
In my opinion, it is useful to give the topic "loops within branches" separately. This way, the difference between multiple condition checks and a single condition check will be clearer.
Tasks for consolidation will be about outputting numbers from A to B, which are entered by the user:
— always in ascending order.
— in ascending or descending order depending on the values of A and B.
The topic of "branches within loops" should only be approached after the student has mastered the techniques: "replacing patterns with variables" and "replacing repeated actions with loops".
The main reason for using branches within loops is anomalies in the pattern. In the middle, it breaks depending on the initial data.
For students capable of finding solutions by combining simple techniques, it is enough to say, "Branches can be written inside loops" and give a task "for example" fully for independent solution.
Example task:
The user inputs number X. Output the numbers from 0 to 9 in a column and place a '+' sign next to the number which is equal to X.
If 0 was entered0+
1
2
3
4
5
6
7
8
9
If 6 was entered0
1
2
3
4
5
6+
7
8
9
If 9 was entered0
1
2
3
4
5
6
7
8
9+
If 777 was entered0
1
2
3
4
5
6
7
8
9
If a brief explanation is insufficient to write with a loop, then we need to achieve a universal solution to the same problem without a loop.
One of two options will result:
Desired
string temp;
temp = Console.ReadLine();
int x;
x = int.Parse(temp);
if (x==0) {
Console.WriteLine(0 + "+");
} else {
Console.WriteLine(0);
}
if (x==1) {
Console.WriteLine(1 + "+");
} else {
Console.WriteLine(1);
}
if (x==2) {
Console.WriteLine(2 + "+");
} else {
Console.WriteLine(2);
}
if (x==3) {
Console.WriteLine(3 + "+");
} else {
Console.WriteLine(3);
}
if (x==4) {
Console.WriteLine(4 + "+");
} else {
Console.WriteLine(4);
}
if (x==5) {
Console.WriteLine(5 + "+");
} else {
Console.WriteLine(5);
}
if (x==6) {
Console.WriteLine(6 + "+");
} else {
Console.WriteLine(6);
}
if (x==7) {
Console.WriteLine(7 + "+");
} else {
Console.WriteLine(7);
}
if (x==8) {
Console.WriteLine(8 + "+");
} else {
Console.WriteLine(8);
}
if (x==9) {
Console.WriteLine(9 + "+");
} else {
Console.WriteLine(9);
}
Possible
string temp;
temp = Console.ReadLine();
int x;
x = int.Parse(temp);
if (x==0) {
Console.WriteLine("0+n1n2n3n4n5n6n7n8n9");
}
if (x==1) {
Console.WriteLine("0n1+n2n3n4n5n6n7n8n9");
}
if (x==2) {
Console.WriteLine("0n1n2+n3n4n5n6n7n8n9");
}
if (x==3) {
Console.WriteLine("0n1n2n3+n4n5n6n7n8n9");
}
if (x==4) {
Console.WriteLine("0n1n2n3n4+n5n6n7n8n9");
}
if (x==5) {
Console.WriteLine("0n1n2n3n4n5+n6n7n8n9");
}
if (x==6) {
Console.WriteLine("0n1n2n3n4n5n6+n7n8n9");
}
if (x==7) {
Console.WriteLine("0n1n2n3n4n5n6n7+n8n9");
}
if (x==8) {
Console.WriteLine("0n1n2n3n4n5n6n7n8+n9");
}
if (x==9) {
Console.WriteLine("0n1n2n3n4n5n6n7n8n9+");
}
I give a similar task in advance, during the study of branching.
If the student has arrived at a 'possible' option, then it's important to explain that there can be multiple solutions to the same problem. However, they differ in their resilience to changing requirements. Ask the question: 'How many places in the code will need to be fixed if we have to add one more number?' In the 'possible' option, an additional branch will need to be added and the new number written in 10 different places. In the 'desired' option, only one additional branch needs to be added.
Set the task to reproduce the 'desired' option, then find the pattern in the code, perform the variable replacement, and write a loop.
If you have an idea on how to solve this task without a loop in some other way, please write it in the comments.
Loops within loops
In this topic, it's important to note that:
— counters for the inner and outer loops must be different variables.
— the counter for the inner loop needs to be reset multiple times (i.e., in the body of the outer loop).
In tasks involving text output, you cannot start by printing one character in several lines and then the second. You need to output all the characters of the first line first, then all the characters of the second line, and so on.
It's best to start the explanation of the topic on loops within loops by explaining the importance of resetting the counter.
Example task:
The user inputs two numbers: R and T. Output two lines of the symbol "#". The first line should have R characters. The second line should have T characters. If any number is negative, output an error message.
R=5, T=11#####
###########
R=20, T=3####################
###
R=-1, T=6The value of R must be non-negative.
R=6, T=-2The value of T must be non-negative.
It is clear that this task also has at least two possible solutions.
Desired
string temp;
int R;
int T;
temp = Console.ReadLine();
R = int.Parse(temp);
temp = Console.ReadLine();
T = int.Parse(temp);
int i = 0;
while (i < R)
{
Console.Write("#");
i = i + 1;
}
Console.WriteLine();
i = 0;
while (i < T)
{
Console.Write("#");
i = i + 1;
}
Option #1
string temp;
int R;
int T;
temp = Console.ReadLine();
R = int.Parse(temp);
temp = Console.ReadLine();
T = int.Parse(temp);
int i = 0;
while (i < R)
{
Console.Write("#");
i = i + 1;
}
Console.WriteLine();
int j = 0;
j = 0;
while (j < T)
{
Console.Write("#");
j = j + 1;
}
The difference is that in the "possible" solution for outputting the second line, a second variable was used. It is necessary to insist on using the same variable for both loops. This restriction can be justified by the fact that a solution with one counter for two loops will illustrate the term "resetting the counter." Understanding this term is essential when solving subsequent problems. As a compromise, both solutions to the task can be retained.
A typical problem with using one counter variable for two loops manifests itself like this:
R=5, T=11#####
######
The number of characters in the second line does not correspond to the value of T. If help is needed with this problem, one should "point out" the notes on common problems with loops. This is symptom #3. It can be diagnosed by adding the output of the counter value right before the second loop. It is fixed by resetting. However, it is better not to reveal this immediately. The student should try to formulate at least one hypothesis.
Of course, there is another option for solving it. But I have never seen it from students. At the stage of learning loops, discussing it would distract attention. It can be returned to later when studying functions that work with strings.
Option #2
string temp;
int R;
int T;
temp = Console.ReadLine();
R = int.Parse(temp);
temp = Console.ReadLine();
T = int.Parse(temp);
Console.WriteLine(new String('#', R));
Console.WriteLine(new String('#', T));
The next mandatory task:
Display the numbers from 0 to 9 on the screen. Each number should be on a new line. The number of digits per line (W) is input via the keyboard.
W=10
1
2
3
4
5
6
7
8
9
W=100000000000
1111111111
2222222222
3333333333
4444444444
5555555555
6666666666
7777777777
8888888888
9999999999
If the student has mastered the variable replacement technique, they will manage quite quickly. The possible issue again will be the variable reset. If they are struggling with the conversion, it means they rushed, and should work on simpler tasks.
Thank you for your attention. Please like and subscribe to the channel.
P.S. If you find typos or errors in the text, please let me know. You can do this by highlighting part of the text and pressing '⌘ + Enter' on Mac or 'Ctrl / Enter' on classic keyboards, or through personal messages. If these options are unavailable, please report errors in the comments. Thank you!
Only registered users can participate in the survey. , please.
Survey for readers without karma
20,0%I teach professionally, +12
10,0%I teach professionally, -11
70,0%I do not teach, +17
0,0%I do not teach, -10
0,0%Other0
10 users have voted. 5 users abstained.
Source: habr.com
