I'm trying to pass a simple array through a function to compute the mean.
int main()
{
int n = 0; // the number of grades in the array
double *a; // the array of grades
cout << "Enter number of scores: ";
cin >> n;
a = new double[n]; // the array of grades set
// to the size of the user input
cout << "Enter scores separated by blanks: ";
for(int i=0; i<n; i++)
{
cin >> a[i];
}
computeMean(a, n);
}
double computeMean (double values[ ], int n)
{
double sum;
double mean = 0;
mean += (*values/n);
return mean;
}
Right now the code is only taking the mean of the last number that was inputted.
There's no loop in your function. It should be something like:
double sum = 0;
for (int i = 0; i != n; ++i)
sum += values[i];
return sum / n;
I'm surprised your current version only takes the last number, it should only take the first number, since *values is the same as values[0].
A better solution uses idiomatic C++:
return std::accumulate(values, values + n, 0.0) / n;
std::accumulate should do the trick.
#include <numeric>
double computeMean (double values[ ], int n) {
return std::accumulate( values, values + n, 0. ) / n;
}
Is this a homework question?
You nead to step through all of the values in your array. You're currently outputting the first number in the array divided by the number of items.
Related
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.
I know how to do that without using a function ,for example for any n numbers I have the following program:
#include<stdio.h>
int main()
{
int n, i;
float sum = 0, x;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("\n\n\nEnter %d elements\n\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &x);
sum += x;
}
printf("\n\n\nAverage of the entered numbers is = %f", (sum/n));
return 0;
}
Or this one which do that using arrays:
#include <iostream>
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
But is it possible to use functions?if yes then how? thank you so much for helping.
As an alternative to using fundamental types to store your values C++ provides std::vector to handle numeric storage (with automatic memory management) instead of plain old arrays, and it provides many tools, like std::accumulate. Using what C++ provides can substantially reduce your function to:
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
In fact a complete example can require only a dozen or so additional lines, e.g.
#include <iostream>
#include <vector>
#include <numeric>
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
int main (void) {
int n; /* temporary integer */
std::vector<int> v {}; /* vector of int */
while (std::cin >> n) /* while good integer read */
v.push_back(n); /* add to vector */
std::cout << "\naverage: " << avg(v) << '\n'; /* output result */
}
Above, input is taken from stdin and it will handle as many integers as you would like to enter (or redirect from a file as input). The std::accumulate simply sums the stored integers in the vector and then to complete the average, you simply divide by the number of elements (with a cast to double to prevent integer-division).
Example Use/Output
$ ./bin/accumulate_vect
10
20
34
done
average: 21.3333
(note: you can enter any non-integer (or manual EOF) to end input of values, "done" was simply used above, but it could just as well be 'q' or "gorilla" -- any non-integer)
It is good to work both with plain-old array (because there is a lot of legacy code out there that uses them), but equally good to know that new code written can take advantage of the nice containers and numeric routines C++ now provides (and has for a decade or so).
So, I created two options for you, one use vector and that's really comfortable because you can find out the size with a function-member and the other with array
#include <iostream>
#include <vector>
float average(std::vector<int> vec)
{
float sum = 0;
for (int i = 0; i < vec.size(); ++i)
{
sum += vec[i];
}
sum /= vec.size();
return sum;
}
float average(int arr[],const int n)
{
float sum = 0;
for (int i = 0; i < n; ++i)
{
sum += arr[i];
}
sum /= n;
return sum;
}
int main() {
std::vector<int> vec = { 1,2,3,4,5,6,99};
int arr[7] = { 1,2,3,4,5,6,99 };
std::cout << average(vec) << " " << average(arr, 7);
}
This is an example meant to give you an idea about what needs to be done. You can do this the following way:
// we pass an array "a" that has N elements
double average(int a[], const int N)
{
int sum = 0;
// we go through each element and we sum them up
for(int i = 0; i < N; ++i)
{
sum+=a[i];
}
// we divide the sum by the number of elements
// but we first have to multiply the number of elements by 1.0
// in order to prevent integer division from happening
return sum/(N*1.0);
}
int main()
{
const int N = 3;
int a[N];
cin >> a[0] >> a[1] >> a[2];
cout << average(a, N) << endl;
return 0;
}
how to do that without using a function
Quite simple. Just put your code in a function, let's call it calculateAverage and return the average value from it. What should this function take as input?
The list of numbers (array of numbers)
Total numbers (n)
So let's first get the input from the user and put it into the array, you have already done it:
for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
}
Now, lets make a small function i.e., calculateAverage():
int calculateAverage(int numbers[], int total)
{
int sum = 0; // always initialize your variables
for(int i = 0; i < total; ++i)
{
sum += numbers[i];
}
const int average = sum / total; // it is constant and should never change
// so we qualify it as 'const'
//return this value
return average
}
There are a few important points to note here.
When you pass an array into a function, you will loose size information i.e, how many elements it contains or it can contain. This is because it decays into a pointer. So how do we fix this? There are a couple of ways,
pass the size information in the function, like we passed total
Use an std::vector (when you don't know how many elements the user will enter). std::vector is a dynamic array, it will grow as required. If you know the number of elements beforehand, you can use std::array
A few problems with your code:
using namespace std;
Don't do this. Instead if you want something out of std, for e.g., cout you can do:
using std::cout
using std::cin
...
or you can just write std::cout everytime.
int n, i;
float num[100], sum=0.0, average;
Always initialize your variables before you use them. If you don't know the value they should be initialized to, just default initialize using {};
int n{}, i{};
float num[100]{}, sum=0.0, average{};
It is not mandatory, but good practice to declare variables on separate lines. This makes your code more readable.
For a project I need to write a program that reads in a series of positive integers, stored in an array, terminated by a -1. Then it should reverse the order of the array and print that along with the average of all the numbers.
ex: Input: 21 34 63
Output: 63 34 21 Ave: 39.3
I am not sure where to begin. I thought maybe getting a user input in a while loop. So,
int num, i;
const int SIZE = 9;
int arr [SIZE] = {i};
i = 1;
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
arr[i] = num;
i++;
}
cout << arr;
Okay so, first how do I create an array that takes user inputs and stores it as separate variables in the array? (Above is my unsuccessful attempt at that.)
Thats a simple problem. You first need to take the input and then reverse it.
int num=0, i,j,k;
const int SIZE = 99; //any upperbound value, just to ensure user doesnt enter more values then size of array
int arr [SIZE] = {0}; //better to initialize with 0
i = 0; //considering 0 indexed
int sum=0; // for average
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
if(num!=-1)
{
arr[i] = num;
sum+=num;
}
i++;
}
int temp;
//now reversing
// size of the input array is now i
for(j=0,k=i-1;j<k;j++,k--)
{
temp=arr[j];
arr[j]=arr[k];
arr[k]=temp;
}
//what i am doing here is- keeping the index j on the beginning of the
//array and k to the end of the array. Then swap the values at j and k, then
//increase j and decrease k to move to next pair of points. We do this until j is
//less then k, means until we doesnt reach mid of the array
//printing the reversed array and average
cout<<"reversed array"<<endl;
for(j=0;j<i;j++)
cout<<arr[j]<<" ";
cout<<"average"<<float(sum)/i;
see the comments for suggestions
Since you are writing your program in c++, you should take a look at std::vector and the reverse function that the STL provides you.
Using the above tools the solution to your problem is the following:
#include <vector>//include to use std::vector
#include <algorithm>//include to use reverse
int main()
{
std::vector<int> v;
int i;
float sum = 0.0f;
while(std::cin>>i && i != -1)
{
v.push_back(i);
sum+=i;
}
reverse(v.begin(),v.end());
for(int num : v)
std::cout<<num<<" ";
std::cout<<"average:"<<sum/v.size()<<std::endl;
}
I tried to calculate average and when I enter 1 2 3 0 , the average is 2.00 but when I enter 10 20 90 100 0,the average is 227871776.00. I am not able to identify what is going wrong here. I feel like my sum and count is not working properly but I can't figure out why.
double calculateAverage(int numbers[], int count )
{
int sum = 0;
double average;
while (count < arraysize && numbers[count] != 0)
{
count ++;
}
for (int i= 0 ; i < count; i++)
{
sum += numbers[i];
}
average = static_cast<double>(sum) /count;
return average;
}
Why bother even making your own count loop, when you have std:accumulate.
#include <numeric>
#include <iostream>
double calculateAverage(int numbers[], size_t count)
{
int sum = std::accumulate(numbers, numbers + count, 0);
return sum / count;
}
int main()
{
//int numbers[] = {1, 2, 3, 4, 5};
int numbers[] = {10, 20, 90, 100};
std::cout << "average is " <<
calculateAverage(numbers, sizeof(numbers) / sizeof(int)) << '\n';
}
Your code was quite confused. Why pass a count if you're going to count the array anyway? Also 0 is a valid value in the array and so it makes a flawed sentinel value.
#include<iostream>
using namespace std;
double calculateAverage(int numbers[], int count )
{
int sum = 0; //sum is used to add all the values in the array
double average;
for (int i= 0 ; i < count; i++)
sum += numbers[i];
average = static_cast<double>(sum) /count;
return average;
}
int main()
{
int lim; //size of the array
cout<<"Enter the number of elements in array\n";
cin>>lim;
cout<<"Enter the values \n";
int num[lim]; //the array is initialized to desired size
for(int i=0;i<lim;i++)
cin>>num[i]; //the values are taken from user
cout<<"\nAverage = "<<calculateAverage(num,lim)<<"\n"; //the array and the size of array is passed to calculate average function or you can even calculate size of array using (sizeof(array)/sizeof(array[firstelement])
return 0;
}
Recreate the code overall
It is hard to understand (your code).
Mine:
double calculateAverage(double numbers[], double count )
{
double sum = 0;
double average=0;
for(int counter=0;counter<count;counter++)
{
sum+=numbers[counter];
}
cout<<sum<<"\n";
average=sum/count;
return average;
}
Explaination:
First the function will take an array of double
and count is how many is there in the array (I tried to stick into your code)
The for loop runs based on the count variable.
the sum adds the value of the element in the array numbers.
Divide to get the average.
numbers[count] != 0 could produce errors when you have 0 appear earlier in the array. Also, where do you initialize arraysize? It could be null somehow or a very weird number. I recommend calling the numbers length instead. But there's no reason to use the while loop bc you have an array size already known
I am very very new to C++ and I am trying to call the function "jacobi" which performs a user specified number of iterations for the jacobi method (or at least I hope so). On the line where I call 'jacobi' I get the error "No matching function to call to "jacobi". I have read other posts similar to this one and have tried to apply it to my own code but I have been unsuccessful. Maybe there are other issues in my code causing this problem. As mentioned I am very new C++ so any help would be appreciated and please break it down for me.
#include <iostream>
using namespace std;
void jacobi (int size, int max, int B[size], int A[size][size], int init[size], int x[size]){
////
//// JACOBI
////
int i,j,k,sum[size];
k = 1;
while (k <= max) // Only continue to max number of iterations
{
for (i = 0; i < size; i++)
{
sum[i] = B[i];
for (j = 0; j < size; j++)
{
if (i != j)
{
sum[i] = sum[i] - A[i][j] * init[j]; // summation
}
}
}
for (i = 0; i < size; i++) ////HERE LIES THE DIFFERENCE BETWEEN Guass-Seidel and Jacobi
{
x[i] = sum[i]/A[i][i]; // divide summation by a[i][i]
init[i] = x[i]; //use new_x(k+1) as init_x(k) for next iteration
}
k++;
}
cout << "Jacobi Approximation to "<<k-1<<" iterations is: \n";
for(i=0;i<size;i++)
{
cout <<x[i]<< "\n"; // print found approximation.
}
cout << "\n";
return;
}
int main (){
// User INPUT
// n: number of equations and unknowns
int n;
cout << "Enter the number of equations: \n";
cin >> n;
// Nmax: max number of iterations
int Nmax;
cout << "Enter max number of interations: \n";
cin >> Nmax;
// int tol;
// cout << "Enter the tolerance level: " ;
// cin >> tol;
// b[n] and a[n][n]: array of coefficients of 'A' and array of int 'b'
int b[n];
int i,j;
cout << "Enter 'b' of Ax = b, separated by a space: \n";
for (i = 0; i < n; i++)
{
cin >> b[i];
}
// user enters coefficients and builds matrix
int a[n][n];
int init_x[n],new_x[n];
cout << "Enter matrix coefficients or 'A' of Ax = b, by row and separate by a space: \n";
for (i = 0; i < n; i++)
{
init_x[i] = 0;
new_x[i] = 0;
for (j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
jacobi (n, Nmax, b, a, init_x, new_x);
}
The problem:
There are several problems, related to the use of arrays:
You can't pass arrays as parameter by value.
You can't pass multidimensional arrays as parameter if the dimensions are variable
You can't define arrays of variable length in C++
Of course there are ways to do all these kind of things, but it uses different principles (dynamic allocation, use of pointers) and requires additional work (especially for the access of multidimensional array elements).
Fortunately, there is a much easier solution also !
The solution:
For this kind of code you should go for vector : these manage variable length and can be passed by value.
For the jacobi() function, all you have to do is to change its definition:
void jacobi(int size, int max, vector<int> B, vector<vector<int>> A, vector<int> init, vector<int> x) {
int i, j, k;
vector<int> sum(size); // vector of 'size' empty elements
// The rest of the function will work unchanged
...
}
Attention however: the vectors can be of variable size and this jacobio implementation assumes that all the vectors are of the expected size. In professional level code you should check that it's the case.
For the implementation of main(), the code is almost unchanged. All you have to do is to replace array definitions by vector definitions:
...
vector<int> b(n); // creates a vector that is initialized with n elements.
...
vector<vector<int>> a(n,vector<int>(n)); // same idea for 2 dimensional vector (i.e. a vector of vectors)
vector<int> init_x(n), new_x(n); // same principle as for b
...
I need some help creating an array with 10 number that the user can pick. Had a post about this yesterday but misstook arrays for vectors..
Need to calculate the average value of the numbers, need pseudocode for it as well.
Any help would be awesome, I do have a school book but the array examples in it will just not work (as you can se in the code I'll add).
This is what I got sofar:
#include <iostream>
#include <array>
using namespace std;
int main()
{
int n[10];
for (int i = 0; i < 10; i++)
{
cout << "Please enter number " << i + 1 << ": ";
cin >> n[i];
}
float average(int v[], int n)
{
float sum = 0;
for (int i = 0; i < n; i++)
{
sum += v[i]; //sum all the numbers in the vector v
}
return sum / n;
}
system("pause");
}
the part to calculate the average I got help with from the last post I had. But everything else won't work "/ So basicly I need help to make a array with 10 user input numbers. Cheers
The only thing that you wrote correctly is function average. I would add qualifier const to the parameter of the function
#include <iostream>
#include <cstdlib>
using namespace std;
float average( const int v[], int n )
{
float sum = 0.0f;
for ( int i = 0; i < n; i++ )
{
sum += v[i]; //sum all the numbers in the vector v
}
return sum / n;
}
Or statmenet
return sum / n;
could be substituted for
return ( n == 0 ? 0.0f : sum / n );
Take into account that functions shall be defined outside any other functions and a function declaration shall appear before usage of the function.
You need not header <array> because it is not used. But you need to include header <cstdlib> because you use function system.
As it is written in your assigment you need enter arbitrary values for the array
int main()
{
const int N = 10;
int a[N];
cout << "Enter " << N << " integer values: ";
for ( int i = 0; i < N; i++ ) cin >> a[i];
cout << "Average of the numbers is equal to " << average( a, N ) << endl;
system( "pause" );
return 0;
}
int n[10]; - n is an array of ints, not strings, so why are you doing n[0] = "Number 1: ";? You should instead loop and ask for an input from the user.
After you do this, you should place average function outsude the main function and call it from the main.
I advise you to go through a basic tutorial.
Function definition should always be outside main.
int n[10] mean n is array of integers of size 10. They are not array of pointers of type char * to hold strings
There isn't a caller for function average. Subroutines work like, callers will call callee passing arguments to perform operations on them and return them back - pass by reference.