How to teach to overcome difficulties, and at the same time write cycles

Despite the fact that we will talk about one of the basic topics, this article is written for experienced professionals. The goal is to show what misconceptions beginners in programming have. For practicing developers, these problems have long been solved, forgotten or not noticed at all. The article may come in handy if suddenly you have to help someone with this topic. The article draws parallels with material from various books on programming by Schildt, Stroustrup, Okulov.

The topic about cycles was chosen because quite a lot of people are eliminated on it when mastering programming.

This technique is designed for weak students. As a rule, the strong ones do not get stuck on this topic and there is no need to invent special methods for them. The secondary goal of the article is to transfer this technique from the class “works for all students, but only for one teacher” to the class “works for all students, all teachers”. I do not claim absolute originality. If you are already using a similar methodology to teach this topic, please write how your version differs. If you decide to apply, tell us how it went. If a similar technique is described in some book, please write the title.


I worked out this technique for 4 years, working individually with students of different levels of training. In total, about fifty students and two thousand hours of classes. At first, students were forever stuck on this topic and left. After each student, the methodology and materials were adjusted. For the past year, students have not been stuck on this topic, so I decided to share my best practices.

Why so many letters? Cycles are elementary!

As I wrote above, for practicing developers and for strong students, the complexity of the concept of cycles can be underestimated. For example, you can arrange a long lecture, see nodding heads and intelligent eyes. But when you try to solve some problem, a stupor and inexplicable problems begin. After the lecture, the students probably had only a partial understanding. The situation is aggravated by the fact that students themselves cannot voice what exactly their delusion is.
One day I realized that students perceive my examples as hieroglyphs. That is, as indivisible pieces of text in which you need to add some kind of “magic” letter and it will work.
Sometimes I noticed that students think that in order to solve a particular problem, some other construction that I just haven't told yet. Although the solution required only a slight modification of the example.

So I came up with the idea that the focus should not be on the syntax of expressions, but on the idea of ​​refactoring repetitive code with loops. Once students master this idea, then any syntax is pulled up with small exercises.

Who and why do I teach?

Since there are no entrance exams, there can be both strong and very weak students in the classroom. You can read more about my students in the article Portrait of students of evening courses
I strived to ensure that programming was mastered by everyone who wants it.
My classes are held individually and the student pays his own money for each. It would seem that students will optimize costs and demand a minimum. However, people go to face-to-face classes with a live teacher not for the knowledge itself, but for the confidence that they have learned, for a sense of progress and for approval from an expert (teacher). If students do not feel progress in their learning, they will leave. In general, classes can be structured in such a way that students feel progress in increasing the number of familiar structures. That is, first we study in detail while, then we study for, then do while, and now we have a course for a thousand and one nights, in which only cycles are studied for two months, and at the end - a student who wrote the standard library under dictation. However, in order to solve practical problems, one needs not only knowledge of the material, but also independence in its application and in the search for new information. Therefore, for full-time courses, I think the correct principle is to teach the minimum and encourage independent study of the nuances and related topics. In the topic about cycles, I consider the while construction as a minimum. On it you can understand the principle. Knowing the principle, you can master both for and do-while on your own.

To achieve mastery of the material by weak students, it is not enough to describe the syntax. It is necessary to give more simple, but varied tasks and paint examples in more detail. Ultimately, the speed of mastering is limited by the student's ability to transform expressions and search for patterns. For smart students, most assignments will be boring. When studying with them, you can not insist on solving 100% of the problems. My content can be viewed at my github. True, the repository is more like a grimoire of a warlock - no one but me will understand what is where, and if you fail the check, you can go crazy

The methodology is practice-oriented

The theory is explained by the example of solving the problem. In a programming fundamentals class that explores branches and loops, you just can't deliver a useful hour-long lecture on one topic. 15-20 minutes is enough to explain the concept. The main difficulties appear when performing practical tasks.
Beginning teachers can throw out operators, branches, loops and arrays in one lecture. But students will face the problem of assimilation of this information.
After all, it is necessary not only to tell the material, but also to make sure that the listeners understand it.

