How to get average from array - c++

Trying to get some C++ basics but have a problem. I need to get an average value of temperature array values. Posting code in here. I know that I've done something wrong, because I'm getting the wrong answers. Can you please tell me what's wrong?
#include <iostream>
using namespace std;
int main()
{
int d = 0, i;
double avg = 0, sum = 0, Temperature[100];
// -----------------------------------------
cin >> d;
for (i = 1; i <= d; i++)
{
cin >> Temperature[i];
}
for (i = 1; i <= d; i++)
{
cout << Temperature[i] << endl; // was Temperatura[i] ?
}
for (i = 1; i <= d; i++);
{
sum += Temperature[i];
}
avg= sum / d;
cout << "Average: " << avg << " Sum: " << sum << endl;
system("pause");
return 0;
}

The problem is a result of silly mistake:-
for (i = 1; i <= d; i++); << semicolon
Remove semicolon from end of for loop.

Maybe it because the input number d is larger than 100
#include <iostream>
using namespace std;
int main()
{
int d = 0, i;
double avg = 0, sum = 0, *Temperature=0;
// -----------------------------------------
cin >> d;
Temperature=new double[d]; //<== Use new to allocate array
for (i = 0; i < d; i++) //<== Normaly array start at 0
{
cin >> Temperature[i];
}
for (i = 0; i < d; i++)
{
cout << Temperatura[i] <<endl;
}
for (i = 0; i < d; i++);
{
sum += Temperature[i];
}
average = sum / d;
cout << "Average: " << avg << " Sum: " << sum << endl;
if(Temperature!=0) //<== Free memory
{
delete []Temperature;
}
system("pause");
return 0;
}

You don't need to initialize int d; if you are taking d as input before it use for first time.
Once d taken as input. Now declare the int Temperature[d]; so that if the total number of observation exceed 100 it should work.
Now iterate the array, for taking input and calculating sum. Note that - Array indices starts from zero instead of one. Goes to d-1.
for() loop doesn't have; at the end.

Steps:
You declare the Temperatures array, the number of temperatures (you used 'd', but you don't need to initialize it with 0, just read it) and a variable which keeps the sum of Temperatures (ex.: double sum = 0)
In a for loop (for i = 1; i <= d; i++ || for i = 0; i < d; i++) you read the Temperatures and increase the sum with each of the elemens (sum += Temperatures[i] || sum = sum + Temperatures[i]
Output: cout << sum / n; Formula : average = (elem1 + elem2 + ... + elem n) / n

Related

Maximum and minimum values not printing in main () function

I am doing a code on tracking how much food tigers eat in 1 week and I am tracking 3 tigers.
I am supposed to print average, maximum and minimum. Whenever I run the code it doesn't print the max or minimum, only the initialized values I have in the function. I am assuming the int main() ignores my return values completely, but I can't see why is that. I have done many functions before and I do the same code every time and call it in main
Here is the code:
int main(){
cout << "Enter whether you want to find minimum for tiger 1 2 or 3. (Please
only enter 0, 1 or 2): ";
cin >> temp;
if (temp < 0) {
cout << "CAN'T RUN NEGATIVE NUMBERS";
exit(2);
}
least(food, temp, minimum);
cout << "\n";
cout << "The Tiger " << temp << " has minimum: " << minimum << " ";
cout << "\n \n ";
}
float least(float food[][DAYS], int temp, float min) //loop for days only
{
minimum = food[0][0];
//temp has to be less than 3
for (int j = 0; j < DAYS; ++j) {
if (min<food[temp][j]) {
min = food[temp][j];
}
}
cout << min << " ";
return max;
}
system("PAUSE");
return 0;
}
Since you are not using the return value, use the max and min argument as reference variable in your function definitions. Also the comparison in least & Most functions seems to be wrong. It should be the opposite way.
float least(float food[][DAYS], int temp, float &min) //loop for days only
{
min = food[0][0]; //temp has to be les
for (int j = 0; j < DAYS; ++j) {
if (min>food[temp][j]) {
min = food[temp][j];
}
}
cout << min << " ";
return min;
}
float Most(float food[][DAYS], int amb, float &max) //loop for days only
{
max = food[0][0];
//amb has to be less than 3
for (int j = 0; j < DAYS; ++j) {
if (max<food[amb][j]) {
max = food[amb][j];
}
}
cout << max << " ";
return max;
}
You do not use your methods' return values. Replace
Most(food, amb, maximum);
and
least(food, temp, minimum);
with
maximum = Most(food, amb, maximum);
and
minimum = least(food, temp, minimum);

Need to pass 2D array to function and find sum of row c++

