Thread: multiple an array by another array?

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

    Question multiple an array by another array?

    Code:
    /*if i have*/
    
    array1[2]={1,2};
    array2[2]={3,4};
    
    /*how do I do (1*3)+(2*4)=11?
    
    I tried the one below, but sure it won't work*/
    
    for(i=0;i<=2;i++)
    {
      total+=array1[i]*array2[i];
    }
    
    /*thanks for your help*/

  2. #2
    pwns nooblars
    Join Date
    Oct 2005
    Location
    Portland, Or
    Posts
    1,094
    Did you intialize total to 0?

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    1) Initialise total to zero before the loop.

    2) The end criterion needs to be i < 2, not i <= 2.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Apr 2009
    Posts
    29
    if it's i<2 then it won't go over i=2? because it's <2? Hmm?

  5. #5
    pwns nooblars
    Join Date
    Oct 2005
    Location
    Portland, Or
    Posts
    1,094
    Arrays are 0 indexed meaning they count up from 0..

    0,1,2,3,4,5,6...

    So the first 2 elements are 0 and 1, so your conditional for your for statement should be i < 2 (While 'i' is less than 2).

  6. #6
    Registered User
    Join Date
    Apr 2009
    Posts
    29
    thanks, i was talking rubbish.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  2. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  3. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM
  4. two dimensional dynamic array?
    By ichijoji in forum C++ Programming
    Replies: 6
    Last Post: 04-14-2003, 04:27 PM
  5. Creating 2D arrays on heap
    By sundeeptuteja in forum C++ Programming
    Replies: 6
    Last Post: 08-16-2002, 11:44 AM