help!!!

i made this,but how can do it with better way?
(i want to count the average of numbers into the list)
1
2
3
4
5
6
7
8
9
10
11
12
:
#include<iostream>
using namespace std;

main()
{
  int array[5]={1,2,3,4,5};
  int sum=0;

   sum=sum+array[0]+array[1]+array[2]+array[3]+array[4];
   cout<<sum/5;
}
"old" C++:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
using namespace std;

main()
{

  int array[]={1,2,3,4,5};
  int sum=0;

	int size = sizeof(array)/sizeof(int);
	cout << "size of array: " << size << endl;
	for(int i = 0; i < size; i++)
		sum += array[i];
   cout<<sum/size;
}


In the Cx11 there's an own array data type, but atm I can't give you an example for this.
Last edited on
Well, if your array will contain 100 elements you will list all elements in the expression? And what about 1000 elements?:)
So it is much better to use a loop to calculate the sum.

By the way the main shall have return type int

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>

int main()
{
   const int N = 5;
   int array[N] = { 1, 2, 3, 4, 5 };
   int sum = 0;

   for ( int i = 0; i < N; i++ ) sum += array[i];

   std::cout << "The average is " << sum / N << std::endl;
}


Now let assume that you need to caculate the average of an array with 100 elements. How to initialize the array in this case? The simplest way is to use standard C++ algorithms. You can use std::iota to initialize the array and std::accumulate to get the sum of array elements.
The code will look the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include <numeric>

int main()
{
   const int N = 100;
   int array[N];

   std::iota( std::begin( array ), std::end( array ), 1 );

   int average = std::accumulate( std::begin( array ), std::end( array ), 0 ) / N;

   std::cout << "The average is " << average << std::endl;
}



Last edited on
thank you guys!!!
Am I right in thinking that std::iota is only in the C++11 standard?

I'm aware of it's unofficial use in earlier standards but I'm pretty sure the std implementation is C++11 only.
You are right. std::iota is included in the C++ 11 Standard. But it can be substituted for a user-defined algorithm or for a very simple loop.
Last edited on
Topic archived. No new replies allowed.