Learn To Program With C Noel Kalicharan pdf


Full text





arn to






Learn to




Learn to Program using the Popular

C Programming Language

Noel Kalicharan

Learn to Program with C

B O O K S F O R P R O F E S S I O N A L S B Y P R O F E S S I O N A L S®


Learn to Program with C teaches computer programming to the complete beginner using the native C language. As such, it assumes you have no knowledge whatsoever about programming. The main goal of this book is to teach fundamental programming principles using C, one of the most widely used programming languages in the world today.

We discuss only those features and statements in C that are necessary to achieve our goal. Once you learn the principles well, they can be applied to any language. If you are worried that you are not good at high-school mathematics, don’t be. It is a myth that you must be good at mathematics to learn programming.

C is considered a ‘modern’ language even though its roots date back to the 1970s. Originally, C was designed for writing ‘systems’ programs—things like operating systems, editors, compilers, assemblers and input/output utility programs. But, today, C is used for writing all kinds of applications as well—word processing programs, spreadsheet programs, database management programs, accounting programs, games, robots, embedded systems/electronics (i.e., Arduino), educational soft ware—the list is endless.

• How to get started with programming using the C language • How to use the basics of C

• How to program with sequence, selection and repetition logic • How to work with characters

• How to work with functions • How to use arrays

Shelve in:

Programming Languages/ANSI C

User level:



9 7 8 1 4 8 4 2 1 3 7 2 8 ISBN 978-1-4842-1372-8


Learn to Program

with C


Copyright © 2015 by Noel Kalicharan

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law.

ISBN-13 (pbk): 978-1-4842-1372-8 ISBN-13 (electronic): 978-1-4842-1371-1

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Managing Director: Welmoed Spahr Lead Editor: Steve Anglin

Technical Reviewer: Rohan Walia

Editorial Board: Steve Anglin, Louise Corrigan, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing

Coordinating Editor: Mark Powers Copy Editor: Karen Jameson Compositor: SPi Global Indexer: SPi Global Artist: SPi Global

Distributed to the book trade worldwide by Springer Science+Business Media New York,

233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail

orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

For information on translations, please e-mail rights@apress.com, or visit www.apress.com.

Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales.


Contents at a Glance

About the Author �����������������������������������������������������������������������������������������������������


About the Technical Reviewer �������������������������������������������������������������������������������


Acknowledgments ��������������������������������������������������������������������������������������������������


Preface �������������������������������������������������������������������������������������������������������������������


Chapter 1: Elementary Programming Concepts ����������������������������������������������������


Chapter 2: C – The Basics ������������������������������������������������������������������������������������


Chapter 3: Programs with Sequence Logic ���������������������������������������������������������


Chapter 4: Programs with Selection Logic ����������������������������������������������������������


Chapter 5: Programs with Repetition Logic ���������������������������������������������������������


Chapter 6: Characters ����������������������������������������������������������������������������������������


Chapter 7: Functions �����������������������������������������������������������������������������������������


Chapter 8: Arrays ����������������������������������������������������������������������������������������������


Chapter 9: Searching, Sorting, and Merging �����������������������������������������������������


Chapter 10: Structures ��������������������������������������������������������������������������������������




About the Author �����������������������������������������������������������������������������������������������������


About the Technical Reviewer �������������������������������������������������������������������������������


Acknowledgments ��������������������������������������������������������������������������������������������������


Preface ������������������������������������������������������������������������������������������������������������������


Chapter 1: Elementary Programming Concepts ����������������������������������������������������


1.1 Programs, Languages, and Compilers ...


1.2 How a Computer Solves a Problem ...


1.2.1 Define the Problem ...3

1.2.2 Analyze the Problem ...4

1.2.3 Develop an Algorithm to Solve the Problem ...4

1.2.4 Write the Program for the Algorithm ...6

1.2.5 Test and Debug the Program ...8

1.2.6 Document the Program...9

1.2.7 Maintain the Program ...9

1.3 How a Computer Executes a Program ...


1.4 Data Types ...


1.5 Characters ...


1.6 Welcome to C Programming ...


1.6.1 Run the Program ...13


1.7 Write Output with printf ...


1.7.1 The Newline Character, \n (backslash n) ...15

1.7.2 Escape Sequences ...16

1.7.3 Print the Value of a Variable ...16



1.9 Programming with Variables ...


Chapter 2: C – The Basics ������������������������������������������������������������������������������������


2.1 Introduction ...


2.2 The C Alphabet ...


2.3 C Tokens ...


2.3.1 Spacing Within a Program ...25

2.3.2 Reserved Words ...27

2.3.3 Identifiers ...27

2.3.4 Some Naming Conventions...28

2.4 Basic Data Types ...


2.5 Integer Numbers - int ...


2.5.1 Declaring Variables ...29