So I need to create a function to find the sum of rows in my 2D array. Array is fixed, matrix[5][5], and user inputs 25 integers.
I know how to find the sum of my rows using the following code:
//for sake of ease lets say user inputs numbers 1-25
for (r = 0; r < 5; r++)
{
for (c = 0; c < 5; c++)
{
sum = sum + matrix[r][c]
}
cout << "\n" << sum;
sum = 0;
}
//the code above will display the sum of each row as follows:
15
40
65
90
115
I want to display the totals for each row as
Row 1:
Sum =
Row 2:
Sum =
etc...
How do I pass the array to a function in order to find the sum of each row and how do I separate the individual sum of rows to display like I want?
I have read a chapter on passing multidimensional arrays to functions like 4 times over in a c++ beginners book, I have read and looked at many different forums online and maybe it is because I have been starring at it for too long I am not seeing the answer but I have given myself a headache. I really just want to understand how to pass it. I have tried to modify the passing of an array to a function to find the sum of all the integers in the array but I could not get it to work for what I needed.
ETA(10/7/2017 1535 PCT):
So I am trying the following to try and pass my 2D array to a function and calculate the sum...
void total(int matrix[][5], int n, int m)
{ // I am getting an error here though that states "expected a ';' "
for (r = 0; r < n; r++)
{
int sum = 0;
for (c = 0; c < m; c++)
sum += matrix[r][c];
}
cout << "Row " << r << " = " << sum << endl;
}
Is this even how you create a function with a 2D array?
ETA (10/7/2017 2100 PCT)
So I think I figured out how to pass the array, but I cannot seem to get it to do the proper math, meaning this does not sum up the rows....
#include "stdafx.h"
#include "iostream"
using namespace std;
int total( const int [][5], int, int);
int main()
{
int c, r, matrix[5][5];
cout << "Please input any 25 numbers you'd like, seperated by a space, then press enter:" << endl;
for (r = 0; r < 5; r++)
{
for (c = 0; c < 5; c++)
{
cin >> matrix[r][c];
}
}
getchar();
cout << endl << "Matrix: " << endl;
for (r = 0; r < 5; r++)
{
cout << endl;
for (c = 0; c < 5; c++)
{
cout << matrix[r][c] << "\t";
}
cout << endl;
}
cout << "Please press the enter key to get the sums of each row << endl;
getchar();
cout << "Sum = " << total << endl; //this displays "Sum = 013513F2"
system("PAUSE");
}
int total(const int matrix[][5], int R, int C)
{
int sum = 0;
for (int r = 0; r < R; r++)
{
for (int c = 0; c < C; c++)
{
sum = sum + matrix[r][c];
}
}
return sum;
}
Passing an array of any dimension can be done by using the syntax: type (&name)[numElements] by reference. Or by pointer you would replace the & with a *. Below is a basic example that compiles, which passes the array by reference to the pass2Darray function. Alternatively, you could simply use a regular array with size [5 * 5] to ensure that it's entirely contiguous. Since a 2D array is not natively something that exists in C++. And then, since you're working with matrices, you can access it in column major by [row * i + col] or in row major by [col * j + row].
#include <iostream>
// Reference to multiArray
// int (&someName)[num][num]
// Pointer to multiArray
// int (*someName)[num][num]
void pass2Darray(int (&passed)[1][1]) {
std::cout << passed[0][0];
}
int main() {
int arr[1][1] = { {1} };
pass2Darray(arr);
return 0;
}
Just to help the future readers this is what I came up with. Took a lot of research and a million different trial and errors but here it is:
int math(int a[5]) //The function the array has been passed to
{
//Declaring the variables in the function
int sum = 0;
double average = 0;
int min = 0;
int max = 0;
min = a[0]; //setting the minimum value to compare to
for (int C = 0; C < 5; C++) //Creates the loop to go through the row elements
{
sum = sum + a[C]; // calculates the sum of each row
if (a[C] < min) min = a[C]; //assigns the element of lowest value from row
if (a[C] > max) max = a[C]; //assigns the element of highest value from row
}
average = sum / 5; //calculates the average of each row
cout << "Sum = " << sum << endl; //Outputs sum
cout << "Average = " << average << endl; //Outputs average
cout << "Min = " << min << endl; //Outputs min
cout << "Max = " << max << endl; //Oututs max
cout << endl;
return 0; //return value for function
}
Down the line that calls the function and displays the output I was looking for:
for (r = 0; r < 5; r++) //sets up row loop for display
{
cout << "Row " << r+1 << ":" << endl;
math(matrix[r]); //displays calculations done in math function
cout << endl;
}
Hope this helps someone down the road...

Doesn't calculate min and max grades in program. (c++) (fstream)

