Simple addition in while.
Jul 16, 2014 at 10:04pm UTC
Hi :)
Let's say I have a file with numbers, each on a line.
Which is the most simple way to sum up the numbers from the file, using as less variables and instructions as possible.
Any more simple way than this ?
1 2 3 4
int temp,sum=0;
while (file>>temp){
sum+=temp;
}
Any way to do the addition in the condition ?
Jul 16, 2014 at 10:07pm UTC
Any way to do the addition in the condition ?
You could but its not any different than what you did. I wouldn't see any benefit over
1 2 3 4 5 6
int temp, sum = 0;
while (file >> temp && sum += temp);
//or
int temp, sum = 0;
while (file >> temp && sum += temp){}
All 3 do the same thing.
Jul 16, 2014 at 10:43pm UTC
Thank you. I was wondering if one can do this with just a variable.
Last edited on Jul 16, 2014 at 10:59pm UTC
Topic archived. No new replies allowed.