liveBook · Manning

Imperative programming

As explained in Modern C, Third Edition

A programming paradigm in which programs specify computations as ordered commands that change program state or direct execution.

Imperative programming organizes computation as orders given to a computer. A C program combines declarations, statements, function calls, and control structures to direct specific tasks. section 1.0 section 1.1

Listing 1.1 The first example of a C program
/* This may look like nonsense, but really is -*- mode: C -*- * 1 /
#include <stdlib.h> 2 
#include <stdio.h>  
3 
/* The main thing that this program does. */ 4 
int main(int argc, [[maybe_unused]] char* argv[argc+1]) { 
// Declarations 5 
double A[5] = { 6 
[0] = 9.0, 7 
[1] = 2.9, 
[4] = 3.E+25, 8 
[3] = .00007, 
};
9 
// Doing some work 10 
for (size_t i = 0; i < 5; ++i) {  11 
printf("element %zu is %g, \tits square is %g\n", 
i,
A[i], 12 
A[i]*A[i]); 13 
}
14 
return EXIT_SUCCESS; 15 
}

The first C example declares an array, assigns selected elements, iterates with a for loop, calls printf, and returns success. section 1.0

Read the program from the inside out: printf is a function call with arguments, including a format string and computed expressions. The for statement repeatedly performs the output statement for each array element. section 1.1 section 1.0

    printf("element %zu is %g, \tits square is %g\n",
          i,
          A[i],
          A[i]*A[i]);

This excerpt isolates the imperative action: pass the index, an array value, and its square to printf. section 1.1

 > ./getting-started
 element 0 is 9,         its square is 81
 element 1 is 2.9,       its square is 8.41
 element 2 is 0,         its square is 0
 element 3 is 7e-05,     its square is 4.9e-09
 element 4 is 3e+25,     its square is 9e+50

Running the program produces five terminal lines, making the ordered computation visible through each element and its square. section 1.1

How Modern C, Third Edition covers it

How deep it goes
Explains declarations, statements, function calls, arguments, expressions, and loops through one executable C example.
Examples
Demonstrates an array loop that prints five elements and their squares to a terminal.
What you can do after
Evaluate how C statements and function calls issue ordered commands and produce terminal output.
How it connects
Connects imperative programming with C, statements, functions, arguments, expressions, arrays, and for loops.

Also explained in

Compare how 14 books explain imperative programming →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.