converting c program to c++

Hello everyone.
I have tried to convert the following c program into c++ but my problem now is to change array in the program into vector.please help


[c code]
/* Convert this program to C++
* change to C++ io
* change to one line comments
* change defines of constants to const
* change array to vector<>
* inline any short function
*/

#include <stdio.h>
#define N 40
void sum(int*p, int n, int d[])
{
int i;
*p = 0;
for(i = 0; i < n; ++i)
*p = *p + d[i];
}
int main()
{
int i;
int accum = 0;
int data[N];
for(i = 0; i < N; ++i)

data[i] = i;

sum(&accum, N, data);
printf("sum is %d\n", accum);
return 0;
}


This is my c++ code :


// Convert this program to C++
// change to C++ io
//change to one line comments
// change defines of constants to const
// change array to vector<>
// inline any short function

#include <iostream>
#include<vector>
const int N =40;
void sum(int*p, int n, int d[])
{
int i;
*p = 0;
for(i = 0; i < n; ++i)
*p = *p + d[i];
}
int main()
{
int i;
int accum = 0;
int data[N];
for(i = 0; i < N; ++i)

data[i] = i;

sum(&accum, N, data);
cout<<" sum is "<< accum<<endl;
return 0;
}




Try something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <vector>

using namespace std;

const int N = 40;

template <typename T>
int sum(T val)
{
	int s = 0;
	for(int i = 0; i < val.size(); ++i)
		s += val[i];
	return s;
}

int main()
{
	vector<int> vec;
	
	for(int i = 0; i < N; ++i)
		vec.push_back(i);
		
	cout<<" sum is "<< sum(vec) << '\n';
	return 0;
}


Output:

sum is 780

Using a template function you can pass many types of variables to T val, e.g. vector( like here), integer, floating, double.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>

constexpr int N = 40 ;

int main()
{
    std::vector<int> data(N); // vector of N integers

    std::iota( std::begin(data), std::end(data), 0 ) ; // fill up with 0, 1, 2 ... N-1

    std::cout << "sum is " // sum of the integers in data
               << std::accumulate( std::begin(data), std::end(data), 0 ) << '\n' ;
}
Topic archived. No new replies allowed.