programming methodology, Lecture notes of Programming Languages

introduction to c programming language

Typology: Lecture notes

2019/2020

Uploaded on 01/29/2020

peter-karanja
peter-karanja 🇰🇪

2 documents

1 / 48

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Programming Methodology Notes Page 1
PROGRAMMING METHODOLOGY
CHAPTER ONE
Overview of Computer Programming Methodology
1.1 What is Computer Programming Methodology
A Methodology is a system of methods with its orderly and integrated collection of various methods, tools and
notations. A computer program is a series of instructions written in the language of the computer which
specifies processing operations that the computer is to carry out on data. It is a coded list of instructions that
tell" a computer how to perform a set of calculations or operations.
Programming is the process of producing a computer program. Programming involves the following activities;
writing a program, compiling the program, running the program, debugging the programs. The whole process
is repeated until the program is finished.
1.2. Problem Solving with Computer;
There are a number of concepts of relevance to problem solving using computers. Two particular concepts
includes computability and complexity. A problem is said to be computable if it can in principle be performed
by a machine. Some mathematical functions are not computable. The complexity of a problem is measured in
terms of resources required, time and storage
The steps involved in solving a problem using a computer program includes;
Step 1. Define the Problem: State in the clearest possible terms the problem you wish to solve. It is impossible
to write a computer program to solve a problem that has been ambiguously or imprecisely stated.
Step 2. Devise an Algorithm: An algorithm is a step-by-step procedure for solving the problem. Each of the
steps must be a simple operation which the computer is capable of doing. A universally-used
representation of an algorithm is a flowchart or flow diagram, in which boxes representing procedural
steps are connected by arrows indicating the proper sequence of the steps. In many problems you will
need to define a mathematical procedure, expressed in strictly numerical terms since the use of
computers to do higher level analytic processes such as solving algebraic equations or doing integrals
in a non-numerical fashion is relatively limited. The Algorithm can also be represented using Pseudo-
code
Step 3. Code the Program: The steps in an algorithm, translated into a series of instructions to the computer,
comprise the computer program. There are many languages in which computer programs can be
coded, each with its own syntax, vocabulary, and special features.
Step 4. Debug the Program: Most programs of any length don't work properly the first time they are run and
must therefore be debugged." Often, during the debugging phase, errors and ambiguities in the
Chapter Objectives
By the end of this chapter the learner should be able to;
Describe the steps involved in solving a problem using a computer.
Be able to represent the Algorithm to solve a problem in flow-charts and Pseudo-code.
Be able to describe and differentiate the types of programming methods.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30

Partial preview of the text

Download programming methodology and more Lecture notes Programming Languages in PDF only on Docsity!

PROGRAMMING METHODOLOGY

CHAPTER ONE

Overview of Computer Programming Methodology

1.1 What is Computer Programming Methodology A Methodology is a system of methods with its orderly and integrated collection of various methods, tools and notations. A computer program is a series of instructions written in the language of the computer which specifies processing operations that the computer is to carry out on data. It is a coded list of instructions that tell" a computer how to perform a set of calculations or operations.

Programming is the process of producing a computer program. Programming involves the following activities; writing a program, compiling the program, running the program, debugging the programs. The whole process is repeated until the program is finished.

1.2. Problem Solving with Computer; There are a number of concepts of relevance to problem solving using computers. Two particular concepts includes computability and complexity. A problem is said to be computable if it can in principle be performed by a machine. Some mathematical functions are not computable. The complexity of a problem is measured in terms of resources required, time and storage

