Public Group

Array / Pointer problem

This topic is 4552 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

ok I am having some trouble getting this code to work the problem lies in the "while" statement here is the code any help and/or explanation would be appreciated!
//Header: AddNums.h

//Function Prototypes:

#include <iostream>
using namespace std;

//Fuction Code
return Num1+Num2;
}
long Result;
long i;

Result = 0;
while(NumOfNums--)
Result+= NumArray;

return Result;
}

int main() {
cout <<"Result of two numbers added = "<<Result<<endl;
long Array[5] = {10,20,30,40,50};
cout <<"Result of combined array total = "<<Result2 << endl;
system("SLEEP");
}



Share on other sites
i is initialized, therefore NumArray points ... somewhere that's unlikely to actually be in the array.

Furthermore, if you want to sum all the values, you need to make your index change somehow, otherwise, you'll just be adding the same value over and over.

You can try either something like:
for(i=0; i<NumOfNums; ++i)    Result+= NumArray;

or something like
i = 0;while(NumOfNums--){    Result += NumArray    ++i;}

Or something equivalent.

Share on other sites
while(NumofNums--) goes on forever. you want it to stop at 0 but when it is 0 it sees "hey I can substract 1 from NumofNums to get -1 and so on

Share on other sites
Quote:
 Original post by Vegettexwhile(NumofNums--) goes on forever. you want it to stop at 0 but when it is 0 it sees "hey I can substract 1 from NumofNums to get -1 and so on

Not true.

It evaulates the variable "NumofNums", if its zero it quits the loop. Otherwise, it decrements it and program flow continues for another iteration.

Share on other sites
Quote:
Original post by rip-off
Quote:
 Original post by Vegettexwhile(NumofNums--) goes on forever. you want it to stop at 0 but when it is 0 it sees "hey I can substract 1 from NumofNums to get -1 and so on

Not true.

It evaulates the variable "NumofNums", if its zero it quits the loop. Otherwise, it decrements it and program flow continues for another iteration.

Ouch, yeah, I am still sleeping....shouldn't go out anymore :P

{
long Result = 0, i = 0;
while(NumOfNums--)
Result+= NumArray[i++];
return Result;
}

should just work fine :)

bah alcohol :) ahwel, I am awake now :)

Share on other sites
Thanks for the help! IT works fine now! you know it would be something stupid like not defining a value for i! Duh!

1. 1
Rutin
44
2. 2
3. 3
4. 4
5. 5

• 11
• 9
• 12
• 10
• 13
• Forum Statistics

• Total Topics
632984
• Total Posts
3009712
• Who's Online (See full list)

There are no registered users currently online

×