Upload
dangnhu
View
216
Download
1
Embed Size (px)
Introduction to Programming
1 The Catholic University of Eastern Africa
P.o Box 62157-00200, Nairobi Kenya
© Edward Kioko 2013
Machakos University College
(A constituent College of Kenyatta University)
P.O Box 136-90100, Machakos Kenya Telephone: 044-21604 Email: [email protected] Website:
http://www.machakosuniversity.ac.ke
SCO102: introduction to programming
Prepared by:
Edward M Kioko
Email:[email protected]
Tel:+254 (0) 725 695 782
August, 2014
Purpose of the module
In this 3 month instructor-led course, student shall learn the
fundamental skills for programming languages. Learners will use a
high level language (C programming language) to solve scientific
problem. The module provides a basic an entry point for students in
the field of software engineering.
Learning Outcomes
By the end of the module, students will be able to:
Understand the basic principles in programming
Understand problem solving strategies
Understand the process of creation of a computer
program and the different approach
Use high level language to code, write, compile, link
and execute a program with emphasis on scientific
applications
Introduction to Programming
2 The Catholic University of Eastern Africa
P.o Box 62157-00200, Nairobi Kenya
© Edward Kioko 2013
Course outline
Programme : BSc Computer science
Module Name : introduction to programming
Module Code : SCO 102
Credit Hours : 2hours per week; Lab work 3 hours per
week Semester
Semester : August-Dec 2014/2015
Course Leader : Edward Kioko
Meeting hours : Friday 8:00-1:00
Venue : Electrical Lab
E-mail : [email protected]
Website : http://www.edwardchris.net
Program : Regular
Module Schedule (August –December 2014/2015)
Week
Topic/Content Comment
1 & 2 Student registration & introduction to the module
Introduction to programming methodology
Programming language levels
Factors to consider while selecting a
programming language
Translators
Overview of C language
Development environment and cycle
Syntax of a C program
3 Program design and logic
Algorithm
Flowcharts & Pseudo code
4 & 5
Basic Elements of programming
Identifiers and keywords
Commenting in
data types
Operators
Constants and variables
6 & 7
Control structures
Decision control structure
loop
Continuous Assessment Test
8 & 9 Modular programming in C( functions)
Introduction to Programming
3 The Catholic University of Eastern Africa
P.o Box 62157-00200, Nairobi Kenya
© Edward Kioko 2013
10 & 11
Arrays in C
Lab Practical
END OF SEMESTER EXAMINATIONS
Teaching Methodologies:
Lectures, demonstrations, group/class discussions and practical
exercises
Instructional Materials/Equipment:
Computers, projectors, whiteboards and writing materials.
Course Assessment:
I CAT: 10%
Assignments 10%
Lab 20%
Exam: 60% .
100%
Recommended References:
1. Kerinignan, B. W., & Ritchie, D. M. (2010). The C
programming Language (second Edition ed.). New jersey:
Prentice Hall P T R.
2. King, K. C Programming: A Modern Approach.
Introduction to Programming
4 The Catholic University of Eastern Africa
P.o Box 62157-00200, Nairobi Kenya
© Edward Kioko 2013
Contents Chapter One: Introduction to programming ...................................... 6
1.1 Chapter objectives ............................................................... 6
1.2 Introduction to programming .............................................. 6
1.3 Programming levels............................................................. 6
1.4 Factors to consider while selecting a programming
language ....................................................................................... 10
1.5 Translators ......................................................................... 11
1.6 The development environment and the development cycle
13
1.7 Overview of C language .................................................... 13
1.8 C program structure and syntax ........................................ 13
1.9 Chapter summary .............................................................. 15
1.10 Chapter exercise ............................................................ 15
1.11 Further reading suggestion ............................................ 15
Chapter Two: Program Design Process and Logic .......................... 16
2.1 Chapter objectives ............................................................. 16
2.2 Introduction ....................................................................... 16
2.3 Program development Lifecycle (PDLC) ......................... 16
2.4 Programming design and logic tools ................................. 17
2.5 Algorithms ......................................................................... 17
2.6 Flow charts ........................................................................ 18
2.7 Pseudocode........................................................................ 20
2.8 Control Structures/Logical Structures ............................... 21
2.9 Chapter summary .............................................................. 27
2.10 Chapter exercise ............................................................ 27
3.1 Chapter objectives ............................................................. 28
3.2 Introduction ....................................................................... 28
3.3 Key words ......................................................................... 28
3.4 Comments in C.................................................................. 28
Chapter three: Fundamentals of C programming ............................ 28
3.5 Data types in C .................................................................. 29
3.6 Variables ........................................................................... 30
3.7.1 Numeric variables ........................................................ 31
3.7.2 Character variables ..................................................... 31
3.7.3 Assignment ................................................................... 31
3.7 Constants in c programming ............................................. 32
3.8 Arithmetic operators ......................................................... 32
3.9 Escape sequence ................................................................ 32
3.10 Statements ..................................................................... 32
3.11 Casting Data Types ....................................................... 32
3.12 Input and output ............................................................. 33
Introduction to Programming
5 The Catholic University of Eastern Africa
P.o Box 62157-00200, Nairobi Kenya
© Edward Kioko 2013
3.13 Formatted input–scanf ................................................... 33
3.14 Character I/O — getchar& putchar ............................... 35
Chapter Four: Control structures in C .............................................. 36
5.1 Introduction ....................................................................... 36
5.2 Chapter objectives ............................................................. 36
5.3 Boolean expressions and relational operators ................... 36
5.4 Compound Boolean expressions using logical operators .. 36
5.5 Control structures in C ...................................................... 37
5.6 Decision control structures ................................................ 37
4.5.1 Switch statement in C .................................................... 41
5.7 Repetitive control structures in C ...................................... 42
5.8 Chapter summary .............................................................. 46
5.9 Chapter exercise ................................................................ 47
5.10 Further reading suggestions ........................................... 47
Chapter Five: Functions in C ........................................................... 48
5.1 Introduction ....................................................................... 48
5.2 Chapter objectives ............................................................. 48
5.3 Benefits associated with Functions ................................... 48
5.4 Defining a function in C.................................................... 48
5.5 Function declaration .......................................................... 49
5.6 Function calls .................................................................... 50
5.7 Parameters and arguments ................................................ 51
5.8 Recursive functions in C ................................................... 53
5.8.1 Number Factorial ........................................................... 54
5.8.2 Fibonacci Series ............................................................ 54
5.9 Variable scope ................................................................... 55
5.9.1 Local Variables .............................................................. 55
5.9.2 Global Variables ............................................................ 56
5.9.3 Formal Parameters ......................................................... 57
5.10 Chapter summary .......................................................... 58
5.11 Chapter exercises ........................................................... 58
5.12 Further reading suggestions ........................................... 58
Introduction to Programming
6
Machakos University College
P.o Box 136-90100 Machakos|Tel:044-21604|Fax:044-20253
Website: www.machakosuniversity.ac.ke
Chapter One: Introduction to programming
1.1 Chapter objectives
By the end of this, learners should be able to:
Understand programming levels
Learn fundamental concepts underlying programming
languages
Understand the Program Development Life Cycle (PDLC)
Understand the factors to consider while selecting a
programming language
Indentify the different parts of a C program
Able to write, debug and execute a simple C program
1.2 Introduction to programming
Users communicate with the computer in a language understood by
it. It needs to be instructed to perform all the tasks. The instructions
are provided in the form of computer programs, which are
developed by a programmer using a programming language. The
language, which the user employs to interact with the computer is
known as computer programming language. The process of using
such languages to instruct the computer is known
as programming or coding.
We can therefore define a programming language as computer
language used by programmers to develop applications, scripts, or
other set of instructions for a computer to execute.
It is a series of instructions that instruct the computer on how to
perform tasks
1.3 Programming levels
The figure below is intended to illustrate several key points about
programming languages. First, programming languages are built
upon and relate directly to the underlying computer (hardware). In
fact, they are designed to control the operation of the hardware.
Second, these programming languages can be divided into TWO
major groups; low and high level programming languages
Low-level Languages are machine-dependent i.e. must run
on specific machines. They require extensive knowledge of
computer hardware and its configuration. They are further
divided in to Machine language and Assembly language
High-Level Languages are machine-independent hence can
ran on different types of machines
Introduction to Programming
7
Machakos University College
P.o Box 136-90100 Machakos|Tel:044-21604|Fax:044-20253
Website: www.machakosuniversity.ac.ke
Figure 1: Levels of Programming Languages
Machine Language
It’s the only language that is directly understood by the computer
therefore it does not need any translation. Its written as strings of 1′s
(one) and 0’s (zero. Program instruction may look like this:
1011000111101. It is considered to be first generation language.
Advantage of Machine Language
The only advantage is that program of machine language run very
fast because no translation program is required for the CPU.
Disadvantages of Machine Language
It is very difficult to program in machine language. The
programmer has to know details of hardware to write
program.
The programmer has to remember a lot of codes to write a
program which might easily result in program errors.
It is difficult to debug the program.
Assembly Language
Instead of using a string of binary bits in a machine language,
assembly language use English-like words as commands that can be
easily interpreted by programmers. These commands are referred to
as mnemonics. Examples of mnemonics in assembly language
include ADD, SUB, MUL, DIV.
Programming Language
Low Level High level
Machine Language Assembly Language
Procedural Object oriented
Introduction to Programming
8
Machakos University College
P.o Box 136-90100 Machakos|Tel:044-21604|Fax:044-20253
Website: www.machakosuniversity.ac.ke
Assembly language source must be translated into machine code by
a separate program known as assembler. The machine code can run
on its own at any time therefore the assembler and the source code
are no longer needed.
If you make any changes to the source code, the assembler shall be
needed to recompile the program again and generate a new object
program.
Advantages of Assembly Language
Mnemonics are easier to understand hence saving the
programmer lot of time and effort.
It is easier to correct errors and modify program instructions.
Assembly Language has the same efficiency of execution as
the machine level language. Because this is one-to-one
translator between assembly language program and its
corresponding machine language program.
Disadvantages of Assembly Language:
Its machine dependent hence a program written for one
computer might not run in other computers with different
hardware configuration i.e. there is no program portability.
It is necessary to remember the registers of CPU and
mnemonic instructions by the programmer.
Several mnemonic instructions are needed to write in
assembly language than a single line in high-level language.
Thus, assembly language programs are longer than the high
language programs.
1.3.1.1 Advantages of Low-level Languages
Low-level languages have the advantage that they can be written to
take advantage of any peculiarities in the architecture of the central
CPU. Thus, a program written in a low-level language can be
extremely efficient, making optimum use of both computer memory
and processing time.
1.3.1.2 Disadvantages of Low-level Languages
To write a low-level program takes a substantial amount of time, as
well as a clear understanding of the inner workings of the processor
itself. Therefore, low-level programming is typically used only for
very small programs, or for segments of code that are highly critical
and must run as efficiently as possible.
1.3.1.1 High-Level Languages
High-level programming languages allow the specification of a
problem solution in terms closer to those used by human beings.
These languages were designed to make programming far easier,
Introduction to Programming
9
Machakos University College
P.o Box 136-90100 Machakos|Tel:044-21604|Fax:044-20253
Website: www.machakosuniversity.ac.ke
less error-prone and to remove the programmer from having to know
the details of the internal structure of a particular computer. These
high-level languages were much closer to human language.
Examples include Java, Python, Prolog e.t.c.
They are very convenient but very far removed from the computer
they are running on. They are independent hence can run on
different types of machines
Programming paradigms
Procedural programming
Programming instructions to tell the computer what to accomplish
and how to accomplish it. Some common procedural programming
languages include BASIC, COBOL, C among others e.t.c
Object Oriented Approach
Structured programming doesn’t explain how to keep data and
programs together. However with OOP approach, data and programs
(methods) are packaged into a single unit called an object. OOP are
event driven. Example of OOP languages include C ++, java and
java applets
Advantages of High-level Languages
High-level languages permit faster development of large programs.
The final program as executed by the computer is not as efficient,
but the savings in programmer time generally far outweigh the
inefficiencies of the finished product. This is because the cost of
writing a program is nearly constant for each line of code, regardless
of the language. Thus, a high-level language where each line of code
translates to 10 machine instructions costs only one tenth as much in
program development as a low-level language where each line of
code represents only a single machine instruction.
1.4 Web page program development tools
They are tools used to create web pages. Example of these tools
includes:
HTML (Hypertext MarkUp Language) - it’s not actually a
programming language but contains special codes used to
create and format web pages. It usually uses tags that should
be kept as an ASCII file
Dynamic HTML(DHTML)-allows users to add more
graphics and interactivity on the web page e.g. perform
animations.
Extensible MarkUp language (XML) allows web page
developers to create tags that describe data pass to client so
that the client can process the data rather than the server.
Introduction to Programming
10
Machakos University College
P.o Box 136-90100 Machakos|Tel:044-21604|Fax:044-20253
Website: www.machakosuniversity.ac.ke
XHTML( eXtensible HTML) includes features of HTML
and XML
WML (Wireless Markup Language) allows web page
developers to design pages specifically for micro browsers. It
uses the Wireless Application Protocol (WAP)
Web page authoring which include Dreamweaver,
FrontPage, Joomla flash e.t.c.
1.5 Factors to consider while selecting a programming language
The features of one programming language may differ from the
other. One can be easy and simple, while others can be difficult and
complex. A program written for a specific task may have few lines
in one language, while many lines in the other. We judge the success
and strength of a programming language with respect to standard
features.
There a number of factors while selecting a programming just to
mention a few
Ease of Use
It’s the most important factor in choosing a language. The language
should be easy in writing codes for the programs and executing
them. The ease and clarity of a language depends upon its syntax. It
should be capable enough to provide clear, simple and unified set of
concepts. The vocabulary of the language should resemble English
(or some other natural language). Symbols, abbreviations and
jargons should be avoided unless they are already known to most
people. Any concept that cannot be easily explained to amateurs
should not be included in the language.
Good Programming Language Features
Its definition should be independent of any particular hardware or
operating system. It should support software engineering
technology, discourage or prohibit poor practices, and promote or
support maintenance activities. It should support the required level
of system reliability and safety. If the language does not support the
basic requirements, then it is advisable to learn a new language and
then start the application development.
Nature of Application
Each language provides certain distinctive features, which separates
it from other languages. For example, Java should be used to write
an application that runs over the Internet, whereas to develop a
system application, C and C++ are used.
Introduction to Programming
11
Machakos University College
P.o Box 136-90100 Machakos|Tel:044-21604|Fax:044-20253
Website: www.machakosuniversity.ac.ke
Language Acquaintance
In cases where a number of languages may suit the application to be
developed, the most familiar language to the programmers should be
chosen.
Ease of Learning
Sometimes, it may necessity the programmer has to learn a new
language in order develop an application. In such a case, the first
step is to find out which language, along with its alternatives, would
be suitable for the proposed application. Then, the programmer has
to decide which language is easier to learn and use.
Control over Resources
Apart from the ease of use, the control factor should also be
considered while selecting a language. Easy to learn and use feature
of the language does not mean that the application created with it
will be the most powerful. Certain applications require more control
over the hardware and hence the control factor should not be
ignored. If the application developed by an easy language is not
efficient enough, then it is better to slug it out with a more complex
language. For example, Visual Basic provides an easier way to
develop an application, but it does not have the same control over
the resources as other languages such as Visual C++ or Delphi.
1.5.1 Speed Requirement
Some applications e.g. railway or air reservation need to be quick as
compared to batch processing applications such as payroll and
inventory control. In such cases, the execution efficiency is
important and the programmer should use assembly language
instead of high-level languages. The main reason behind this is that
assembly language usually has a shorter production time as
compared to high-level languages.
1.6 Translators
It’s a program that converts source statement into machine language.
The source statements are just like English words. The computer
interprets the instructions as 1's and 0's. A program can be written in
assembly language as well as in high-level language. This written
program is called the source program. The source program is to be
converted to the machine language, which is called an object
program
Translators can be classified as depicted below follows
Introduction to Programming
12
Machakos University College
P.o Box 136-90100 Machakos|Tel:044-21604|Fax:044-20253
Website: www.machakosuniversity.ac.ke
Translators are as follows:
a) Assembler
b) Compiler
c) Interpreter
1.6.1 Assembler
They are programs that convert assembly code to equivalent
machine code. It will translate the symbolic codes of programs of an
assembly language into machine language instructions. The
symbolic language is translated to the machine code in the ratio of
one is to one symbolic instructions to one machine code instructions.
1.6.2 Compiler
It is a program which translates a high level language program into
a machine language program. A compiler is more intelligent than an
assembler. It checks all kinds of limits, ranges, errors etc. But its
program run time is more and occupies a larger part of the memory.
It s relatively slow in speed since it goes through the entire program
and then translates the entire program into machine codes.
If a compiler runs on a computer and produces the machine codes
for the same computer then it is known as a self compiler or resident
compiler. On the other hand, if a compiler runs on a computer and
produces the machine codes for other computer then it is known as a
cross compiler.
Compilers will show errors and warnings for the statements
violating the syntax rules of the language. They also have the ability
of linking subroutines of the program.
1.6.3 Interpreter
It translates high level languages into machine code. It translates
only one statement of the program at a time. It reads only one
statement of program, translates it and executes it. Then it reads the
next statement of the program again translates it and executes it. In
this way it proceeds further till all the statements are translated and
executed.
On the other hand, a compiler goes through the entire program and
then translates the entire program into machine codes. A compiler is
5 to 25 times faster than an interpreter.
Introduction to Programming
13
Machakos University College
P.o Box 136-90100 Machakos|Tel:044-21604|Fax:044-20253
Website: www.machakosuniversity.ac.ke
By the compiler, the machine codes are saved permanently for
future reference. On the other hand, the machine codes produced by
interpreter are not saved. An interpreter is a small program as
compared to compiler. It occupies less memory space, so it can be
used in a smaller system which has limited memory space.
1.7 The development environment and the development cycle
Programs goes through 3 main phases during development: editing
(writing the program), compiling (i.e., translating the program to
executable code and detecting syntax errors) and running the
program and checking for logical errors (called debugging).
1. Editing
This involves typing in the program with a text editor and making
corrections if necessary. The program is stored as a text file on the
disk
2. Compile
The translator converts the source into machine language code
(object code), which it stores on the disk .A linker then links the
object code with standard library routines that the program may use
and creates an executable image, which is also saved on disk,
usually as a file with the file name without any extension (e.g.
hello).
3. Execute
The executable is loaded from the disk to memory and CPU
executes the program one instruction at a time.
1.8 Overview of C language
It was developed in 1972 by Dennis Ritchie at the Bell telephone
laboratories for use with Unix operating system. It was designed for
system programming because of its low level memory management
and its construct are close to the machine instructions.
1.9 C program structure and syntax
Every C program consists of a header and a main body and has the
following structure.
// Comment statements, which are ignored by computer
#include <header file name >
Void main()
{
declaration of variables ;
statements ;
return 0;
}
We will consider each line of the above program for convenience
the program is reproduced on the next page with line numbers to
Introduction to Programming
14
Machakos University College
P.o Box 136-90100 Machakos|Tel:044-21604|Fax:044-20253
Website: www.machakosuniversity.ac.ke
allow us to comment on details of the program. However, you must
not put line numbers in an actual program.
Line 1: At the top of the program are comments and instructions,
which will not be executed. Lines beginning with // indicate
that the rest of the line is a comment. Comments are inserted
by programmers to help people read and understand the
program. Here the comment states the purpose of the program.
Comments are not executed by the computer. They can in
general be placed anywhere in a program.
Line 2: Lines beginning with # are instructions to the compiler’s
pre-processor. They include instruction says ―what follows is a
file name, find that file and insert its contents right here‖.
It is used to include the contents of a file of definitions that
may be used in the program.
Line 3 The word main is very important, and must appear once (and
only once) in every C program. This is the point where
execution is begun when the program is run. It does not have
to be the first statement in the program but it must exist as the
entry point. The use of the term main is actually a function
definition. Functions must return a value and the term void is
used to denote that the main program does not return a value.
Following the ―main‖ program name is a pair of parentheses,
which are an indication to the compiler that this is a function.
The two braces are used to define the limits of the program
itself: in this case, the main function. The actual program
statements go between the two braces.
Line 4 The opening (left) brace marks the beginning of the main
body of the program. The main body consists of instructions,
which can be declarations defining the data or statements on
how the data should be processed. All C declarations and
statements must end with a semicolon.
Line 5 printf is a predefined function. To sent output on the monitor,
the text is put within the function parentheses and bounded by
quotation marks. The definition of this function is defined in the
STDIO library (the Standard Input/output library). To compile and
link this program the #include statement is required. The end result
is that whatever is included between the quotation marks in the
1. //sample program 2. #include "stdio.h" 3. void main() 4. {
printf ("This is a line of text to output.\n"); 5. }
Introduction to Programming
15
Machakos University College
P.o Box 136-90100 Machakos|Tel:044-21604|Fax:044-20253
Website: www.machakosuniversity.ac.ke
printf function will be displayed on the monitor when the program is
run. Notice the semi-colon at the end of the line. C uses a semi-
colon as a statement terminator, so the semi-colon is required as a
signal to the compiler that this line is complete.
Line 6 The closing (right) brace marks the end of the main body of
the program.
1.10 Chapter summary
1.11 Chapter exercise
1.12 Further reading suggestion