The steps involved in solving a problem using a computer program includes; Step 1. Define the Problem: State in the clearest possible terms the problem you wish to solve. It is impossible to write a computer program to solve a problem that has been ambiguously or imprecisely stated. Step 2. Devise an Algorithm: An algorithm is a step-by-step procedure for solving the problem. Each of the steps must be a simple operation which the computer is capable of doing. A universally-used representation of an algorithm is a flowchart or flow diagram, in which boxes representing procedural steps are connected by arrows indicating the proper sequence of the steps. In many problems you will need to define a mathematical procedure, expressed in strictly numerical terms since the use of computers to do higher level analytic processes such as solving algebraic equations or doing integrals in a non-numerical fashion is relatively limited. The Algorithm can also be represented using Pseudo- code Step 3. Code the Program: The steps in an algorithm, translated into a series of instructions to the computer, comprise the computer program. There are many languages in which computer programs can be coded, each with its own syntax, vocabulary, and special features. Step 4. Debug the Program: Most programs of any length don't work properly the first time they are run and must therefore be debugged." Often, during the debugging phase, errors and ambiguities in the

Chapter Objectives By the end of this chapter the learner should be able to; Describe the steps involved in solving a problem using a computer. Be able to represent the Algorithm to solve a problem in flow-charts and Pseudo-code. Be able to describe and differentiate the types of programming methods.

original statement of the problem reveal themselves, calling for basic revisions in the solution algorithm. Step 5. Run the Program: After the program has been fully debugged you run it, possibly using many sets of input data. This step may take anywhere from a few seconds to many hours depending on the complexity of the problem and the speed of the computer. Step 6. Analyze the Results: Often the output from a computer program requires considerable further analysis. In some cases, even though the program worked perfectly, you may find that you solved the “wrong" problem. There is an acronym well known to computer users: GIGO, which stands for “garbage in, garbage out."

1.2.1. Problem Algorithm An Algorithm is a logical sequence of discrete steps that describe a complete solution to a given problem in a finite amount of time independently of the software or hardware of the computer. It is the set of rules that define how a particular problem can be solved in finite number of steps. Algorithms are very essential as they instructs the computer what specific steps it needs to perform to carry out a particular task or solve a problem. Every algorithm should have the following five characteristics: Input, Output, Definiteness, Effectiveness and Termination. An Algorithm has the following properties; It must be precise and unambiguous It must give the correct solution in all cases It must eventually end.

Efficiency and Analysis of the Algorithm The efficiency of an Algorithm means how fast it can produce the correct results for the given problem. The Algorithm efficiency depends upon its time complexity and space complexity. The complexity of an algorithm is a function that provides the running time and space for data, depending on the size provided by us. Two important factors for judging the complexity of an Algorithm are; space complexity which refers to the amount of memory required by the algorithm for it execution and generation of the final output and time Complexity which refers to the amount of computer time required by an algorithm for its execution, which includes both the compile time and run time. The compile time of an algorithm does not depend on the instance characteristics of the algorithm. The run time of an algorithm is estimated by determining the number of various operation, such as addition, subtraction, multiplication, division, load and store executed by it.

The analysis of an algorithm determines the amount of resources, such as time and space required by it for its execution. Generally, the algorithms are formulated to work with the inputs or arbitrary length. Algorithm analysis provides theoretical estimates required by an algorithm to solve a problem. The steps of an Algorithm, they can be presented using Flow charts and pseudo-codes.

1.3. Flow Charts A flow chart is a traditional means of showing in diagrammatic form, the sequence of steps to be undertaken in solving a problem. Flowcharts or flow diagrams are important tools in writing a computer program. A flowchart allows you to plan the sequence of steps in a program before writing it. The flowchart serves as a visual representation which many programmers find indispensable in planning any program of at least moderate complexity.

1.3.1. Elements of a Flowchart. A flowchart consists of a set of boxes, the shapes of which indicate specific operations. The separate boxes are connected with arrows to show the sequences in which the various operations are performed. We use these standard symbols:

Limitations of program flowcharts

  • Not easily translated into programming language.

1.4. Pseudo code An alternative method of representing an Algorithm to the flowcharts. Pseudo code is halfway between English and programming language and is based upon a few simple grammatical construction which avoid the ambiguities of English but which can be easily converted into computer programming language. Pseudo code is an informal high-level description of a computer programming algorithm, which omits details that are not essential for human understanding of the algorithm, is easier for humans to understand than conventional programming language code, is compact and environment-independent description of the key principles of an algorithm and resembles skeleton programs including dummy code and can be compiled without errors.