The fact of mastering the topic is determined by how the student copes with independent work.
If a student managed to solve a problem on a topic without the help of a teacher, then the topic has been mastered. To provide self-checking, each task is described by a table with test scenarios. Tasks have a pronounced order. It is not recommended to skip tasks. If the current task is too difficult, then it is useless to move on to the next one. She's even more difficult. In order for the student to master the current complex task, several techniques are explained to him using the example of the first task. Actually, the whole content of the topic comes down to methods of overcoming difficulties. Cycles are more of a side effect.

The first task is always an example. The second one differs slightly and is performed "independently" immediately after the first under the supervision of a teacher. All subsequent tasks are aimed at paying attention to various little things that can cause confusion.

The explanation of the example is a dialog in which the student needs to call back propagation and cross-validation to make sure that they have mastered a portion of the material.

I will be banal and declare that the first example on the topic is very important. If there is material for extensive independent work, the omissions of the first example can be corrected. If there is nothing else besides the example, then the student most likely will not master the topic.

while or for?

One of the controversial issues is the choice of construction for an example: while or for. One day, a practicing developer friend with no teaching experience spent an hour trying to convince me that the for loop was the easiest to understand. The arguments boiled down to "everything is clear in it and laid out in places." However, the root cause of the difficulties of real beginners is in the very idea of ​​\uXNUMXb\uXNUMXbthe cycle, and not in writing it. If a person does not understand this idea, then he will have difficulties with syntax. As soon as the idea is realized, then the problems of code design disappear by themselves.

In my materials, the theme of cycles follows the theme of branching. The external similarity of if and while allows us to draw a direct analogy: "when the condition in the heading is true, then the body is executed." The peculiarity of the cycle is only that the body is executed many times.

My second argument is that while requires less styling than for. Less formatting means fewer stupid mistakes with missing commas and brackets. Beginners are not yet so attentive and meticulous as to automatically avoid syntactical errors.
The third argument is that many good books explain while first.

If the student can easily transform expressions, then you can talk about for in passing. The student then chooses what he likes best. If the transformations cause difficulties, then it is better not to scatter attention. Let the student solve everything with while first. Once you've mastered the topic of loops, you can rewrite the solutions to work out the while to for conversion.
Postcondition loops are a pretty rare beast. I don't spend time on it at all. If a student has mastered the ideas of identifying patterns and transforming expressions, he will be able to figure it out without my help.

When demonstrating the first example to strong students, I draw your attention to the fact that in the first example it is important to fix not only the decision, but also the entire chain of actions that led to the result. Lazy students can neglect writing and transfer only the final algorithm to themselves. They need to be convinced that one day they will have a difficult task. To solve it, you will need to follow the steps as in this example. That is why it is important to fix all the stages. In the following tasks, it will be possible to leave only the final version of the solution.

The main idea of ​​automation is that we instruct the computer to do routine work for a person. One of the basic techniques is writing cycles. It is used when several identical repetitive actions are written in a program in a row.

Explicit is better than implicit

It may seem like a good idea in the first looping task to display some identical phrase several times on the screen. For example:

Hurrah, it works!
Hurrah, it works!
Hurrah, it works!
Hurrah, it works!
Hurrah, it works!
Hurrah, it works!
Hurrah, it works!
Hurrah, it works!

This option is bad because the output does not show the value of the counter. This is a problem for beginners. Don't underestimate her. At first, this problem was the first, and the problem of printing a series of numbers in ascending order was the second. I had to introduce additional terms "cycle N times" and "cycle from A to B", which are essentially the same thing. In order not to produce unnecessary entities, I decided to show only an example with the output of a series of numbers. Few succeed without training in learning to keep a counter in their head and simulate the behavior of a program in their head. For some students, for the first time, they encounter modeling “in the mind” precisely on the topic of cycles.
After some practice, I give the task of repeating the same text for an independent solution. If you give a visible counter first and then an invisible counter, then students have fewer problems. Sometimes the hint "do not write the counter on the screen" is enough.

How is it explained by others?

