C ++ while loop does not start

So, the idea is to ask the user about each element of the array, but after entering the input for the first question (where he asks for the number of elements) nothing happens. I can’t understand why.

#include <iostream>

int main()
{
        int numGrades;
        tryAgain:
        std::cout << "Enter number of grades" << std::endl;
        std::cin >> numGrades;

            if (numGrades > 30)
                {
                std::cout << "Please enter a valid number of grades" << std::endl;
                goto tryAgain;
                }


        int grades[numGrades - 1];
        int gradeCount = 0;
        while (gradeCount < numGrades);
            {
            std::cout << "Enter grade number" << gradeCount + 1 << ":";
            std::cin >> grades[gradeCount];

            ++ gradeCount;
            }   

        std::cout << grades;
        return 0;   
}
+4
source share
3 answers

Construction while (true);means while (true) {}(i.e., an infinite loop).

So when you write

while (gradeCount < numGrades);
{
  // ...
}

you have the following:

while (gradeCount < numGrades)
{
}

{
  // ...
}

The second block will never be executed if gradeCount < numGrades.

+6
source

You're using

while (gradeCount < numGrades);

with a semicolon (;) at the end of this line so that the next line does not exit, because the condition is always true, since there is no increment or decrement in the corresponding variables.

(;)

while (gradeCount < numGrades)
+1

Please check out this code, there were few problems. One of them is a semicolon, and the second is printing gradesand memory allocation grades. A constant memory value must have a constant value. A dynamic allocation is added here, since the number of classes is not fixed or constant ... Here is the code:

#include <iostream>

int main()
{
        int numGrades;
        tryAgain:
        std::cout << "Enter number of grades" << std::endl;
        std::cin >> numGrades;

            if (numGrades > 30)
                {
                std::cout << "Please enter a valid number of grades" << std::endl;
                goto tryAgain;
                }



        int *grades = (int *)malloc(numGrades * sizeof(int)); //allocating dynamic memory

        int gradeCount = 0;
        while (gradeCount < numGrades)
            {
            std::cout << "Enter grade number" << gradeCount + 1 << ":";
            std::cin >> grades[gradeCount];

            ++ gradeCount;
            }   


        for(int i =0;i<numGrades;i++)
        {
            std::cout << grades[i] << std::endl;
        }

        free(grades);//releasing memory

        return 0;   
}
0
source

Source: https://habr.com/ru/post/1655020/


All Articles