Pseudo code assumes that programming procedures no matter how complex may be reduced to a combination of controlled sequences, selection, or repetition of basic operations. This gives rise to the control structures found in pseudo-code.

1.5. Program Control Structures Control Structure Pseudo code Flow Chart Sequence: In the absence of selection, or repetition, program statements are executed in the sequence in which the appear in the program

1 st^ Instruction

2 nd^ Instruction

3 rd^ Instruction

Selection Part of decision making and allows alternative actions to be taken according to the conditions that exist at particular stages in program execution

IF

condition THEN actions ELSE actions ENDIF Or

CASE a). Actions b). Actions c). Actions d). Actions ENDCASE

Repetition also called “looping” There are many programming problems in which the same sequence of statements needs to be performed again and again for a definite or indefinite number of times

WHILE

condition DO Actions ENDWHILE

No Yes

a b c

No

REPEAT

actions UNTIL condition

1.6. Programming Methods

1.6.1 Top-down and Bottom-up methodology A top-down approach (is also known as step-wise design) is essentially the breaking down of a system to gain insight into its compositional sub-systems. In a top-down approach an overview of the system is formulated, specifying but not detailing any first-level subsystems. Each subsystem is then refined in yet greater detail, sometimes in many additional subsystem levels, until the entire specification is reduced to base elements. A top-down model is often specified with the assistance of "black boxes", these make it easier to manipulate. However, black boxes may fail to elucidate elementary mechanisms or be detailed enough to realistically validate the model.

Top - down-design starts with a description of the overall system and usually consists of a hierarchical structure which contains more detailed descriptions of the system at each lower level. The lower level design details continue until further subdivision is no longer possible, i.e., until the system is described in terms of its "atomic" parts. This method involves a hierarchical or tree-like structure for a system as illustrated by the following diagram:

At the top level, we have that part of the system which deals with the overall system; a kind of system overview or main top-level module.

Top down programming method process

  1. Define exactly what data the program will get and what it has to do with them.
  2. If the task is simple enough, write the program code.
  3. Otherwise, split the task into smaller parts and define exactly the duty of each part and interface to the rest of the program.
  4. Repeat the steps 1–4 separately for each subtask.

Advantages of the Top-Down Design Method

  • It is easier to comprehend the solution of a smaller and less complicated problem than to grasp the solution of a large and complex problem. Separating the low level work from the higher level abstractions leads to a modular design. Modular design means development can be self contained. Much less time consuming (each programmer is only involved in a part of the big project).

No

Yes

developed especially for this purpose, though it is much derided as a toy language, and appears to have never been used in commercial development. It appears that existing languages such as COBOL and FORTRAN were changed to accommodate Dijkstra‟s structures, or that programming included these structures through more indirect methods.

Later generation languages such as C are fully-fledged structured programming languages; these are from the third generation and procedural, in that they are both written and executed step-by-step. C, in its turn, has formed the foundation for the object-oriented language C++.

The three structures allowed in structured programming are sequence , selection , and iteration. Structures are also thought of in terms of substitution and combination, i.e. structures can be substituted or combined with other structures as long as the result equals a sequential structure. Structured programming also pays attention to design and testing with emphasis on a top-down approach. The top-down approach uses modularity as a means to ensure that the program is both legible and manageable, and also that these modules can be tested as they are developed. This is beneficial as it ensures that all modules should be tested and that bugs can be found in the modules that have most recently been added or altered.

Structured programming also places emphasis on program documentation, which can be in the form of a chart or the structured coding/listing. This documentation allows for subsequent updating of modules, making these modules easier to locate in the program. Modularity also ensures greater opportunity for re-use of modules during development.

