Hi again,

Suppose we have an array. Array(3). The user has written 5, 6, and 7 to (0) (1) (2) within that array.

How would I add them up? If it's like Array(0) + Array(1) + Array (2) that's all very well but..

What if the array size was (10). How could I add up only the filled element. ASAIK, adding up elements that have not been assigned data to will cause very wierd and bad things to happen.

Thanks...again.

Recommended Answers

All 4 Replies

You need to keep track of the size of your array, then loop over the contents which have been filled, adding them. If it was an array of Objects, and the array was initialized to null (same as Java?), you could also use an if statement such as... if (element != null) total+= element.value;

How about the use of an std::vector, heres a small example.

#include <iostream>
#include <vector>

int main() {
  // Init vector
  std::vector<int> nums;

  // Add objects to vector
  nums.push_back( 5 );
  nums.push_back( 6 );
  nums.push_back( 7 );

  // Add them all together
  int total = 0;
  for (size_t i = 0; i < nums.size(); ++i)
    total += nums[i];

  // Display total
  std::cout << total;
}

Would it be possible to just convert an entire array to a variable? Perhaps like this,

array[2]
int array[0]  = 5 array[1] = 6
int x
x=array;
cout <<"I am now a variable therefore I equal" << X=;

X equalled 11.

What if array[5], and the first two elements had the same contents, would x still be able to become 11?

I'd prefer to keep things simple, so would'nt like to use vectors + classes until I go thru it at uni.

Thanks

>I'd prefer to keep things simple, so would'nt like to use vectors + classes until I go thru it at uni.
Well, that wont work the way your trying, so if you want to keep things simple, stick with std::vector.

But if you need a solution that doesn't require a vector, do something like this:

#include <iostream>

int main() {
  // Init vector
  int nums[3];

  // Add objects to vector
  nums[0] = 5;
  nums[1] = 6;
  nums[2] = 7;

  // Add them all together
  int total = 0;
  int count = sizeof(nums) / sizeof(int);

  for (size_t i = 0; i < count; ++i)
    total += nums[i];

  // Display total
  std::cout << total;
}

Though, in this example, the array will not be resizable. If you make the nums array larger to begin with than you actually need, then you need to make sure each integer has a value of 0 so that when totalling up the values, they aren't included. It can be done like this:

int nums[10] = { 0 };

Hope this helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.