2.5.2 Integer Expressions ...29

2.5.3 Precedence of Operators ...30

2.5.4 Print an Integer Using a “Field Width” ...31

2.6 Floating-Point Numbers – float and double ...


2.6.1 Print double and float Variables ...34

2.6.2 Assignment Between double and float ...36

2.6.3 Floating-Point Expressions ...36

2.6.4 Expressions with Integer and Floating-Point Values...37

2.6.5 Assigning double/float to int ...38

2.7 Strings ...


2.8 The Assignment Statement ...



Chapter 3: Programs with Sequence Logic ���������������������������������������������������������


3.1 Introduction ...


3.2 Read Data Supplied by a User ...


3.3 scanf ...


3.3.1 Read Data Into a float Variable ...52

3.3.2 Read Data Into a double Variable ...52

3.4 Read Strings ...


3.5 Examples ...


3.5.1 Problem 1 - Average ...55

3.5.2 Problem 2 - Square ...56

3.5.3 Problem 3 - Banking ...57

3.5.4 Problem 4 – Tickets ...60

Chapter 4: Programs with Selection Logic ����������������������������������������������������������


4.1 Introduction ...


4.2 Boolean Expressions ...


4.2.1 AND, && ...66

4.2.2 OR, || ...67

4.2.3 NOT, ! ...68

4.3 The if Construct ...


4.3.1 Find the Sum of Two Lengths ...72

4.4 The if...else Construct ...


4.4.1 Calculate Pay ...77

4.5 On Program Testing ...


4.6 Symbolic Constants ...


4.6.1 The #define Directive ...81

4.6.2 Example – Symbolic Constants ...82

4.7 More Examples ...


4.7.1 Print a Letter Grade ...83


Chapter 5: Programs with Repetition Logic ���������������������������������������������������������


5.1 Introduction ...


5.2 The while Construct ...


5.2.1 Highest Common Factor ...96

5.3 Keep a Count ...


5.3.1 Find Average ...99

5.4 Increment and Decrement Operators ...


5.5 Assignment Operators ...


5.6 Find Largest ...


5.7 Find Smallest ...


5.8 Read Data from a File ...


5.8.1 fscanf ...108

5.8.2 Find Average of Numbers in a File ...108

5.9 Send Output to a File ...


5.9.1 fprintf ...111

5.10 Payroll ...


5.11 The for Construct ...


5.11.1 The for Statement in C ...120

5.11.2 A Bit of Aesthetics ... 125

5.12 Multiplication Tables ...


5.13 Temperature Conversion Table ...


5.14 Expressive Power of for ...


5.15 The do...while Statement ...


5.15.1 Highest Common Factor ...133

5.15.2 Interest at the Bank ...134

Chapter 6: Characters ����������������������������������������������������������������������������������������


6.1 Character Sets ...


6.2 Character Constants and Values...



6.4 Characters in Arithmetic Expressions ...


6.4.1 Uppercase To/From Lowercase ...144

6.5 Read and Print Characters ...


6.6 Count Characters ...


6.6.1 Count Characters in a Line ...153

6.7 Count Blanks in a Line of Data ...


6.8 Compare Characters ...


6.9 Read Characters from a File ...


6.10 Write Characters to a File ...


6.10.1 Echo Input, Number Lines ...157

6.11 Convert Digit Characters to Integer ...


Chapter 7: Functions �����������������������������������������������������������������������������������������


7.1 About Functions ...


7.2 skipLines ...


7.3 A Program with a Function ...


7.3.1 The Function Header ...168

7.3.2 How a Function Gets Its Data ...169

7.4 max ...


7.5 Print the Day ...


7.6 Highest Common Factor ...


7.6.1 Using HCF to Find LCM ...177

7.7 factorial ...


7.7.1 Using Factorial ...181

7.7.2 Combinations ...182

7.8 Job Charge ...


7.9 Calculate Pay ...


7.10 Sum of Exact Divisors ...



7.11 Some Character Functions ...


7.11.1 Position of a Letter in the Alphabet ...189

7.12 Fetch the Next Integer ...


Chapter 8: Arrays ����������������������������������������������������������������������������������������������


8.1 Simple vs Array Variable ...


8.2 Array Declaration ...


8.3 Store Values in an Array ...


8.3.1 About Not Using Element 0 ...203

8.4 Average and Differences from Average ...


8.5 Letter Frequency Count ...


8.6 Making Better Use of fopen ...


8.7 Array as Argument to a Function ...


8.8 String – Array of Characters ...


8.8.1 Reverse the Characters in a String ... 217

8.9 Palindrome ...


8.9.1 A Better Palindrome Function ...223

8.10 Array of Strings – Name of Day Revisited ...


8.11 A Flexible getString Function ...


8.12 A Geography Quiz Program...


8.13 Find the Largest Number ...


8.14 Find the Smallest Number ...