1.7. Programming Aims Good programming principles and practice aim at producing a program with the following characteristics;

  • Reliability: the program can be depended upon always to do what it is supposed to do
  • Maintainability: the program will be easy to change or modify when the need arises
  • Portability: the program will be transferable to a different computer with a minimum modification.
  • Readability: the program will be easy for a programmer to read and understand.
  • Performance: the program causes the tasks to be done quickly and efficiently.
  • Storage saving: the program is not allowed to be unnecessarily long

1.8. Programming Paradigms A programming paradigm is a pattern of problem solving thought that underlies a particular genre of programs and languages. Four distinct and fundamental programming paradigms have evolved over the last three decades;

  • Imperative programming;
  • Object-oriented programming
  • Functional programming
  • Logic Programming;

1.8.1. Imperative programming; The oldest and the most well-developed, it emerged with the first computers in the 1940s and its elements directly mirror the architectural characteristics of modern computers as well. The program and its variables are stored together and the program contains a series of commands that perform calculations, assign values to variables, retrieve input, produce out, or redirect control elsewhere in the series.

Procedural abstraction is an essential building block for imperative programming as are assignments, loops, sequences, conditional statements and exception handling. Imperative languages also support variable

declaration and expressions. The predominant imperative programming languages include Cobol, Fortran, C Ada and Perl.

Commands are normally executed in the order they appear in the memory, while conditional and unconditional branching statements can interrupt this normal flow of execution. Originally the commands included assignment statements, conditional statements and branching statements. The assignments statements provided the ability to dynamically update the value stored in the memory location, while conditional and branching statements could be combined to allow a set of statements to be either skipped or repeatedly executed. The main features of Imperative programming includes;

  • Control structures;
  • Input/output
  • Error and exception handling
  • Procedural abstraction
  • Expressions and assignments
  • Library support for data structures

1.8.2. Object-oriented (OO) programming: Provides a model in which the program is a collection of objects that interact with each other by passing messages that transform their state. The message passing allows the data objects to become active rather than passive. Object classification, inheritance and message passing are fundamental building blocks for OO programming. Major languages includes, C++, Java and C#.

1.8.3 Functional Programming: Emerged in the early 1960s and its creation was motivated by the needs of researchers in artificial intelligence and its sub-fields- symbolic computation, theorem proving, rule-based systems and natural language processing. Models a computational problem as a collection of mathematical functions, each with an input (domain) and a result (range) spaces.

1.8.4. Logic Programming Logic (declarative) programming allows a program to model a problem by declaring what outcome the program should accomplish, rather than how it should be accomplished. Sometimes called rule-based languages, since the program‟s declarations look more like a set of rules, or constraints on the problem, rather than a sequence of commands to be carried out.

Chapter Review Questions

  1. Describe the processing of solving a problem using computers
  2. Define a problem Algorithm
  3. What are the advantages and disadvantages of using flow-charts to represent problem algorithm
  4. What are the advantages and disadvantages of representing a problem algorithm using pseudo-codes.
  5. A School is interested in computerizing their students grading system which is as follows; Marks Grade 80 - 100 A 60 - 79 B 50 - 59 C 40 - 49 D 0 - 39 E

a) Draw a flow chart to represent the solution.

CHAPTER TWO

Programming Languages

2.1. What is a Programming Language There are many definitions of what constitutes a programming language, and none of these is the „correct‟ answer. What might have defined a programming language in the 19th century would not necessarily be detailed enough for a modern definition. Programming languages are needed to allow human beings and computers to talk to each other. Computers, as yet, are unable to understand our everyday language or, in fact, the way we talk about the world. Computers understand logic expressed mathematically through what is known as machine code. Computer language consists of 1s and 0s or the binary system , which the majority of human beings would find very difficult to communicate in. Computer languages enable humans to write in a form that is more compatible with a human system of communication. This is then translated into a form that the computer can understand. Here are some different ideas on what constitutes a programming language. A programming language has been defined as a tool to help the programmer. A way of writing that can be read by both a human being and a machine. A sequence of instructions for the machine to carry out. A way for a human being to communicate with a machine that is unable to understand natural language. A computer language offers a means of writing algorithms that can be understood by both human being and machine. Machines are unable to understand natural language, so a human being uses algorithms that are translated into machine code by the programming language. Machine code is difficult for humans to use, so a language „translates‟ human readable language into machine readable form. A computer program offers humans a standard way of expressing algorithms to solve particular problems. As languages offer a convention it allows other humans to read the program, and change it if they need to.

