0

I have a question for an exam and by the way that it sounds, it could be a trap question:

How many assignments will there be executed in the following algorithm if n and p are considered to be integers?

p=1;
n=279;

while (n>=100) { 
  p=p*10;
  n=n-100;
} 

I would say that there are 4 assignments in the while loop and two before the while ... so 6 ? I'm not sure why the question highlights the integer feature of the variables.

CCBet
  • 416
  • 1
  • 6
  • 19
  • 1
    Knowing they're integers, you know they can go negative by subtraction. Unsigned integers couldn't. – Mike Kinghan Mar 05 '16 at 17:52
  • 1
    Wasn't trying to answer the question, just accounting for the significance of *integer*. If `n` was *unsigned* it would loop forever. Since the code is C-like but not compilable C, I don't know whether to count `p=1; n=279;` as *assignments* or *initializations*. Sloppy question IMO. If it's not multiple choice you might say "It depends..." and explain both ways. – Mike Kinghan Mar 05 '16 at 18:21
  • Sloppy question IMO also. That's why i have the doubt about how many would there be ... But which would be the difference between a initialization (i asume it's the operation through which a value is assigned to the variable) and asignment ? is assignment considered the situation when the same variable will get through another operation a new value ? – CCBet Mar 05 '16 at 18:29
  • Correct. Initialization = variable created with value. Assignment = old variable assumes new value. – Mike Kinghan Mar 05 '16 at 18:33

1 Answers1

1

I'd say 6 because the declaration seems to be somewhere else -- it's not

int p=1, n=279; 

Ok, even in that case I'd lean towards 6 because the declarations imply assignments (and this thread seems to agree: Difference between declaration statement and assignment statement in C? ), but this is fortunately not the question here.

Community
  • 1
  • 1
Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51