fork download
  1. #include <iostream>
  2.  
  3. // using namespace std; // avoid this, especially at global scope
  4.  
  5. // use whitespace to make it more readable
  6. void print_array( const int arg[], int length, char seperator )
  7. {
  8. int i = 0 ;
  9. for( ; i < length-1 ; ++i )
  10. std::cout << arg[i] << seperator ;
  11. if( length > 0 ) std::cout << arg[i] ; // print the last element
  12. }
  13.  
  14. // seperate words in identifiers with an _ (or change of case)
  15. int add_array( const int arg[], int length ) // make it const-correct
  16. {
  17. int sum = 0 ; // give this a more intuitive name
  18. for( int i=0; i<length; ++i ) // get into the habit of using prefix increment/decrement
  19. sum = sum + arg[i] ;
  20.  
  21. // the function should just return the sum and leave the decision about what the
  22. // sum is to be used for to the caller.
  23.  
  24. return sum ;
  25. }
  26.  
  27. int main()
  28. {
  29. const int first_array[] = {5,5,5,5}; // const-correct
  30. const int second_array[] = {6,16,26,36,46,56}; // const-correct
  31.  
  32. // why should we hard code magic numbers
  33. // when the compiler can calculate it for us?
  34. const int sz_first = sizeof(first_array) / sizeof( first_array[0] ) ;
  35. const int sz_second = sizeof(second_array) / sizeof( second_array[0] ) ;
  36.  
  37. print_array( first_array, sz_first, '+' ) ;
  38. std::cout << " == " << add_array( first_array, sz_first ) << '\n' ;
  39.  
  40. print_array( second_array, sz_second, '+' ) ;
  41. std::cout << " == " << add_array( second_array, sz_second ) << '\n' ;
  42.  
  43. // there is an implicit return 0 ; here
  44. }
  45.  
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
5+5+5+5 == 20
6+16+26+36+46+56 == 186