2.2. Types of Programming Languages There are three levels of programming languages; Machine language (low level language) Assembly (or symbolic) language Procedure-oriented language (high level language)

Chapter Objectives By the end of this chapter the learner should be able to Define a programming language Describe the types of programming languages Differentiate and explain advantages and disadvantages of the various types of programming languages Describe the High level languages translation processes Describe the criteria for Programming language evaluation

2.2.1. Machine language The lowest-level programming language (except for computers that utilize programmable microcode) Machine languages are the only languages understood by computers. While easily understood by computers, machine languages are almost impossible for humans to use because they consist entirely of numbers. It is a programming language in which the instructions are in a form that allows the computer to perform them immediately, without any further translation being required. Instructions are in the form of a Binary code also called machine code and are called machine instructions. Commonly referred to as the First Generation language

2.2.2. Assembly Language Introduced in 1950s, reduced programming complexity and provided some standardization to build and applications. Also referred to second generation language. The 1 and 0 in machine language are replaced by with abbreviations or mnemonic code. It consists of a series of instructions and mnemonics that correspond to a stream of executable instructions. It is converted into machine code with the help of an assembler. Common features includes; Mnemonic code; used in place of the operation code part of the instruction eg SUB for substract, which are fairly easy to remember Symbolic Addresses which are used in place of actual machine addresses. A programmer can choose a symbol and use it consistently to refer to one particular item of data. Example FNO to represent First No. The symbolically written program has to be translated into machine language before being used operationally. A 1 to 1 translation to machine language, ie one symbolic instruction produces one machine instruction/code.

Advantages of Assembly language over machine language It is easy to locate and identify syntax errors, thus it is easy to debug it. It is easier to develop a computer application using assembly language in comparison with machine language Assembly language operates very efficiently.

2.2.3. High level language A Machine independent and a Problem oriented (POL) programming language. High level language is portable across different machine types (architectures); The machine independence of the high level languages means that in principle it should be possible to make the same high-level language run on different machines. It reflects the type of problem solved rather than the features of the machine.

High level languages are more abstract, easier to use and more portable across platforms as compared to low- level programming languages. A programmer uses variables, arrays or Boolean expressions to develop the logic to solve a problem. Source programs are written in statements akin to English. A high level language code is executed by translating it into the corresponding machine language code with the help of a compiler or interpreter. High level languages can be classified into the following categories; Procedure-oriented languages (third generation) Problem-oriented languages (fourth generation) Natural languages (fifth generation).

Procedure languages. High-level languages designed to solve general-purpose problems, example BASIC, COBOL, FORTRAN, C, C++ and JAVA. They are designed to express the logic and procedure of a problem. Though the syntax of the languages may be different, they use English-like commands that are easy to follow. They are portable.

Translates the source program code into machine code Includes linkages for closed sub-routine Allocates areas of main storage Produces the object program. Produces a printed copy (listing) of the source code and object code Produces a list of errors found during compilation.

2.3.2. Interpreter: The interpreter is a translation program that converts each high-level language statement into the corresponding machine code. The translation process is carried out just before the program statement is executed. Instead of the entire program, one program statement at a time is translated and executed immediately. When using an interpreter, the source code translated every time the program is executed

The commonly interpreted languages include BASIC and PERL. Though interpreters are easier to create as compared to compilers, the compiled languages can be executed more efficiently and are faster. Interpreters are appropriate in; Handling user commands in an interactive system Debugging programs as they run (removing program faults). Handling software produced for or by a different computer.

