0

Ok so i have an int array that looks like this:

int money[] = {};

and then I added values to that array by doing scanf, and then added each scanf value to the array with a for-loop, ONE number at a time:

for (int i = 0; i < 1; i++)
{
    money[i] = currentPrice;
}

So after doing this a few times (with scanf) my array looks like this:

money[] = {50, 75, 1, 40, 4};

How can I use a for-loop to go through all elements in the list and add them together and print them out?

int total = blablabla.......
printf(total);
Wain
  • 118,658
  • 15
  • 128
  • 151
aliazik
  • 195
  • 1
  • 5
  • 13
  • Does objective-C allow zero size arrays? Because that isn't standard C. – juanchopanza Apr 26 '15 at 14:54
  • Is this a C or Objective-C question? You cant dynamically resize C arrays since they are just contiguous blocks of memory, and you aren't using `NSMutableArray` and `NSNumber` which would be the easier solution if you want to use Obj-C – Rich Tolley Apr 26 '15 at 14:59
  • I tried writing NSArray money = {} but it did not work. How do I do that? And how would I add numbers to the array, using scanf? – aliazik Apr 26 '15 at 15:02

1 Answers1

-1
int total = 0;
for (int i = 0; i < arrayCount; i++) {
    total += money[i];
}

printf("%i", total);

Note that you need to keep a reference to the number of ints in your array.

Also I must point out that your code:

for (int i = 0; i < 1; i++)
{
    money[i] = currentPrice;
}

Is not adding a value to the array it is just rewriting the value currentPrice to the 0th index of the array. Therefore your array will never have a length > 1.

Check out this tutorial

Here is a basic example of adding ints to an array using scanf:

#include <stdio.h>

#define MAX_COUNT 10

int myArr[10];
int currentCount = 0;

void addInt();

int main(int argc, const char * argv[]) {


    for (int i = 0; i < MAX_COUNT; i++) {
        addInt();
    }
    int total = 0;
    for (int i = 0; i < MAX_COUNT; i++) {
        total += myArr[i];
    }
    printf("%i", total);

    return 0;
}

void addInt() {
    int new;
    scanf("Enter num: %i", &new);
    myArr[currentCount] = new;
    // Keep reference of number of elements in array...
    currentCount++;
}
Rob Sanders
  • 5,197
  • 3
  • 31
  • 58
  • how do I get the arrayCount? – aliazik Apr 26 '15 at 14:42
  • When you "add" a value to the array you need to have another int that tracks the count (easiest option). See [this SO question](http://stackoverflow.com/questions/10290610/how-can-i-find-the-number-of-elements-in-an-array) for more details. – Rob Sanders Apr 26 '15 at 14:43
  • That website is blocked in my country. Can you please provide a code example instead, on how to add integer values to the array, using scanf? – aliazik Apr 26 '15 at 14:54