Sum of random number

Here I have a program that asks for how many random numbers I would like to generate. Say one of the number is "6828". The sum of it would be 24 (6+8+2+8). How do I program this? I have absolutely no clue of the next steps.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>

using namespace std;

int read_validate(int a, int b)
{
    int k = 0;

    bool ok;

    do
    {
        cout << "Enter sequence: ";
        cin >> k;

        ok = (k >= a && k <= b);

        if (!ok) //(ok == false)
            cout << "Invalid sequence length!!" << endl;

    } while (!ok);   //while (ok == false)

    return k;

}

void generate_seq(int V[], int n)
{
    const int MAX_interval=9999;

        //srand(time(0));

        for(int i = 0; i < n; i++)
            V[i] = rand()%MAX_interval; //generate and store a random digit1
}

void display_seq(int V[], int n, int n_col)
{
    cout << "The sequence:" << endl;

    for(int i = 0; i < n; i++)
    {
        cout << setw(6) << V[i];
        if ((i+1) % n_col == 0 )
            cout << endl;
    }
    cout << endl;
}



int main()
{
    const int max_size = 200;
    const int min_size = 0;
    const int cols = 8;

    int seq[max_size];
    int n=0;

    n=read_validate(min_size, max_size);

    generate_seq(seq, n);

    display_seq(seq, n, cols);

}
Here is my first crack at it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <ctime>
#include <string>

int main(){

	srand(unsigned(time(0)));
	std::string str = std::to_string(rand() % 10000);
	int sum = 0;
	
	std::cout << str << std::endl;

	for (unsigned int i = 0; i < str.length(); i++)
		//Fun times with character math
		sum += str.at(i) - 48;

	std::cout << sum << std::endl;

	return 0;
}
On a second thought,

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
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <ctime>
using namespace std;

int main()
{
	const int MAX = 10000;
	int number;
	int sum = 0;
	vector<int> vec;

	srand(static_cast<unsigned>(time(NULL)));
	ostream_iterator<int> output (cout," + ");
	
	number = rand()%MAX;
	
	cout<<number<<endl;
	while(number != 0)
	{
		vec.push_back(number%10);
		number /= 10;
	}

	sum = accumulate(vec.begin(),vec.end(),0);

	copy(vec.begin(),vec.end(),output);

	cout<<" = "<<sum<<endl;
	cin.ignore();
	return 0;
}	
Topic archived. No new replies allowed.