2.4. Computer Program Compilation Process A computer program compilation process involves the following five stages;

  1. Lexical analysis: the source program is transformed into tokens. During the transformation all whitespaces and comments are discarded. All character sequences that do not form valid tokens are discarded and an error message is generated.
  2. Syntactical analysis: analysis to ensure the program syntax is appropriate to the language. Failure results in an error message been generated.
  3. Type / Semantic checking: responsible for ensuring that the compile-time semantic rules of the language are enforced. An error message is generated if the semantic rules are violated
  4. Code optimization: improves the intermediate code based on the target machine architecture
  5. Code generation: target machine code is generated.

The first three stages are concerned with finding and reporting errors to the programmer, while the last two are concerned with generating efficient machine code to run on the targeted computer.

Source Machine Code Code

2.5. Evaluating Languages Programming languages can be evaluated from a number of viewpoints, depending on either the programmer, the environment in which the programmer works or the standards of the organisation. When developing software, a programmer should consider which language is most suitable to the task, rather than relying on a language with which they are familiar. You wouldn‟t want to use a spreadsheet to develop a database. All the features of the language need to be considered rather than just one particular feature. A wrong choice can mean that the software has to be re-written, which can be very frustrating and time consuming.

Lexical Analysis

Syntaticical Analysis

Type / Semantic Analysis

Code Optimization

Code Generation

There are a number of different ways that the programmer can think about the design of the system, from the top-down of structured programming to object oriented design issues. Some languages are geared towards one particular style of design, whilst others incorporate many types. Each of these language paradigms enables the programmer to consider the problem from a different viewpoint. There are a few basic questions that can be asked to help when making these decisions:

  1. How readable is the language, to humans? If parts of the program are going to be read or altered separately from the entire program is might be worth considering how legible they are going to be. It is also useful to consider the length of names allowed in the language, for instance an early form of Fortran allowed for only 6 characters. This can lead to clumsy abbreviations that are difficult to read. Statements such as GO TO, FOR, WHILE and LOOP have increased the readability of programs, and lead to neater programs. These statements also affect the syntax or grammar.
  2. When it comes to writing the program, how easy is it to write the program in this particular language? A programming language that is easy to write in can make the process easier and faster. It may help to reduce mistakes. FOR loops and other types of statement allow the programmer to write much simpler code. This will save time and money, and also make the program smaller.
  3. How reliable is the language? Not all languages create robust programs, and some help the programmer to avoid making errors. A program that is not robust can cause errors, and code can „decay‟. Any language that helps the programmer to avoid mistakes will make it easier to use.
  4. How much would it cost to develop using a given language? Is the language expensive to use and to maintain? Programs may need to be updated or redeveloped, and an expensive language may make this prohibitive.
  5. How complicated is the syntax going to be? Syntax is an important consideration. Clarity and ease of understanding are important, as is a syntax that seems logical and sensible. Errors are very likely to occur where one area of syntax too closely resembles another, and the program may prove difficult to debug. Some theorists reason that if it is difficult to write a program to parse the language, then it follows that it will be problematical for the programmer to get it right.
  6. Does the language have standards? Languages that have standards for writing programs have greater readability; for instance Java has standards for naming, commenting and capitalization.

2.6. The Programming Language Generations The language generations span many decades, and begin with the development of machine code. Each generation adds new features and capabilities for the programmer to use. Languages are designed to create programs of a particular type, or to deal with particular problems. Modern languages have led to the development of completely different styles of programming involving the use of more human-like or natural language and re-usable pieces of code. The first generation of languages was machine language. Instructions and addresses were numerical. These programs were linked to the machine they were developed on. The second generation allowed symbolic instructions and addresses. The program was translated by an assembler. Languages of this generation include IBM, BAL, and VAX Macro. These languages were still dependent on the machine they were developed on. Third generation languages allowed the programmer to concentrate on the problem rather than the machine they were writing for. Other innovations included structured programming and database management systems. 3GL languages include FORTRAN, COBOL, Pascal, Ada, C, and BASIC. All 3GL languages are much easier for the human being to understand. 4GL languages (fourth generation). These are known as non-procedural, they concentrate on what you want to do rather than how you are going to do it. 4GL languages include SQL, Postscript, and relational database orientated languages.

