A
arnuld
it compiles and runs and at one place it produces strange output becaus
eof a semantic-bug. i can't find it:
/* C++ Primer - 4/e
*
* exercise 7.12
* STATEMENT:
* write a programme to calculate the sum of the elements in an
array. write th e function 3 times.each time using a different approach
to manage the array bounds.
*
*/
#include <iostream>
/* i wanted both parameters, the pointer itself the int to which the
pointer points, to be const but for me this "const" thing in C++ is too
complex to be understood
, any help on that */
/* Method-1: using Pointers (like iterators) */
int print_sum_iter( const int *pbegin, const int *pend ) {
int sum = 0;
while( pbegin != pend )
{
sum += *pbegin++;
}
return sum;
}
/* Method-2: using indexing */
int print_sum_index( const int ia[], size_t arr_size ) {
int sum = 0;
for( size_t i=0; i != arr_size; ++i)
{
sum += ia;
}
return sum;
}
/* Method-3: using NULL terminator */
int print_sum_NULL( const int *parr ) {
int sum = 0;
while( *parr != '\0' )
{
sum += *parr++;
}
return sum;
}
int main()
{
const int arr_size = 3;
int ia[arr_size] = { 0, 2, 4 };
std::cout << "print_sum_iter: "
<< print_sum_iter( ia, ia + arr_size ) << "\n";
std::cout << "print_sum_index: "
<< print_sum_index( ia, arr_size )
<< "\n";
std::cout << "print_sum_NULL: "
<< print_sum_NULL( ia )
<< std::endl;
return 0;
}
/* OUTPUT
~/programming/cpp $ g++ -ansi -pedantic -Wall -Wextra ex_07-12.cpp
~/programming/cpp $ ./a.out
print_sum_iter: 6
print_sum_index: 6
print_sum_NULL: 0
~/programming/cpp $
*/
eof a semantic-bug. i can't find it:
/* C++ Primer - 4/e
*
* exercise 7.12
* STATEMENT:
* write a programme to calculate the sum of the elements in an
array. write th e function 3 times.each time using a different approach
to manage the array bounds.
*
*/
#include <iostream>
/* i wanted both parameters, the pointer itself the int to which the
pointer points, to be const but for me this "const" thing in C++ is too
complex to be understood
/* Method-1: using Pointers (like iterators) */
int print_sum_iter( const int *pbegin, const int *pend ) {
int sum = 0;
while( pbegin != pend )
{
sum += *pbegin++;
}
return sum;
}
/* Method-2: using indexing */
int print_sum_index( const int ia[], size_t arr_size ) {
int sum = 0;
for( size_t i=0; i != arr_size; ++i)
{
sum += ia;
}
return sum;
}
/* Method-3: using NULL terminator */
int print_sum_NULL( const int *parr ) {
int sum = 0;
while( *parr != '\0' )
{
sum += *parr++;
}
return sum;
}
int main()
{
const int arr_size = 3;
int ia[arr_size] = { 0, 2, 4 };
std::cout << "print_sum_iter: "
<< print_sum_iter( ia, ia + arr_size ) << "\n";
std::cout << "print_sum_index: "
<< print_sum_index( ia, arr_size )
<< "\n";
std::cout << "print_sum_NULL: "
<< print_sum_NULL( ia )
<< std::endl;
return 0;
}
/* OUTPUT
~/programming/cpp $ g++ -ansi -pedantic -Wall -Wextra ex_07-12.cpp
~/programming/cpp $ ./a.out
print_sum_iter: 6
print_sum_index: 6
print_sum_NULL: 0
~/programming/cpp $
*/