Theory of Programming Languages/Imperative Programming

From Wikiversity
Jump to navigation Jump to search

This is a lesson in in the course, Theory of Programming Languages, which is a part of The School of Computer Science

Objective[edit]

Books-aj.svg aj ashton 01f.png

In this lesson, students will learn about the imperative paradigm of programming.

Students will be able to answer these questions:

  • How do imperative programs function?
  • Why are loops important in imperative programs?

Imperative programming[edit]

BASIC (which stands for Beginner's All-purpose Symbolic Instruction Code) was an imperative language used on most microcomputers of the 1970's.

Imperative programming - not unlike the imperative tense in human languages - is based on commands. This is different than declarations which are the staple of declarative languages. Rather than making claims about the universe, programmers only issue instructions for what a program should do. Almost all computers follow an imperative paradigm at a hardware level - the CPU follows instructions from machine code line-by-line. Therefore it is unsurprising that most computer languages are imperative in nature.

Executing instructions linearly need not be a limitation for programmers. Loops, an important component of procedural programs, allow a sequence of instructions to be executed multiple times. Branches, jumps, and procedure calls further extend functionality of programs by allowing the point of execution to shift.


Let's look at an example of some imperative programming - consider this simple example in BASIC: (Although you may be unfamiliar with imperative languages, try to read this program as best as you can.)

5 LET S = 0
10 MAT INPUT V
20 LET N = NUM
30 IF N = 0 THEN 99
40 FOR I = 1 TO N
45 LET S = S + V(I)
50 NEXT I
60 PRINT S/N
70 GO TO 5
99 END

As you may have been able to gather, this program loops through a given input, and computes the average.

Assignments[edit]

Crystal Clear app kedit.svg
  • Look up five languages which are imperative. Find some sample code from each and follow the point of execution, examining the functionality of the program.
  • Write some imperative pseudocode for these problems:
  1. Finding the square root of an inputted number.
  2. Computing the length of a list.
  3. Using at least one function call, computing the factorial of an input.

Tulliana launch.png Completion status: this resource is just getting off the ground. Please feel welcome to help!