CHAPTER THREE

Introduction to C Programming

3.1. What is C program C is an imperative (procedural) systems implementation language. C is called a high level, compiler language. The aim of any high level computer language is to provide an easy and natural way of giving a programme of instructions to a computer (a computer program). The language of the raw computer is a stream of numbers called machine code. As you might expect, the action which results from a single machine code instruction is very primitive and many thousands of them are required to make a program which does anything substantial.

C is one of a large number of high level languages which can be used for general purpose programming, that is, anything from writing small programs for personal amusement to writing complex applications. C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at Bell telephone Laboratories. It is unusual in several ways. Before C, high level languages were criticized by machine code programmers because they shielded the user from the working details of the computer, with their black box approach, to such an extent that the languages become inflexible: in other words, they did not allow programmers to use all the facilities which the machine has to offer. C, on the other hand, was designed to give access to any level of the machine down to raw machine code and because of this it is perhaps the most flexible of all high level languages.

The C language has been equipped with features that allow programs to be organized in an easy and logical way. This is vitally important for writing lengthy programs because complex problems are only manageable with a clear organization and program structure. C allows meaningful variable names and meaningful function names to be used in programs without any loss of efficiency and it gives a complete freedom of style; it has a set of very flexible loop constructions (for, while, do) and neat ways of making decisions. These provide an excellent basis for controlling the flow of programs.

Another unusual feature of C is the way it can express ideas concisely. The richness of a language shapes what it can talk about. C gives us the apparatus to build neat and compact programs. This sounds, first of all, either like a great bonus or something a bit suspect. Its conciseness can be a mixed blessing: the aim is to try to seek a balance between the often conflicting interests of readability of programs and their conciseness. Because this side of programming is so often presumed to be understood, we shall try to develop a style which finds the right balance.

Chapter Objectives By the end of this chapter the learner should be able to; Describe the characteristics of C programming language. Describe the process of developing and Executing a C program Describe the compilation process of a C program and C program file naming conventions. Differentiate between Syntax and Logical Errors Describe the structure / format of a C Program

C allows things which are disallowed in other languages: this is no defect, but a very powerful freedom which, when used with caution, opens up possibilities enormously. It does mean however that there are aspects of C which can run away with themselves unless some care is taken. The programmer carries an extra responsibility to write a careful and thoughtful program. The reward for this care is that fast, efficient programs can be produced.

C tries to make the best of a computer by linking as closely as possible to the local environment. It is no longer necessary to have to put up with hopelessly inadequate input/output facilities anymore (a legacy of the timesharing/mainframe computer era): one can use everything that a computer has to offer. Above all it is flexible. Clearly no language can guarantee intrinsically good programs: there is always a responsibility on the programmer, personally, to ensure that a program is neat, logical and well organized, but it can give a framework in which it is easy to do so.

The C compiler combines the capabilities of an assembly language with features of a high-level language thus making it suited for writing both system software and business packages. C program uses a variety of data types and operators thus making programs written in C to be efficient and fast. C is highly portable and is well suited for structured programming. C is basically a collection of functions that are supported by the C library and because new functions can be added to the C library, C has the ability to extend itself.

3.2. Characteristics of C We briefly list some of C's characteristics that define the language and also have lead to its popularity as a programming language. Small size Extensive use of function calls Loose typing -- unlike PASCAL Structured language Low level (BitWise) programming readily available Pointer implementation - extensive use of pointers for memory, array, structures and functions.

C has now become a widely used professional language for various reasons. It has high-level constructs. It can handle low-level activities. It produces efficient programs. It can be compiled on a variety of computers.

Its main drawback is that it has poor error detection which can make it off putting to the beginner. However diligence in this matter can pay off handsomely since having learned the rules of C we can break them. Not many languages allow this. This if done properly and carefully leads to the power of C programming.

3.3. Executing a C program The steps involved in executing a C program includes; Creating the program Compiling the program Linking the program with functions that are needed from the C library Executing the program

