Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ for-loop, while-loop and do-while-loop #195

Open
Qingquan-Li opened this issue Jun 19, 2022 · 0 comments
Open

C++ for-loop, while-loop and do-while-loop #195

Qingquan-Li opened this issue Jun 19, 2022 · 0 comments
Labels

Comments

@Qingquan-Li
Copy link
Owner

Assignment: Write a program to ask the user to enter students' grades and then calculate the total grade.


1. for loop:

#include <iostream>

using namespace std;

int main() {
    int num_students;
    float stu_grade; // student's numeric course grade
    float total_grade = 0;

    cout << "How many students are in the class? ";
    cin >> num_students;

    for (int i = 1; i <= num_students; i++) {
        cout << "Please enter the #" << i << " student's numeric course grade: ";
        cin >> stu_grade;
        total_grade += stu_grade;
    }

    cout << "The total grade of the class is: " << total_grade << endl;

    return 0;
}

2. while loop:

#include <iostream>

using namespace std;

int main() {
    const int SENTINEL_VAL = -1;
    float stu_grade; // student's numeric course grade
    float total_grade = 0;

    cout << "Type a student's numeric course grade (type -1 if you don't have any more grade): ";
    cin >> stu_grade;

    while (stu_grade != SENTINEL_VAL) {
        total_grade += stu_grade;
        cout << "Type a student's numeric course grade (type -1 if you don't have any more grade): ";
        cin >> stu_grade;
        // total_grade += stu_grade; // should at the beginning, otherwise, the -1 will be add.
    }

    cout << "The total grade of the class is: " << total_grade << endl;

    return 0;
}

3. do while loop:

#include <iostream>

using namespace std;

int main() {
    char user_response;
    float stu_grade; // student's numeric course grade
    float total_grade = 0;

    do {
        cout << "Type a student's numeric course grade: ";
        cin >> stu_grade;
        total_grade += stu_grade;
        cout << "Do you have another grade to type? (Y/N) ";
        cin >> user_response;
    } while (user_response == 'Y' || user_response == 'y');

    cout << "The total grade of the class is: " << total_grade << endl;

    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant