Reputation: 89
So, I used following code but my friends say this code is incorrect as I am using third variable in for-loop. Kindly help.
int x = 0;
int y = 0;
for ( int i = 0; i < 10; i++)
{
cin >> y;
x = x + y;
}
cout << x;
Upvotes: 0
Views: 1178
Reputation: 94329
I see no rules restricting the types of variables, so you could just use an array and do it in one variable:
int arr[3] = {0};
for (; arr[0] < 10; ++arr) {
cin >> arr[1];
arr[2] += arr[1];
}
cout << arr[2];
However, you could also do it using a recursive function using two variables (if you consider the function argument a variable); this doesn't even need a loop (though I'm not sure if the and a loop
part means that you have to use a loop, in which case you could of course just put a sneaky do { ... } while(0);
somewhere. ;-)
int sum(int x) {
if (x == 0) {
return 0;
}
int v;
cin >> v;
return v + sum(x - 1);
}
cout << sum(10);
Upvotes: 0
Reputation: 9407
If I understand correct you want to use this x += y;
. This is a two-variable inside a loop method that does the same functionality as x = x + y;
that they considered a three-variables inside a loop.
Upvotes: 0
Reputation: 320531
If you can restrict the range of the sum, you can do something like
const unsigned LIMIT = 1000000;
unsigned x;
for ( x = LIMIT * 10; x >= LIMIT; x -= LIMIT)
{
unsigned y;
cin >> y;
x += y;
}
cout << x;
This would be an arithmetic equivalent of other bit-fiddling tricks based on squeezing two values into one variable, as in @Richard Hodges's answer.
But that requires restricting the range of the sum.
Upvotes: 1
Reputation: 69882
Rationale:
Use a 64-bit value as the accumulator since it's unlikely that users will enter numbers that large.
Use the top 8 bits (could be 4) of the accumulator as the counter.
#include <iostream>
int main()
{
using namespace std;
int64_t accum = int64_t { 10 } << 56;
while (accum & (int64_t{0xff} << 56))
{
int next;
cin >> next;
accum += next;
accum -= int64_t { 1 } << 56;
}
cout << accum << endl;
return 0;
}
Upvotes: 1
Reputation: 441
I see nothing wrong with this code. More descriptive variables would be more helpful maybe (i.e. y
-> userInput
, x
-> sum
).
Upvotes: 2