In most teaching materials on the Internet, the cycle syntax is given as part of a "lecture". For example, developer.mozilla.org (currently) describes a few more constructs along with the while loop. In this case, only the constructions themselves are given in the form of templates. The result of their launch is described in words, but there is no illustration. In my opinion, such a presentation of the topic multiplies the usefulness of such materials by zero. A student can rewrite the code and run it himself, but a benchmark is still needed for comparison. How to understand that the example is rewritten correctly if there is nothing to compare the result with?
When only a template is given, without an example, it becomes even more difficult for the student. How to understand that code fragments are placed in the template correctly? You can try to write somehowand then run. But if there is no standard for comparing the result, then the launch will not help either.

In the Intuitive C++ course, the loop syntax is buried in the third page of Lecture 4 on the topic "statements". When explaining the syntax of loops, special emphasis is placed on the term "operator". The term is presented as a set of facts like “symbol; is a statement", "{} is a compound statement", "loop body must be a statement". I don't like this approach because it kind of hides important relationships behind one term. Parsing the program source code into terms at this level is necessary for compiler developers to implement the language specification, but not for students in the first approximation. Newcomers to programming rarely have enough meticulousness to be so careful about the terms. A rare person remembers and understands new words the first time. Almost no one can correctly apply a term they have just learned. Therefore, students have a bunch of errors like “I wrote while(a<7);{, but the program does not work.”
In my opinion, at the beginning it is better to give the construction syntax immediately with parentheses. The option without brackets should be explained only if the student had a specific question “why does it work here without brackets”.

In Okulov's 2012 book Fundamentals of Programming, an introduction to loops begins with the for pattern, then gives recommendations on its use, and then immediately goes to the experimental section of the lesson. I understand that the book was written for that minority of very bright students who rarely come to my classes.

Popular books always write the result of code snippets. For example, Schildt's "Java 8. Complete Guide" 2015 edition. First, a template is given, then an example program, and immediately after it, the result of the execution.

As an example, consider a while loop that does the reverse
counting from 10, and exactly 10 lines of "bars" are output:

//Продемонстрировать применение оператора цикла while
class While {
    public static void main(String args []) {
        int n = 10;
        while (n > 0) {
            System.out.println("такт " + n);
            n--;
        }
    }
}

When run, this program outputs ten "bars" as follows:
такт 10
такт 9
такт 8
такт 7
такт 6
такт 5
такт 4
такт 3
такт 2
такт 1

The template, sample program, and output approach is also used in Javascript for Kids and in the js course at w3schools.com. The web page format even makes this example interactive.

In Stroustrup's 2016 book Principles and Practice with C++, the author goes even further. The first step is to explain what result should be obtained, and after that they show the text of the program. Moreover, as an example, they take not just a random program, but give an excursion into history. It helps to draw attention to it. “Look, this is not just some useless text. You see something meaningful."

As an example of an iteration, consider the first program executed on a stored program machine (EDSAC). It was written by David Wheeler at the Cambridge University Computer Laboratory on May 6, 1949. This program calculates and prints a simple list of squares.
0 0
1 1
2 4
3 9
4 16
...
98 9604
99 9801

Here, each line contains a number followed by a tab character ('t') and the square of that number. The C++ version of this program looks like this:

//Вычисляем и распечатываем таблицу квадратов чисел 0-99
int main()
{
    int i = 0; // Начинаем с нуля
    while(i < 100){
        cout << i << 't' << square(i) << 'n';
        ++i;
    }
}

Curiously, the syntax template is not described in this book. Stroustrup in the instructor's guide (translation) emphasizes that it respects the intelligence of its students. Perhaps the ability to identify a pattern in a few examples is considered a manifestation of such intelligence.

As I explain myself

Stroustrup's approach - describing the result, then solving the problem, and then the student's own analysis - seems to be the most thoughtful. Therefore, I decided to take it as a basis, but to tell on a less historical example - the task of displaying a "table of contents". She forms a recognizable anchor, so that later she can say “remember the task about the table of contents” and so that students remember exactly her. In my example, I tried to warn two more of the most common misconceptions. Later I will write about them in more detail.

