Chapter 1 Introduction to Programming-1
Chapter 1 Introduction to Programming-1
R
Chapter 1 – Introduction
1 Introduction
U
Programming is the art of writing computer instructions in a language that the computer can interpret
and/or understand. In this topic, we shall look at some basic definitions and introduce some basic concepts
in programming.
UL
Definition 1. A computer is an electronic machine that accepts data as its input, process these data based
on some instructions to produce information as it output. These instructions that guide a computer on
how to process the data is what we refer to as a program.
Definition 2. Data – These are raw facts and figures found in a user environment
G
Definition 3. Information – This is meaningful processed data
Definition 4. Program – A program is a set of unambiguous instructions, written in a high level language,
that guide a computer on how to perform some specific task.
AN
Definition 6. High level languages are computer programming languages that use English-like and mathe-
matical notation to express computer instruction. Examples of these languages are Java, C++, C, Python,
PHP etc. We will use C for this unit. If you need to add two numbers a and b in high level language you
will have an instruction like a + b, which uses a mathematical notation. A program written in high level
language is often referred to as a source code.
.
DR
However, computers (read computer hardware) does not understand these languages. Therefore, these
languages have to be converted to low level languages or machine level languages for the computer (hardware)
to execute the instructions.
Definition 7. Low level language are computer programming languages that use mnemonics (read com-
mands) to express computer instruction. An example of this language is Assembly language. If you need to
add two numbers 6 and 4 in low level language you will have an instruction like ADD(4,6).
Definition 8. Machine language express computer instructions as a stream/collection of zeros (0) and
ones (1). Assume add operation is expressed as 11001001 and the number 1 is expressed as 00000001 and
number 2 is expressed as 00000010, the operation 1+2 will be expressed (something like) 00000001 00000010
11001001 in machine language. A program written in machine language is often referred to as a object
code.
Definition 9. Editor - An editor allows the programmer to enter the program source code and save it to
files. Most programming editors increase programmer productivity by using colors to highlight language
features.
Definition 10. Compiler - A compiler translates the source code to target code. The target code may be
the machine language for a particular platform or embedded device. The target code could be another source
language; for example, the earliest C++ compiler translated C++ into C, another higher-level language.
R
The resulting C code was then processed by a C compiler to produce an executable program.
Definition 11. Interpreter - An interpreter is like a compiler, in that it translates higher-level source code
into target code (usually machine language). It works differently, however. While a compiler produces
an executable program that may run many times with no additional translation needed, an interpreter
translates source code statements into machine language each time a user runs the program. A compiled
U
program does not need to be recompiled to run, but an interpreted program must be reinterpreted each
time it executes.
UL
Definition 12. Debugger - A debugger allows a programmer to more easily trace a programs execution
in order to locate and correct errors in the programs implementation. With a debugger, a developer can
simultaneously run a program and see which line in the source code is responsible for the programs current
actions. The programmer can watch the values of variables and other program elements to see if their values
change as expected. Debuggers are valuable for locating errors (also called bugs) and repairing programs
that contain errors.
G
Now we have said that we have several programming languages like C, C++, Java, PHP, Python etc. But,
what is a language? Consider the following sentences and state if its English or Kiswahili
AN
English or Kiswahili
You must have noticed that non of the four sentences above is English or Kiswahili. Why?
.
DR
1. First sentence, as much as all its word have a distinct meaning in Kiswahili, it breaks the rule of
Kiswahili language that requires a sentence to start with a capital letter.
2. Second sentence, all words have a meaning in English, but sentence does not terminate with a full
stop as required by English rules.
3. Third sentence is either Kiswahili nor English. Although it observes all the rules of both languages,
some words have no meaning in English while others have no meaning in Kiswahili.
1.1 Why C?
• Compact, fast, and powerful
R
• It is portable – Can run on different platforms like Windows, Linux, Mac
• C is the native language of UNIX and many windows apps are done in C
U
• Easy to interface with system devices/assembly routines
UL
• Every executable statement must end with a semi-colon
• Function return type must match the type returned by the function
G
• C is case sensitive. All C instructions must be in lower case
Definition 15. Expression is a collection of variables, constants and operators that evaluate to some value.
For example
y = 4x + c (1)
Definition 16. A variable is a named memory location whose content may vary/change.
There are some rules that must be observed when naming variables:-
1. Variable name should not start with a digit, may start with alphabet or an underscore
.
DR
These data types are shown in Table 2. Fill in the blanks in the Table.
R
int 16 or 32 or 64 bits
long 32 bits
float 32 bits
double 64 bits
U
1.3 Declaring a variable
A variable is a named memory location in which data of a certain type can be stored. The contents of a
UL
variable can change, thus the name. User defined variables must be declared before they can be used in a
program. It is during the declaration phase that the actual memory for the variable is reserved. All variables
in C must be declared before use.
Get into the habit of declaring variables using lowercase characters. Remember that C is case sensitive.
where DATATYPE is one of the 8 primitive data types. It could be int, float, char, bool, double etc.
For example, the code in Listing 1 shows 2 variables (length and width) declared as integers and one
variable (area) declared as a float.
1 int length, width;
2 float area;
.
You can use assignment operator (=) to give/assign a value to a variable during variable declaration as
1 int length = 10;
2 int width = 20;
3 float area = length ∗ width;
Note that, the value assigned to variable can be a result of an expression as shown on Line 3 of Listing 2.
1.4 Constants
Definition 18. A constant is a value that appears in a program and does not change during the entire
execution of the program.
Remember, preprocessor commands start with # symbol and are NOT terminated by a semicolon.
Declaring a symbolic or named constant follows the general structure shown in Listing 3.
1 #define NAME value
R
Listing 3: How to define symbolic/named constant
U
2 int main()
3 {
4 #define PI 3.142 //PI is a named constant
5 int radius = 7;
6 float area = PI ∗ radius ∗ radius ;
7
8
9
10
11 }
return 0;
UL
float perimeter = 2 ∗ PI ∗ radius; // 2 is a Literal constant
printf (”Area = %f Perimeter = %f”, area, perimeter);
Listing 4: Constants in C
G
Note that, whenever a defined symbol, like PI in this case, appears in a program, it is replaced by its actual
value, for this case 3.142 is inserted at the position the symbol PI appears in Line 6 and 7 of Listing 4.
1.5 Comments
.
Definition 19. A comment in a non-executable line of code meant for in-line documentation of the program.
DR
Comments are commonly used to explain complex algorithms being implemented in the program.
There are two types of comments in C
1. Single line comments - These comments start with double forward slashes (//) and only occupy a
single line. For example line 1 in Listing 5 shows a single line comment.
1 //This is a single line comment
2. Multi-line comment - These comments start with a forward slash and an asterisk and may occupy
several lines and must be terminated by an asterisk and a forward slash. For example line 1. . . 3 in
Listing 6 shows a multi-line comment.
R
1.6 Errors/bugs
Definition 20. An error (bug) is a mistake or an omission in a program that causes the program to stop
executing of the program may continue to execute but give wrong results. There are three types of errors
U
that can be commited in programming
(i) Syntax error – This is an error that occurs when a programmer fails to observe rules of a particular
programming language. Example of syntax errors are:-
UL
• Not terminating a statement with a semi-colon
• Mistyping a keyword/reserved word
• Omitting some necessary punctuation like a comma
• Using an opening brace (bracket) without a corresponding closing brace
G
It is easy to detect these errors because the compiler tells you where they are and what caused them.
(ii) Logical error – This error occurs when a programmer uses a wrong algorithm to solve a problem.
The error does not stop the program from executing, the program will continue executing but give
AN
wrong results. For example using the formula a = 3.142 + rad + rad to calculate area of a circle where
rad is the magnitude of the radius.
(iii) Runtime error – This error occurs when the program is executing and it encounters an illegal
statement (like division by zero) or a statement that cannot be executed (like trying to open a file
that does not exist).
For this case, Line 2 instructs the preprocessor to include a library called stdio.h. The angle brack-
ets around the library name instructs the preprocessor to search for the library from th root directory where
that particular compiler is installed.
If the resource to be include in enclosed in double quotation marks, that instructs the preprocessor to
search for that particular resource in the current directory where the source file is saved.
R
Line 3 and 4 is a multi-line comment.
Line 5 is the header of a main function. Every C program must have a main function for it to exe-
cute.
U
Line 6 to 11 is a block of code that makes the body of the main function.
Line 8 we are calling a printf() function defined in the stdio.h library and we give it a string to dis-
play on the console (screen).
UL
Definition 21. String – This is a collection of characters enclosed in double quotation marks.
Line 10 is fulfilling the promise the main function made that it will return an integer (int) to signify that
it has finished executing.
G
Figure 2 shows the output of the code in Listing 7.
AN
Definition 24. Block of code – A block of code is a collection of lines of code enclosed in curl brackets
({}) and the compiler treats them as a single statement
DR
The escape character indicates that printf() is supposed to do something out of the ordinary.
When the compiler encounters a backslash in a string, it looks ahead at the next character and com-
bines it with the backslash to form an escape sequence.
The escape sequence \n means newline. This tells the compiler to display the string and move the
R
the current cursor position
\ Backslash. Insert a backslash character in a string
\” Double quote. Insert double quotes character in a string
U
1.9 Operators
These are symbols that denote type of operation to be performed on the data. There are three main
categories of operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
UL
G
1.9.1 Arithmetic operators
Table 4 shows arithmetic operators Note use of various symbols not used in algebra. Like asterisk (*)
indicates mmultiplication and the percentage sign (%) denotes the remainder operation.
DR
Integer division and remainder operator: – When you divide an integer with another integer you get
an integers. For example 7/2 = 3 and NOT 3.5. The remainder operator yields the modulus/remainder
after integer division. For example 7 % 2 = 1 and 5 % 6 = 5.
Parentheses for grouping sub-expression: – Parentheses (brackets) are used in the same manner it is
used in algebra to denote that some sub-expression should be performed first before others. For example,
to multiply b by the sum of c and d is written as b ∗ (c + d).
2. Multiplication, division and modulus/remainder are evaluated second. If all or two appear in the same
expression, they are evaluated left-to-right.
3. Addition and subtraction are evaluated third. If both appear in the same expression, they are evaluated
left-to-right.
R
These are special types of arithmetic operator that adds or subtracts one from the previous value held in a
variable.
1. Increment operator (Its symbol is ++) - It adds one to the previous value. There are two types
U
of increment operators
(i) Pre-increment – Adds one to the previous value before using the new value with another expres-
sion.
1
2
3
int x = 10;
int y = ++x;
UL
printf (”x = %d y = %d\n”, x, y);
Listing 8: Pre-increment
G
Figure 3: Output of the code in Listing 8
AN
The output in Figure 3 shows that the value stored in x that is 10 is incremented (increased by
1) before being assigned to the variable y.
Listing 9: Pre-increment
DR
The output in Figure 4 shows that the value held in variable a is first incremented before being
used for addition to value 10 (see line 2 of code in Listing 9) that is why b has the value 21
which is 11 + 10.
(ii) Post-increment – Adds one to the previous value after using the new value with another expres-
sion.
R
The output in Figure 5 shows that the value stored in x that is 10 is incremented (increased by
1) after being assigned to the variable y.
U
1 int a = 10;
2 int b = a++ + 10;
3 printf (”a = %d b = %d”, a, b);
UL
Figure 6: Output of the code in Listing 11
G
The output in Figure 6 shows that the value held in variable a is incremented after being used
for addition to value 10 (see line 2 of code in Listing 11) that is why b has the value 20 which
AN
is 10 + 10.
2. Decrement operator (Its symbol is −−) – It subtracts one from the previous value. There are
two types of decrement operators
(i) Pre-decrement – Subtracts one from the previous value before using the new value with another
operator.
1 int x = 10;
2 int y = −−x;
3 printf (”x = %d y = %d\n”, x, y);
.
The output in Figure 7 shows that the value stored in x that is 10 is decremented (reduced by
1) before being assigned to the variable y.
R
The output in Figure 8 shows that the value held in variable a is first decremented before being
used for addition to value 10 (see line 2 of code in Listing 13) that is why b has the value 19
which is 9 + 10.
(ii) Post-decrement – Subtracts one from the previous value after using the new value with another
operator (expression).
U
1 int x = 10;
2 int y = x−−;
3 printf (”x = %d y = %d\n”, x, y);
The output in Figure 9 shows that the value stored in x that is 10 is decremented (reduced by
AN
The output in Figure 10 shows that the value held in variable a is decremented after being used
for addition to value 10 (see line 2 of code in Listing 15) that is why b has the value 20 which
is 10 + 10 and a has the value 9.
where op denotes an arithmetic operator which can be either of (+, -, *, /, %) We can combine assignment
operator and arithmetic operators as
R
Can be written as
x += b ∗ 10
Table 5 shows how arithmetic operators can be combined with assignment operator
U
Arithmetic operator Combined Example Equivalent
+ += a += b a=a+b
%
-
*
/
UL -=
*=
/=
%=
a -= b
a *= b
a /= b
a %= b
a=a-b
a=a*b
a=a/b
a=a%b
G
1.9.3 Relational and equality operators
These operators check two quantities and return true (1) or false (0). They are used for comparison of two
quantities. Table 6 shows these operators and what they mean.
AN
Equality operators
DR
= == x == y x is equal to y
6 = != x != y x is not equal to y
1. AND–Symbol is && – It checks two logical conditions and return true (1) if both conditions are
true (1) or return false (0) if either (any) of the conditions is false (0). Summary of AND can be
R
5
6 }
At Line 3 of this code, we are using logical AND to check two conditions:-
U
• If the value in y is greater than 5
• If the value in x is an even number (If we divide by 2 and the remainder is zero)
2. OR – Symbol is || – It checks two logical conditions and return true (1) if any of the conditions is
true (1) or return false (0) if both conditions are false (0). Summary of OR can be seen as
1+1=1
G
1+0=1
0+1=1
0+0=0
AN
We will use these logical operators mostly in our second topic – SELECTION
The first argument of the printf() function ”a = %d b = %d” is referred to as control string.
R
When the printf() is executed, it starts printing the text in the control string until it encounters a %
character.
The % sign is a special character in C and marks the beginning of a format specifier. A format specifier
U
controls how the value of a variable will be displayed on the screen.
When a format specifier is found,printf() looks up the next argument (in this case a), displays its value
and continues on.
UL
The d character that follows the % indicates that a (d)ecimal integer will be displayed.
• Format specifiers. For this case we have two %d meaning two integers are gona be displayed
• Escape sequence for this case we have \n meaning after displaying, go to next line
The arguments list can be made up of variables,constants, expressions, or function calls – anything that
produces a value which can be displayed.
Note that, the number and order of format specifiers must match the number and order
.
of arguments in the argument list. Table 7 shows what format specifiers should be used with what
data types
DR
R
Line 4 reads an integer (specified by the %d format specifier) into the variable x.
The scanf() function, which accepts input from the keyboard, has a control string and an address list.
In the control string, the format specifier %d shows what data type is expected. The &x argument specifies
the memory location (address of x) of the variable the input will be placed in.
U
The & character has a very special meaning in C. It is the address operator. (Much more with & when we
get to pointers).
UL
Line 5 just shows that you can read several values (of different data types) using a single scanf() state-
ment. Though I do not like that, use a single scanf() for a single input. It also good to precede
every input with a prompt message (using printf()) to make your program interactive. Consider the program
in Listing 20 which reads radius of a circle from the keyboard and calculates area and perimeter of the circle.
1 #include<stdio.h>
2 int main()
G
3 {
4 #define PI 3.142
5 int rad;
6 double area;
AN
7 float perimeter;
8 printf (”Enter radius of the circle : ”);
9 scanf(”%d”, &rad);
10 area = PI ∗ rad ∗ rad;
11 perimeter = 2 ∗ PI ∗ rad;
12 printf (”Radius = %d\n”, rad);
13 printf (”Area = %lf\tPerimeter = %f”, area, perimeter);
14
15 return 0;
16 }
.
Listing 20: Read radius from keyboard and calculate area and perimeter of the circle
DR