8.15 A Voting Problem ...


Chapter 9: Searching, Sorting, and Merging �����������������������������������������������������


9.1 Sequential Search ...


9.2 Selection Sort ...


9.2.1 Analysis of Selection Sort ...252

9.3 Insertion Sort ...


9.3.1 Analysis of Insertion Sort ...258


9.4 Sort an Array of Strings ...


9.4.1 Variable-Length Arrays ...260

9.5 Sort Parallel Arrays ...


9.6 Binary Search ...


9.7 Word Frequency Count ...


9.8 Merge Sorted Lists ...


9.8.1 Implement the Merge ...273

Chapter 10: Structures ��������������������������������������������������������������������������������������


10.1 The Need for Structures ...


10.2 How to Declare a Structure ...


10.2.1 typedef ...283

10.3 Array of Structure ...


10.4 Search an Array of Structure ...


10.5 Sort an Array of Structure ...


10.6 Read, Search, and Sort a Structure ...


10.7 Nested Structures ...


10.8 Work with Fractions ...


10.8.1 Manipulate Fractions ...294

10.9 A Voting Problem ...


10.10 Pass Structures to Functions ...



About the Author

Dr. Noel Kalicharan is a Senior Lecturer in Computer Science


About the Technical Reviewer

Rohan Walia is a Senior Software Consultant with extensive

experience in client-server, web-based, and enterprise application development. He is an Oracle Certified ADF Implementation Specialist and a Sun Certified Java Programmer. Rohan is





This book attempts to teach computer programming to the complete beginner using the C language. As such, it assumes you have no knowledge whatsoever about programming. And if you are worried that you are not good at high-school mathematics, don’t be. It is a myth that you must be good at mathematics to learn programming. In this book, knowledge of primary school mathematics is all that is required—basic addition, subtraction, multiplication, division, finding the percentage of some quantity, finding an average or the larger of two quantities.

Some of our most outstanding students over the last thirty years have been people with little mathematics background from all walks of life—politicians, civil servants, sports people, housewives, secretaries, clerical assistants, artists, musicians and teachers. On the other hand, we’ve had mathematical folks who didn’t do as well as might be expected.

What will be an asset is the ability to think logically or to follow a logical argument. If you are good at presenting convincing arguments, you will probably be a good programmer. Even if you aren’t, programming is the perfect vehicle for teaching logical thinking skills. You should learn programming for these skills even if you never intend to become a serious programmer.

The main goal of this book is to teach fundamental programming principles using C, one of the most widely used programming languages in the world today. C is considered a ‘modern’ language even though its roots date back to the 1970s. Originally, C was designed for writing ‘systems’ programs—things like operating systems, editors, compilers, assemblers and input/ output utility programs. But, today, C is used for writing all kinds of applications programs as well—word processing programs, spreadsheet programs, database management programs, accounting programs, games, educational software—the list is endless.

However, this book is more about teaching programming basics than it is about teaching C. We discuss only those features and statements in C that are necessary to achieve our goal. Once you learn the principles well, they can be applied to any language.

Chapter 1 gives an overview of the programming process. Chapter 2 describes the basic building blocks needed to write programs. Chapter 3 explains how to write programs with the simplest kind of logic—sequence logic. Chapter 4 shows how to write programs which can make decisions. Chapter 5 explains the notion of ‘looping’ and how to use this powerful programming idea to solve more interesting problems. Chapter 6 deals with the oft-neglected, but important, topic of working with characters. Chapter 7 introduces functions—the key concept needed for writing large programs. Chapter 8 tackles the nemesis of many would-be programmers—array processing. Chapter 9 explains how lists of items stored in arrays can be searched, sorted and merged. And Chapter 10 deals with structures—the collection of one or more items, possibly of different types, grouped together under a single name for convenient handling.


Of course, you must learn some features. But it is far better to learn a few features and be able to use them to solve many problems rather than learn many features but can’t use them to solve anything. For this reason, this book introduces a feature (like an if statement, say) and then discusses many examples to illustrate how the feature can be used to solve different problems.

This book is intended for anyone who is learning programming for the first time, regardless of age or institution. The material has been taught successfully to students preparing for high-school examinations in Computer Studies or Information Technology, students at college, university and other tertiary-level institutions.

The presentation is based on the experience that many people have difficulty in learning programming. To try and overcome this, we use an approach which provides clear examples, detailed explanations of very basic concepts and numerous interesting problems (not just artificial exercises whose only use is to illustrate some language feature).

While computer programming is essentially a mental activity and you can learn a fair amount of programming from just reading the book, it is important that you “get your hands dirty” by writing and running programs. One of life’s thrills is to write your first program and get it to run successfully on a computer. Don’t miss out on it.

