-1

This program takes the name of the course, grade and the number of units of a course to calculate the grade point average. I want the program to exit the while loop after the user enters the letter q and display the phrase outside the loop.

#include <iostream>
using namespace std;
int main()
{
    char name[20];
    float unit;
    float score;
    float avg = 0;
    float total = 0;
    int q=0, c=0;
    
    while (name[20]!= q)

    {
        
            cout << "Enter a Name";
            cin >> name;
            cout << "Enter  score";
            cin >> score;
            cout << "Enter unit of surce";
            cin >> unit;
            avg = avg + score * unit;
            total = total + unit;

            cout << "cantinue(c) or break(q)";
            cin >> name[20];
        
        
    }

    avg = avg / total;
    cout << "gpa :" << " " << avg;



    return 0;
}


sebap123
  • 2,541
  • 6
  • 45
  • 81
Eli Sh
  • 1
  • 2

1 Answers1

0

Problem:

  1. You're comparing a char with an int variable called q. That won't break the loop when the user enters 'q', it will break the loop when the player enters the character that corresponds to the value that the q variable stores (in your case it is probably 0 in ASCII that is '\0').
  2. Additionally, you're accessing a variable that is out of the bonds of the array which is Undefined Behaviour. You should write name[19] instead.

Solution:

Compare name[19] to 'q' instead.

while(name[19] != 'q')
...
std::cin >> name[19];

Additional information:

  1. using namespace std; is considered a bad practice (More info here).
  2. During the first check of the while condition your char variable is uninitializated, which will result in Undefined Behaviour. Solve this initialazing it to some value or using a do while loop instead;
  3. I would recommend to create an additional char variable to store the character that controls the exit.

Full code:

#include <iostream>

int main()
{
    char name[20];
    float unit;
    float score;
    float avg = 0;
    float total = 0;
    char quit;

    do
    {
            std::cout << "Enter a Name: ";
            std::cin >> name;
            std::cout << "Enter  score: ";
            std::cin >> score;
            std::cout << "Enter unit of source: ";
            std::cin >> unit;
            avg = avg + score * unit;
            total = total + unit;

            std::cout << "Continue(c) or break(q): ";
            std::cin >> quit;
    } while(quit != 'q');
    avg = avg / total;
    std::cout << "gpa :" << " " << avg;
    return 0;
}

Gary Strivin'
  • 908
  • 7
  • 20