In this task, we get acquainted with the methods of solving complex problems. The initial decision should be made primitive and simple. Well, then you can think about how to improve this solution.
Введение
Глава 1
Глава 2
Глава 3
Глава 4
Глава 5
Глава 6
Глава 7
Заключение

According to my observations, the “pattern-example-result” approach in various combinations still leads to the fact that students perceive the cycle as a hieroglyph. This was manifested in the fact that they did not understand why they should write a condition there, how to choose between i++ and i— and other seemingly obvious things. To avoid these misconceptions, the approach to the story of cycles should emphasize the meaning of repeating the same actions, and only then - shaping them with the help of a construction. Therefore, before giving the cycle syntax, you need to solve the problem "on the forehead". A primitive solution to the table of contents problem looks like this:

Console.WriteLine("Введение");
Console.WriteLine("Глава 1");
Console.WriteLine("Глава 2");
Console.WriteLine("Глава 3");
Console.WriteLine("Глава 4");
Console.WriteLine("Глава 5");
Console.WriteLine("Глава 6");
Console.WriteLine("Глава 7");
Console.WriteLine("Заключение");

How can it be improved?
Replace monotonous actions with a cycle.
What actions are repeated in a row without changes?
There are none in this snippet. However, the commands for deriving the word “Chapter” with a number are very similar to each other.
Therefore, the next step is to find the difference between the fragments. It is only in this task that everything is obvious, then not single commands will be repeated, but code blocks of 5 lines or more. You will have to search not just in the list of commands, but in branching or loop constructions.
In the example, the difference between the commands is in the number after the word "Chapter".
Once the difference is found, you need to understand the pattern of change. Is the different fragment a number? Is it constantly increasing or decreasing? How does the value of a number change between two commands side by side?
In the example, the number after the word "Chapter" increases with a step of 1. The difference is found, the pattern is revealed. Now you can replace the differing fragment with a variable.
You need to declare such a variable before the first of the repeating fragments. Such a variable is usually referred to as I or j, or something more elaborate. Its initial value must be equal to the first value displayed on the screen. In the example, the first value is 1.
What initial value should be taken to display a series of numbers "100, 101, 102, 103, 104, 105"?
The first number in this row is 100.
After each output command, you need to increase the value of this variable by 1. This unit is the change step.
What step will be in the series of numbers "100, 102, 104, 106"?
Step 2 on this row.
After replacing the differing fragment with a variable, the code will look like this:

Console.WriteLine("Введение");
int i;
i = 0;
Console.WriteLine("Глава " + i);
i = i + 1;
Console.WriteLine("Глава " + i);
i = i + 1;
Console.WriteLine("Глава " + i);
i = i + 1;
Console.WriteLine("Глава " + i);
i = i + 1;
Console.WriteLine("Глава " + i);
i = i + 1;
Console.WriteLine("Глава " + i);
i = i + 1;
Console.WriteLine("Глава " + i);
i = i + 1;
Console.WriteLine("Заключение");

After applying the “express the pattern of a variable” technique, several groups of identical actions are obtained in the code, which go in a row. Now repetitive actions can be replaced with a cycle.

The sequence of solving the problem, where you need to use cycles, consists of the following steps:

  1. Solve head-on with many separate commands
  2. Find a pattern
  3. Express the pattern of a variable
  4. Arrange as a cycle

Further, new terms are introduced so that the student does not find himself in a situation “I understand everything, but I cannot say”:
- counter - always a variable that is needed to track the number of cycle steps. Usually an integer that is compared to the limit.
- step of the counter - description of the pattern of change of the counter.
- restriction - a number or variable with which the counter is compared so that the algorithm is finite. The value of the counter changes so as to approach the limit.
- loop body - a set of commands that will be repeated. When it says “the command is written inside the loop”, they mean exactly the body.
- loop iteration - single execution of the loop body.
- loop condition - a logical expression that determines whether another iteration will be performed. (Here there may be confusion with branching constructions)
You need to be prepared for the fact that at first students will use the terms for other purposes. This applies to both the strong and the weak. Establishing a common language is an art. Now I’ll write briefly: you need to set the task “select a code fragment with <term>” and use these terms yourself correctly in a conversation.
After converting with a loop, a fragment is obtained:

