I can't figure out why I can't calculate the average. The output of the average is same as the other look the details in the picture below. My teacher told me to return the AVG to 0, but I don't know where to put it.
#include <iostream>
using namespace std;
const int ROW = 3;
const int COL = 3;
const int D = 3;
void display(int nums[ROW][COL]);
void show(int ID[D]);
int main()
{
int nums[ROW][COL];
int ID[D];
double AVG = 0;
for (int i = 1; i <= ROW; i++) {
cout << "Enter student ID[" << i << "]: ";
cin >> ID[i];
for (int j = 0; j < COL; j++) {
cout << "Enter student[" << i << "] Grades [" << j + 1 << "]:";
cin >> nums[i][j];
AVG = AVG + nums[i][j];
}
AVG = AVG / 3;
}
for (int i = 1; i <= ROW; i++) {
cout << "Student ID: " << ID[i] << endl;
for (int j = 0; j < COL; j++) {
cout << "Score: " << nums[i][j] << endl;
}
cout << "Average: " << AVG << endl;
}
return 0;
}
You Have some problem regarding this issues:
you take AVG as double but other variable as integer.so there is a datatype error.
2.you have problem doing array indexing.
Here Is the Solution. Here I declare AVG as an integer type array so that it remains same as your code.
#include
using namespace std;
const int ROW = 3;
const int COL = 3;
const int D = 3;
void display(int nums[ROW][COL]);
void show(int ID[D]);
int main ()
{
int nums[ROW][COL];
int ID[D];
int AVG[ROW];
for(int i=1; i<=ROW; i++)
{
cout << "Enter student ID[" << i <<"]: ";
cin>>ID[i];
AVG[i-1]=0;
for(int j=0; j<COL; j++)
{
cout<<"Enter student[" << i << "] Grades [" <<j+1<<"]:" ;
cin>>nums[i-1][j];
AVG[i-1] = AVG[i-1] + nums[i-1][j];
}
AVG[i-1] = AVG[i-1] / 3;
}
for(int i=1; i<=ROW; i++)
{
cout <<"Student ID: " << ID[i] << endl;
for(int j=0; j<COL; j++)
{
cout<<"Score: "<<nums[i-1][j]<<endl;
}
cout << "Average: " << AVG[i-1]<< endl;
}
return 0;
}
Currently you are calculating the average as follows;
First iteration:
(90 + 90 + 90) / 3 = 90
Second iteration:
(90 + 80 + 80 + 80)/3 = 110
Third iteration:
(110 + 70 + 70 + 70)/3 = 106
If you want to get the average of all grades, do this;
double AVG = 0;
double avg_tmp;
for (int i = 1; i <= ROW; i++) {
avg_tmp = 0;
cout << "Enter student ID[" << i << "]: ";
cin >> ID[i];
for (int j = 0; j < COL; j++) {
cout << "Enter student[" << i << "] Grades [" << j + 1 << "]:";
cin >> nums[i][j];
avg_tmp += nums[i][j];
}
AVG += avg_tmp / 3;
}
Your biggest issue is you invoke Undefined Behavior with your loop limits for for (int i = 1; i <= ROW; i++). In C/C++ all array indexes are Zero-Based with valid indexes of 0 <= i < n. So your i loop must be for (int i = 0; i < ROW; i++).
You do NOT need to compute the sum or average in your first set of loops. The first set of nested loops are you Input Loops where you are simply filling the elements of ID and nums. You only need AVG in your second set of nested loops (e.g. your Output Loops) Avoid mixing input and output logic.
Only declare and initialize your variables in the scope where they are needed. This will fix what your professor is talking above. If you only declare and initialize AVG within the first output-loop where the average will be computed, it will automatically be reset to zero for each student.
Putting it altogether, you could do:
#include <iostream>
const int ROW = 3; /* good job on declaring constants */
const int COL = 3;
const int D = 3;
int main()
{
int nums[ROW][COL] = {{0}}; /* initialize all plain-old arrays */
int ID[D] = {0};
for (int i = 0; i < ROW; i++) {
std::cout << "\nEnter student ID[" << i + 1 << "]: ";
/* you must validate EVERY user-input */
if (!(std::cin >> ID[i])) {
std::cerr << "error: invalid integer input.\n";
return 1;
}
for (int j = 0; j < COL; j++) {
if (!j)
std::cout.put('\n');
std::cout << "Enter student[" << i+1 << "] Grades [" << j+1 << "]: ";
if (!(std::cin >> nums[i][j])) { /* ditto */
std::cout << "error: invalid integer input.\n";
return 1;
}
}
}
for (int i = 0; i < ROW; i++) {
double AVG = 0.; /* declare / initialize in scope needed */
std::cout << "\nStudent ID: " << ID[i] << '\n';
for (int j = 0; j < COL; j++) {
std::cout << " Score: " << nums[i][j] << '\n';
AVG += nums[i][j]; /* sum each score */
}
std::cout << "Average: " << AVG / COL << '\n';
}
}
Example Use/Output
$ ./bin/studentavg
Enter student ID[1]: 1
Enter student[1] Grades [1]: 90
Enter student[1] Grades [2]: 89
Enter student[1] Grades [3]: 91
Enter student ID[2]: 2
Enter student[2] Grades [1]: 79
Enter student[2] Grades [2]: 81
Enter student[2] Grades [3]: 80
Enter student ID[3]: 3
Enter student[3] Grades [1]: 71
Enter student[3] Grades [2]: 70
Enter student[3] Grades [3]: 69
Student ID: 1
Score: 90
Score: 89
Score: 91
Average: 90
Student ID: 2
Score: 79
Score: 81
Score: 80
Average: 80
Student ID: 3
Score: 71
Score: 70
Score: 69
Average: 70
Look things over and let me know if you have further questions.
package test;
import java.util.*;
public class DoubleArray {
public static void main(String[] args) {
String[][] arr = {{"Ram", "100"}, {"Mohan", "80"}, {"Ram", "70"}, {"Mohan", "60"}, {"Chitra", "80"}, {"Ram", "88"}};
HashMap<String, Integer> pf = new HashMap<String, Integer>();
List<String> as = new ArrayList<>();
for (int row = 0; row < arr.length; row++) {
if (pf.containsKey(arr[row][0])) {
as.add(arr[row][0]);
pf.put(arr[row][0], ((pf.get(arr[row][0]) + Integer.parseInt(arr[row][1]))));
} else {
as.add(arr[row][0]);
pf.put(arr[row][0], Integer.parseInt(arr[row][1]));
}
}
int value = 0;
for (Map.Entry<String, Integer> entry : pf.entrySet()) {
pf.put(entry.getKey(), entry.getValue() / Collections.frequency(as, entry.getKey()));
value = Collections.max(pf.values());
if (entry.getValue() == value) {
System.out.println(entry.getKey() + "," + entry.getValue());
}
}
}
}
Related
I recently have been having trouble with this simple problem, at the end of the code there are two blocks of text dedicated to finding the highest/lowest grade from what the user inputted.
That was simple enough and it works well, but I also need to print the a row corresponding to the lowest/highest graded student.
Essentially I'm working with the marks[5][4] array, the first array being the students, the second array being the exams.
If the lowest graded student was the student on array [2][] then I would I want to print out [2][i] using a for loop.
For the second array it works fine, the problem is I'm having problem on how to link the lowest graded student to the first array link.
I tried to use the count1 and count loops but they return a mess. I have been at this for a few hours and need a nudge in the right direction.
Thank you very much.
#include<iostream>
using namespace std;
int main()
{
char grade[5];
double avg[5];
string name[5];
int marks[5][4];
for (int i = 0; i < 5; i++) {
cout << "\n enter student" << i + 1 << "name :";
cin >> name[i];
cout << "\n enter four subject marks:";
for (int j = 0; j < 4; j++) {
cin >> marks[i][j];
}
}
for (int i = 0; i < 5; i++)
{
int sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + marks[i][j];
}
avg[i] = sum / 4;
if (avg[i] > 90.0 && avg[i] <= 100.0) {
grade[i] = 'A';
}
else if (avg[i] > 80.0 && avg[i] <= 90.0) {
grade[i] = 'B';
}
else if (avg[i] > 70.0 && avg[i] <= 80.0) {
grade[i] = 'C';
}
else if (avg[i] > 60.0 && avg[i] <= 70.0) {
grade[i] = 'D';
}
else if (avg[i] <= 60.0) {
grade[i] = 'F';
}
}
for (int i = 0; i < 5; i++)
{
cout << "\nName :" << name[i];
cout << "\tAverage : " << avg[i];
cout << "\tGrade : " << grade[i];
}
for (int i = 0; i < 4; i++)
{
int sum2 = 0;
for (int j = 0; j < 5; j++) {
sum2 = sum2 + marks[j][i];
}
cout << "\n";
cout << "The average of each exam " << i+1 << " is " << "%" << sum2 / 5;
}
//LOWEST
int count1;
int lowest;
lowest = avg[0];
for (count1 = 1; count1 < 5; count1++)
{
if (avg[count1] < lowest)
lowest = avg[count1];
}
cout << "\n";
cout << "The lowest average grade is is: " << lowest << ".\n";
for (int i = 0; i < 4; i++) {
cout << marks[count1][i] << " ";
}
cout << endl;
//Ends lowest.
//HIGHEST
int count;
int highest;
highest = avg[0];
for (count = 1; count < 5; count++)
{
if (avg[count] > highest)
highest = avg[count];
}
cout << "\n";
cout << "The highest average grade is is: " << highest << ".\n";
for (int i = 0; i < 4; i++) {
cout << marks[count][i] << " ";
}
cout << endl;
//Ends highest.
return 0;
}
From what I understand, you need to link the name with the lowest avg student
I recommend that instead of initializing lowest and highest with the average, initialize it with the index of the lowest and highest average. You can then compare the averages in the for loop like this
if (avg[lowest] >= avg[count1])
lowest = count1;
or you can follow Sam's solution, create another variable to store the index of the current lowest and highest avg
I am trying to write a program that takes user input for the number of hours worked by 6 employees of a company to store in a two-dimensional array and prints the output in the following format:
Employee Number Hours
01 a
02 b
03 c
04 d
05 e
06 f
where a-f would be the user entered integer values.
I have experimented with several methods but am unable to get my desired output. I am attaching the recent attempt:
#include <iostream>
using namespace std;
int main()
{
int array[6][2]; // 6 by 2 matrix to store employee name and hours worked
int i, j;
cout << "Enter the number of hours worked by 6 employees: " << endl;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 2; j++)
{
cin >> array[i][j];
cout << array[i][j] << "\t" << endl;
break;
}
cout << endl;
}
}
What changes should I make to get the required output?
You should take the input first. Then in order to print with column name you should first print those column names and then print the values.
Your code should be like this -
#include <iostream>
using namespace std;
int main()
{
int array[6][2]; // 6 by 2 matrix to store employee name and hours worked
int i, j;
cout << "Enter the number of hours worked by 6 employees: " << endl;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 2; j++)
{
cin >> array[i][j];
}
}
cout << "Employee Number \t Hours" << endl;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 2; j++)
{
cout << array[i][j] << "\t\t\t ";
}
cout << endl;
}
}
Output:
Edit:
For your requirement from the comment, new code will be
int main()
{
int array[6][2]; // 6 by 2 matrix to store employee name and hours worked
int i, j;
cout << "Enter the number of hours worked by 6 employees: " << endl;
cout << "Employee Number \t Hours" << endl;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 2; j++)
{
cin >> array[i][j];
cout << array[i][j] << "\t\t\t ";
}
cout << endl;
}
}
the problem arises when I use a different number of rows and columns, for example, 2 by 3 otherwise, it is running okay. the sum of column outputs garbage values
I can't seem to understand where the bug is.
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
int a[10][10];
int i,row,column, j, s = 0, sum = 0;
cout<<"Enter Number of rows: ";
cin>>row;
cout<<"Enter Number of columns: ";
cin>>column;
cout<< "Enter elements Matrix \n";
for (i = 0; i < row; i++)
for (j = 0; j < column; j++)
cin >> a[i][j];
cout << "Matrix Entered By you is \n";
for (i = 0; i < row; i++)
{
for (j = 0; j <column; j++)
cout << a[i][j] << " ";
cout << endl;
}
for (i = 0; i < row; i++)
{
for (j = 0; j <column; j++)
s = s + a[i][j];
cout << "Sum of Row " << i + 1 << " is: " << s;
s = 0;
cout << endl;
}
cout << endl;
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
s = s + a[j][i];
cout << "Sum of Column " << i + 1 << " is: " << s;
s = 0;
cout << endl;
}
}
You are not iterating correctly to get your columns sum, column and row are switched up. change to:
for (i = 0; i < column; i++) // <-----
{
for (j = 0; j < row; j++) // <-----
s = s + a[j][i];
cout << "Sum of Column " << i + 1 << " is: " << s;
s = 0;
cout << endl;
}
Consider a 3x4 matrix:
1 2 3 4
1 2 3 4
1 2 3 4
Your current loop would access it in the following manner, invoking undefined behavior.
[1] [2] [3] 4
[1] [2] [3] 4
[1] [2] [3] 4
[?] [?] [?]
I am trying to find the lowest student average in a golf game. but I could not find out how. all my attempts ended up finding the highest average which is the opposite of what I want to display.
*
*
*
*
*
*
*
*
*
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
double total = 0; double totalr = 0;
const int round = 3; double less=0;
const int player = 5;
string name[player]={"Mike Sims ", "Paula Hill ", "Steve Jones", "Joll Burton", "Lee Smith "};
double average=0, avestudent, averound; string dummy;
int score[round][player] =
{ 78, 71, 72, 73, 74 , 76, 78, 75, 74, 79 , 74, 75, 73, 72, 78 };
cout << "Player Round1 Round2 Round3 Ave./Student"<<endl;
for (int i = 0; i <player ; i++)
{
cout << setw(10) << left << name[i]; total = 0;
for (int j = 0; j <round ; j++)
{
cout << setw(16) << right << score[j][i];
total = total + score[j][i]; avestudent = total / (int)round;
}
cout << fixed << setprecision(1);
cout <<setw(20)<< avestudent ;
cout << endl;
}
cout << endl;
cout << setw(10) << left << "Ave./Round ";
for (int i = 0; i <round; i++)
{
totalr = 0;
for (int j = 0; j <player; j++)
totalr = totalr + score[i][j];
averound = totalr / player;
cout << setw(13)<< " "<<averound;
}
cout<< endl;
double lowest = score[round][player];
for (int j = 0; j < round; j++)
{
lowest = 0;
for (int i = 0; i < player; i++)
{
avestudent = total / (int)round;
lowest = avestudent;
if (score[j][i] < lowest)
lowest = score[j][i];
}
}
cout << lowest << " was the best recorded student average from the rounds of golf." << endl;
cout << fixed << setprecision(1) << endl;
}
Honestly I'm not exactly sure what your logic/ workflow is in trying to find the lowest average. In this case, I would just create an array to save the different averages. (So change your avestudent variable into an array)
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
double total = 0;
double totalr = 0;
const int round = 3;
double less=0;
const int player = 5;
string name[player]={"Mike Sims ", "Paula Hill ", "Steve Jones", "Joll Burton", "Lee Smith "};
double average=0, averound; string dummy;
double avestudent[player];
int score[round][player] = { 78, 71, 72, 73, 74 , 76, 78, 75, 74, 79 , 74, 75, 73, 72, 78 };
cout << "Player Round1 Round2 Round3 Ave./Student"<<endl;
for (int i = 0; i <player ; i++)
{
cout << setw(10) << left << name[i];
total = 0;
for (int j = 0; j <round ; j++)
{
cout << setw(16) << right << score[j][i];
total = total + score[j][i];
avestudent[i] = total / (int)round;
}
cout << fixed << setprecision(1);
cout <<setw(20)<< avestudent[i] ;
cout << endl;
}
cout << endl;
cout << setw(10) << left << "Ave./Round ";
for (int i = 0; i <round; i++)
{
totalr = 0;
for (int j = 0; j <player; j++)
{
totalr = totalr + score[i][j];
}
averound = totalr / player;
cout << setw(13)<< " "<<averound;
}
cout<< endl;
double lowest = score[round][player];
for (int j = 0; j < round; j++)
{
lowest = avestudent[0];
for (int i = 1; i < player; i++)
{
if (avestudent[i] < lowest)
{
lowest = avestudent[i];
}
}
}
cout << lowest << " was the best recorded student average from the rounds of golf." << endl;
cout << fixed << setprecision(1);
cout << endl;
}
The big issue with your code is that you're trying to initialize lowest to score[round][player]. You can't do this because these are the sizes of the array.
If there is an array int array[5]; you cannot access array[5]. The highest index that is reachable is array[4] because the array uses spaces 0,1,2,3,4 to hold the five integers.
Here's what I came up with:
int sums[player] = {};
int lowest_score = 0;
int lowest_player = 0;
double lowest_avg = 0.0;
for (int r = 0; r < round; r++)
{
for (int p = 0; p < player; p++)
{
sums[p] += score[r][p];
}
}
for (int p = 0; p < player; p++)
{
if ((p == 0) || (sums[p] < lowest_score))
{
lowest_player = p;
lowest_score = sums[p];
}
}
lowest_avg = ((double)lowest_score) / round;
std::cout << "The player with the lowest average score is " << name[lowest_player] << ". With an average score of " << lowest_avg << std::endl;
I have a problem with getting the min,max, and average of an elements of 2D array.
I have a 2D array which contains Students and Grades.
I am generating the grades with rand. For example When I enter 2,2 it prints me out
Courses : 01 02 Average Min Max
ID
01 8 50 29
02 74 59 29
, My average function takes the first ones average and doesnt take the others average.
Here is my code ;
int A[30][30];
int findAverage(int noOfStudents ,int noOfGrades ){
float sum,average;
for (int i = 0 ; i < noOfGrades ; i++) {
for (int j = 0; j<noOfStudents; j++) {
sum += A[i][j];
}
average = sum / noOfGrades;
// cout << " " << format(average);
sum = 0;
return format(average);
}
and here how I use it
int main() {
int noOfCourses , noOfStudents;
cin >> noOfCourses >> noOfStudents;
cout << "Courses : " ;
for (int i = 0; i < noOfCourses; i++) {
if (i+1 >= 10) {
cout << i+1 << " ";
}else{
cout <<"0" << i+1 << " ";
}
}
cout << "Average Min Max";
for(int i=0; i<noOfStudents; i++) { //This loops on the rows.
for(int j=0; j<noOfCourses; j++) { //This loops on the columns
A[i][j] = genGrade();
}
}
cout << "\n ID " << endl;
for(int i=0; i<noOfStudents; i++) { //This loops on the rows.
if (i+1 >= 10) {
cout <<" " << i+1 << " ";
}else{
cout <<" 0" << i+1 << " ";
}
//cout <<" 0" << i+1 << " ";
for(int j=0; j<noOfCourses; j++) { //This loops on the columns
if (A[i][j] >= 10 && A[i][j] <=99) {
cout <<" " << A[i][j] << " ";
}
if(A[i][j] < 10) {
cout <<" " << A[i][j] << " ";
}
if (A[i][j] == 100) {
cout << A[i][j] << " ";
}
}
cout <<" "<<findAverage(noOfStudents,noOfCourses);
cout << endl;
}
}
What am I doing wrong ? Also How could I get the min,max of the per array?
I would strong recommend using containers for this task. For example you could do the following
typedef std::vector<float> grades;
std::vector<grades> student_grades;
//populate
for(const grades& gr : student_grades) {
float min, max, avg;
std::tie(min, max)=std::minmax(gr.begin(), gr.end());
avg=std::accumulate(gr.begin(), gr.end(), 0.0) / gr.size());
std::cout << "Min" << min << " Max: " << max << " Avg: " << avg << std::endl;
}
http://en.cppreference.com/w/cpp/algorithm/minmax
http://en.cppreference.com/w/cpp/algorithm/accumulate
http://en.cppreference.com/w/cpp/utility/tuple/tie
For starters, you are returning from inside your loop:
for (int i = 0 ; i < noOfGrades ; i++) {
for (int j = 0; j<noOfStudents; j++) {
...
}
...
return ...;
}
Can you see how the outer loop will only ever execute once?
The problem is that in your findAverage function you have a return statement within the loop that is looping through the rows. If you want a very simple fix add another parameter to the findAverage function that indicates which row to calculate the average for.
int findAverage(int course ,int noOfGrades ){
float sum,average;
for (int j = 0; j<noOfStudents; j++) {
sum += A[course][j];
}
average = sum / noOfGrades;
return format(average);
}
and call it like this
cout <<" "<<findAverage(i,noOfCourses);