Thread: Completely stumped on += operator. (5 lines of code)

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    158

    Completely stumped on += operator. (5 lines of code)

    Code:
    void declare_winner (int temp2[],int counter,int i) {
        
        for(i=0;i<=3;i++){
        
        counter += temp2[i];
            
        } // prints out a WRONG value (358484)
            
         counter = temp2[0]+ temp2[1]+ temp2[2]+ temp2[3]; // prints out the correct value
         
        
        printf("%d",counter);
    
    
    }
    I know they're the same to C, but how come one prints out a completely wrong value? I'm really stumped on this. Am i accessing out of bounds using the for loop?
    Last edited by tmac619619; 08-22-2015 at 03:51 PM. Reason: SOLVED. counter was not initiliazed to 0

  2. #2
    Registered User
    Join Date
    Oct 2012
    Posts
    158
    Thanks Solved!

  3. #3
    Registered User
    Join Date
    Mar 2014
    Location
    Corning, New York, USA
    Posts
    96
    Where did you get the solution? Just in case anyone else reads this, to me, it looks like the problem is within your for loop. This line in particular:
    Code:
    counter += temp2[i];
    . You say the bottom one works correctly,
    Code:
    counter = temp2[0]+ temp2[1]+ temp2[2]+ temp2[3];
    . The first can be written like:
    Code:
    counter = counter + temp2[i];
    . This equates to
    Code:
    counter = counter + temp2[0] + temp2[1] + temp2[2] + temp2[3];
    .


    I see in your comment you put the reason as to what the problem is. In the loop, you add the value of counter to counter, and then you add temp2[i]. The other, you just add temp2[i] essentially. Your solution is correct, initialize counter to 0 before you go into the for loop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Cannonball trajectory issue, I'm completely stumped!
    By Kyler45 in forum C++ Programming
    Replies: 1
    Last Post: 10-11-2014, 11:22 AM
  2. Stumped on old 16-bit code
    By TAZIN in forum Windows Programming
    Replies: 17
    Last Post: 12-15-2010, 09:20 AM
  3. Problem with deleting completely blank lines
    By dnguyen1022 in forum C Programming
    Replies: 3
    Last Post: 12-07-2008, 11:51 AM
  4. Lines of code per day.
    By abachler in forum A Brief History of Cprogramming.com
    Replies: 19
    Last Post: 10-26-2007, 09:20 AM
  5. Completely seperating parts of code
    By Boksha in forum C++ Programming
    Replies: 3
    Last Post: 08-14-2005, 11:36 AM