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);
Related
#include <iostream>
using namespace std;
int main()
{
int n, G;
float num[500], sum=0.0, average,Grades;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 500 || n <= 0)
{
cout << "Error! number should in range of (1 to 500)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(G = 0; G < n; ++G)
{
cout << G + 1 << ". Enter number: ";
cin >> num[G];
sum += num[G];
}
average = sum / n;
Grades = num[G] >= average;
cout<<endl;
cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average : " <<Grades<< endl;
cout << "Number of grades above the Average = "<<(int) Grades;
return 0;
}
i coded this code but the Number of grades above the Average and Grades above or equal the Average don't work it just print 0
i tried to print the Grades >= the avg but it print 0
also num of Grades also print 0
where is the error ?
I think you was trying to do something like this:
...
int grades_on_avg, upper_grades = 0;
for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
for(int i = 0; i < n; ++i) // use separate for loop and redefined index
{
if(num[i] == average) // compare to average
grades_on_avg++;
else if(num[i] > average) // if bigger than average
upper_grades++;
}
cout<<endl;
cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average =" << (grades_on_avg + upper_grades) << endl;
cout << "Number of grades above the Average = "<< upper_grades ;
You assign boolean value to Grades variable. Also, you refer to element outside of the array: G variable is equal to n after exiting for-loop, but max index you can use is n - 1 (basic programming rule). So, you should change your code into something like this:
...
int avgGrades{0};
int avgAboveGrades{0};
for(int i{0}; i < n; ++i)
{
if(num [i] == average)
{
++avgGrades;
}
else if(num [i] > average)
{
++avgAboveGrades;
}
}
If you prefer more elegant ways of doing so, you can use std::count_if() function but it's more tricky and requires knowledge about lambdas.
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
#include <iostream>
using namespace std;
int main()
{
int n, a, b,min,max, Prod = 1, Sum = 0;
cout << "Initialize an array n: ";
cin >> n;
do
{
cout << "Input the start value: ";
cin >> a;
cout << "Input the end value: ";
cin >> b;
if (!(a < b))
{
cout << "a is bigger than b, please enter new values " << endl;
continue;
}
} while (!(a < b));
int* lpi_arr;
lpi_arr = new int[n];
srand(time(NULL));
cout << "Int numbers from " << a << " to " << b << endl;
for (int i = 0; i < n; i++)
{
lpi_arr[i] = rand() % (b - a) + a;
cout << lpi_arr[i] << " ";
}
max = lpi_arr[0];
for (int i = 0; i < n; i++)
{
if (max < lpi_arr[i])
max = lpi_arr[i];
}
min = lpi_arr[0];
for (int i = 0; i < n; i++)
{
if (min > lpi_arr[i])
min = lpi_arr[i];
}
cout << "\nmin element is = " << min << endl;
cout << "\nmax element is = " << max << endl;
for (int i = max + 1; i < min; i++)
Prod *= lpi_arr[i];
for (int i = 0; lpi_arr[i] < 0 && i < n; i++)
Sum += lpi_arr[i];
cout << "Summ =" << Sum << endl << "Prod = " << Prod << endl;
delete[] lpi_arr;
}
The main purpose of this code is to calculate the sum of negative numbers of an array, and multiplication of elements located between the maximum and minimum elements of an array.
The problem is that the code implements only 1(one) as an answer, and I don't know how to change it. Every other part of the code works well, but if you have any recommendations I'd also like to read it. Waiting for your help.
Your issue is that you're confusing array indexes with array values.
Here you're assigning max (and same with min) to an array value.
max = lpi_arr[i];
Here you're treating max (and same with min) as an array index.
for (int i = max + 1; i < min; i++)
Prod *= lpi_arr[i];
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());
}
}
}
}
I am trying to filter an array given by the user on basis of whether it is positive even, positive odd, negative even, or negative odd.
And, based on this filtration, I am trying to put them in the respected array but my code is working for the 1st part; i.e. it is taking user array but the problem is: It is not entering my filtration code.
The code is here:
#include<iostream>
#include<limits>
#include <functional>
using namespace std;
int main()
{
int n ;
cout<<"\n Enter the size of array :-";
cin>>n;
int numbers[n];
int peven[n],podd[n],neven[n],nodd[n];
for (int i = 0; i < n ; i++){
cout<<"\n Enter value "<<i+1<<" = ";
cin>>numbers[i];
}
cout<<"\n\n";
for (int i = 0; i < n ; i++){
cout<<" "<<numbers[i];
}
cout<<"\n\n";
for(int j = 0;j<n;j++){
if ( ((numbers[j]%2) == 0) && (numbers[j] > 0) ) {
for(int i = 0; i<1; i--){
cin>>peven[i];
i++;
}
}
else if ( ((numbers[j]%2) == 0) && (numbers[j] < 0) ){
for(int i = 0; i<1; i--){
cin>>neven[i];
i++;
}
}
else if ( ((numbers[j]%2) != 0) && (numbers[j] > 0) ){
for(int i = 0; i<1; i--){
cin>>podd[i];
i++;
}
}
else {
for(int i = 0; i<1; i--){
cin>>nodd[i];
i++;
}
}
}
cout<<"\n The +ve even number array is :- "<<peven[n];
cout<<"\n The +ve odd number array is :- "<<podd[n];
cout<<"\n The -ve even number array is :- "<<neven[n];
cout<<"\n The -ve odd number array is :- "<<nodd[n];
return 0;
}
There are several problems in your code. Here is a list (which is not exhaustive) :
it is forbidden to create a constant size array with an integer which is not constant :
cin>>n;
int numbers[n];
As Sam Varshavchik mentioned, it is not possible to finish this loop :
for(int i = 0; i<1; i--)
You have no reason to read value from cin after you fill the array to filter. Line like this one should be modified :
cin>>peven[i];
Here is a correction :
#include <iostream>
#include <vector>
#include<limits>
#include <functional>
using namespace std;
int main()
{
vector<int> peven, podd, neven, nodd;
int n;
cout << "Enter the size of vector :-" << endl;
cin >> n;
vector<int> numbers(n, 0);
for (int i = 0; i < n; i++) {
cout << "Enter value " << i + 1 << endl;
cin >> numbers[i];
}
cout << endl;
cout << "Your vector contains : [";
for (int i = 0; i < n; i++) {
cout << " " << numbers[i];
}
cout << " ]" << endl;
cout << endl;
for (int j = 0; j < n; j++) {
if (((numbers[j] % 2) == 0) && (numbers[j] >= 0)) {
peven.push_back(numbers[j]);
}
else if (((numbers[j] % 2) == 0) && (numbers[j] < 0)) {
neven.push_back(numbers[j]);
}
else if (((numbers[j] % 2) != 0) && (numbers[j] >= 0)) {
podd.push_back(numbers[j]);
}
else {
nodd.push_back(numbers[j]);
}
}
cout << "\n The +ve even number array is : [";
for (int j = 0; j < (int)peven.size(); j++) {
cout << " " << peven[j];
}
cout << "] " << endl;
cout << "\n The +ve odd number array is : [";
for (int j = 0; j < (int)podd.size(); j++) {
cout << " " << podd[j];
}
cout << "] " << endl;
cout << "\n The -ve even number array is : [";
for (int j = 0; j < (int)neven.size(); j++) {
cout << " " << neven[j];
}
cout << "] " << endl;
cout << "\n The -ve odd number array is : [";
for (int j = 0; j < (int)nodd.size(); j++) {
cout << " " << nodd[j];
}
cout << "] " << endl;
return 0;
}