Structured Programming – Why Aren’t Operations Contained Within Output Commands?

pseudocodestructured-programming

I'm going through an introductory programming book and it lists a simple example in pseudocode:

Start
  input myNumber
  set myAnswer = myNumber * 2
  output myAnswer
Stop

Why can't we omit creating another variable called myAnswer and just put the operation into the output command, like this:

Start
  input myNumber
  output myNumber * 2
Stop

Why is the former correct and latter not?

Best Answer

You could but the other is so you see what is going on and so you can use myAnswer later in the program. If you use your second one, you cannot reuse myAnswer.

So later down in the program you might want:

myAnswer + 5
myAnswer + 1
etc.

You might have different operations you want to use it for.

Consider swapping numbers:

Start
  input myNumber
  set myAnswerA = myNumber * 2
  output myAnswerA
  set myAnswerB = myNumber * 3
  output myAnswerB
  set temp = myAnswerA
  set myAnswerA = myAnswerB
  set myAnswerA = temp
  output myAnswerA
  output myAnswerB
Stop

That would be difficult without variables. Computer books start real basic, and most programming is easy until you see complexity. Most everything is trivial in tutorials, and it is only in complexity do you see where things do or do not make sense.