Elementary Programming Concepts - C Programming For Beginners (2015)

C Programming For Beginners (2015)

CHAPTER 1

Elementary Programming Concepts

In this chapter, we will explain the following:

§ How a computer solves a problem

§ The various stages in the development of a computer program: from problem definition to finished program

§ How a computer executes a program

§ What is a ‘data type’ and its fundamental role in writing a program

§ The role of characters—the basic building blocks of all programs

§ The concepts of constants and variables

§ The distinction between syntax and logic errors

§ How to produce basic output in C using the printf statement

§ What is an escape sequence

§ How descriptive or explanatory comments can be included in your program

§ What is an assignment statement and how to write one in C

1.1 Programs, Languages and Compilers

We are all familiar with the computer’s ability to perform a wide variety of tasks. For instance, we can use it to play games, write a letter or a book, perform accounting functions for a company, learn a foreign language, listen to music on a CD, send a fax or search for information on the Internet. How is this possible, all on the same machine? The answer lies with programming—the creation of a sequence of instructions which the computer can perform (we say “execute”) to accomplish each task. This sequence of instructions is called a program. Each task requires a different program:

§ To play a game, we need a game-playing program.

§ To write a letter or a book, we need a word processing program.

§ To do accounts, we need an accounting program.

§ To learn Spanish, we need a program that teaches Spanish.

§ To listen to a CD, we need a music-playing program.

§ To send a fax, we need a fax-sending program.

§ To use the Internet, we need a program called a ‘Web browser’.

For every task we want to perform, we need an appropriate program. And in order for the computer to run a program, the program must be stored (we sometimes say loaded) in the computer’s memory.

But what is the nature of a program? First, we need to know that computers are built to execute instructions written in what is called machine language. In machine language, everything is expressed in terms of the binary number system—1s and 0s. Each computer has its own machine language and the computer can execute instructions written in that language only.

The instructions themselves are very simple, for example, add or subtract two numbers, compare one number with another or copy a number from one place to another. How, then, can the computer perform such a wide variety of tasks, solving such a wide variety of problems, with such simple instructions?

The answer is that no matter how complex an activity may seem, it can usually be broken down into a series of simple steps. It is the ability to analyze a complex problem and express its solution in terms of simple computer instructions that is one of the hallmarks of a good programmer.

Machine language is considered a low-level programming language. In the early days of computing (1940s and 50s) programmers had to write programs in machine language, that is, express all their instructions using 1s and 0s.