But do not stop there. The only way to learn programming well is to write programs to solve new problems. The end-of-chapter exercises are a very rich source of problems, a result of the author’s forty-odd years in the teaching of programming.

Thank you for taking the time to read this book. I hope your venture into programming is a successful and enjoyable one.


Elementary Programming


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 that 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 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.


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, A and B, he could write


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 that 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 that will be part of the final program documentation.

1.2.1 Define the Problem


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 that 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 that, 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 tire, 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 toward the end.

Another method for searching for the word would be one that 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 that 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.

(22) 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.

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 such as 1. 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.

(23) 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 labeled. 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


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 that 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 that 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


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 that 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 that 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 that 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 that 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)


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 that must be written is user documentation. This enables a nontechnical 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 that 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 that 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:


instruction 1 instruction 2 instruction 3


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.” Consider the statement:

Caroline bought 3 dresses for $199.95

Here, 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).


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 such as (, ), $, =, <, >, +, -, /, *, 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


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 that 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


The body of main contains one statement:


printf is a standard output function that, 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.

Programming Note as mentioned in the preface, one of life’s thrills is to write your first program and get it to run successfully on a computer. Don’t miss out on it. see appendix D for instructions on how to get a C compiler.

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 that 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


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"); }


#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


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


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,


(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");


exerCise: write a program to print the lyriCs of

your favorite 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 afterUse 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:


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);



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 that 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.


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,


is written as

b = 25;


set sum to a + b

is written as

sum = a + b;

Onefinal 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 three main categories; what are they? 9. Distinguish between a syntax error and a logic error.


11. name five 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:

There is a tide in the affairs of men

Which, taken at the flood, leads on to fortune

16. Write a program to print any four lines of your favorite song or poem. 17. same as exercise 16, but print a blank line after each line.

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

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

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

19. if a is 29 and b is 14, what is printed by the following statements?

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

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

20. if rate = 15, what is printed by


C – The Basics

In this chapter, we will explain the following:

• What is an alphabet, a character set, and a token

• What is a syntax rule and a syntax error

• What is a reserved word

• How to create identifiers in C

• What is a symbolic constant

• The C data types—int, float, and double

• How to write int and double expressions

• How to print an integer using a field width

• How to print a floating-point number to a required number of decimal places

• What happens when int and double values are mixed in the same expression

• What happens when we assign int to double and double to int

• How to declare a variable to hold a string

• How to assign a string value to a string variable

• Some problems to avoid when using the assignment statement

2.1 Introduction

In this chapter, we discuss some basic concepts you need to know in order to write programs in the C programming language.

A programming language is similar to speaking languages in many respects. It has an


when writing programs. If you violate a rule, your program will contain a syntax error. When you attempt to compile the program, the compiler will inform you of the error. You must correct it and try again.

The first step to becoming a good programmer is learning the syntax rules of the

programming language. This is the easy part, and many people mistakenly believe that this makes them a programmer. It is like saying that learning some rules of English grammar and being able to write some correctly formed sentences makes one a novelist. Novel-writing skills require much more than learning some rules of grammar. Among other things, it requires insight, creativity, and a knack for using the right words in a given situation.

In the same vein, a good programmer must be able to creatively use the features of the language to solve a wide variety of problems in an elegant and efficient manner. This is the difficult part and can be achieved only by long, hard study of problem-solving algorithms and writing programs to solve a wide range of problems. But we must start with baby steps.

2.2 The C Alphabet

In Section 1.4 we introduced the idea of a character. We can think of the C alphabet as consisting of all the characters one could type on a standard English keyboard: for example, the digits; uppercase and lowercase letters; and special characters such as +, =, <, >, &, and %.

More formally, C uses the ASCII (American Standard Code for Information Interchange, pronounced ass-key) character set. This is a character standard that includes the letters, digits, and special characters found on a standard keyboard. It also includes control characters such as backspace, tab, line feed, form feed, and carriage return. Each character is assigned a numeric code. The ASCII codes run from 0 to 127.

The programs in this book will be written using the ASCII character set. The characters in the ASCII character set are shown in Appendix B.

Character handling will be discussed in detail in Chapter 6.

2.3 C Tokens

The tokens of a language are the basic building blocks that can be put together to construct programs. A token can be a reserved word (such as int or while), an identifier (such as b or sum), a constant (such as 25 or "Alice in Wonderland"), a delimiter (such as } or ;) or an operator (such as + or =).

For example, consider the following portion of Program P1.4 given at the end of the last chapter:

int main() { int a, b, sum; a = 14;

b = 25; sum = a + b;


Figure 8-1. Declaration of int score[60]
Figure 8 1 Declaration of int score 60 . View in document p.211
Figure 8-2. The array day
Figure 8 2 The array day. View in document p.238
Figure 8-3. The 2-dimensional array day
Figure 8 3 The 2 dimensional array day. View in document p.239
Download now (323 Page)