Myprog.c myprog.obj myprog.exe

Via compiler via linker

3.6. Errors Errors are mistakes which we the programmers make. There are different kinds of error:

3.6.1. Syntax Error Every language has got set of rules. If you make a mistake while using the language, then it is called syntax error.

Errors in the syntax, or word structure of a program are caught before you run it, at compilation time by the compiler program. They are listed all in one go, with the line number, in the text file, at which the error occurred and a message to say what was wrong. A program with syntax errors will cause a compiler program to stop trying to generate machine code and will not create an executable. However, a compiler will usually not stop at the first error it encounters but will attempt to continue checking the syntax of a program right to the last line before aborting, and it is common to submit a program for compilation only to receive a long and un-gratifying list of errors from the compiler.

As a rule, look for the first error, fix that, and then recompile. Of course, after you have become experienced, you will recognize when subsequent error messages are due to independent problems and when they are due to a cascade. But at the beginning, just look for and fix the first error.

Use of Upper and Lower Case One of the reasons why the compiler can fail to produce the executable file for a program is you have mistyped something, even through the careless use of upper and lower case characters. The C language is case dependent. Unlike languages such as Pascal and some versions of BASIC, the C compiler distinguishes between small letters and capital letters. This is a potential source of quite trivial errors which can be difficult to spot. If a letter is typed in the wrong case, the compiler will complain and it will not produce an executable program.

3.6.2. Logical or Intention Error Errors in goal or purpose (logical errors) occur when you write a program that works, but does not do what you intend it to do. You intend to send a letter to all drivers whose licenses will expire soon; instead, you send a letter to all drivers whose licenses will expire sometime. If the compilation of a program is successful, then a new file is created. This file will contain machine code which can be executed according to the rules of the computer's local operating system.

When a programmer wants to make alterations and corrections to a C program, these have to be made in the source text file itself using an editor; the program, or the salient parts, must then be recompiled.

Written in C Written in machine language

Written in Machine language

Other code from library Written in machine language

3.7. C Libraries In C, a library is a set of functions contained within a single "archive" file. The core of the C language is small and simple. Special functionality is provided in the form of libraries of ready-made functions. This is what makes C so portable. Libraries are files of ready-compiled code which we can merge with a C program at compilation time. Libraries provide frequently used functionality and, in practice, at least one library must be included in every program: the so-called C library, of standard functions.

Each library comes with a number of associated header files which make the functions easier to use. Header files contains the prototypes of the functions contained within the library that may be used by a program, and declarations of special data types and macro symbols used with these functions. It is up to every programmer to make sure that libraries are added at compilation time by typing an optional string to the compiler.

Including Library files in C Program The most commonly used header file is the standard input/output library which is called stdio.h. This belongs to a subset of the standard C library which deals with file handling and provides standard facilities for input to and output from a program. Examples of Libraries header files Stdio.h, (printf() function) maths.h (for mathematical functions) etc. conio.h ( for handling screen out puts such as pausing program execution getch() function) The format for including the header file is #include header.h

3.8. C Program Structure C program is can be divided into modules and functions. Modules: A module is a set of functions that perform related operations. A simple program consists of one file; i.e., one module. More complex programs are built of several modules. Modules have two parts: the public interface, which gives a user all the information necessary to use the module; and the private section, which actually does the work.

Functions; the basic building block in a C program is the function. In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. It must have a name and it is reusable ie it can be executed from as many different parts in a C Program as required. Information passed to the function is called arguments and is specified when the function is called. And the function either returns some value to the point it was called from or returns nothing.

Every C Program will have one or more functions and there is one mandatory function which is called main() function. This function is prefixed with keyword int which means this function returns an integer value when it exits. This integer value is returned using return statement.

Structure of a Function There are two main parts of the function. The function header and the function body. int sum(int x, int y) { int ans = 0; //holds the answer that will be returned ans = x + y; //calculate the sum return ans //return the answer }

Function: a sub-program that may include one or more statements designed to perform a specific task