Home‎ > ‎Assignments‎ > ‎Hour of Code‎ > ‎Solutions‎ > ‎

Credit Due | Solution

Programming Assignment

Where Credit is Due

Solution

 

 There are (at least) two possible solutions to this Programming Assignment: 

 

Alternate Solution 1
[remember to indent and comment appropriately]

 //credits.cpp
// Programming Assignment #2
// Where Credit is Due

#include <iostream>
using namespace std;

int main()
{
int n, credits, totcred=0;
float avgcred;
char StudentID [9];
cout << "How many students in the class? "; cin >> n;
for (int i=0; i<n; i++) {
cout << "Student ID #? "; cin >> StudentID;
cout << "Number of credits? "; cin >> credits;
totcred = totcred + credits;
}
avgcred = totcred / (1.0*n);
cout << "The average number of credits carried by students in this \n";
cout << "class this semester is " << avgcred << endl;

return 0;
} //end main

 

 

 

Alternate Solution 2
[remember to indent and comment appropriately]

//credits.cpp
// Programming Assignment #2
// Where Credit is Due
// using string library

#include <iostream>
#include <string>
using namespace std;

int main(){
char endchar;
int n=0, credits;
float sum=0, mean;
string StudentID;
cout << "To stop this program, enter a '000' for Student ID.";
cout << "\n\nEnter Student ID: ";
cin >> StudentID;
while (StudentID != "000") {
cout << "Enter number of credits: ";
cin >> credits;
cout << "\nStudent " << StudentID << " is taking " << credits << " credits.\n";
sum += credits;
n++;
cout << "\n\nEnter Student ID: ";
cin >> StudentID;
}
mean = sum / n;
cout << endl << "=============================================" << endl << endl;
cout << "The average number of credits carried by students in this \n";
cout << "class this semester is " << mean << endl;

cout << "\n\nType any character and press Enter to close this window. ";
cin >> endchar;

return 0;
}

 

Comments