The point of this program is to open and read a text file, with student's academic code -> aem and the grade he/she has overall. Then, if the grade of a particular student is greater than 5, it will write his/her academic code on the text named successful, as well as the grade etc.
My problem is that it calculates the average of those 5 students grades correctly but it does not calculate the max and min grades. When I run the program, the window coming up, shows the correct average of the course, however max and min grades are always 0.
Can anyone help me? Probably I don't compare them in the right way.
#include <iostream>
#include <fstream>
using namespace std;
const int arraySize = 5;
int main(int argc, char** argv)
{
ifstream d;
d.open("students.txt");
ofstream b;
b.open("succesful.txt");
ofstream c;
c.open("unsuccesful.txt");
int aem;
double a[arraySize];
int min, max;
double grades, average;
grades = average = 0;
min = max = 0;
for (int i = 0; i < arraySize; i++)
{
d >> aem >> a[i];
grades = grades + a[i];
average = grades / arraySize;
if (a[i] >= 5) b << aem << " " << a[i] << endl;
else c << aem << " " << a[i] << endl;
}
for (int i = 0; i < arraySize; i++)
{
if (a[i] = max)
max = a[i];
break;
if (a[i] = min)
min = a[i];
break;
}
cout << "The average is:" << average;
cout << "Maximum is:" << max;
cout << "Minimum is:" << min;
d.close(); c.close(); b.close();
system("pause");
return 0;
}
int main(int argc, char** argv)
There's no need argc and argv to be here. It can be just int main().
int min, max;
double grades, average;
grades = average = 0;
min = max = 0;
Assigning value after declaration is unnecessary and inefficient. Also, 0 is an integer, not a floating point. You can just initialize them: int min = 0, max = 0; double grades = .0, average = .0;
grades = grades + a[i];
Can be shortened to grades += a[i];
average = grades / arraySize;
This statement is inside a for-loop pointlessly. You can do this after the loop.
for (int i = 1; i < arraySize; i++) {
You forgot the zeroth element of a. int i = 1; must be replaced to int i = 0;
if (i >= max)
max = i;
if (i <= min)
min = i;
You've mistaken a[i] for i. And if a[i] and max already compare equal, there is no need to assign a[i] to max. They can be just:
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
And,
system("pause");
std::system is dependent to the system environment and can have unexpected behavior. It should be replaced to:
std::cout << "Press enter key." << std::endl;
std::cin.get();

How to count how many times each number has been encountered?

I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}

Sum of Numbers C++

I am supposed to write a program that asks the user for a positive integer value. The program should use a loop to get the sum of
all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of
1, 2, 3, 4, ... 50.
But for some reason it is not working, i am having trouble with my for loops but this is what i have down so far.
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
int i = 0;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
for (int i=0; i < positiveInteger; i++)
{
i = startingNumber + 1;
cout << i;
}
return 0;
}
I am just at a loss right now why it isn't working properly.
The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.
try this:
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
cout << "Please input an integer upto 100." << endl;
cin >> positiveInteger;
int result = 0;
for (int i=startingNumber; i <= positiveInteger; i++)
{
result += i;
cout << result;
}
cout << result;
return 0;
}
I have the following formula that works without loops. I discovered it while trying to find a formula for factorials:
#include <iostream>
using namespace std;
int main() {
unsigned int positiveInteger;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
cout << (positiveInteger * (positiveInteger + 1)) / 2;
return 0;
}
You can try:
int sum = startingNumber;
for (int i=0; i < positiveInteger; i++) {
sum += i;
}
cout << sum;
But much easier is to note that the sum 1+2+...+n = n*(n+1) / 2, so you do not need a loop at all, just use the formula n*(n+1)/2.
mystycs, you are using the variable i to control your loop, however you are editing the value of i within the loop:
for (int i=0; i < positiveInteger; i++)
{
i = startingNumber + 1;
cout << i;
}
Try this instead:
int sum = 0;
for (int i=0; i < positiveInteger; i++)
{
sum = sum + i;
cout << sum << " " << i;
}
int result = 0;
for (int i=0; i < positiveInteger; i++)
{
result = startingNumber + 1;
cout << result;
}
First, you have two variables of the same name i. This calls for confusion.
Second, you should declare a variable called sum, which is initially zero. Then, in a loop, you should add to it the numbers from 1 upto and including positiveInteger. After that, you should output the sum.
You are just updating the value of i in the loop. The value of i should also be added each time.
It is never a good idea to update the value of i inside the for loop. The for loop index should only be used as a counter. In your case, changing the value of i inside the loop will cause all sorts of confusion.
Create variable total that holds the sum of the numbers up to i.
So
for (int i = 0; i < positiveInteger; i++)
total += i;