blog
blog copied to clipboard
C++ for-loop, while-loop and do-while-loop
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;
}