Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ while loop not starting [closed]

Tags:

c++

while-loop

So the idea is to ask the user for each element of the array, but after an input is given for the first question (where it asks for the amount of elements), nothing happens. Can't figure out 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;   
}
like image 786
CptJohnMiller74 Avatar asked Mar 11 '23 02:03

CptJohnMiller74


2 Answers

The constuction while (true); means while (true) {} (i.e. infinite loop).

So, when you write

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

you have the following:

while (gradeCount < numGrades)
{
}

{
  // ...
}

Second block will never be executed if gradeCount < numGrades.

like image 184
Ilya Avatar answered Mar 15 '23 18:03

Ilya


You are using

while (gradeCount < numGrades);

with a semi-colon (;) at the end of this line so the next line will not exectue because the condition is always true as there is no increment or decrement in the respective variables.

In short just remove the (;)

while (gradeCount < numGrades)
like image 43
Ahsan Avatar answered Mar 15 '23 19:03

Ahsan