Thread: Array Adding

  1. #1
    K4D4Ver
    Guest

    Post Array Adding

    Hey, i was having trouble figuring out how to add array numbers besides:
    array[0]+array[1]+array[2]........
    I'm trying to figure out how to do the addition with a for statement or something.

    Any Help!?!?!?!?

    thanks

  2. #2
    I'm Back
    Join Date
    Dec 2001
    Posts
    556
    Code:
    --
    --
    sum=0;
    
    for(i=0;i<10;i++)
     sum=sum+arr[i];
    cout<<"ARRAY TOTAL : "<<sum;
    --
    --
    -

  3. #3
    Registered User Ion Blade's Avatar
    Join Date
    May 2002
    Posts
    35
    Try this:
    Code:
        int array [] = {3, 6, 9, 12, 15}; //your array...
        int n, result=0;
    
        for ( n=0 ; n<5 ; n++ )
        {
            result += array[n];
        }
        cout << result;
    the += in that means, "this variable equals itself plus this"
    Last edited by Ion Blade; 05-21-2002 at 11:29 PM.
    "Im going to have peaceful dreams of brackets and semicolons strapped on crucifixes, screaming for mercy" - Someone who doesn't like programming.

  4. #4
    ResurgentBarbecue UnclePunker's Avatar
    Join Date
    May 2002
    Posts
    128
    This works, I hope the explanation is good enough.

    Code:
    #include <iostream.h>
    
    int main(void)
    {
    	 int count, sum=0; //count is the for loop control variable
    	 int array[5];
    
    	 /*start count at 0 as that is the first element in the array, count goes up
    	 to 4, as 0 to 4 equals the 5 elements in the array, the count ++ means add 1 to
    	 the count each time the loop goes round, you use count in the brackets of array
    	 to tell it which element to first initialise to its own number (0,1, 2, 3, 4)
    	 and then to add that to the sum variable*/
    
    	 for (count=0; count<=4; count++)
    	 {
    		  array[count]=count;
    		  sum=sum+array[count];
    	 }
    
    	 cout<<"array sum: "<<sum; //print out sum because you have added the elements to it
    return 0;
    }
    Last edited by UnclePunker; 05-22-2002 at 03:29 AM.

  5. #5
    K4D4Ver
    Guest
    thanks, that was a no brainer.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. Modify an single passed array element
    By swgh in forum C Programming
    Replies: 3
    Last Post: 08-04-2007, 08:58 AM
  3. Adding elements to array?
    By INFERNO2K in forum C++ Programming
    Replies: 4
    Last Post: 12-15-2005, 01:56 PM
  4. Adding Scores from a string array
    By MB1 in forum C++ Programming
    Replies: 6
    Last Post: 11-11-2005, 07:27 AM
  5. Creating 2D arrays on heap
    By sundeeptuteja in forum C++ Programming
    Replies: 6
    Last Post: 08-16-2002, 11:44 AM