The basics of programming in c++ for beginners

Tasks: A for loop in c ++

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).

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.

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.

If you have questions, please contact us in the comments.

161 thoughts on “Tasks: A for loop in c ++

  1. Guys!You are welcome, help with a problem about clock athletes! I can not sum up a total payment of all athletes

    #include
    using namespace std;

    int main()
    {
    setlocale(LC_ALL, "rus");
    int visitors = 0;
    int number_for_hours = 0;
    int money = 100;
    int sum;

    cout << visitors;

    for (int i = 0; i < visitors; i++)
    {

    cout << i + 1 << number_for_hours;
    cout << endl;
    cout << "Оплата " << i + 1 << " посетителя: " << number_for_hours*money<<endl;

    }
    sum = number_for_hours*money;
    sum += sum;

    cout << "Всего оплата: " << sum;

    _getchar_nolock();
    _getchar_nolock();
    return 0;
    }

    1. You're a little beguiled cin and cout. ))
      And some things left out. See code:

      #include
      using namespace std;

      int main()
      {
      setlocale(LC_ALL, "rus");
      int visitors = 0;
      int number_for_hours = 0; // для ввода часов каждого посетителя
      int final_hours = 0; // счетчик для накопления общего кол-ва часов
      int money = 100;
      int sum;
      cout < < "Введите кол-во посетителей за день: "; cin >> visitors; // ввод кол-ва посетителей

      for (int i = 0; i < visitors; i++) { cout << i + 1 << "-й посетитель провел в спортзале (часов): "; cin >> number_for_hours;
      final_hours += number_for_hours;
      //cout < < "Оплата " << i + 1 << " посетителя: " << number_for_hours*money << endl; // благодаря счетчику final_hours - єта строка не нужна // посчитаем ниже } sum = final_hours * money; cout << "Всего оплата: " << sum << endl; return 0; }

  2. Why do i initiate zero? Do write i = 1 is not easy? It affected and the first example in a lesson

    1. You can write and i = 1 (with equal success) … like any other value.

      In the language C / C ++ usage zero The initial value for a for loop is, rather, tradition, habit of programmers.
      This is because, that indexation arrays begin with 0, for a cycle in most cases (more often) It is used to move through the array.

  3. #include
    #include

    using namespace std;

    int main() {
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);

    int size;
    int tmp;
    int min = 0;
    int max = 0;
    int middle;
    int count = 0;

    cout <> size;
    cout << endl;
    if (size <= 0) cout << "Ошибка количество поситетелей не может быть равна нулю или меньше нуля" << endl;
    else {
    for (int i = 0; i < size; i ) {
    cout << "Введите возраст " << i + 1 <> tmp;
    if (tmp max || !max) max = tmp;
    count += tmp;
    }
    cout << endl;

    if (size == 1) cout << "Сегодня был всего один посетитель его возраст был " << min << " years" << endl;
    else {
    cout << "Спорт зал сегодня посетило: " << size << " visitor" << endl;
    cout << "Самому младшему посетителю " << min << " years" << endl;
    cout << "Самому старшему посетителю " << max << " years" << endl;
    cout << "Средний возраст посетителей " << count / size << " years" << endl;
    }
    }

    return 0;
    }

  4. Please tell me if that's you can solve the task with the payment of the gym?

    #include;

    using namespace std;

    int main()
    {
    setlocale(LC_ALL, ".1251");

    int i = 0;
    int AllPeople = 0;
    int money = 10;
    int hour = 0;
    int SumMoney = 0;
    int SumHour = 0;

    cout <> AllPeople;

    for (i = 0; i < AllPeople; i++)
    {
    cout << "\nВведите количество проведенных в спортзале часов для " << i + 1 <> hour;
    }
    SumHour = AllPeople*hour;
    SumMoney = money*SumHour;

    cout << "\nОбщее время тренировок равно " << SumHour <<endl;
    cout << "\nОбщая сумма за все тренировки посетителей равна " << SumMoney << "$" << endl;

    system("PAUSE");
    return 0;
    }

  5. On 10 cut lines to your code 3 task)

    #include
    using namespace std;

    int main()
    {
    setlocale(LC_ALL, "rus");
    int boxes(0);
    int amount;
    cout < 0; boxes -= amount, i++) {
    cout << "\nСколько ящиков погрузить в " << i + 1 <> amount;
    if (boxes > amount)
    cout << "Осталось коробок: " << boxes - amount < boxes) {
    cout << "Недопустимое количество. Введите еще раз\n";
    cout << "Сколько ящиков погрузить в " << i+1 <> amount;
    cout << "Осталось коробок: " << boxes - amount << endl;
    }
    };
    if (boxes == 0)
    cout << "\nKоробки закончились!\n\n";
    system("pause");
    return 0;
    }

  6. Sorry, the first time as the unsuccessful copied(

    #include
    using namespace std;

    int main()
    {
    setlocale(LC_ALL, "rus");
    int boxes(0);
    int amount;
    cout < 0; boxes -= amount, i++) {
    cout << "\nСколько ящиков погрузить в " << i + 1 <> amount;
    if (boxes > amount)
    cout << "Осталось коробок: " << boxes - amount < boxes) {
    cout << "Недопустимое количество. Введите еще раз\n";
    cout << "Сколько ящиков погрузить в " << i+1 <> amount;
    cout << "Осталось коробок: " << boxes - amount << endl;
    }
    };
    if (boxes == 0)
    cout << "\nKоробки закончились!\n\n";
    system("pause");
    return 0;
    }

  7. Regarding the second objective, – я в цикл for добавил 3-ее условие. Если i равен 0, то minAge присвоить age. При этом minAge инициализируется у меня числом 0, but not 100. Это сделано затем, что не понятно откуда берётся магическое число 100. А если человеку, let us say, 105 years? Ведь есть люди, живущие больше 100 years. С таким числом при вашем подходе условие не будет выполняться. Насколько долго должны жить люди судя программедругой вопрос. Можно загуглить возраст самого долгоживущего и поставить его возраст как предел.

  8. после повтора в программе не выходя из нее не обнуляется переменная как мне кажется coast как ее обнулить ?

Leave a Reply

Your email address will not be published. Required fields are marked *