Once you begin to tasks, therefore already know what for loop. Let's look at a few of the tasks, solution in which it is applied, and, thereby, strengthen the knowledge gained. Programming practice– the best way to deal with the material and store information for a long time.
1. Write a program, that will show on the screen the number of the square, entered by the user. The user has to decide for himself – exit the program or continue writing. (Tip – You must run an infinite loop, which provide for termination of his, upon the occurrence of certain conditions).
Show code
Задача: оператор for 1
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
usingnamespacestd;
intmain()
{
setlocale(LC_ALL,"rus");
intdigit=0;// число для расчета
charexit='y';// для выхода или продолжения
for(;;)
{
cout<<"Введите число: ";
cin>>digit;
cout<<"Квадрат "<<digit<<" = "<<digit*digit;
cout<<"\nПродолжить ввод чисел - Y, Выйти - N: ";
cin>>exit;// выбор пользователя
if(exit!='y'&&exit!='Y')
break;// прервать цикл
}
return0;
}
В задаче, as you can see, provided for continuation of the work, вне зависимости в каком регистре введена буква Y (в нижнем или в верхнем).
Result:
2. In the gym every day comes a certain number of visitors. It should prompt the user to enter such data: how many people visited the gym for the day, enter the age of each visitor and ultimately show the age of the oldest and the youngest of them, as well as to calculate the average age of visitors.
Show code
Задача: оператор for 2
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
usingnamespacestd;
intmain()
{
setlocale(LC_ALL,"rus");
intage=0;// будет вводить пользователь
intmaxAge=0;// для записи максимального количества лет
intminAge=100;// для записи минимального количества лет
intsum=0;// общая сумма для расчета среднего
intaverage=0;// для записи среднего возраста посетителей
intamount=0;// количество посетителей спортзала
cout<<"Введите количество посетителей спортзала: ";
cin>>amount;
for(inti=0;i<amount;i++)
{
cout<<"Введите возраст "<<i+1<<"-го посетителя: ";// запрос на введение числа
cin>>age;
if(age>maxAge)// если оно больше, чем хранит переменная max
maxAge=age;// записываем в неё это число
if(age<minAge)
minAge=age;
sum+=age;// накопление общей суммы
}
average=sum/amount;// подсчет среднего возраста
cout<<"\nСредний возраст всех посетителей: "<<average<<endl;
cout<<"\nСамый взрослый: "<<maxAge<<endl;
cout<<"\nСамый молодой: "<<minAge<<endl;
return0;
}
The variable min we initialized value 100, so the program can work properly. If it was initialized value 0, conditionif (age < minAge) would not satisfy the ever, asage is always more 0. Thus the value of variable minAge would always remain zero.
Result:
For the job yourself, We offer you to solve a similar task. Arrange the number of visitors entering the gym and the number of hours spent by each of them in the gym. As a result, calculate and display the total amount, which customers have paid for training.
3. In stock has a certain number of boxes of apples (in this example, 15). When the car arrives for pickup, ask the user to enter, how many boxes loaded into the first car, the second and so on, until there are no more boxes of apples. Provide case, When the user enters the number of boxes more, than there is in stock.
Show code
Задача: оператор for 3
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
usingnamespacestd;
intmain()
{
setlocale(LC_ALL,"rus");
intboxWithApples=15;// количество ящиков на складе
intamountBoxesForSale=0;// количество отгружаемых ящиков
cout<<"Сейчас на складе "<<boxWithApples<<" ящиков с яблоками.\n\n";
for(inti=1;;i++)// счетчик i будет считать количество машин к погрузке
{
cout<<"Сколько ящиков загрузить в "<<i<<"-ю машину? ";
cin>>amountBoxesForSale;
if(amountBoxesForSale>boxWithApples)
{
cout<<"\nНа складе недостаточно товара!";
cout<<"Осталось только "<<boxWithApples<<" ящиков\n\n";
i--;// уменьшить счетчик на единицу
}
else
{
boxWithApples-=amountBoxesForSale;// перезаписываем значение
cout<<"Осталось "<<boxWithApples<<" ящиков.\n";
}
if(boxWithApples==0)// если ящиков больше нет - выйти из цикла
{
cout<<"Яблоки закончились! Давай до свидания!\n";
break;
}
}
return0;
}
"I" count in string 21 reduced per unit, so that the next iteration of the loop to show the correct serial number of the machine.
Result:
If you have questions, please contact us in the comments.
4.4
48
161 thoughts on “Tasks: A for loop in c ++”
my second task #include using namespace std; int main() { int chelovek;//буду вводить кол во человек int vozrast;// буду вводить возраст int ma=0;// максимум int mi=100;// минимум int sr=0;//подсчёт суммы int sr1=0;//среднее
if (vozrast>ma)//если возраст больше максимума, отобразиться первое после ноля ma=vozrast; if (vozrast<mi)//если возраст меньше минимума, отобразиться первое число от 100, при условии что возраст не превышает 100 mi=vozrast; sr+=vozrast;//подсчитываю сумму
Additional task assignment 2. I have a question. I really wanted to enter the name of each visitor and then the hours, but it doesn't work with the name. #include using namespace std; int main() { int chelovek;//буду вводить кол во человек float chasi;//количество часов float sum=0;//объявляю сумму
cout<<chelovek;
for(int i=1;i<=chelovek;i++) { cout<< "posetitel "<< i <>chasi;
slightly reworked problem 3. The number of boxes in it is not fixed. #include using namespace std; int main() { int apple=0; int vvod=0; int sum=0; int itog=0; int um=0;
cout<< apple;
for (int i=1; ;i++) { cout<<"vvedite kolihestvo dla mashinu "<<" "<< i<> vvod; sum=vvod+sum;
And this is how I solved the 3rd problem int main() { setlocale(0, ""); int jas, vv, n=0; cout << jas; for (; jas != 0 ;) { cout << vv; if (vv > jas) { cout << "Так не пойдет, ящиков меньше!\n"; cout << "Их осталось " << jas << "\n"; } else { jas -= vv; n++; } } cout << "Молодец! Ты погрузил все ящики в " << n << " грузовиков\n"; return 0; }
People, explain who can. I don’t understand the logic behind the for loop (int i = 0; i < amount; i ) in the second problem. I.e, чем является переменная "i" и почему "i < amount".
my second task
#includeusing namespace std;
int main()
{
int chelovek;//буду вводить кол во человек
int vozrast;// буду вводить возраст
int ma=0;// максимум
int mi=100;// минимум
int sr=0;//подсчёт суммы
int sr1=0;//среднее
cout<<chelovek;
for(int i=1;i<=chelovek;i++)
{
cout<<"vvedite vozrst heloveka "<< i<>vozrast;
if (vozrast>ma)//если возраст больше максимума, отобразиться первое после ноля
ma=vozrast;
if (vozrast<mi)//если возраст меньше минимума, отобразиться первое число от 100, при условии что возраст не превышает 100
mi=vozrast;
sr+=vozrast;//подсчитываю сумму
}
sr1=sr/chelovek;//считаю среднее
cout<<"Samiy starshiy "<<endl;
cout<<ma<<endl;
cout<<"Samiy mladshiy"<< endl<<mi<<endl;
cout <<"sredniy vozrast"<<endl<<sr1<<endl;
return 0;
}
Additional task assignment 2.
I have a question.
I really wanted to enter the name of each visitor and then the hours, but it doesn't work with the name.
#includeusing namespace std;
int main()
{
int chelovek;//буду вводить кол во человек
float chasi;//количество часов
float sum=0;//объявляю сумму
cout<<chelovek;
for(int i=1;i<=chelovek;i++)
{
cout<< "posetitel "<< i <>chasi;
sum=sum+chasi;
}
cout<<"obshaya summa chasov "<< sum;
return 0;
}
slightly reworked problem 3. The number of boxes in it is not fixed.
#includeusing namespace std;
int main()
{
int apple=0;
int vvod=0;
int sum=0;
int itog=0;
int um=0;
cout<< apple;
for (int i=1; ;i++)
{
cout<<"vvedite kolihestvo dla mashinu "<<" "<< i<> vvod;
sum=vvod+sum;
if(sum>apple)
{
itog=sum-apple;
cout<<"prosti drug,no ne vlazit "<< itog <<" yashikov ";
break;
}
}
return 0;
}
int stock = 5;int car = 0;
for (;;)
{
CAR : cout << car;
if (car > stock)
{
cout << "Данное количество нет на складе! \n";
goto CAR;
}
stock -= car;
cout << "Остаток: " << stock << endl;
if (stock == 0)
{
cout << "Яблоки закончились! \n";
break;
}
}
int main(){
setlocale(LC_ALL, "rus");
int number = 0;
int result = 0;
WELCOME : cout << number;
result = number * number;
cout << result << endl;
goto WELCOME;
}
int main(){
setlocale(LC_ALL, "rus");
int number = 0;
int result = 0;
bool choise = true;
for (;;)
{
AGAIN : cout <> number;
result = number * number;
cout << "Ваш результат: " << result << endl;
cout << choise;
if (!(choise == 0))
{
break;
}
}
}
And this is how I solved the 3rd problem
int main(){
setlocale(0, "");
int jas, vv, n=0;
cout << jas;
for (; jas != 0 ;)
{
cout << vv;
if (vv > jas)
{
cout << "Так не пойдет, ящиков меньше!\n";
cout << "Их осталось " << jas << "\n";
}
else
{
jas -= vv;
n++;
}
}
cout << "Молодец! Ты погрузил все ящики в " << n << " грузовиков\n";
return 0;
}
People, explain who can.
I don’t understand the logic behind the for loop (int i = 0; i < amount; i ) in the second problem.
I.e, чем является переменная "i" и почему "i < amount".