Calculating GPA with Loops in C++

  • Comp Sci
  • Thread starter MostlyHarmless
  • Start date
  • Tags
    C++ Loops
In summary: Please enter the credit hours for the previously entered grade: \n"; cin >> CreditHours;//Incomplete/Questionable //if (CreditHours <= 0)}if (TotalCredits > 0){//Calculating and printing the final GPA. float gpa = TotalPoints / TotalCredits; cout << "Your GPA is:"<< gpa <<endl;}return 0;}The attempt at a solution uses three loops:
  • #1
MostlyHarmless
345
15

Homework Statement



I'm to write a program that calculates GPA using loops to allow numerous inputs and using Error checking to be sure that inputs are valid.

I'm having trouble figuring out how to make my loop repeat if a the input is invalid.
And I'm also having a little trouble with the stop condition, currently I have the loop break if the user inputs -1 for both of the requested inputs, but what I wanted is for the loop to break if the Grade input is -1 and then not continue to the Credit hour input.

*I forgot to add, I'm not allowed to use arrays in this assignment.*

Homework Equations


The Attempt at a Solution



Code:
#include <iostream>
using namespace std;
int main ()

{

//Defining variables that will be used during code.
float CreditHours;
int LetterGrade;
float Total;
float TotalCredits = 0;
float TotalPoints = 0;
//Asking for input from user

 cout <<"Please enter the grade for your class: 4 for A, 3 for B, 2 for C, 1 for D, 0 for F,  or '-1' when you're $

   cin >> LetterGrade;
// Logic to ensure valid letter grade input
// if (LetterGrade = 
 cout << "Please enter the credit hours for the previously entered grade: \n";
  
   cin >> CreditHours;

//initializing the loop for more grade inputs
//FIX LOOP
 while (LetterGrade != -1)

{
  //Updating Totals
  Total = LetterGrade * CreditHours;
  TotalPoints = TotalPoints +  Total;
  TotalCredits = TotalCredits + CreditHours;
  

 cout << "Please enter the grade for your class: 4 for A, 3 for B, 2 for  C, 1 for D, 0 for F, or -1 when you're d$

  cin >> LetterGrade;

 cout << "Please enter the credit hours for the previously entered grade: \n";

  cin >> CreditHours;
//Incomplete/Questionable
 //if (CreditHours <= 0)
 // cout << "Please be sure your Credit Hours add up to a positive, non-zero value\n"; 
}

if (TotalCredits > 0)

{
//Calculating and printing the final GPA.
  float gpa = TotalPoints / TotalCredits;

  cout << "Your GPA is:"<< gpa <<endl;
}

return 0;

}
Here is my test output, which you can see IS calculating the correct GPA (Hooray), however, I still need to implement the error checking logic. And I will probably change the input method to using A B C D F, rather than 4 3 2 1 0, I just did it this way for simplicities sake for the moment.

Code:
Please enter the grade for your class: 4 for A, 3 for B, 2 for C, 1 for D, 0 for F,  or '-1' when you're done inputting grades:
4
Please enter the credit hours for the previously entered grade: 
3
Please enter the grade for your class: 4 for A, 3 for B, 2 for  C, 1 for D, 0 for F, or -1 when you're done inputting grades:
4
Please enter the credit hours for the previously entered grade: 
3
Please enter the grade for your class: 4 for A, 3 for B, 2 for  C, 1 for D, 0 for F, or -1 when you're done inputting grades:
-1
Please enter the credit hours for the previously entered grade: 
-1
Your GPA is:4
 
Last edited:
Physics news on Phys.org
  • #2
I'm having trouble figuring out how to make my loop repeat if a the input is invalid.
In the same way it repeats if the input is valid. Check the input.

There are two concepts how to get out of the loop:
- use a break statement
- use a conditional for the second question (ask only of the answer for the first question is valid)

I would include the first class in the loop, and use a do-while loop, by the way.
Indentation looks messy, but that might be a result of the code-tags here.
 
  • #3
Code:
#include <iostream>
using namespace std;
int main ()

