0% found this document useful (0 votes)
30 views

Chapter Three

Uploaded by

n64157257
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Chapter Three

Uploaded by

n64157257
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CHAPTER THREE: Introduction to C Programming

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

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.

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

3.4 Compiling a C Program


A C program is first written in the form of a number of text files using a screen editor. This form of the
program is called the source program. It is not possible to execute this file directly. The completed source
file is passed to a compiler a program which generates a new file containing a machine code translation of
the source text. The compiler translates the source code into machine code, and the compiled code is
called the object code. The object code may require an additional stage where it is linked with other
object code that readies the program for execution. The machine code created by the linker is called the
executable code or executable program. Instructions in the program are finally executed when the
executable program is executed (run). During the stages of compilation, linking, and running, error
messages may occur that require the programmer to make corrections to the program source (debugging).
The cycle of modifying the source code, compiling, linking, and running continues until the program is
complete and free of errors.

A compiler usually operates in two or more phases (and each phase may have stages within it).
A two-phase compiler works in the following way:
Phase 1 scans a source program, perhaps generating an intermediate code (quadruples or pcode) which
helps to simplify the grammar of the language for subsequent processing. It then converts the intermediate
code into a file of object code (though this is usually not executable yet). A separate object file is built for
each separate source file. In the GNU C compiler, these two stages are run with the command gcc -c; the
output is one or more .o files.

Phase 2 is a Linker. This program appends standard library code to the object file so that the code is
complete and can "stand alone". A C compiler linker suffers the slightly arduous task of linking together
all the functions in the C program. Even at this stage, the compiler can fail, if it finds that it has a
reference to a function which does not exist. With the GNU C compiler this stage is activated by the
command gcc -o or ld.

3.5. C Program File naming convention


The compiler uses a special convention for the file names, so that we do not confuse their contents. The
name of a source program (the code which you write) is filename.c. The compiler generates a file of
object code from this called filename.obj. The final program, when linked to libraries is called
filename.exe