Console.WriteLine("Введение");
int i = 0;
while (i < 7) {
    Console.WriteLine("Глава " + i);
    i = i + 1;
}
Console.WriteLine("Заключение");

Main misconception

One popular misconception among students is that they put actions inside the loop construct that only need to be done once. For example like this:

;
int i = 0;
while (i < 7) {
    Console.WriteLine("Введение")
    Console.WriteLine("Глава " + i);
    i = i + 1;
    Console.WriteLine("Заключение");
}

Students run into this problem all the time, both at the beginning and in more difficult tasks.
The crown hint in this case:

How many times do you need to repeat writing a command: once or many times?

The output commands for the words "Introduction" and "Conclusion", as well as the declaration and initialization of the variable i, are not like other repetitive actions. They are executed only once, so they need to be written outside the loop body.

All three stages of the solution should remain in the code, so that later you can refer to them in case of difficulties. It is enough to comment out the first two options so that they do not interfere.
The student's attention should be drawn to the following facts:
- In the loop condition, the counter and the limit are usually compared. The counter can change in the loop body, but the limit cannot. To break this rule, you need to formulate good reasons.
- Commands for displaying the words "Introduction" and "Conclusion" are outside the loop body. We need to complete them 1 time. "Introduction" - before repeating the actions, "Conclusion" - after.
In the process of consolidating this topic, mastering the following, as well as dealing with difficulties, it is useful even for strong students to ask the question: “How many times should this action be performed? One or many?

Development of additional skills

In the process of studying cycles, students are still training the skill of diagnosing and solving problems. To conduct a diagnosis, the student needs to present the desired result and compare it with the actual result. The corrective actions depend on the difference between them.
Since students at this stage still have a poor idea of ​​\uXNUMXb\uXNUMXbthe “desired” result, they can focus on test data. As a rule, no one at this stage still understands what can go wrong and how to deal with it. Therefore, I give a description of typical problems and several ways to solve them for writing in a notebook. The choice of the most suitable of them is the task of the student himself.
A record is needed to ask “did it work out as expected?”, “Which of these situations turned out now?”, “Did the applied solution help?”.

  1. The number of actions is 1 less or more than expected. Solutions:
    — increase the initial value of the counter by 1.
    — replace the strict comparison operator (< or >) with a non-strict one (<= or >=).
    — change the limit value to 1.
  2. The actions in the loop are performed without stopping, endlessly. Solutions:
    — add a command to change the counter, if it is missing.
    — fix the command to change the counter so that its value becomes closer to the limit.
    — remove the constraint change command if it is in the loop body.
  3. The number of activities in the loop is more than 1 less or more than expected. The action in the loop never executed. First you need to find out the actual values ​​of the variables just before the start of the loop. Solutions:
    — change the initial value of the constraint
    — change the initial value of the counter

Usually problem 3 is due to using the wrong variable or non-zeroing the counter.

After this explanation, the student may still have various misconceptions about how cycles work.
To dispel the most common, I give tasks:

  1. In which the limit, the initial value of the counter or the step of the counter is entered by the user.
  2. In which the value of the counter needs to be used in some arithmetic expression. Preferably with a counter in the radical expression or in the denominator, so that the difference is non-linear.
  3. In which the value of the counter is not displayed on the screen during the loop. For example, displaying the required number of identical fragments of text or drawing a figure with turtle graphics.
  4. In which you need to perform some repetitive actions first, and then others.
  5. In which you need to perform other actions before and after repeated

For each task, you need to provide test data and the expected result.

To understand how fast you can move, you need to let them read the conditions of these problems and ask: “how do they differ from the example?”, “What needs to be changed in the example in order to solve them?”. If the student answers meaningfully, then let him solve at least one in class, and the rest at home on his own. If the solution is successful, then you can start explaining about the conditions inside the cycles.
If with an independent solution to the difficulty, then you need to work out everything in class. So that the solution of the problem does not resemble drawing an owl, I recommend first solving the problem is not universal. That is, so that the solution passes the first test and does not use the loop construct. Well, then apply the transformations to achieve the universality of the solution.

