Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

} // end foreach Console.WriteLine(); Console.WriteLine();

Console.WriteLine("Please press enter key to continue");

Console.ReadLine();

} // end main } // end class

}// end namespace

As you can see, this program has three for loops. Each for loop demonstrates a different variation of the basic for loop.

Skipping Numbers

The first loop in this program counts by 5’s to 100 by slightly changing the parts of the for loop statement. In this program, I use the lowercase i as a counting variable.

In the Real World

Although I have told you in other places that 1 is a bad character variable name, there is a grand tradition regarding the use of i as a for loop sentry variable, especially if that variable will not be used for anything else. The use of i in this situation goes all the way back to the earliest versions of FORTRAN, where integer variables had to start with the letters i, j, and so on. Even programmers who have never written any significant code in FORTRAN (like me) follow the tradition and frequently use i as a generic counting variable. For such a young endeavor, computer programming has a rich history.

The key line for making the program count to 100 by 5’s is

for(i = 0; i <= 100; i += 5){

It means “start i at 0, keep going as long as i is less than or equal to 100, and add 5 to i each time through the loop." The += syntax is similar to the ++ syntax but allows you to add any value to a variable. Therefore,

i += 5;

is the same as

i = i + 5;

but the first version is easier to type. Programmers are lazy, so they prefer the more concise syntax.

Counting Backwards

When you understand the basic mechanics of the for loop, it isn’t much of a surprise that you can make a loop go backwards. However, you must be careful because a couple things have to change to make a backwards loop. The line that looks like

for(i = 10; i > 0; i−−){

64

Соседние файлы в предмете Программирование на C++