code question

Hi, I just learned about looping in c++. I came across the following problem:
Write a program that asks the user to type in numbers. After each entry, the program should report the cumulative sum of the entries to date. The program should terminate when the user enters 0.

Here's my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// num_sum.cpp -- finding the sum of numbers typed in by the user
#include <iostream>
using namespace std;
int main()
{
  int size;
  int nos[size];
  cout << "Enter the number of nos. you want to add: ";
  cin >> size; // size denotes the numbers taken in the array
  
  cin >> nos[size];
  
  int sum = 0;
  while (nos[size] != '0')  // while the input is not '0'
    {
      sum += nos[size];    // sum value is incremented by the no. entered
    }

  cout << "The sum is: " << sum << endl;
  return 0;
}


Unfortunately, when I run the code I get the following error:
Segmentation fault (core dumped)

where did I go wrong?
thanks in advance
Last edited on
one problem is that size of an array must be known at compile time:

1
2
  int size; // wrong, what's the size?
  int nos[size];


instead:
1
2
const int size = 30;
int nos[size];


your while loops also contains a bug because you're comparing against '0' which is a constant character but your "nos" array will often be filled with random junk so you can't rely on that:
1
2
3
4
while (nos[size] != '0')  // while the input is not '0'
    {
      sum += nos[size];    // sum value is incremented by the no. entered
    }


you should either initialize it with zeros like this
1
2
for(int i = 0; i < size; ++i)
    nos[i] = 0;


or use memset function:
memset(nos, 0, sizeof(nos));


one more problem is that the user will input a single number, so you do not need a whole array to store single number. but that depends on what you want realy.

edit:
presumably you may want to just sum the inputs, if so your loops should look like this:
1
2
3
4
5
6
7
8
9
10
11
12
	for (int i = 0; i < size; ++i)
	{
		cout << "Enter the number of nos. you want to add at" << i << ": ";
		cin >> nos[i];
	}

	int sum = 0;
	int No = -1;
	while (++No < size)  // summ all the inputs
	{
		sum += nos[No];    // sum value is incremented by the No. entered
	}
Last edited on
Registered users can post here. Sign in or register to post.