Loops and branches

In my opinion, it is useful to give the topic "cycles within branches" separately. So that later you can see the difference between multiple checks of the condition and a single one.
Tasks for fixing will be about displaying numbers from A to B, which are entered by the user:
- always ascending.
- ascending or descending, depending on the values ​​of A and B.

The topic of “branching within cycles” should be moved on only after the student has mastered the techniques: “replacing a pattern with a variable” and “replacing repetitive actions with a cycle”.
The main reason for branching within loops is anomalies in patterns. In the middle, it is broken depending on the source data.
For those students who are able to search for a solution by combining simple tricks, it is enough to say “branching can be written inside loops” and give the problem “for example” completely for an independent solution.
Example task:

The user enters the number X. Display the numbers from 0 to 9 in a column and put a '+' sign in front of the number that 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 not enough to write with a cycle, then you need to achieve a universal solution to the same problem without a cycle.
You will get one of two options:
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, while studying the topic of branching.
If the student got a “possible” option, then you need to tell that there can be many solutions to the same problem. However, they differ in resistance to changes in requirements. Ask the question: “How many places in the code will need to be corrected if one more number needs to be added?” In the "possible" version, you will need to add another branch and add a new number in 10 other places. In the "desired" it is enough to add only one branch.
Set the task to reproduce the “desired” option, then find a pattern in the code, perform a variable substitution and write a loop.
If you have an idea how to solve this problem without a loop in some other way, please write in the comments.

Cycles within cycles

In this topic, you need to pay attention to the fact that:
- counters for the inner and outer loop must be different variables.
- the counter for the inner loop must be reset many times (that is, in the body of the outer loop).
- in text output tasks, you cannot first write one letter in several lines, and then the second. You must first print all the letters of the first line, then all the letters of the second, and so on.

The best way to explain the topic of loops within loops is to explain the importance of resetting the counter.
Example task:

The user enters two numbers: R and T. Output two strings of "#" characters. The first line should contain R pieces of characters. There are T pieces in the second line. If any number is negative, print an error message.

R=5, T=11#####
###########

R=20, T=3###################
# # #

R=-1, T=6R value must be non-negative

R=6, T=-2The value of T must be non-negative

Obviously, this problem also has at least two 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;
}

Possible #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, a second variable was used to output the second line. We must insist on using the same variable for both loops. This limitation can be justified by the fact that the solution with one counter for two cycles will be an illustration of the term "counter zeroing". Understanding this term is necessary when solving the following problems. As a compromise, you can keep both solutions to the problem.

A typical problem with using one counter variable for two loops appears like this:
R=5, T=11#####
# # # # # #

The number of characters in the second line does not match the value of T. If you need help with this problem, then you need to “poke your nose” in the abstract about typical problems with loops. This is symptom number 3. Diagnosed by adding the output of the counter value just before the second loop. Corrected by resetting. But it's better not to tell right away. The student must try to formulate at least one hypothesis.

There is, of course, another solution. But I have never seen him with students. At the stage of studying the cycles, the story about him will scatter attention. You can come back to it later when you study string functions.
Possible #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));

Next required task:

Display numbers from 0 to 9 on the screen. Each number should be on its own line. The number of digits per line (W) is entered from 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 technique of changing the variable, then he will cope fairly quickly. A possible problem will be again in zeroing the variable. If it does not cope with the transformation, then you are in a hurry and you need to solve simpler problems.

Thank you for your attention. Like, subscribe to the channel.

PS If you find any typos or errors in the text, please let me know. This can be done by selecting a piece of text and pressing “⌘ + Enter” on Mac, and “Ctrl / Enter” on classic keyboards, or through private messages. If these options are not available, write about the errors in the comments. Thank you!

Only registered users can participate in the survey. Sign in, you are welcome.

Poll for readers without karma

  • 20,0%I teach professionally, +12

  • 10,0%I teach professionally, -11

  • 70,0%I don't teach, +17

  • 0,0%I don't teach, -10

  • 0,0%Other0

10 users voted. 5 users abstained.

Source: habr.com

Add a comment