summing up an array?

This is a discussion on summing up an array? within the C Programming forums, part of the General Programming Boards category; Code: #include <conio.h> #include <stdio.h> int main() { int i,total,array[3]={4,5,6}; total=0; for(i=0;i<3;i++) { total+=array[i]+array[i+1]; printf("%i",(total)); } getch(); } /*above is ...

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    29

    summing up an array?

    Code:
    #include <conio.h>
    #include <stdio.h>
    
    int main()
    {
      int i,total,array[3]={4,5,6};
    
      total=0;
    
      for(i=0;i<3;i++)
      {
        total+=array[i]+array[i+1];
        printf("%i",(total));
      }
    
    getch();
    }
    
    /*above is incorrect, but how do I do 4+5+6=15?*/

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,773
    You just need to add the current array element to the total.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Apr 2009
    Posts
    29
    how?

  4. #4
    Registered User
    Join Date
    Oct 2006
    Posts
    250
    Hint:

    The following:

    Quote Originally Posted by Dakaa View Post
    Code:
        total+=array[i]+array[i+1];
    Expands to:

    Code:
    total = total + array[i] + array[i+1];

  5. #5
    Registered User
    Join Date
    Apr 2009
    Posts
    29
    sweet.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 10:33 AM
  2. [question]Analyzing data in a two-dimensional array
    By burbose in forum C Programming
    Replies: 2
    Last Post: 06-13-2005, 07:31 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. Array Program
    By emmx in forum C Programming
    Replies: 3
    Last Post: 08-31-2003, 12:44 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21