Освой самостоятельно С++ за 21 день.
Шрифт:
Контрольные вопросы
1. Можно ли в цикле for инициализировать сразу несколько переменных-счетчиков?
2. Почему следует избегать использование оператора goto?
3. Можно ли с помощью оператора for организовать цикл, тело которого не будет выполняться?
4. Можно ли организовать цикл while внутри цикла for?
5. Можно ли организовать цикл, который никогда не завершится? Приведите
6. Что происходит при запуске бесконечного цикла?
Упражнения
1. Каким будет значение переменной x после завершения цикла for (int x = 0; x < 100; x++)?
2. Создайте вложенный цикл for, заполняющий нулями массив размером 10x10.
3. Организуйте цикл for, счетчик которого изменяется от 100 до 200 с шагом 2.
4. Организуйте цикл while, счетчик которого изменяется от 100 до 200 с шагом 2.
5. Организуйте цикл do...while, счетчик которого изменяется от 100 до 200 с шагом 2.
6. Жучки: найдите ошибку в приведенном фрагменте программы.
int counter = 0;
while (counter < 10)
{
cout << "counter: " << counter;
}
7. Жучки: найдите ошибку в приведенном фрагменте программы.
for(int counter = 0; counter < 10; counter++);
cout << counter << " ";
8. Жучки: найдите ошибку в приведенном фрагменте программы.
int counter = 100;
while (counter < 10)
{
cout << "counter: " << counter;
counter--;
}
9. Жучки: найдите ошибку в приведенном фрагменте программы.
cout << "Enter а number between 0 and 5: ";
cin >> theNumber;
switch (theNumber)
{
case 0:
doZero;
case 1: // идем дальше
case 2: // идем дальше
case 3: // идем дальше
case 4: // идем дальше
case 5:
doOneToFive;
break;
default:
doDefault;
break;
}
Подведение итогов
Листинг. Итоги первой недели
1: #include <iostream.h>
2: intintboolfalsetrue
3: enum CHOICE { DrawRect = 1, GetArea,
4: GetPerim, ChangeDimensions, Quit} ;
5: // Объявление класса Rectangle
6: class Rectangle
7: {
8: public:
9: // constructors
10: Rectangle(int width, int height);
11: ~Rectangle;
12:
13: //
14: int GetHeight const { return itsHeight; }
15: int GetWidth const { return itsWidth; }
16: int GetArea const { return itsHeight * itsWidth; }
17: int GetPerim const { return 2*itsHeight + 2*itsWidth; }
18: void SetSize(int newWidth, int newHeight);
19:
20: // Прочие методы
21:
22:
23: private:
24: int itsWidth;
25: int itsHeight;
26: };
27:
28: // Выполнение методов класса
29: void Rectangle::SetSize(int newWidth, int newHeight)
30: {
31: itsWidth = newWidth;
32: itsHeight = newHeight;
33: }
34:
35:
36: Rectangle::Rectangle(lnt width, int height)
37: {
38: itsWidth = width;
39: itsHeight = height;
40: }
41:
42: Rectangle::~Rectangle { }
43:
44: int DoMenu;
45: void DoDrawRect(Rectangle);
46: void DoGetArea(Rectangle);
47: void DoGetPerim(Rectangle);
48:
49: int main
50: {
51: // Инициализация объекта rectangle значением 30,5
52: Rectangle theRect(30,5);
53:
54: int choice = DrawRect;
55: int fQuit = false;
56:
57: while (!fQuit)
58: {
59: choice = DoMenu;
60: if (choice < DrawRect || choice > Quit)
61: {
62: cout << "\nInvalid Choice, please try again.\n\n"
63: continue;
64: }
65: switch (choice)
66: {
67: case DrawRect:
68: DoDrawRect(theRect);
69: break;
70: case GetArea:
71: DoGetArea(theRect);
72: break;
73: case GetPerim:
74: DoGetPerim(theRect);
75: break;
76: case ChangeDimensions:
77: int newLength, newWidth;
78: cout << "\nNew width: ";
79: cin >> newWidth;
80: cout << "New height: ";
81: cin >> newLength;
82: theRect.SetSize(newWidth, newLength);
83: DoDrawRect(theRect);
84: break;
85: case Quit:
86: fQuit = true;
87: cout << "\nExiting...\n\n";
88: break;