Array Question

(first of all sorry if i make any mistake on my english)
Well I'm new at programing , and the first and only language i can so far is c++ as i was learning Array , i was working on adding many elements together with arry but at the end it was just a long code line:

m(s[0]+s[1]+s[2]+s[3]+s[4]+s[5]+s[6]+s[7]+s[8]+s[9]+s[10]+s[11]+s[12]+s[13]+s[14])/15;

I want to know if there is a way to make it shorter, in a kind of way of not nedding to write such a long code line.

Thank you :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const int N = 15 ;
const int array[N] = { 1, 23, 4, 56, 7, 8, 9, 87, 65, 43, 21, 23, 4, 56, 7 } ;

int sum = 0 ;
// recommended - range-based loop: for each value in array, add to sum
for( int value : array ) sum += value ;
std::cout << "sum: " << sum << "  average: " << double(sum) / N << '\n' ;

sum = 0 ;
// classical for-loop: for value at each position in the in array, add to sum
for( int i = 0 ; i < N ; ++i ) sum += array[i] ;
std::cout << "sum: " << sum << "  average: " << double(sum) / N << '\n' ;

sum = 0 ;
// classical for-loop using iterator (pointer)
for( auto iter = std::begin(array) ; iter != std::end(array) ; ++iter ) sum += *iter ;
std::cout << "sum: " << sum << "  average: " << double(sum) / N << '\n' ;
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

size_t SIZE = 15;//array size as global variable
int main()
{
    double a[SIZE];//declare array
    double avg = 0;//a variable to hold the average

    for (size_t i = 0; i < SIZE; i++)
    {
        a[i] = i;//fill the array;
        avg += (double)(a[i]/SIZE);//running average cast to double
    }
 
    std::cout << avg <<"\n";//print average
}

edit: OOPS, just realised the great JLBorges has himself (herself?) replied. OP: disregard my post, you're better off learning from the guru!!
Last edited on
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <numeric>
using namespace std;

int main()
{
   const int N = 15 ;
   const int array[N] = { 1, 23, 4, 56, 7, 8, 9, 87, 65, 43, 21, 23, 4, 56, 7 } ;
   cout << "Mean is " << accumulate(array,array+N,0) / ( N + 0.0 );
}
Topic archived. No new replies allowed.