To make life a little easier for them, assembly language was developed. This was closely related to machine language but it allowed the programmer to use mnemonic instruction codes (such as ADD and names for storage locations (such as sum) rather than strings of binary digits (bits). For instance, a programmer could refer to a number by sum rather than have to remember that the number was stored in memory location 1000011101101011.

A program called an assembler is used to convert an assembly language program into machine language. Still, programming this way had several drawbacks:

§ It was very tedious and error prone.

§ It forced the programmer to think in terms of the machine rather than in terms of his problem.

§ A program written in the machine language of one computer could not be run on a computer with a different machine language. Changing your computer could mean having to rewrite all your programs.

To overcome these problems, high-level or problem-oriented languages were developed in the late 1950s and 60s. The most popular of these were FORTRAN (FORmula TRANslation) and COBOL (COmmon Business-Oriented Language). FORTRAN was designed for solving scientific and engineering problems which involved a great deal of numerical computation. COBOL was designed to solve the data-processing problems of the business community.

The idea was to allow the programmer to think about a problem in terms familiar to him and relevant to the problem rather than have to worry about the machine. So, for instance, if he wanted to know the larger of two quantities, Aand B, he could write

IF A IS GREATER THAN B THEN BIGGER = A ELSE BIGGER = B

rather than have to fiddle with several machine or assembly language instructions to get the same result. Thus high-level languages enabled the programmer to concentrate on solving the problem at hand, without the added burden of worrying about the idiosyncrasies of a particular machine.

However, the computer still could only execute instructions written in machine language. A program called a compiler is used to translate a program written in a high-level language to machine language.

Thus we speak of a FORTRAN compiler or a COBOL compiler for translating FORTRAN and COBOL programs, respectively. But that’s not the whole story. Since each computer has its own machine language, we must have, say, a FORTRAN compiler for a Lenovo ThinkPad computer and a FORTRAN compiler for a MacBook computer.

1.2 How a Computer Solves a Problem

Solving a problem on a computer involves the following activities:

1. Define the problem.

2. Analyze the problem.

3. Develop an algorithm (a method) for solving the problem.

4. Write the computer program which implements the algorithm.

5. Test and debug (find the errors in) the program.

6. Document the program. (Explain how the program works and how to use it.)

7. Maintain the program.

There is normally some overlap of these activities. For example, with a large program, a portion may be written and tested before another portion is written. Also, documentation should be done at the same time as all the other activities; each activity produces its own items of documentation which will be part of the final program documentation.

1.2.1 Define the Problem

Suppose we want to help a child work out the areas of squares. This defines a problem to be solved. However, a brief analysis reveals that the definition is not complete or specific enough to proceed with developing a program. Talking with the child might reveal that she needs a program which requests her to enter the length of a side of the square; the program then prints the area of the square.

1.2.2 Analyze the Problem

We further analyze the problem to

§ Ensure that we have the clearest possible understanding of it.

§ Determine general requirements such as the main inputs to the program and the main outputs from the program. For more complex programs, we would, for instance, also need to decide on the kinds of files which may be needed.

If there are several ways of solving the problem, we should consider the alternatives and choose the best or most appropriate one.

In this example, the input to the program is the length of one side of the square and the output is the area of the square. We only need to know how to calculate the area. If the side is s, then the area, a, is calculated by this:

a = s × s

1.2.3 Develop an Algorithm to Solve the Problem

An algorithm is a set of instructions which, if faithfully followed, will produce a solution to a given problem or perform some specified task. When an instruction is followed, we say it is executed. We can speak of an algorithm for finding a word in a dictionary, for changing a punctured tyre or for playing a video game.

For any problem, there will normally be more than one algorithm to solve it. Each algorithm will have its own advantages and disadvantages. When we are searching for a word in the dictionary, one method would be to start at the beginning and look at each word in turn. A second method would be to start at the end and search backwards. Here, an advantage of the first method is that it would find a word faster if it were at the beginning, while the second method would be faster if the word were towards the end.

Another method for searching for the word would be one which used the fact that the words in a dictionary are in alphabetical order—this is the method we all use when looking up a word in a dictionary. In any situation, a programmer would usually have a choice of algorithms, and it is one of her more important jobs to decide which algorithm is the best, and why this is so.

In our example, we must write the instructions in our algorithm in such a way that they can be easily converted into a form which the computer can follow. Computer instructions fall into three main categories:

1. Input instructions, used for supplying data from the ‘outside world’ to a program; this is usually done via the keyboard or a file.

2. Processing instructions, used for manipulating data inside the computer. These instructions allow us to add, subtract, multiply and divide; they also allow us to compare two values, and act according to the result of the comparison. Also, we can move data from one location in the computer’s memory to another location.

3. Output instructions, used for getting information out of the computer to the outside world.

1.2.3.1 Data and Variables

All computer programs, except the most trivial, are written to operate on data. For example:

§ The data for an action game might be keys pressed or the position of the cursor when the mouse is clicked.

§ The data for a word processing program are the keys pressed while you are typing a letter.

§ The data for an accounting program would include, among other things, expenses and income.

§ The data for a program that teaches Spanish could be an English word that you type in response to a question.

Recall that a program must be stored in the computer’s memory for it to be run. When data is supplied to a program, that data is also stored in memory. Thus we think of memory as a place for holding programs and data. One of the nice things about programming in a high-level language (as opposed to machine language) is that you don’t have to worry about which memory locations are used to store your data. But how do we refer to an item of data, given that there may be many data items in memory?

Think of memory as a set of boxes (or storage locations). Each box can hold one item of data, for example, one number. We can give a name to a box, and we will be able to refer to that box by the given name. In our example, we will need two boxes, one to hold the side of the square and one to hold the area. We will call these boxes s and a, respectively.

s

a

If we wish, we can change the value in a box at any time; since the values can vary, s and a are called variable names, or simply variables. Thus a variable is a name associated with a particular memory location or, if you wish, it is a label for the memory location. We can speak of giving a variable a value, or setting a variable to a specific value, 1, say. Important points to remember are:

§ A box can hold only one value at a time; if we put in a new value, the old one is lost.

§ We must not assume that a box contains any value unless we specifically store a value in the box. In particular, we must not assume that the box contains zero.

Variables are a common feature of computer programs. It is very difficult to imagine what programming would be like without them. In everyday life, we often use variables. For example, we speak of an ‘address’. Here, ‘address’ is a variable whose value depends on the person under consideration. Other common variables are telephone number, name of school, subject, size of population, type of car, television model, etc. (What are some possible values of these variables?)

1.2.3.2 Example – Develop the Algorithm

Using the notion of an algorithm and the concept of a variable, we develop the following algorithm for calculating the area of a square, given one side:

Algorithm for calculating area of square, given one side

1. Ask the user for the length of a side

2. Store the value in the box s

3. Calculate the area of the square (s × s)

4. Store the area in the box a

5. Print the value in box a, appropriately labelled

6. Stop

When an algorithm is developed, it must be checked to make sure that it is doing its intended job correctly. We can test an algorithm by ‘playing computer’, that is, we execute the instructions by hand, using appropriate data values. This process is called dry running or desk checking the algorithm. It is used to pinpoint any errors in logic before the computer program is actually written. We should never start to write programming code unless we are confident that the algorithm is correct.

1.2.4 Write the Program for the Algorithm

We have specified the algorithm using English statements. However, these statements are sufficiently ‘computer-oriented’ for a computer program to be written directly from them. Before we do this, let us see how we expect the program to work from the user’s point of view.

First, the program will type the request for the length of a side; we say the program prompts the user to supply data. The screen display might look like this:

Enter length of side:

The computer will then wait for the user to type the length. Suppose the user types 12. The display will look like this:

Enter length of side: 12

The program will then accept (we say read) the number typed, calculate the area and print the result. The display may look like this:

Enter length of side: 12

Area of square is 144

Here we have specified what the output of the program should look like. For instance, there is a blank line between the prompt line and the line that gives the answer; we have also specified the exact form of the answer. This is a simple example of output design. This is necessary since the programmer cannot write the program unless he knows the precise output required.

In order to write the computer program from the algorithm, a suitable programming language must be chosen. We can think of a program as a set of instructions, written in a programming language, which, when executed, will produce a solution to a given problem or perform some specified task.

The major difference between an algorithm and a program is that an algorithm can be written using informal language without having to follow any special rules (though some conventions are usually followed) whereas a program is written in a programming language and must follow all the rules (the syntax rules) of the language. (Similarly, if we wish to write correct English, we must follow the syntax rules of the English language.)

In this book, we will be showing you how to write programs in C, the programming language developed by Ken Thompson and Dennis Ritchie of Bell Laboratories, and one of the most popular and widely used today.

Program P1.1 is a C program which requests the user to enter the length of a side and prints the area of the square:

Program P1.1

#include <stdio.h>

int main() {

int a, s;

printf("Enter length of side: ");

scanf("%d", &s); //store length in s

a = s * s; //calculate area; store in a

printf("\nArea of square is %d\n", a);

}

It is not too important that you understand anything about this program at this time. But you can observe that a C program has something (a function) called main followed by opening and closing brackets. Between the left brace {and the right brace } we have what is called the body of the function. The statement

int a, s;

is called a declaration. The parts after // are comments which help to explain the program but have no effect when the program is run. And * is used to denote multiplication.

All of these terms will be explained in detail in due course.

Finally, a program written in a high-level language is usually referred to as a source program or source code.

1.2.5 Test and Debug the Program

Having written the program, the next job is to test it to find out whether it is doing its intended job. Testing a program involves the following steps:

1. Compile the program: recall that a computer can execute a program written in machine language only. Before the computer can run our C program, the latter must be converted to machine language. We say that the source code must be converted to object code or machine code. The program which does this job is called a compiler. Appendix D tells you how you can acquire a C compiler for writing and running your programs.

2. Among other things, a compiler will check the source code for syntax errors—errors which arise from breaking the rules for writing statements in the language. For example, a common syntax error in writing C programs is to omit a semicolon or to put one where it is not required.

3. If the program contains syntax errors, these must be corrected before compiling it again. When the program is free from syntax errors, the compiler will convert it to machine language and we can go on to the next step.

4. Run the program: here we request the computer to execute the program and we supply data to the program for which we know the answer. Such data is called test data. Some values we can use for the length of a side are 3, 12 and 20.

5. If the program does not give us the answers 9, 144 and 400, respectively, then we know that the program contains at least one logic error. A logic error is one which causes a program to give incorrect results for valid data. A logic error may also cause a program to crash (come to an abrupt halt).

6. If a program contains logic errors, we must debug the program; we must find and correct any errors that are causing the program to produce wrong answers.

To illustrate, suppose the statement which calculates the area was written (incorrectly) as:

a = s + s;

and when the program is run, 10 is entered for the length. (Below, 10 is underlined to indicate it is typed by the user.) Assume we know that the area should be 100. But when the program is run, it prints this:

Enter length of side: 10

Area of square is 20

Since this is not the answer we expect, we know that there is an error (perhaps more than one) in the program. Since the area is wrong, the logical place to start looking for the error is in the statement which calculates the area. If we look closely, we should discover that + was typed instead of *. When this correction is made, the program works fine.

1.2.6 Document the Program

The final job is to complete the documentation of the program. So far, our documentation includes the following:

§ The statement of the problem.

§ The algorithm for solving the problem.

§ The program listing.

§ Test data and the results produced by the program.

These are some of the items that make up the technical documentation of the program. This is documentation that is useful to a programmer, perhaps for modifying the program at a later stage.

The other kind of documentation which must be written is user documentation. This enables a non-technical person to use the program without needing to know about the internal workings of the program. Among other things, the user needs to know how to load the program in the computer and how to use the various features of the program. If appropriate, the user will also need to know how to handle unusual situations which may arise while the program is being used.

1.2.7 Maintain the Program

Except for things like class assignments, programs are normally meant to be used over a long period of time. During this time, errors may be discovered which previously went unnoticed. Errors may also surface because of conditions or data that never arose before. Whatever the reason, such errors must be corrected.

But a program may need to be modified for other reasons. Perhaps the assumptions made when the program was written have now changed due to changed company policy or even due to a change in government regulations (e.g. changes in income tax rates). Perhaps the company is changing its computer system and the program needs to be ‘migrated’ to the new system. We say the program must be ‘maintained’.

Whether or not this is easy to do depends a lot on how the original program was written. If it was well-designed and properly documented, then the job of the maintenance programmer would be made so much easier.

1.3 How a Computer Executes a Program

First, recall that a computer can execute a program written in machine language only. For the computer to execute the instructions of such a program, those instructions must be loaded into the computer’s memory (also called primary storage), like this:

memory

instruction 1

instruction 2

instruction 3

etc.

You can think of memory as a series of storage locations, numbered consecutively starting at 0. Thus you can speak of memory location 27 or memory location 31548. The number associated with a memory location is called its address.

A computer runs a program by executing its first instruction, then the second, then the third, and so on. It is possible that one instruction might say to jump over several instructions to a particular one and continue executing from there. Another might say to go back to a previous instruction and execute it again.

No matter what the instructions are, the computer faithfully executes them exactly as specified. That is why it is so important that programs specify precisely and exactly what must be done. The computer cannot know what you intend, it can only execute what you actually write. If you give the computer the wrong instruction, it will blindly execute it just as you specify.

1.4 Data Types

Every day we meet names and numbers—at home, at work, at school or at play. A person’s name is a type of data; so is a number. We can thus speak of the two data types called ‘name’ and ‘number’. In the statement:

Caroline bought 3 dresses for $199.95

we can find:

§ An example of a name: Caroline.

§ Two examples of numbers: 3 and 199.95.

Usually, we find it convenient to divide numbers into two kinds:

1. Whole numbers, or integers.

2. Numbers with a decimal point, so-called real or floating-point numbers.

In the example, 3 is an integer and 199.95 is a real number.

Exercise: Identify the data types—names, integers and real numbers—in the following:

1. Bill’s batting average was 35.25 with a highest score of 99.

2. Abigail, who lives at 41 Third Avenue, worked 36 hours at $11.50 per hour.

3. In his 8 subjects, Richard’s average mark was 68.5.

Generally speaking, programs are written to manipulate data of various types. We use the term numeric to refer to numbers (integer or floating-point). We use the term string to refer to non-numeric data such as a name, address, job description, title of a song or vehicle number (which is not really a number as far as the computer is concerned—it usually contains letters, e.g. PAB6052).

Programming languages in general, and C in particular, precisely define the various types of data which can be manipulated by programs written in those languages. Integer, real (or floating-point), character (data consisting of a single character such as 'K' or '%') and string data types are the most common.

Each data type defines constants of that type. For example,

§ Some integer constants are 3, -52, 0 and 9813.

§ Some real (or floating-point) constants are 3.142, -5.0, 345.21 and 1.16.

§ Some character constants are 't', '+', '8' and 'R'.

§ Some string constants are "Hi there", "Wherefore art thou, Romeo?" and "C World".

Note that, in C, a character constant is delimited by single quotes and a string constant is delimited by double quotes.

When we use a variable in a program, we have to say what type of data (the kind of constants) we intend to store in that variable—we say we must declare the variable. It is usually an error if we declare a variable to be of one type and then attempt to store a different type of value in it. For example, it would be an error to attempt to store a string constant in an integer variable. C data types are discussed in detail in Chapter 2.

1.5 Characters

In computer terminology, we use the term character to refer to any one of the following:

§ A digit from 0 to 9.

§ An uppercase letter from A to Z.

§ A lowercase letter from a to z.

§ A special symbol like (, ), $, =, <, >, +, -, /, *, etc.

The following are commonly used terms:

letter – one of a to z or A to Z

lowercase letter – one of a to z

uppercase letter – one of A to Z

digit – one of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

special character – any symbol except a letter or a digit e.g. +, <, $, &, *, /, =

alphabetic – used to refer to a letter

numeric – used to refer to a digit

alphanumeric – used to refer to a letter or a digit

Characters are the basic building blocks used in writing programs.

We put characters together to form variables and constants.

We put variables, constants and special characters to form expressions such as

(a + 2.5) * (b – c)

We add special words such as if, else and while to form statements such as

if (a > 0) b = a + 2; else b = a – 2;

And we put statements together to form programs.

1.6 Welcome to C Programming

We take a quick peek at the C programming language by writing a program to print the message

Welcome to Trinidad & Tobago

One solution is Program P1.2.

Program P1.2

#include <stdio.h>

int main() {

printf("Welcome to Trinidad & Tobago");

}

The statement

#include <stdio.h>

is called a compiler directive. This simply means that it provides information the compiler needs to compile your program. In C, input/output instructions are provided by means of standard functions stored in a standard library. These functions use variable (and other) declarations stored in a special header file called stdio.h. Any program which uses an input/output instruction (such as printf) must inform the compiler to include the declarations in the file stdio.h with the program. If this is not done, the compiler will not know how to interpret the input/output statements used in the program.

A C program consists of one or more functions (or, subprograms), one of which must be called main. Our solution consists of just one function so it must be called main. The (round) brackets after main are necessary because, in C, a function name is followed by a list of arguments, enclosed in brackets. If there are no arguments, the brackets must still be present. Here, main has no arguments so the brackets alone are present. The word int before main indicate the type of value returned by main. We will explain this in more detail later.

Every function has a section called the body of the function. The body is where the work of the function is performed. The left and right braces, { and }, are used to define the start and end, respectively, of the body. In C, one or more statements enclosed by { and } is called a block or compound statement.

The body of main contains one statement:

printf("Welcome to Trinidad & Tobago");

printf is a standard output function which, in this example, takes one argument, a string constant "Welcome to Trinidad & Tobago". Note that, as with all functions, the argument is enclosed in round brackets. The semicolon is used to indicate the end of the statement. We say the semicolon terminates the statement. When executed, this statement will print

Welcome to Trinidad & Tobago

on the ‘standard output’. For now, take this to mean the screen.

1.6.1 Run the Program

Having written the program on paper, the next task is to get it running on a real computer. How this is done varies somewhat from one computer system to the next but, in general, the following steps must be performed:

1. Type the program to a file. The file could be named welcome.c; it is good practice to use .c as the filename extension to those files which contain C source code.

2. Invoke your C compiler to compile the program in the file welcome.c. For instance, you may have to start up your C compiler and open the file welcome.c from the File menu or you may simply have to double-click on the file welcome.c to start-up the compiler.

3. Once the file is open, typically there will be a menu command to Compile or Run the program. (Generally, Run implies Compile and Run). If any (syntax) errors are detected during the compile phase, you must correct these errors and try again.

4. When all errors have been corrected and the program is Run, it will print

Welcome to Trinidad & Tobago

1.6.2 A Word on Program Layout

C does not require the program to be laid out as in the example. An equivalent program is

#include <stdio.h>

int main() { printf("Welcome to Trinidad & Tobago"); }

or

#include <stdio.h>

int main()

{

printf("Welcome to Trinidad & Tobago");

}

For this small program, it probably does not matter which version we use. However, as program size increases, it becomes imperative that the layout of the program highlights the logical structure of the program.

This improves its readability, making it easier to understand. Indentation and clearly indicating which { matches which } can help in this regard. We will see the value of this principle as our programs become bigger.

1.7 Write Output with printf

Suppose we want to write a program to print the following lines from The Gitanjali by Rabindranath Tagore:

Where the mind is without fear

And the head is held high

Our initial attempt might be this:

#include <stdio.h>

int main() {

printf("Where the mind is without fear");

printf("And the head is held high");

}

However, when run, this program will print:

Where the mind is without fearAnd the head is held high

Note that the two strings are joined together (we say the strings are concatenated). This happens because printf does not place output on a new line, unless this is specified explicitly. Put another way, printf does not automatically supply a newline character after printing its argument(s). A newline character would cause subsequent output to begin at the left margin of the next line.

In the example, a newline character is not supplied after fear is printed so that And the head... is printed on the same line as fear and immediately after it.

1.7.1 The Newline Character, \n (backslash n)

To get the desired effect, we must tell printf to supply a newline character after printing ...without fear. We do this by using the character sequence \n (backslash n) as in Program P1.3.

Program P1.3

#include <stdio.h>

int main() {

printf("Where the mind is without fear\n");

printf("And the head is held high\n");

}

The first \n says to terminate the current output line; subsequent output will start at the left margin of the next line. Thus, And the... will be printed on a new line. The second \n has the effect of terminating the second line. If it were not present, the output will still come out right, but only because this is the last line of output.

A program prints all pending output just before it terminates. (This is also the reason why our first program worked without \n.)

As an embellishment, suppose we want to put a blank line between our two lines of output, like this:

Where the mind is without fear

And the head is held high

Each of the following sets of statements will accomplish this:

printf("Where the mind is without fear\n\n");

printf("And the head is held high\n");

printf("Where the mind is without fear\n");

printf("\nAnd the head is held high\n");

printf("Where the mind is without fear\n");

printf("\n");

printf("And the head is held high\n");

We just have to make sure we print two \n's between fear and And. The first \n ends the first line; the second ends the second line, in effect, printing a blank line. C gives us a lot of flexibility in how we write statements to produce a desired effect.

Exercise: Write a program to print the lyrics of your favourite song.

1.7.2 Escape Sequences

Within the string argument to printf, the backslash (\) signals that a special effect is needed at this point. The character following the backslash specifies what to do. This combination (\ followed by another character) is referred to as an escape sequence. The following are some escape sequences you can use in a string in a printf statement:

\n issue a newline character

\f issue a new page (form feed) character

\t issue a tab character

\" print "

\\ print \

For example, using an escape sequence is the only way to print a double quote as part of your output. Suppose we want to print the line

Use " to begin and end a string

If we typed

printf("Use " to begin and end a string\n");

then C would assume that the double quote after Use ends the string (causing a subsequent error when it can’t figure out what to do with to). Using the escape sequence \", we can correctly print the line with:

printf("Use \" to begin and end a string\n");

Exercise: Write a statement to print the line:

An escape sequence starts with \

1.7.3 Print the Value of a Variable

So far, we have used printf to print the value of a string constant (that is, the characters of the string excluding the quotes). We now show how we can print the value of a variable ignoring, for the moment, how the variable gets its value. (We will see how in Chapter 2.) Suppose the integer variable m has the value 52. The statement:

printf("The number of students = %d\n", m);

will print this:

The number of students = 52

This printf is a bit different from those we have seen so far. This one has two arguments—a string and a variable. The string, called the format string, contains a format specification %d. (In our previous examples, the format string contained no format specifications.) The effect, in this case, is that the format string is printed as before, except that the %d is replaced by the value of the second argument, m. Thus, %d is replaced by 52, giving this:

The number of students = 52

We will explain printf and format specifications in more detail in Chapter 2 but, for now, note that we use the specification %d if we want to print an integer value.

What if we want to print more than one value? This can be done provided that each value has a corresponding format specification. For example, suppose that a has the value 14 and b has the value 25. Consider the statement:

printf("The sum of %d and %d is %d\n", a, b, a + b);

This printf has four arguments—the format string and three values to be printed: a, b and a+b. The format string must contain three format specifications: the first will correspond to a, the second to b and the third to a+b. When the format string is printed, each %d will be replaced by the value of its corresponding argument, giving this:

The sum of 14 and 25 is 39

Exercise: What is printed by the following statement?

printf("%d + %d = %d\n", a, b, a + b);

1.8 Comments

All programming languages let you include comments in your programs. Comments can be used to remind yourself (and others) of what processing is taking place or what a particular variable is being used for. They can be used to explain or clarify any aspect of a program which may be difficult to understand by just reading the programming statements. This is very important since the easier it is to understand a program, the more confidence you will have that it is correct. It is worth adding anything which makes a program easier to understand.

Remember that a comment (or lack of it) has absolutely no effect on how the program runs. If you remove all the comments from a program, it will run exactly the same way as with the comments.

Each language has its own way of specifying how a comment must be written. In C, we write a comment by enclosing it within /* and */, for example:

/* This program prints a greeting */

A comment extends from /* to the next */ and may span one or more lines. The following is a valid comment:

/* This program reads characters one at a time

and counts the number of letters found */

C also lets you use // to write one-line comments. The comment extends from // to the end of the line, for example:

a = s * s; //calculate area; store in a

In this book, we will use mainly one-line comments.

1.9 Programming with Variables

To reinforce the ideas discussed so far, let us write a program which adds the numbers 14 and 25 and prints the sum.

We would need storage locations for the two numbers and the sum. The values to be stored in these locations are integer values. To refer to these locations, we make up the names a, b and sum, say. (Any other names would do. In C, as in all programming languages, there are rules to follow for making up variable names, for instance, a name must start with a letter and cannot contain spaces. We will see the C rules in the next chapter.)

One possible algorithm might look like this:

set a to 14

set b to 25

set sum to a + b

print sum

The algorithm consists of four statements. The following explains the meaning of each statement:

§ set a to 14 : store the number 14 in memory location a; this is an example of an assignment statement.

§ set b to 25: store the number 25 in memory location b.

§ set sum to a + b: add the numbers in memory locations a and b and store the sum in location sum. The result is that 39 is stored in sum.

§ print sum : print (on the screen) the value in sum, i.e. 39.

Program P1.4 shows how we can write this algorithm as a C program.

Program P1.4

//This program prints the sum of 14 and 25. It shows how

//to declare variables in C and assign values to them.

#include <stdio.h>

int main() {

int a, b, sum;

a = 14;

b = 25;

sum = a + b;

printf("%d + %d = %d\n", a, b, sum);

}

When run, this program will print the following:

14 + 25 = 39

In C, variables are declared as integer using the required word int. (In programming terminology, we say that int is a reserved word.) Thus, the statement

int a, b, sum;

declares that a, b and sum are integer variables. In C, all variables must be declared before they are used in a program. Note that the variables are separated by commas, with a semicolon after the last one. If we need to declare just one variable (a, say), we will write

int a;

The statement

a = 14;

is C’s way of writing the assignment statement

set a to 14

It is sometimes pronounced “a becomes 14”. In C, an assignment statement consists of a variable (a in the example), followed by an equals sign (=), followed by the value to be assigned to the variable (14 in the example), followed by a semicolon. In general, the value can be a constant (like 14), a variable (like b) or an expression (like a + b). Thus,

set b to 25

is written as

b = 25;

and

set sum to a + b

is written as

sum = a + b;

One final point: you may have gathered from a previous exercise that, for this problem, the variable sum is not really necessary. We could, for instance, have omitted sum from the program altogether and used this:

int a, b;

a = 14;

b = 25;

printf("%d + %d = %d\n", a, b, a + b);

to give the same result since C lets us use an expression (e.g. a + b) as an argument to printf. However, if the program were longer and we needed to use the sum in other places, it would be wise to calculate and store the sum once (in sum, say). Whenever the sum is needed, we use sum rather than recalculate a + b each time.

Now that we have a general idea of what is involved in writing a program, we are ready to get down to the nitty-gritty of C programming.

EXERCISES 1

1. What makes it possible to do such a variety of things on a computer?

2. Computers can execute instructions written in what language?

3. Give two advantages of assembly language over machine language.

4. Give two advantages of a high-level language over assembly language.

5. Describe two main tasks performed by a compiler.

6. Describe the steps required to solve a problem on a computer.

7. Distinguish between an algorithm and a program.

8. Programming instructions fall into 3 main categories; what are they?

9. Distinguish between a syntax error and a logic error.

10. What is meant by “debugging a program”?

11. Name 5 data types commonly used in programming and give examples of constants of each type.

12. What are the different classes into which characters can be divided? Give examples in each class.

13. What is the purpose of comments in a program?

14. Write a program to print Welcome to C on the screen.

15. Write a program to print the following:

16. There is a tide in the affairs of men

17. Which, taken at the flood, leads on to fortune

18. Write a program to print any 4 lines of your favourite song or poem.

19. Same as exercise 16, but print a blank line after each line.

20. If a is 29 and b is 5, what is printed by each of the following statements?

21. printf("The product of %d and %d is %d\n", a, b, a * b);

22. printf("%d + %d = %d\n", a, b, a + b);

23. printf("%d - %d = %d\n", a, b, a - b);

24. printf("%d x %d = %d\n", a, b, a * b);

25. If a is 29 and b is 14, what is printed by the following statements?

26. printf("%d + \n", a);

27. printf("%d\n", b);

28. printf("--\n");

29. printf("%d\n", a + b);

30. If rate = 15, what is printed by

31. (a) printf("rate\n")?

32. (b) printf("%d\n", rate)?