{

//Defining variables that will be used during code.
float CreditHours;
int LetterGrade = 0;
float Total;
float TotalCredits = 0;
float TotalPoints = 0;

while (LetterGrade != -1)
  {

  //Updating Totals
   Total = LetterGrade * CreditHours;
   TotalPoints = TotalPoints +  Total;
   TotalCredits = TotalCredits + CreditHours;

        //Requesting grade input from user
        cout << "Please enter the grade for your class: 4 for A, 3 for B, 2 for  C, 1 for D, 0 for F, or -1 when y$

        //Nested loop to force valid input
            while (true)
                 {
                 cin >> LetterGrade;
                 if ((LetterGrade > 4) || (LetterGrade < -1))
                 cout << "Please enter a valid input (0, 1, 2, 3, or 4):\n";
                 else
                     break;
                 }      //Close nested loop

        // Loop break condition
            if (LetterGrade != -1)
                {
                //Requesting credit hour input from user
                cout << "Please enter the credit hours for the previously entered grade: \n";

                //Nested loop(Inside if statement> inside main loop) to force valid input
                  while (true)
                        {
                        cin >> CreditHours;
                        if ((CreditHours > 5) || (CreditHours < 1))
                        cout << "Please enter a valid value for your credit hours!\n";
                        else
                            break;
                         }      //Close nested loop                 } //Close  conditional if statement
   }    //Close main loop

//Calculating and printing the final GPA.
  float gpa = TotalPoints / TotalCredits;

  cout << "Your GPA is:"<< gpa << endl;

return 0;

}

This is what I ended up with, and it seems to be working fine. Is the indentation still messy?
 
  • #4
Jesse H. said:
This is what I ended up with, and it seems to be working fine. Is the indentation still messy?
Why is the first cout indented and the first while(true) indented yet again when they are not part of an outer if or loop?
 
  • #5
Indentation is a little better, but could be improved. One typical practice for the braces in a for or while loop or an if-else statement block is to put the opening brace immediately below the f in for or the w in while, like so:
Code:
while (<something)
{
   statement1;
   statement2;
   ...
}

Some of your indentation makes no sense. The basic idea is that statements that execute the same number of types have the same indentation. For example, you have this in your code:
Code:
TotalCredits = TotalCredits + CreditHours;

     //Requesting grade input from user
     cout << "Please enter the grade for your class: 4 for A, 3 for B, 2 for  C, 1 for D, 0 for F, or -1 when y$

     //Nested loop to force valid input
         while (true)
              {
              cin >> LetterGrade;
              if ((LetterGrade > 4) || (LetterGrade < -1))
              cout << "Please enter a valid input (0, 1, 2, 3, or 4):\n";
              else
                  break;
              }

I would do it like this:
Code:
TotalCredits = TotalCredits + CreditHours;

//Requesting grade input from user
cout << "Please enter the grade for your class: 4 for A, 3 for B, 2 for  C, 1 for D, 0 for F, or -1 when y$

//Nested loop to force valid input
while (true)
{
     cin >> LetterGrade;
     if ((LetterGrade > 4) || (LetterGrade < -1))
     {
          cout << "Please enter a valid input (0, 1, 2, 3, or 4):\n";
     }
     else
     {
          break;
     } 
     <other statements>
}

Notice that I added braces in your if statement. Although they're not necessary if there is only a single statement in the body of the if, a very common error creeps in when you add another statement and forget that you now need a pair of braces.

They way you have your outer while loop formatted, it's easy to overlook the fact that what you identify as "loop break condition" is actually part of the while loop. When code is properly indented, it's easy to see what's in the body of a control structure (e.g., loop or branch). Without proper indentation, it's difficult to grasp what's going on.
 
  • #6
rcgldr said:
Why is the first cout indented and the first while(true) indented yet again when they are not part of an outer if or loop?

I'm not hip to the coding format. :)

The reason that made sense to me, and forgive my terminology, because the while loop is the input statement that is being requested by the proceeding output statement.

Basically I went through and indented it so that it was clear to me what followed what. Oblivious to the norms of programming.
 
  • #7
Jesse H. said:
I'm not hip to the coding format. :)

The reason that made sense to me, and forgive my terminology, because the while loop is the input statement that is being requested by the proceeding output statement.

Basically I went through and indented it so that it was clear to me what followed what.
If one statement follows another, and both execute the same number of times, their indentation level should be the same. For this reason, these three statements should be at the same level:
Code:
TotalCredits = TotalCredits + CreditHours;
cout << "Please enter the grade for your class: 4 for A, 3 for B, 2 for  C, 1 for D, 0 for F, or -1 when y$
while (true)
{
   ...
}
It should be clear what follows what by the placement on the page. With everything else being equal, a statement below another one executes after the first one. What makes things not equal is a control structure that disrupts the sequential flow of execution, such as a loop of some kind or a branch structure (if -else, switch).
Jesse H. said:
Oblivious to the norms of programming.
We'll help you with that:-p
 

Related to Calculating GPA with Loops in C++

1. How do I use a loop to repeatedly ask for user input in C++?

To repeatedly ask for user input in C++, you can use a while loop or a do-while loop. Both of these loop structures will continue to execute as long as a certain condition is true. Inside the loop, you can prompt the user for input using the cin statement. Once the user enters their input, you can store it in a variable and use it as needed in your program.

2. How do I use a loop to output a certain number of times in C++?

You can use a for loop to output a certain number of times in C++. The for loop has a specific syntax that allows you to set an initial value, a condition, and an increment or decrement for a counter variable. Inside the loop, you can use the cout statement to output any desired text or values. Once the counter reaches the specified number of iterations, the loop will end.

3. Can I use nested loops for input/output in C++?

Yes, you can use nested loops for input/output in C++. Nested loops are simply loops that are contained within other loops. This can be useful for situations where you need to ask for input or output multiple times in a specific pattern. Just be sure to keep track of your loop variables and conditions to avoid any infinite loops.

4. How do I break out of a loop in C++?

You can use the break statement to break out of a loop in C++. This statement will immediately terminate the loop and continue with the rest of the program. You can also use the continue statement to skip over the current iteration of the loop and continue with the next one. These statements are useful for controlling the flow of your loops and preventing them from getting stuck in an infinite loop.

5. Is there a limit to the number of times a loop can execute in C++?

There is no specific limit to the number of times a loop can execute in C++. However, it is important to keep in mind that using loops with a large number of iterations can slow down your program and use up memory. It is best to use efficient and optimized code to avoid any potential issues with loop execution.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
24
Views
2K
  • Programming and Computer Science
Replies
17
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
2K
  • Programming and Computer Science
2
Replies
36
Views
2K
Back
Top