267

8--

  • Upload
    kubik

  • View
    9

  • Download
    0

Embed Size (px)

DESCRIPTION

posdru

Citation preview

  • AAddrriiaannaa AALLBBUU

    EDITURA CONSPRESS

    2013

  • Copyright 2013, Editura Conspress

    EDITURA CONSPRESS este recunoscut de

    Consiliul Naional al Cercetrii tiinifice din nvmntul Superior

    Lucrare elaborat n cadrul proiectului: "Reea naional de centre pentru dezvoltarea programelor de studii cu rute flexibile i a unor instrumente didactice la specializarea de licen i masterat, din domeniul Ingineria Sistemelor"

    Descrierea CIP a Bibliotecii Naionale a Romniei

    ALBU, ADRIANA Computer programming: the C language / Adriana Albu Bucureti : Conspress, 2013 Bibliogr. ISBN 978-973-100-270-5 681.3

    Colecia Carte universitar

    CONSPRESS B-dul Lacul Tei nr 124, sector 2

    cod 020396, Bucureti Tel: (021) 242 2719 / 300; Fax: (021) 242 0781

  • To my Grandparents

  • Contents

    Introduction .......................................................................................................... 9

    Chapter 1 Programming basics .......................................................................... 11

    Chapter 2 Logical diagrams ............................................................................... 15

    2.1 The elements of a logical diagram ........................................................... 15

    2.2 Solved problems ....................................................................................... 20

    2.3 Questions and exercises ........................................................................... 24

    Chapter 3 Data and data types ........................................................................... 30

    3.1 General concepts ...................................................................................... 30

    3.1.1 Data types .......................................................................................... 31

    3.1.2 Variables ........................................................................................... 34

    3.1.3 Constants ........................................................................................... 34

    3.1.4 Operators ........................................................................................... 35

    3.1.5 Expressions ....................................................................................... 38

    3.2 Data types description .............................................................................. 41

    3.2.1 The integer type ................................................................................ 41

    3.2.2 The real type ..................................................................................... 43

    3.2.3 The char type ..................................................................................... 43

    3.2.4 The logical type ................................................................................. 44

    3.2.5 The void type .................................................................................... 45

    3.2.6 Type casting ...................................................................................... 45

    3.3 Questions and exercises ........................................................................... 46

    Chapter 4 A first C program .............................................................................. 50

    4.1 Stages of a C program implementation .................................................... 50

    4.2 The structure of a C program ................................................................... 51

    4.3 Possible errors .......................................................................................... 55

  • Computer Programming The C Language

    6

    4.4 Questions and exercises ........................................................................... 56

    Chapter 5 Library functions ............................................................................... 59

    5.1 Input/output functions .............................................................................. 59

    5.2 Mathematical functions ............................................................................ 67

    5.3 Conversion functions ............................................................................... 70

    5.4 Other functions ......................................................................................... 71

    5.5 Questions and exercises ........................................................................... 74

    Chapter 6 Instructions ........................................................................................ 78

    6.1 Simple instructions ................................................................................... 79

    6.1.1 The assignment instruction ............................................................... 79

    6.1.2 The function call ............................................................................... 80

    6.2 Alternative instructions ............................................................................ 80

    6.2.1 The if instruction ............................................................................ 816.2.2 The switch instruction ................................................................... 85

    6.3 Repetitive instructions ............................................................................. 90

    6.3.1 The for instruction .......................................................................... 906.3.2 The while instruction ..................................................................... 956.3.3 The do while instruction .............................................................. 99

    6.4 Solved problems ..................................................................................... 101

    6.5 Questions and exercises ......................................................................... 107

    Chapter 7 Arrays .............................................................................................. 113

    7.1 Single-dimensional arrays ...................................................................... 113

    7.1.1 Declaring a single-dimensional array ............................................. 114

    7.1.2 Accessing elements ......................................................................... 114

    7.1.3 Initialization of elements ................................................................. 115

    7.1.4 Reading the elements values from the keyboard ........................... 115

    7.1.5 Displaying the elements / Traversing an array ............................... 116

  • Contents

    7

    7.1.6 A complete example ....................................................................... 116

    7.2 Two-dimensional arrays ......................................................................... 117

    7.2.1 Declaring a two-dimensional array ................................................. 117

    7.2.2 Accessing elements ......................................................................... 118

    7.2.3 Initialization of elements ................................................................. 118

    7.2.4 Reading the elements values from the keyboard ........................... 119

    7.2.5 Printing a matrix ............................................................................. 119

    7.2.6 Traversing a matrix ......................................................................... 120

    7.2.7 Particular ways of traversing a square matrix ................................. 121

    7.2.8 A complete example ....................................................................... 124

    7.3 Solved problems ..................................................................................... 125

    7.4 Questions and exercises ......................................................................... 131

    Chapter 8 Strings .............................................................................................. 135

    8.1 Characters .............................................................................................. 135

    8.2 Strings .................................................................................................... 137

    8.3 Questions and exercises ......................................................................... 145

    Chapter 9 Pointers ............................................................................................ 149

    9.1 Pointer variables ..................................................................................... 149

    9.2 Operations with pointers ........................................................................ 151

    9.3 Pointers and other elements ................................................................... 153

    9.4 Questions and exercises ......................................................................... 156

    Chapter 10 User-defined functions .................................................................. 158

    10.1 User-defined functions ......................................................................... 159

    10.1.1 The prototype of a function ........................................................... 159

    10.1.2 The description of a function ........................................................ 160

    10.1.3 The call of a function .................................................................... 163

    10.1.4 The scope of variables .................................................................. 169

  • Computer Programming The C Language

    8

    10.1.5 Changing the arguments of a function .......................................... 174

    10.1.6 Passing arrays as arguments .......................................................... 176

    10.2 Recursion ............................................................................................. 178

    10.3 Solved problems ................................................................................... 180

    10.4 Questions and exercises ....................................................................... 189

    Chapter 11 User-defined types ......................................................................... 196

    11.1 The structure ........................................................................................ 196

    11.1.1 Definition and use ......................................................................... 196

    11.1.2 Structures and functions ................................................................ 203

    11.1.3 Arrays of structures ....................................................................... 206

    11.1.4 Pointers to structures ..................................................................... 207

    11.2 The enumeration .................................................................................. 209

    11.3 Questions and exercises ....................................................................... 211

    Chapter 12 Files ............................................................................................... 217

    12.1 File handling ........................................................................................ 217

    12.1.1 File opening .................................................................................. 218

    12.1.2 File closing .................................................................................... 220

    12.1.3 File input/output actions ............................................................... 221

    12.1.4 Repositioning the file pointer ........................................................ 227

    12.1.5 File renaming and removing ......................................................... 231

    12.2 A complete example ............................................................................ 233

    12.3 Questions and exercises ....................................................................... 243

    Appendix 1 The set of characters (together with their ASCII codes) .............. 248

    Appendix 2 The keywords of the C programming language ........................... 250

    Appendix 3 Answers to questions and exercises ............................................. 253

    References ........................................................................................................ 263

  • Introduction

    Communication has become a widely used concept over the last decades, play-ing an important role in all activities. People communicate using words or signs when they want to do something together, when they need to interact or to transmit information, feelings and so on. Such a way of communication is also required between humans and computers. A programming language is used in order to transmit to a computer how to perform a special task. Similar to the languages used in human communication, a programming language consists of words, sentences and well defined syntactical rules. In a programming lan-guage, the sentences are combined so that the program is able to provide the communication between human and computer. Without programs, a computer is nothing. On the other hand, a person that is able to write such programs has a lot of advantages over those who know only to use computers and their applica-tions.

    This handbook is easy to read, fast and efficient, being useful to the students who try to become familiar with programming issues. Those who will use this book in their training process as software developers (including the design, not only the implementation) will have the opportunity to become competent in the programming domain, because the offered items lead to acquiring knowledge and skills appropriate to this area.

    Therefore, the book is designed especially for those who made the first steps in programming and offers characteristics that lead to learning the C programming language (a strong, portable and popular language, used to develop applications in various domains). Some of the basic concepts of programming are discussed before presenting the specific aspects of the C language. Therefore it will be much easier to learn and to use other programming languages, because the knowledge base about structured programming already exists.

    This book is carefully split into chapters. The programming concepts are gradu-ally presented, in a natural order, so that the connection between a newly intro-duced notion and the previous notions is very clear and that the learning of a new notion is made on the basis of the already explained concepts. This way, a fast understanding and assimilation of the presented elements is guaranteed.

    The first two chapters depict general aspects, which apply to all programming languages. Several basic notions of this domain are presented in the first chap-ter. The second chapter shows a graphic way of solving problems through

  • Computer Programming The C Language

    10

    logical schemes. Then, specific elements of the C programming language are described, starting with data and data types (the third chapter) and continuing with a first C program (the forth chapter). The next two chapters provide the programmer library functions (the fifth chapter) and instructions (the sixth chapter) available in C programming language. The seventh chapter presents the array management, emphasizing the single-dimensional and the two-dimensional arrays. In C language, strings (presented in the eighth chapter) are a particular case of single-dimensional arrays. The C programming language description continues with pointers characteristics (the ninth chapter). Then follow two chapters that describe how programmers can split programs into functions (the tenth chapter) and how they can define their own data types (the eleventh chapter). In the end, the file handling in C language is presented (the twelfth chapter).

    Throughout all these chapters the theoretical aspects are presented simply and clearly, allowing the reader to quickly understand the discussed elements. The chapters also contain a large number of examples accompanied by comments and explanations, which are intended to support the theoretical part. Examples are mostly whole programs (not just isolated fragments) and were tested before being placed in the text.

    Those who will use this book will also have the possibility to verify their ac-quired knowledge, because each chapter (except for the introductory one) is ending with a set of questions and requirements, generally divided into four categories. The first category of questions focuses on identifying errors; several sequences of code with errors that must be found are presented. In the following category of questions the reader has to specify the result of some expressions, logical diagrams or sequences of code. Then comes a set of multiple choice questions about the content of the chapter; these questions cover both theoreti-cal and practical elements (expressions, sequences of code). The last appendix of the book provides answers and explanations to the questions in these first three categories. The review ends with some problems that involve writing entire programs. Answers to these problems are not provided in the book, the reader having to find himself a solution.

    This book can be covered and understood without the help of an expert because of the clarity of the theoretical aspects and because of the multitude of ex-plained examples, solved problems and answered questions. All those who are interested into the programming world will find this book a real help.

  • Chapter 1 Programming basics

    The computer is able to execute different operations and to offer solutions for a huge number of problems that have to be solved with its help. It only needs to be programmed as such. In other words, the computer executes everything it is asked for, with the imperative condition that it understands what the re-quirements are. Therefore, a certain means of communication between human and computer is needed, and this means is the programming languages.

    The concepts presented in this book are meant to facilitate the transmission of basic informatics and structured programming knowledge to those who are at the beginning of this road. The book can also be useful to those who have some experience in this domain, helping them to consolidate and to organize the knowledge they already have.

    Information is a widely used concept, lately; its meanings are closely related to: control, communication, perception, data, knowledge, representation, patterns. In the computer world data and knowledge are not relate strictly to the word information; they are connected to this word, heaving also specific significa-tions. Thus, data represents the raw material. After being processed, data be-comes information, which is interpreted (given a special meaning) and therefore becomes knowledge. Figure 1.1.1 is a suggestive graphical representation of the connection between these three notions that can create a pyramidal shape based on data (the largest amount), consolidated by information (in the middle of the pyramid) and crowned by knowledge.

    Figure 1.1.1 Pyramidal representation of data, information, and knowledge

    DATA

    KNOWLEDGE

    INFORMATION

  • Computer Programming The C Language

    12

    For instance, symptoms and laboratory tests results of a patient can be consi-dered as data; e.g. the white blood cells level is very high for that patient. The information can be that a white blood cells level that is higher than a specified value can lead to leukemia (this requires a processing of initial data by compar-ing it to a threshold). Finally, knowledge consists in specifying that the patient is in danger.

    At a basic level, the computer processes data. The programmers task is to design and to develop programs that determine the computer to take the raw data and to transform it into information with a special meaning for the user.

    Closely related to information is another concept: informatics the science that studies information processing using automatic systems [DEX98]. Other defini-tions also show that informatics supposes data acquirement, storage, handling, and classification. It studies the structure, the behavior and the interactions between systems that store, process and communicate information. This leads to another concept, frequently dealt with lately, communication. Communication between people is realized by a language that contains of expressions, signs, gestures. But it is impossible to communicate anything to a computer without knowing a language that can be understood by that computer (this means a programming language).

    The Central Processing Unit (CPU) is responsible for solving all problems, but it doesnt understand any human language. It accepts only so called machine code instructions, which are written using binary digits only 0 and 1, therefore transforming programming into a very laborious process. For this reason, some sort of abbreviations were invented (formed by few letters) for the machine code instructions. Therefore the assembly language appeared. Even so, the simplest operations were written with difficulty and involved passing through several steps.

    The repetition of some operations was then noticed. Small separated programs were written for these operations. After that, a new idea emerged: to create a programming language formed of these small programs that received suggestive names. Thus, a problem could have been solved using English words. Obvious-ly, programming became easier and more attractive. This kind of languages have a high level of abstraction (compared to the assembly language), thus they are called high level languages. The first high level languages were COBOL and FORTRAN, followed by Basic, Pascal, Lisp, C, and others.

  • 1 Programming basics

    13

    The C programming language was invented by Dennis RITCHIE in 1972. Although many years have passed since then, this language is still widely used because of its advantages [CH96], [GP00]:

    it is a high level language (it can be easily used thanks to its syntax); never-theless, it provides the power and the flexibility of a machine language be-cause it maintains some features of an assembly language;

    it is highly efficient, being created for writing the operating systems (its a programming language projected by the UNIX operating systems pro-grammers [BK03]);

    it is strong; the C programs can produce a large number of computations in a few steps;

    it is succinct due to the use of a large number of operators (some of them are mathematical operators, others replace particular commands;

    it is portable (can be installed on many different computers); it is popular because of its force and its portability, being used by an im-

    pressive number of programmers;

    it is in permanent development, being the subject of additions and exten-sions.

    All these characteristics make the C programming language a language that any programmer must know. Using the tools of the C language, the development of the programs can be done in an efficient way, resulting high quality final prod-ucts.

    The features of the C programming language allow and encourage structured programming. This kind of programming is based on a theorem, which states that any algorithm can be implemented using only three control structures (figure 1.1.2):

    sequence first an entity of a program is executed, and then the next entity; in other words, parts of a code sequence are executed one after another, without jumps over certain parts (figure 1.1.2 a);

    selection only one of two alternatives is executed, based on the value of a condition (figure 1.1.2 b);

    iteration an entity of a program is repeatedly executed as long as a condi-tion is true (figure 1.1.2 c).

  • Computer Programming The C Language

    14

    a) Sequence b) Selection c) Iteration

    Figure 1.1.2 The three control elements that support the structured programming

    Solving a problem actually involves implementing an algorithm; this means following a number of well-defined steps that must be executed so that the problem is solved. In order to do this, there are three stages that need to be accomplished (also represented in figure 1.1.3):

    problem analysis, in order to exactly determine the original data and the requirements;

    problem representation, in an appropriate manner so that computer can be able to solve it;

    implementation, meaning the writing of a program (using a programming language) in order to solve that problem.

    Figure 1.1.3 Problem solving phases

    Even though the implementation, the last phase of the problem solving process, seems to be the most important, the other two phases are not to be neglected either. The preliminary analysis of the input data and of the requirements is essential for finding a correct solution. It is also very important to create a well-structured program and an explicit flow of executed elements. In order to pro-vide a correct solution for a problem, it is recommended to have a graphical representation of the algorithm that is being used. This is achieved using some elements that form a so-called logical diagram. Each step that is executed to solve a problem is represented by an image with a geometric aspect and a short text that explains what has to be done in that certain step. Details regarding the graphical representation of a problem can be found in the chapter that presents the logical diagrams.

    Analysis Representation Implementation

  • Chapter 2 Logical diagrams

    2.1 The elements of a logical diagram First steps in structured programming will be made using logical diagrams, a very good method to improve the reasoning. The logical diagrams are not con-nected to a specific programming language. They are graphical representations of programs, providing an explicit idea about them. A logical diagram is the simplest way of expressing an algorithm. If a graphical representation of that algorithm is available, then the program that has to implement it will be easily written.

    The logical diagrams might seem archaic. Nevertheless, they are essential when a program is developed, being very useful, especially for the beginners in pro-gramming. It is said that an image is worth a thousand words; the logical dia-grams are exactly the image of a program. Writing the program, after its graphi-cal representation is made, is only routine work [GP00].

    A logical diagram is made by several graphical symbols; any algorithm can be represented using these symbols. The elements that can be used in a logical diagram are hereby presented.

    The START element marks the beginning of the program:

    The STOP element marks the end of the program:

    These two elements define exactly where the graphical representation of a program begins and where it ends. This cancels any questions regarding the delimitation of logical diagrams.

    The output element is used to display the results:

    For example:

    Write a

    STOP

    START

  • Computer Programming The C Language

    16

    The logical diagram of a first program can be made by using these three ele-ments; it displays the message This is my first program (fig-ure 2.1.1). As can be seen, the diagram contains an output element (which prints the message) and the two elements that mark the beginning and the end of the program.

    Figure 2.1.1 A logical diagram that uses the output element

    The input element is used for data reading.

    For example:

    The logical diagram from figure 2.1.2 uses the input element to read the name of a person; that name is then displayed with an output element.

    Figure 2.1.2 A logical diagram that uses the input and the output elements

    Write The name is:name

    START

    STOP

    Read name

    Read a

    Write This is my first program

    START

    STOP

  • 2 Logical diagrams

    17

    The processing element executes operations and it is used when the data is processed (computations or assignments):

    For example:

    A lot of problems can be solved by using the processing element. The following logical diagram calculates the sum and the product of two numbers (fig-ure 2.1.3). An input element is used to read the numbers. Then, in a processing element, the sum and the product are calculated. These are displayed at the end of the diagram with an output element.

    Figure 2.1.3 The logical diagram for calculating the sum and the product of two numbers

    Even more complex problems can be solved with the processing element. For example, the first degree equation: ax+b=0. First, two numbers a and b, representing the coefficients, are read. Then, the x value is calculated and dis-played. The figure 2.1.4 presents a first version of logical diagram that solves the first degree equation.

    START

    Read a,b

    Write sum, product

    STOP

    sum=a+b product=a*b

    b=2*a

  • Computer Programming The C Language

    18

    Figure 2.1.3 Logical diagram for solving the first degree equation (the first version)

    As it can be seen, this logical diagram created to solve the first degree equation has a drawback: it doesnt cover the case where the a coefficient is zero (in which case the division cannot be executed). From the mathematical point of view, the equation ax+b=0 is solved as follows: The value of the a coefficient is verified: if a is not zero, then x=b/a; else, the equation becomes b=0 and the value of the b coefficient must be

    verified:

    o if b is not zero, then the expression b=0 is false, so no solutions for the unknown variable x;

    o if b is zero, then the expression b=0 is true and any real number is solution for the equation (this means that the unknown variable x has an infinite number of solutions).

    In order to solve this problem, another element is necessary: the one given below.

    The decisional element evaluates conditions and it is used when a decision must be made based on two alternatives. The element has to contain a question with two possible answers: yes or no.

    START

    Read a,b

    Write x

    STOP

    x=-b/a

  • 2 Logical diagrams

    19

    For example

    The first degree equation can now be correctly solved using the decisional element and the algorithm described above. The logical diagram presented in figure 2.1.5 follows exactly the stages of this algorithm.

    Figure 2.1.5 Logical diagram for solving the first degree equation (the second version)

    NO YES

    YES NO

    START

    Read a,b

    Write x

    STOP

    x=-b/a

    a0

    b0

    Write No solu-tions

    Write Infinite number of solutions

    YES NO a0 YES NO

  • Computer Programming The C Language

    20

    2.2 Solved problems The logical diagrams are a simple, explicit way of representing an algorithm and of solving a problem, being very useful to those who make their first steps in the structured programming. These graphical elements are an excellent tool that can be used to improve the reasoning when the method to solve a problem is searched. In the following examples, solutions for several other problems are suggested in order to complete the description of logical diagrams.

    2.2.1 First, it is required to calculate the surface of a square with a given side L. The formula S=L*L will be used to find the surface. A first version of logical diagram for solving this problem is presented in the figure 2.2.1. The user must enter (by an input element) the side of the square. Then the surface is calculated (in a processing element) and it is displayed (using an output element).

    Figure 2.2.1 The surface of a square (the first version)

    But what happens if the user, by mistake or by ignorance, enters a negative side for the square? The value is unacceptable, because a dimension cannot be nega-tive. Therefore, the logical diagram from the figure 2.2.1 doesnt properly function for all cases and has to be modified. This problem could be partially

    START

    Read L

    Write S

    STOP

    S=L*L

  • 2 Logical diagrams

    21

    solved if the L value is verified before calculating the surface. If the side is strictly positive (higher than zero), the surface can be calculated and displayed; otherwise, an error message will be shown (figure 2.2.2).

    Figure 2.2.2 The surface of a square (the second version)

    There are cases when the surface (or something similar) must necessarily be calculated. In other words, the user must be forced to enter a valid value (in this case, a positive value). This is realized by a repetitive structure (figure 2.2.3). The user has to reenter the required value as long as this is not valid. Therefore, the program will continue, calculating the surface, only after a positive value is entered.

    NO YES

    START

    Read L

    Write S

    STOP

    S=L*L

    L>0

    Write Incorrect value

  • Computer Programming The C Language

    22

    Figure 2.2.3 The surface of a square (the complete version)

    2.2.2 The following problem is also an example of repetitive structure. The user enters n numbers (n has to be a natural number). The average of these numbers will be calculated and displayed (figure 2.2.4). In order to solve this problem, n must have a positive value. A repetitive structure (similar to that used for the squares surface) will be used to validate the n value. After a positive number is read, the average can be calculated. It represents the sum of the entered ele-ments divided by the number of elements. Therefore, a variable called sum, with the initial value zero, is used (its obvious that the sum is zero before entering any value). In addition to this, at any time during the programs execu-tion, it is necessary to know how many numbers were already read. In order to do this, another variable, called counter, is used; it also has the initial value zero. Then, each number can be read. This is realized in another repetitive structure. Each time a number is read, it is added to the sum and the coun-ter is increased by one. The loop is repeated as long as the counter is less

    NO YES

    START

    Read L

    Write S

    STOP

    S=L*L

    L>0

    Write Incorrect value. Enter a positive

    value.

  • 2 Logical diagrams

    23

    than n. When the condition becomes false, the repetitive structure is left and the execution of the program continues, calculating the average, which is then displayed.

    Figure 2.2.4 The average of n numbers

    NO

    NO

    YES

    START

    Read n

    Write average

    STOP

    average=sum/n

    counter0

    Write Enter a posi-tive value

  • Computer Programming The C Language

    24

    2.3 Questions and exercises A. Find the error.

    1.

    2.

    NO YES

    START

    Read x

    STOP

    x>0

    Write Positive Write Negative

    START

    Read x

    STOP

    x=x+1

    Write x

  • 2 Logical diagrams

    25

    3.

    B. Considering the following logical diagrams, specify what actions they per-

    form.

    4. START

    Read xA,xB,yA,yB

    Write AB

    STOP

    AB xB xA yB yA

    NO YES

    START

    Read x

    STOP

    Write Positive Write Negative

    x>0

    Write Zero

  • Computer Programming The C Language

    26

    5.

    6. START

    Read n

    Write r

    STOP

    r = n modulo 10

    START

    Read a3,a2,a1,a0

    STOP

    b2=3a3 b1=2a2 b0=a1

    Write a3x3+a2x2+a1x+a0

    Write b2x2+b1x+a0

  • 2 Logical diagrams

    27

    7.

    C. Choose the correct answer (one only).

    8. Which of the following statements, regarding logical diagrams, is true? a) they are graphical representations of programs; b) they are not connected to a programming language; c) they are a very good me-thod to improve the reasoning; d) they provide an explicit idea about the programs they represent; e) all answers are correct.

    9. Which of the following elements doesnt exist in a logical diagram? a) decisional; b) output; c) repetitive; d) processing; e) input.

    NO

    NO

    YES

    START

    Read n

    Write p

    STOP

    counter0

    Write Enter a posi-tive value

  • Computer Programming The C Language

    28

    10. The decisional element has the shape of a: a) triangle; b) diamond; c) rectangle; d) trapezoid; e) star.

    11. Which of the following shapes cannot be part of a logical diagram? a) rectangle; b) diamond; c) trapezoid; d) triangle; e) ellipse.

    12. The processing element has the shape of a: a) rectangle; b) circle; c) diamond; d) arc of circle; e) parabo-la.

    13. How many outputs a decisional element has?

    a) none; b) one: Yes; c) two: Yes and No; d) three: Yes, No, Unknown; e) any number, depending on the evaluated expression.

    D. Create logical diagrams to solve the following problems:

    14. Read a real number x. Calculate and display the value of the expression:

    E x,ifx 0;|x|,ifx 0.

    15. Read three numbers a, b and c, representing the coefficients of the second degree equation ax2+bx+c=0. Find and display the solutions of this equation.

    Suggestion: From the mathematical point of view, the second degree equation solving requires several steps. First, the value of the a coeffi-cient is verified:

    o if a is not zero, then =b2-4ac can be calculated; the obtained value is verified:

    if 0, then the equation has two different solutions: x

    and x

    .

  • 2 Logical diagrams

    29

    o if a is equal to zero, then the equation becomes bx+c=0 and the value of the b coefficient must be verified: if b is not zero, then x=c/b; else, the equation becomes c=0 and the value of the c

    coefficient must be verified:

    if c is not zero, then the expression c=0 is false, so no solutions for the unknown variable x;

    if c is equal to zero, then the expression c=0 is true and any real number could be the solution for the equation (this means that the unknown varia-ble x has an infinite number of solutions).

    16. Calculate the surface and the length of a circle with R radius. Suggestion: The following formulas can be used: surface=R2 and length=2R. The radius value must be validated (it has to be posi-tive).

    17. Display the first n Fibonacci numbers. Suggestion: Fibonacci numbers list is a repetitive structure example. The list is represented by a sequence of numbers defined using the following formula:

    Fn 0,ifn 0;1,ifn 1;Fn 1 Fn 2,ifn 1.

    ,wheren 0, 1, 2, 3,

    Therefore, the first two numbers are known (0 and 1) and each of the following numbers is calculated as sum of the preceding two numbers. Thus, the first 10 Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

  • Chapter 3 Data and data types

    3.1 General concepts As seen in the first chapter of this book, the computer stores and processes data; these have different meanings and are essential for solving all kinds of prob-lems. There are two categories of data:

    the ones that can be modified (can change their value) during the execution of the program, called variables;

    the ones that maintain their initial value, without the possibility of changing it, called constants.

    Both variables and constants, before being used in a program, must be declared. The variables have a name, a type and, optional, an initial value. The constants have a name, a type and, mandatory, an initial value. Through this declaration, variables and constants receive memory space.

    The name of a variable or of a constant is made of several characters (letters, digits, special characters), following certain rules. In order to do this, a pro-grammer should know the available set of characters. These can be found in Appendix 1. When the name of a variable or of a constant is set, several restric-tions should be considered [CH96]:

    the first character of the name should be a letter or an underscore (e.g. name or _name);

    following the first character, any combination of digits and letters (except-ing non alphanumeric characters as #, $ or space) can be used (e.g. names like variable1, word2new can be used, but var$ is not a valid name);

    the C programming language is case sensitive; this means that it makes the difference between uppercases (capital letters) and lowercases (small let-ters); this feature of the language should be considered when a variable or a constant is declared and used (e.g. name1 and Name1 are different va-riables);

    there are several reserved words that cannot be used as names for variables or constants; a complete list of these words (also known as keywords) can be found in Appendix 2.

  • 3 Data and data types

    31

    3.1.1 Data types The type of a variable or of a constant depends on what must be represented by that variable or constant; the consequence is how the information is stored in the computers memory. Any entity that is to be processed by the computer must be transposed from its acquired form to a physical form defined by vol-tage. This leads to the basic unit of information representation in memory, which is the bit. It can have the logical values of 0 (if the voltage is between 0 and 0.4 volts) or 1 (for a voltage between 2.4 and 5 volts). Therefore, a bit [NR01] is the elementary and the irreducible information, which captures one of two potential states that are contradictory and complementary.

    Commonly, the bits are grouped together in codes with length that are power of 2. The usual codes are represented by 8, 16, 32, 64, 128, 256 bits. Eight bits create a byte. The table 3.1.1 presents the multiples of the bit and of the byte [NR01].

    Table 3.1.1 Multiples of the bit and of the byte

    Multiples of the bit Multiples of the byte

    1 Kilobit (Kbit) = 210 bits 1 Kilobyte (KB) = 210 bytes

    1 Megabit (Mbit) = 220 bits 1 Megabyte (MB) = 220 bytes

    1 Gigabit (Gbit) = 230 bits 1 Gigabyte (GB) = 230 bytes

    1 Terabit (Tbit) = 240 bits 1 Terabyte (TB) = 240 bytes

    1 Petabit (Pbit) = 250 bits 1 Petabyte (PB) = 250 bytes

    1 Exabit (Ebit) = 260 bits 1 Exabyte (EB) = 260 bytes

    1 Zettabit (Zbit) = 270 bits 1 Zettabyte (ZB) = 270 bytes

    1 Yottabit (Ybit) = 280 bits 1 Yottabyte (YB) = 280 bytes

  • Computer Programming The C Language

    32

    A type represents the multitude of values that a variable or a constant can take. Types have a name and are divided into two main categories:

    standard types are already defined in the C programming language and used as they are (int, float, double, char);

    user-defined types according to the context and to the requirements of a problem, the user can define and then can use its own data types.

    The standard data types, which can be used in the C programming language, (also known as primary types) are presented in table 3.1.2. Together with the name and the type meaning, there is the number of bits used for the representa-tion and the range of values for the data defined by that certain type.

    Table 3.1.2 Data types in C programming language

    Types name Types meaning Dimension Range

    char character 8 bits -128 127

    int integer 16 bits -32.768 32.767

    float real (floating point)

    32 bits 3.4 e-38 3.4 e+38

    double real (floating point, double precision)

    64 bits 1.7 e-308 1.7 e+308

    Data types are often accompanied by the so-called modifiers, which specify the length of the memory space allocated to an element. These are:

    short short; long long; signed with sign; unsigned without sign. Table 3.1.3 contains the C data types, together with the potential modifiers (this is how the derived types resulted) [HS98], [DL06].

  • 3 Data and data types

    33

    Table 3.1.3 Data types and modifiers of the C programming language

    Types name Types meaning Dimension Range

    unsigned char character without sign

    8 bits 0 255

    char or signed char

    character with sign 8 bits -128 127

    unsigned int integer without sign 16 bits 0 65.535

    int or signed int integer with sign 16 bits -32.768 32.767

    unsigned short int

    short integer with-out sign

    8 bits 0 255

    short int or signed short int

    short integer with sign

    8 bits -128 127

    unsigned long int

    long integer without sign

    32 bits 0 4.294.967.295

    long int or signed long int

    long integer with sign

    32 bits -2.147.483.648

    2.147.483.647

    float real (floating point) 32 bits 3,4 e-38 3,4 e+38

    double real (floating point, double precision)

    64 bits 1,7 e-308

    1,7 e+308

    long double long real (floating point, double preci-sion)

    80 bits 3.4 e-4932

    3.4 e+4932

  • Computer Programming The C Language

    34

    The names of the types and of the modifiers are keywords in the C program-ming language, so they are reserved to this aim. It is not allowed to declare variables or constants with these names and its also impossible to create new data types or functions that will have these names. The keywords list of the C programming language can be found in the Appendix 2.

    3.1.2 Variables When a variable is declared, the type of the information stored by that variable must be specified. The variable must also have a name. The general form of an instruction that declares variables is: type var1,var2, , varn; where var1, var2, , varn are the variables names and type is the name of one of the types presented in table 3.1.3 or a user-defined type. Variables are separated by comma, and the declaration is ended with semicolon.

    Examples: int number1, number2, sum; double average; When a variable is declared, it can also receive an initial value, which can be modified during the execution of the program. For example: int counter=0; The previous instruction declares an integer variable, with the name counter and the initial value zero.

    3.1.3 Constants If a program repetitively uses a value, then that value should be declared as constant. It receives a name and it can be used throughout the program with that name. Its similar to Mathematics where the surface of a circle is calculated using the constant , instead of the value 3.14159265 The use of constants in a program has several advantages [CH96]. The most important are related to the fact that due to the constants code becomes easy to understand and easy to modify. If a program uses the constant, then is ob-vious that it represents the ratio between the circumference of a circle and its

  • 3 Data and data types

    35

    diameter in the Euclidian geometry. But if the value 3.1415 is used, then things are not so obvious. Regarding the possibility of changing the values of a con-stant that is being used in a program, the situation is simple: the constant is modified when it is declared and this change of value is visible wherever the constant is being used. But if the program uses only values instead of constants, then the code is more difficult to be modified because all that values should be found and replaced.

    Before using a constant, it must be declared. This action is performed with the keyword const. The general form of the instruction that declares a constant is: const type constant_name = value; where:

    type is the data type of the constant (e.g. int, char, float, etc.); constant_name is the name of the constant (this will be used in the

    program);

    value is the value that the constant will have. The following example declares a floating point constant with the name pi and the value 3.1415: const float pi = 3.1415; Besides the constants that are defined by the user, several predefined symbolic constants can be used in C programming language. For example, there is a constant called M_PI with the value 3.14159265.

    3.1.4 Operators Variables and constants can be included in different operations to obtain new values. In order to do this, operators will be used. Variables, constants and operators will form expressions. Depending on the type of the operation that involves operators, these are divided into several categories. Those most fre-quently used will be discussed below [CH96], [DL06], [GP00].

    relational operators when applied, the result is 1 if the comparison is true and 0 otherwise: < less than (a

  • Computer Programming The C Language

    36

    > greater than (a>b); >= greater than or equal to (a>=b); == equal to (a==b); != not equal to (a!=b).

    additive operators: + plus (addition: a=b+c); minus (subtraction: a=b-c).

    multiplicative operators: * multiplication (a=b*c); / division when two integer numbers are divided, the result is the quo-

    tient (an integer value); if at least one of the operands is a real number, then the result is a real value (a=b/c);

    % modulo the result is the reminder of the division of two integer values (a=b%c); it cannot be used with real operands.

    compound operators these are used for writing expressions faster: += addition assignment the result is stored in the first operand (e.g.: x+=y is similar with x=x+y);

    = subtraction assignment the result is stored in the first operand (e.g.: x=y is similar with x=xy);

    *= multiplication assignment the result is stored in the first operand (e.g.: x*=y is similar with x=x*y);

    /= division assignment the result is stored in the first operand (e.g.: x/=y is similar with x=x/y);

    %= modulo assignment the result is stored in the first operand (e.g.: x%=y is similar with x=x%y).

    logical operators: ! logical negation NOT (p=!q); && logical AND, also known as logical conjunction (p=p1&&p2); || logical OR, also known as logical disjunction (p=p1||p2).

  • 3 Data and data types

    37

    other operators: = assignment copies the right value into the left variable; this way an

    expression is created and a new value is obtained (e.g.: x=7; or i=i+2;);

    ++ increment is an unary operator (this means that it needs only one operand); it can be applied only to integer variables and its effect is the increase in value of that variable by one (x++ or ++x are similar with x=x+1). The operator can be placed before the variables name (prefix or pre-increment) or after the variables name (suffix or post-increment); the difference is that the variable will change its value be-fore, respectively after use;

    decrement decreases the value of its operand by one (x or x are similar with x=x1) and has the same features as the increment operator;

    & reference or address operator indicates the memory address of a vari-able and is placed in front of the variables name (&x);

    ?: ternary (conditional): a?e1:e2 if a is not zero (or true), then the expression e1 is executed; if a is zero (or false) the expression e2 is executed;

    () function call is performed through the functions name, sometimes followed by a list of arguments (e.g.: calculate(a,b));

    (type) cast or type conversion the operator is used to change the type of a variable (e.g. if a floating point variable a is considered and the instruction (int)a is executed, then an integer value will be ob-tained).

    The order of the operations (also called precedence of the operators) is the mathematical one. Table 3.1.4 contains the operators presented in this para-graph starting with the strongest and ending with the weakest, according to their precedence [BK03], [HS98].

    In order to avoid the errors that can be made because of the operators prece-dence, it is better to use parentheses when an extensive expression is made. For example, if the expression x

    must be calculated, it will be written as

  • Computer Programming The C Language

    38

    x 7 y/2 z. This expression is different from x 7 y/2 z, which in fact calculates x

    z.

    Table 3.1.4 The operators precedence

    Category Operators

    unary ++, , (type)

    multiplicative *, /, %

    additive +,

    relational =

    equality ==, !=

    logical AND &&

    logical OR ||

    conditional ?:

    assignment =, +=, -=, *=, /=, %=

    The operators precedence has a very important role when the value of an ex-pression is calculated and knowing the order of applying operators is mandato-ry. For example, the expression (1||1&&0) has the value 1 because operator && is applied before operator || [PT12]. If the order was the other way around, then the result would change.

    3.1.5 Expressions Similar to Mathematics, in a programming language expressions are operations made on operands (variables, constants or other expressions) using operators.

  • 3 Data and data types

    39

    This way a new value is obtained; the type of this new value depends on the operands type. The general form of an expression is:

    E = simple_expression [relational_operator another_simple_expression]

    If an entity is placed between square brackets, then that entity is optional. Therefore, an expression is made by one or more simple expressions connected with relational operators. A simple expression contains terms connected with additive operators. A term has several factors connected with multiplicative operators. Finally, a factor can be: a constant, a variable (represented by its value), the address of a variable (the address operator followed by the name of that variable), a negated variable, a function call, a cast or another expression between parentheses.

    The expressions can be divided into three categories, according to the result that they generate [CH96]:

    mathematical expressions These always have a number as result and are made from values that are con-nected through symbols representing mathematical operations. Parentheses can be used to specify the order of the operations.

    For example:

    the expression 3+4*2 will have the result 24; while (3+4)*2 will be 14.

    text expressions The result of these expressions is a string; this means a sequence of characters that can include digits, letters, punctuations and other symbols (e.g. "Dennis M. RITCHIE"). Unfortunately, the C programming language doesnt have operators for string processing. Instead of operators, text expressions use par-ticular functions that will be presented in the chapter dedicated to strings.

    logical expressions These can have the result 1 or 0, meaning true, respectively false and are created using relational operators. A logical expression is similar to a question with the answer yes or no.

    For example:

    5>1 is a true expression, so the result is 1; 7==0 is false, so it has the result 0;

  • Computer Programming The C Language

    40

    a>=b can be 0 or 1, depending on the values of the considered variables. The logical expressions results and also elements that can have a logical mean-ing can be connected with logical operators, obtaining complex conditions. In order to do this, the logical operators must be well known. In table 3.1.5 two logical variables a and b are considered and the logical operators AND, OR and NOT are applied; all possible results are revealed.

    Table 3.1.5 How to apply logical operators

    a b !a a&&b a||b

    0 0 1 0 0

    0 1 1 0 1

    1 0 0 0 1

    1 1 0 1 1

    For example:

    the expression (7>=5)&&(0!=10) contains two true expressions con-nected through the logical AND operator; the final expression is true, so the result will be 1;

    the expression (7==0)&&(3

  • 3 Data and data types

    41

    3.2 Data types description The following paragraphs present the standard data types that were shortly described before. There are also discussed the operators that can be applied to every type. At the end of each paragraph some examples regarding the use of that data type are presented.

    3.2.1 The integer type In the C programming language there are several types that can be used to represent integer values, each of these types being a subset of the mathematics integer numbers set (Z). Summarized in table 3.1.3, integer types are detailed below.

    unsigned int is used for integers without sign. Such a number is represented using 16 bits and can have values between 0 and 65.535. In the C programming language a constant that can be used to determine the maximum limit of this range is defined. The constant is UINT_MAX and has the value 65.535.

    int or signed int are the types used to represent integers with sign. 16 bits are required for this numbers and the range of values is -32.768 32.767. The C constants that delimit this range are INT_MIN, with the value -32.768, and INT_MAX, with the value 32.767. unsigned short int is the type used for short integers without sign. Numbers are represented on 8 bits, so the range is 0 255. In order to access in a program the upper limit of this domain, the constant USHRT_MAX can be used; it has the value 255.

    short int or signed short int define short integer numbers with sign. These types of numbers are represented on 8 bits and have values between -128 and 127. The limits of this range can be found using the constants SHRT_MIN, which has the value -128, and SHRT_MAX, with the value 127. unsigned long int is a data type used for large, positive integers. These numbers are represented on 32 bits and have values in the range 0 4.294.967.295. The constant ULONG_MAX contains the upper limit of this range.

    long int or signed long int are used for large integers with sign (posi-tive or negative). The representation is made using 32 bits and the numbers are

  • Computer Programming The C Language

    42

    between -2.147.483.648 and 2.147.483.647. The limits of this range can be accessed through the constants LONG_MIN and LONG_MAX. When programs are written, variables must be properly defined. For example, the age of a person can be represented by a variable that has the type un-signed short int because the age is always positive and it is also a short number. But if a force has to be used in a program, then the variables definition must provide a large enough domain, with positive and negative values (int for example).

    The integer numbers can be involved into different operations: relational (=, ==, !=), arithmetical (+, -, *, /, %) or logical (&&, ||). The integer variables can also be incremented (++) or decremented (--). Using the integer type

    The following sequence declares, using the integer type, three variables (x, a and b) and a constant (lambda). The constant has, obviously, an initial value (3 in this case). The variables do not receive initial values when they are de-clared; a and b get values later (2, and -7 respectively), and the value of x is calculated through an expression. The result of this expression is -15. const unsigned int lambda = 3; int x, a, b; a = 2; b = -7; x = lambda * (a + b); The integer variables are often used with the increment and decrement opera-tors. These operators can be placed as prefixes or as suffixes of a variable; the difference is marked by the following two sequences of code. Two integer variables a and x are declared. The second variable, x, has the value 7. The difference is visible when the assignment of the x value to the variable a is made. In the first case, x is incremented after the assignment; in the second case, before the assignment. int a, x; x = 7; a = x++;

    int a, x; x = 7; a = ++x;

    After these three lines of code are executed the results are a=7 and x=8 because x is incremented after the assignment.

    Because x is incremented before the assignment, in this second case the results are a=8 and x=8.

  • 3 Data and data types

    43

    3.2.2 The real type The real numbers (R set of Mathematics) can be included in a C program through the types float, double and long double described in ta-ble 3.1.3. These data types offer the possibility to use real numbers with differ-ent precisions and dimensions, up to the value of 3.4 e+4932.

    float is the data type used to represent, on 32 bits, real numbers with 6 de-cimal places. If a higher accuracy is necessary, then numbers can be declared double (with representation on 64 bits) and in order to extend the precision, the long double type can be used (with representation on 80 bits). The real type variables can be used in expressions with relational operators (=, ==, !=) and with arithmetical operators (+, -, *, /). In relational expressions, the result is a value that has the meaning of true or false (for ex-ample, 7.14 < 17.2 is a true expression, but 3.5 == 7.8 is a false one). Using the real type

    In the following sequence of code two float variables are declared and receive initial values. The first one is used to store the price and the second to store the quantity of a product sold in a period of time. A third variable, also of float type, is declared; its value is calculated multiplying the first two va-riables (representing the collected amount). float price = 4.5, quantity = 125.75, amount; amount = price * quantity;

    3.2.3 The char type This category of data is the set of all possible characters. They can be represented on 8 bits, with or without sign, through two data types (unsigned char and char or signed char) described in table 3.1.3. 256 characters can be encoded on the 8 bits available. All characters are con-verted to integers according to the ASCII code (American Standard Code for Information Interchange). Appendix 1 contains some of these characters, to-gether with the associated ASCII codes.

    Using the char type Some characters are declared and initialized in order to show how to work with this kind of data in a C program.

  • Computer Programming The C Language

    44

    char c1 = 'A'; char c2 = '7'; These characters may be the subject of few standard operations: char c3; c3 = c1 + c2; After executing the sum, the variable c3 will have the value 'x' because in fact the ASCII codes of variables c1 and c2 are added. Relational operators can be applied to characters. Thus, 'D'0). A floating point variable called mark stores the mark of a student obtained at an exam. In order to verify if that mark belongs to the interval (8; 10] the ex-pression (mark>8)&&(mark

  • 3 Data and data types

    45

    3.2.5 The void type This is not really a data type or it can be considered an empty data type, a data type that doesnt have values. From a syntactical point of view, it is placed where a data type is expected. Void is used to specify that a function doesnt return anything (e.g. void aFunction(int x)). It can also appear as the unique argument in the prototype of a function, showing that the function doesnt have any arguments (e.g. float otherFunction(void)).

    3.2.6 Type casting Sometimes the type of an entity must be changed (to benefit from the advantag-es offered by some properties of another type). This can be achieved through a type conversion (cast). There are two kinds of type conversions implicit and explicit [BK03], [HS98].

    The implicit type conversion is automatically made by the compiler and it is necessary when entities with different data types are involved in an expression. This conversion has two directions.

    On the one hand, the conversion modifies a data type into another data type that includes the initial one, as can be seen in the following example. The integer variable b is converted to float and the result is x = 9.47. float a = 2.47, x; int b = 7; x = a + b; In this case, when the expression was evaluated, the most comprehensive type was searched. All the elements of that expression were converted to that type. The order of the data type, starting with the most comprehensive is: double, float, long, int, char [CH96]. On the other hand, if an assignment is made, the source data will be forced to the destination data type [CH96], even if this implies truncated information and loss of precision. The previous example was modified considering the result x an integer variable. The consequence is that all variables from the right side of the assignment sign are forced to become integers and the result is x = 9. float a = 2.47; int b = 7, x; x = a + b;

  • Computer Programming The C Language

    46

    The explicit type conversion is introduced in a program through a type mod-ifier. This is an unary operator that is placed as a prefix to a variable or an expression and changes that information to the specified type. The general form of an explicit type conversion is: (type)expression; It is very simple to use this kind of conversion in a C program. For example, an integer variable a is considered. It stores the ASCII code of a character. Anoth-er variable, x, of char type will store the character associated to the specified ASCII code, changing the content of the variable a from int to char. int a=65; char x; x=(char)a;

    3.3 Questions and exercises A. Find the error.

    1. const int alpha=2; int beta=3; alpha=beta+10;

    2. int a=7, double=2, x; x=double*a;

    3. float x=1, y; y=x++;

    4. unsigned int a=22, b=35; x=a+b;

    5. unsigned int x=12, y=-15, q; q=x-y;

    6. float a=2, b=-3; x=-a/b; float x, y; y=2*x+a-b;

    7. int x=1, y=2, z=3, e; e=x+2y-z;

  • 3 Data and data types

    47

    8. float x=7.5, y; y=x%2;

    9. float 1_mark, 2_mark, final_mark; final_mark=(2*1_mark+2_mark)/final_mark;

    B. Considering the definitions int a=3, b=4;, evaluate the following expressions and specify the result.

    10. E=a/5+1; 11. E=(a++)-(a%2); 12. E=(a++)-(--b); 13. E=(-a)-(--a); 14. E=(a==b); 15. E=(a+b)%4; 16. E=((--b)+a++)%2;

    C. Choose the correct answer (one only). 17. Which of the following data types doesnt exist in the C programming

    language?

    a) int; b) float; c) double; d) char; e) all answers are wrong.

    18. Which of the following variables declarations is wrong?

    a) float mark_one; b) float mark one; c) float markone; d) all declarations are correct; e) all declarations are wrong.

    19. Specify the value of the expression E=((2+4)*3-1)*(3-5)? a) -34; b) 0; c) -24; d) 24; e) the expression contains an error.

    20. Which will be the value of x variable after the following sequence of in-structions is executed? int a=65, x; x=a/2; a) 32.5; b) 1; c) 32; d) 65; e) all answers are wrong.

  • Computer Programming The C Language

    48

    21. Calculate the value of the expression E = 2*(7-(9+5)+4*(21-19). a) 8; b) -6; c) -12; d) 2; e) the expression contains an error.

    22. Which will be the value of m variable after the execution of the follow-ing instructions? double a=7, m; m=a%2; a) 3.5; b) 1; c) 14; d) 49; e) the assignment m=a%2 is imposs-ible.

    23. Which of the following expressions is true if x=1 and y=3? a) (x>=0)&&(y=0)||(y

  • 3 Data and data types

    49

    a) 3; b) 3.14; c) 3.1415; d) 0; e) the assignment x=(int)a is impossible.

    29. Which of the following expressions is false if a=1, b=-3 and c=7? a) !((a+b+c)c)|| ((a!=0)&&(b!=0)); d) !(a>b); e) all expressions are true.

    30. Which of the following data types doesnt exist in the C programming language?

    a) int; b) float; c) string; d) double; e) all answers are wrong.

  • Chapter 4 A first C program

    4.1 Stages of a C program implementation A program is a list of instructions that specify what a computer has to do. In fact, a program represents the implementation of the algorithm that solves a certain problem. The instructions that form a program may refer to: reading information from the keyboard or from a file, writing information on the screen or in a file, making arithmetic and logical operations, comparing entities.

    The first step in making a program is writing it (and obviously saving it) using a text editor. The result is a source file that will have the extension .c (e.g. pro-gram.c). But a source code has no meaning for the computer. It must still undergo some changes.

    Thus, the next step in the development of a program is the source file compila-tion; this means that the program will be translated from the programming language used to write it (C, in this case) to the language of the computer ma-chine, language that is called machine-code [NR01]. This process is performed by a compiler. If the program has errors, these will be displayed and must be solved. The line that contains each error is emphasized and a short message explains the possible cause of the error. Once the program is successfully com-piled, an object file is created a file with the same name as the source file, but with the extension .obj (e.g. program.obj) Next follows the linking phase performed by a linker (or link editor). It con-nects the object code previously created with object codes of library files, of input/output drivers and/or of the operating systems programs [NR01]. The result is a new file, an executable file. This has the same name as the source file, but the extension is .exe (e.g. program.exe). The executable file can be run, obtaining the results for which the program was created.

    Figure 4.1.1 is a graphical representation of the steps followed in a C program development, from the code writing, to the results. It can be observed that the source file represents the input data for the compiler and the object file is the input for the link editor.

  • 4 A first C program

    51

    Figure 4.1.1 The development of a C program

    If a repeated execution of a program is necessary, then it is sufficient to run the executable file. But if the source code is modified, then the compiling and the linking phases must be completed again before the program can be executed once more.

    4.2 The structure of a C program All programs that are written using the C programming language are made by one or more functions. First, a program that contains a single function and displays on the screen the message This is a first C program will be considered. The source code is presented by the program 4.2.1.

    Program 4.2.1 #include void main(void) { printf("This is a first C program."); }

    Source file

    Object file

    Executable file

    Errors?

    Compiling

    Editing

    Displaying errors NOYES

    Linking

    Results

    Running

    Correcting errors

  • Computer Programming The C Language

    52

    All programs require a starting point. In the C programming language the ex-ecution of a program starts with a function called main(). All C programs must have this function. Otherwise, the starting point of the program will not be determined and a linking error will be generated.

    Both outside and inside the main() function there are a lot of other elements that are emphasized by numbers in figure 4.2.1, figure that describes the struc-ture of the previous program. All these elements have a well-defined role, some of them being mandatory in certain contexts.

    Figure 4.2.1 The structure of a C program

    Though the program in figure 4.2.1 has a single objective (to display on the screen a simple message), it needs several tools in order to accomplish this task. Their role is hereby presented.

    1. #include it is called preprocessor directive;

    it specifies that together with the source code of the current pro-gram, another program/file must be considered in order to have a proper functioning of the application;

    usually the files that are included through this directive are library files and contain a number of functions that are used in the program.

    #include void main(void) { printf("This is a first C program."); }

    1 2

    4 3 5

    7 9

    6

    10

    8

    11

  • 4 A first C program

    53

    2. the name of the file that is intended to be included; it must be framed by angle brackets (number 10 in figure 4.2.1); in this case the standard input/output library is included; it contains

    functions that are used to read and to write data; the current program needs to include this library because it has to display a text on the screen (this is done using a function that is described in the included library).

    3. main is the name of a function; in this case it is the name of the most important function of a C pro-

    gram (main()), but it can also be any other function. 4. void or the name of a data type written in front of a functions name

    represents the type of a function (in fact, the type of the value returned by that function);

    the main() function from the presented example doesnt return any-thing; for this reason, in front of its name stands the word void (as shown in the chapter presenting data types, void can be considered an empty data type);

    caution: if nothing is written in front of a functions name, then that function must return an integer value.

    5. (void) or a list of comma delimited variables, each one preceded by its type

    the arguments of that function; the list is enclosed by parentheses and is placed after the name of the

    function, as shown by number 11 in figure 4.2.1;

    if the function doesnt have arguments (as the current case), then the word void will be used to specify this.

    6. { and } the curly brackets mark the beginning and the end of a function or of a

    block of instructions;

  • Computer Programming The C Language

    54

    each time a number of instructions must be executed together, curly brackets will be used to group them.

    7. represents the call of a function this call specifies what the program must execute at that moment; in this case, the function printf() that is called will display a mes-

    sage on the screen (details about this function are presented in the chapter about input/output functions of the library functions).

    8. the list of the arguments used when a function is called if a function requires arguments, these must be sent when the function

    is called;

    the arguments are comma delimited (if there are more than one) and are enclosed by parentheses;

    the parentheses must be present even if the function doesnt require arguments;

    in the presented example the function printf() receives as argu-ment a string delimited by double quotes.

    9. the semicolon ; each C instruction is ending with semicolon; this is the character used to delimit instructions (thus, the compiler

    will understand where an instruction ends and where another one be-gins);

    even if the main() function presented here contains a single instruc-tion (the call of the function printf()), the semicolon delimiter must be used at the end of this instruction;

    in this example the line that contains the beginning of the main() function doesnt have semicolon; the reason for that is that the instruc-tion doesnt end on this line, but on the last line of the program, where the closing curly bracket appears;

    on the other hand, after the curly bracket it is not required to use se-micolon because the curly bracket is only a character that groups ele-ments together and doesnt execute anything by itself [GP00].

    As shown in the example in figure 4.2.1, a C program can contain three types of brackets [GP00]: angle brackets (marked by number 10), curly brackets {}

  • 4 A first C program

    55

    (marked by number 6) and parentheses () (marked by number 11). Square brackets [] are also used (as shown in some of the following chapters). These must be well understood and used correctly. In some cases, if they are not cor-rectly used, then some compilation errors will be displayed and the program can be corrected. In other cases, the compiler doesnt report an error (though these symbols are not placed according to what the flow of instructions must ex-ecute), but the program will not generate correct results.

    Comments in the C programming language Comments can also be included in a C program. These are sequences of text written in natural language, used by the programmer to mark some sections of the program or to give some explanations, so that the written source code is as explicit as possible. Comments are marked accordingly, are ignored by the compiler and are not executed when the program is run.

    The C programming language offers the possibility to use two types of com-ments:

    single line comment is marked by two oblique lines (slashes) // that must be placed at the beginning of the line;

    multi line comment begins with /* and ends with */. Several comments are inserted in the program that was previously presented, in order to illustrate how to use them. Thus, the program 4.2.2 resulted.

    Program 4.2.2 #include //standard input/output library void main(void){

    /*The following function is used to display a message on the screen. It receives the text of the message as argument.*/ printf("This is a first C program.");

    }

    4.3 Possible errors When a program is compiled and linked, errors may emerge if it is not devel-oped according to the rules of the C programming language. The error messages

  • Computer Programming The C Language

    56

    that are displayed are usually explicit enough and are very efficient in finding and removing the errors. Some of the most common errors are hereby pre-sented.

    Function 'f_name' should have a prototype. In this case the compiler doesnt recognize the function f_name(). There are several causes for this problem. If the function is part of a library, then probably that library wasnt specified in a preprocessor #include directive. If the function is a user defined one, then it is possible that the function has not been defined yet (a function must be defined before it can be used). Finally, if none of these cases is true (this means that the library is specified or the function is defined), then the cause could be a misspelling of the functions name.

    Statement missing ;. This error message is generated if the semicolon separator is missing. Usually the message is associated to the line that follows the line without semicolon because the compiler is not able to separate them.

    Compound statement missing }. If this error message is displayed, then a closing curly bracket (that marks the end of an instructions block) is missing.

    Unexpected }. The error message is because of an extra closing curly bracket.

    Undefined symbol 'x'. In this case, a variable (x), that has not been declared yet, is being used. As stated in the chapter about data and data types, any variable must be declared before it can be used. The type of that variable must be specified at the beginning of the program or at the beginning of the function.

    Undefined symbol _main in module c0.asm. This error is gener-ated in the linking phase, not in the compiling one. The reason is that the pro-gram doesnt have a main() function; it was either omitted or misspelled. A C program must have this function in order to be executed.

    4.4 Questions and exercises A. Find the error.

    1. void main(void){ float x,a=2,b=-4;

  • 4 A first C program

    57

    x=-b/a }

    2. void main(void) //this function increments the age int age=18; age++; }

    3. void main(void){ /*this function gives initial values to the coefficients of the first degree equation and calculates the value of the unknown x float x,a=2,b=-4; x=-b/a; }

    4. void main(void){ float x=3,y=4,z=5; surface=(x*y)/2; }

    B. Considering the following programs, specify the value of the expressions that are calculated.

    5. void main(void){ int a, b; float E1, E2; a=7; b=2; E1=a/b; E2=(float)a/b; }

    6. void main(void){ int a, b, E; a=7; b=3; E=a++ + ++b; }

    7. void main(void){ int a, b, E; a=7; b=3; E=a>b; }

  • Computer Programming The C Language

    58

    C. Choose the correct answer (one only). 8. In order to translate a C source file into a machine-code file should be

    used:

    a) a dictionary; b) a compiler; c) a copier; d) a linguist; e) an engineer.

    9. The link editor creates a: a) source file; b) object file; c) executable file; d) remunerable file; e) all answers are wrong.

    10. Which function must be present in any C program?

    a) include; b) void(); c) main(); d) the answers a, b and c are correct; e) all answers are wrong.

    11. If a function does not return anything, what will be written in front of the name of that function?

    a) return; b) void; c) integer; d) main; e) nothing. 12. In the C programming language the instructions can be grouped in a

    block using:

    a) ( and ); b) [ and ]; c) { and }; d) < and >; e) begin and end.

    13. Which of the following signs can be used to insert a comment in a C program?

    a) //; b) #; c) ||; d) &; e)

  • Chapter 5 Library functions

    The C programming language is a very simple language. It only has few in-structions that can be used to solve different problems. But these instructions are not always enough. For instance, the C programming language doesnt provide any method to read information from the keyboard or from a file, to display them on the screen or to write them in a file, to process strings, to work with mathematical functions and so on. For this reason, all C compilers also include a standard library of functions that implement the most frequently used tasks. This library contains several header files that gather certain categories of functions. The programmer can use (or can call) any library function; however, he is forced to specify, at the beginning of the program, in a #include direc-tive, the name of the header file which contains the function that is used in the program.

    In the following paragraphs some of the most frequently used library functions are described [BH92], [SL12]. These are gathered in several categories, accord-ing to the domain they are applied in.

    5.1 Input/output functions This paragraph presents functions that are used to read information from the keyboard and to display them on the screen. The values that are read or written can be characters, strings or numbers of any type. The description begins with the output functions (used to print something on the screen: putchar, puts, printf) and continues with the input functions (used to read something from the keyboard: getchar, gets, scanf).

    5.1.1 int putchar(int char); This function displays on the screen the character received as argument. If the function is performed successfully, it returns the character that was printed; otherwise, the constant EOF (end-of-file) is returned. The header file that con-tains this function is stdio.h.

  • Computer Programming The C Language

    60

    Program 5.1.1 displays on the screen the character A. It can be observed that the header file required for the function putchar() was specified at the begin-ning of the program.

    Program 5.1.1 #include void main(void){ putchar('A');

    } A second example (program 5.1.2) sends a variable of type char as argument to the function putchar(). This variable is declared, receives an initial value and then it is printed on the screen.

    Program 5.1.2 #include void main(void){ char var; var='A'; putchar(var);

    } In order to display a character on the screen, the function int putch(int c) from the conio.h header file can also be used. If succeeds, the function returns the character that was displayed; otherwise it returns EOF. The program example 5.1.3 uses this function to print the character A.

    Program 5.1.3 #include void main(void){ putch('A');

    }

    5.1.2 int puts(const char *s); The call of this function prints on the screen the string s received as argument and sets the position of the cursor to the next line. If succeeds, a non-negative value is returned; on error, the function returns the value EOF. This function is part of the stdio.h header file.

  • 5 Library Functions

    61

    In program 5.1.4 the function puts()receives as argument directly the string that must be displayed. It is also possible to send a string variable that was previously declared, as argument to the function.

    Programul 5.1.4 #include void main(void){ puts("This is a programming course.");

    }

    5.1.3 int printf(const char* format [, argument, ...]); The function is used when formatted data has to be printed on the screen. The header file that must be included in the program is stdio.h. If succeeds, this function returns the number of printed characters; on error, it returns a negative value.

    In a very simple way, this function can be used to print text on screen; in this case, the list of arguments [, argument, ...] is missing and the string format contains only the text that has to be written. Program 5.1.5 depicts this way of using function printf().

    Program 5.1.5 #include void main(void){ printf("The C programming language is useful.");

    } Nevertheless, function printf()proves its qualities when it is used to print formatted values on the screen. This function accepts a set of arguments (va-riables or constants); a formatting specified through a string is applied to these arguments. The formatted arguments are then displayed on the screen.

    The string format may contain: a simple text, printed as it is; the special character % followed by a format descriptor that, in turn, may

    contain:

  • Computer Programming The C Language

    62

    o the minus sign (-) which sets that the printed element is to be aligned to the left (the default alignment is to the right);

    o a number that specifies the minimum length of the field where the element is printed;

    o a dot (.) which separates the fields length by the precision used for the displayed element;

    o a number that specifies the precision (the number of decimals that will be displayed);

    o the conversion type character a character that indicates the type of the printed argument; some of the most frequently used con-version type characters are:

    c character; s string; d, i signed decimal integer; u unsigned decimal integer; f floating point number (float, double).

    o for instance: %c prints a character, %d prints an integer number, %5.2f prints a real number with at least 5 characters, two of these characters being reserved to the decimal part, %-15s prints, using at least 15 characters, a left aligned string.

    the special sign \ followed by: o a character that specifies the place of the next printing:

    \b moves the cursor (the point where the printing be-gins) back with one character, deleting that character;

    \n the next printing will be done on a new line; \t moves the cursor with a horizontal tab to the right.

    o a character that cannot be printed in any other way: \\ prints backslash (\); \ prints apostrophe; \" prints quotation marks.

  • 5 Library Functions

    63

    The program from the example 5.1.6 calls function printf() in order to print the value of the variable weight, which was previously declared and received an initial value. Once the program is run, the text The suitcase is 17 kg will be displayed on the screen.