The endings `dot something' (called file extensions) identify the contents of files for the compiler. The
dotted endings mean that the compiler can generate an executable file with the same name as the original
source - just a different ending. The object file is only working files and should be deleted by the compiler
at the end of compilation. The .c suffix is to tell the compiler that the file contains a C source program and
similarly the other letters indicate non-source files in a convenient way.

Source code: Filename.c


Object code: Filename.obj
Executable code: Filename.exe
The command filename <enter> will execute the program and give results.
Myprog.c myprog.obj myprog.exe

Written in C Written in Written in


machine Machine
language language

Via compiler via linker


Other code from library
Written in machine language

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

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.

Function: a sub-program that may


include one or more statements
designed to perform a specific task.

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 Header
It is the first line of a function, example; int sum(int x, int y). It has three main parts
 The name of the function i.e. sum
 The parameters of the function enclosed in paranthesis
 Return value type i.e. int

Function Body
What ever is written with in { } in the above example is the body of the function.

3.9 C Program format


A C program includes the following sections
1. Documentation Section
2. Linker Section
3. Definition Section
4. Global Declaration Section
5. Main() Function Section
{
Declaration section
Executable Section
}
6. Sub-program Section
Function 1
Function 2
Function3 etc is User defined functions

1.9.1. Documentation Section


This section consists of a set of comments lines giving the name of the program, the author and other
details which the programmer would like to use later. Comments starts with /* and ends with */ and
enhances readability and understandability. Comment lines are not executable statements ie. executed and
are ignored by the compiler. Comments can be inserted wherever there is a blank a space but cannot be
nested (having a comment within a comment)
example /* …………………./* ……………..*/ ……………….*/
1.9.2. Linker Section
This section provides instructions to the compiler to link functions from the system library. C program
have predefined functions stored in the C library. Library functions are grouped category-wise and stored
in different file known as header files. To be able to access the library files it is necessary to tell the
compiler about the files to be accessed.
Instruction Format: #include<file_name>
Example #include<stdio.h> a standard I/O header file containing standard input and output functions

1.9.3. Definition Section


This section allows the definition of all symbolic constants. Statements begin with # sign and do not end
with a ; because the statements are compiler directive statements
Example #define PRINCIPLE 10000

Symbolic constants are usually written in upper case to distinguish them from lower case variables.
Values defined here remain constant throughout the program.

1.9.4. Declaration Section


Section used to declare global variables. The section is also used to declare user defined functions.

3.9.5 main() Function Section


The main() function is a special function used by C system to tell the computer where the program starts.
Every program must have exactly one main function. The main function is the point by where all C
programs start their execution, independently of its location within the source code. It does not matter
whether there are other functions with other names defined before or after it - the instructions contained
within this function's definition will always be the first ones to be executed in any C program. For that
same reason, it is essential that all C programs have a main function. The main function section has the
following sections
 Declaration part: where all variables used in the executable section are declared.
 Executable part: consist of the statements to be executed.
{
Declaration part
Executable part
}
There must be a least one statement in the executable part. The two part must be included between the
opening { and the closing }. Program execution begins at the opening { and closes at the closing }, which
signifies the logical end of the program. All the statements between the { and } forms the function body
and are the instructions to perform the given task. All statements in the Declaration and Executable parts
must end with a semicolon (;)
Formats of main()
 main()
 int main()
 void main()
 main(void)
 int main(void)
( ) or word void means the function has no arguments or parameter and thus does not return any
information to the operating system. int means the function return an integer value to the operating
system

3.9.6 Sub-program section


Contains all user defined functions that are called in the main function
main() /* Main program */
{
do_nothing(); /* Function call */
}
/******************************************************/
do_nothing() /* Function called */
{
}
Example
// Program using function -- comment
#include <stdio.h>
#include<conio.h>
int mul (int a, int b);

int main() /* function body*/


{
int a, b, c;
a = 5;
b = 10;
c = mul (a,b); /* function call*/

printf("Multiplication of %d and %d is %d", a,b,c); /* request to print the answer on the Screen*/
getch(); /*command used to pause the results on the screen*/
}
/* mul() /* ……….. Sub-program mul */
int mul(int x,int y)
{
int p;
p = x*y;
return (p);
}

NB. the values of a & b are passed to x & y respectively when the sub-program is called.

Note the followings


 C is a case sensitive programming language. It means in C printf and Printf will have different
meanings.
 C has a free-form line structure. End of each C statement must be marked with a semicolon.
 Multiple statements can be done on the same line.
 White Spaces (ie tab space and space bar) are ignored.
 Statements can continue over multiple lines.
 Printf is a predefined C function for printing out put
 Everything between the starting and ending quotation marks “ ” to be printed.
 To print on separate line; Use the command \n
 int = integer data type
 float = floating point number data type
 %d = formatting command that prints the output as a decimal integer
 %5.2f” = formatting command that prints the output as a floating point integer with five places in all
and two places to the right of the decimal point.
Program Example 3.1 Program Example 3.2
main() /* program for addition */
{ #include<stdio.h>
printf (“This is my \n”); #include<conio.h>
printf(“computer book”); main()
getch(); { int number;
} float amount;
OR number = 100;
main(() amount = 30.75 + 75.35;
{ printf("%d\n", number);
print(“This is \n my computer book”); printf("%5.2f", amount);
getch(); getch(); /* pause the results on the screen */
} }

Program Example 3.3 Program Example 3.4


/* program to print Hello */ /* program to calculate the Interest rate */
#include <stdio.h> #include <stdio.h>
#include<conio.h> #include<conio.h>
#define PERIOD 10
int main() #define PRINCIPAL 5000.00
{ int main()
printf("hello, world\n"); {
getch(); int year;
} float amount, value, inrate;
amount = PRINCIPAL;
inrate = 0.11;
year = 0;
while(year <= PERIOD)
{printf("%2d %8.2f\n", year, amount);
value = amount + inrate * amount;
year = year + 1;
amount = value;
}
getch();
}

3.10. Breaking out early


Return statement
The program can simply call return(value) anywhere in the function and control will jump out of any
number of loops or whatever and pass the value back to the calling statement without having to finish the
function up to the closing brace }.

The exit() function


The function called exit() can be used to terminate a program at any point, no matter how many levels of
function calls have been made. This is called with a return code, like this:
#define CODE 0
exit (CODE);
This function also calls a number of other functions which perform tidy-up duties such as closing open
files etc.

Chapter Review Questions


1. How is a library file incorporated into a C program?
2. Name the most common library file in C.
3. Is it possible to define new functions with the same names as standard library functions?
4. What is another name for a library file?
5. Describe the structure of C Program
6. Distinguish between
a) main() and main(void)
b) int main() and void main()
7. Find errors if any in the following
#include <stdio.h>
Void main()
{
Print (“Hello C);
}

You might also like