CHAPTER TWO
BASICS OF AC PROGRAM
jectives
‘sub-chapter 1.3 explained the various featur
se Chapter isto discuss the following features
Janguage): Holders of data (v s and constants), and
starements, and expressions. The specific objectives are to;
i
Describe the basi
res of a program. The
(using C
various
structure of a C program;
e Describe how to input and output in C:
Explain the role of variables, constants and
to use them in C;
Describe how to form expressions and highlight the work of
different operators based on the C language;
Introduce the programming errors that the learner expects to
encounter when developing his programs; and
Explain the good programming techniques recommended in
programming.
data types and how
Learning Outcomes
‘At the end of this Chapter, the learner should be able to:
Describe the basic structure of a C program;
Describe how to accomplish the following in C: Inputting,
‘outputting, usage of variables, constants, data types, and
forming of expressions; and
Develop simple C programs.
About C
‘The C Program Structure.
‘ Inputting and Outputting.
Variables, Constants, and Data types.
Operators.
Documentation lines.
Programming Errors.
Good Programming Techniques.
Solved Problems.
Exetcises.
saatts What is C?
- ST high level, machine 107) ee
Wn struc is was developed in tec! 'S Ritoh ¥
language. The we js an extension of an cae oes vtarhagem lan gaagg
— was also developed at Bell Laboratorie
known as B,
ve whose rich set of built-in functions and Peratoy,
C isa robust — complex programs, The C compiler Combines
can be used 10 bi an assembly language (low level Programming)
way ee for both development of system s¢
oh tee San This book however does not conee
foams but rather high level programming.
nitrate on be
2.1.2: Why use C?
Cis usually a preferred langua; ge because;
* — Cprograms are efficient and fast,
* C programs are highly portable can run on different hy,
platforms and operating systems,
1s a structured language -
n
$$$,
t allows the Programmer to so
problems in form of functio, ' (blocks of code), This makes
Program easy to Write, debug, (est and modify, | 3
* Chas flexible syntax that allows the programmer to Write code in,
» The programmer can also write code that is quite
’ ious Programmer, 6
oo {Or capabilities for ‘extending itself’, You ¢
ously add your Own functions to the Cs fjHinclude
yoid main()
{
}
(a), The line #include
This line is a compiler directive line. A compiler directive is an
instruction to the compiler to do a certain thing when it is compiling
your program.
For example the line #include tells the compiler to link the
file (or header file) named stdio.h to the program. This file has
definitions of input and output operations. It contains explanations on
how to do inputting and outputting through the functions seamf() and
Functions, as was explained in Chapter one, are sections of code for
‘compiler can not understand scanf() and printf() statements whenever
statements
start of the main (or the main
the body ae program. eehalt
written in the following form,
af the miataO) function and rety :
te Tpeexplained in Chapter four. hy
tells the compute,
ined in Chapte
with the message toprint \ne te the best language 100 the wer
programe! "4 me
omurn(O))
In this oxample, we have three statements to output the three lines in the
ynoanage
(c). Why use \n in print{( statements?
Tho \w before the start of each line of message in used to format the
output so that the computer takes the cursor to the start of the next line
‘on the sereen before starting outputting what follows:
if we omit \w at the beginning of each statement for example, the three
sentences: will be output on one line
(f), How does the computer execute the statements?
When the progran 1s executed, the computer goes straight to the main()
function and obeys the instructions in sequence i.e. starting from the
first instruction Lo the last (sequential execution)
Control structures (in Chapter three) may however be used to modify
this sequential execution to allow for repetition (repeated execution of
instructions as controlled by a condition) and d mn making
(selecting an alternative, thus executing some instructions and omitting
others).
(g). Some C language rules to note up to this level
e Every statement (or instruction) must end with a semt colon,
* We can combine many statements on the same line as long as each
ends with a semi colon.
+ Byery keyword (¢ include, return, vgid, main, ete) must not be
~ misspelled
rand must consist of sina letters. These are words that
have a special meaning in the language and are also known as
Set ‘You will continue to learn more keywords as You
proceed, ne are however listed in part (h) below.
© Other rules of C language must be obeyed e.g. “ must have #
corresponding ”, { must have a corresponding }, ete
not care where we start typing « ine, We can fF 9
code (the Word Processing indenting) #6"inside void
ve readability of code,
also to
return(0); —
can also ©
t the end of each
(h). Some keywords in c
auto, break, case, char, const, continue, det
extem, float, for, goto, if, int, long, register,
static, struct, switch, typedef, union, un:
2.2.2: How to Execute a C Progra’
The compiler used
The compiler used to test all programs and codi
is Microsoft Visual C++ 6.0 (for Windows oj
the explanation of how to execute a C program i
compiler is used for both C and C++ programs.
However, explanation based on U;
x (specifically
You can also use another com
C compiler.
piler to test the pro;
Point to Note
* ~~ You should however nots
get some errors if.
Visual C++ 6.0
fe that there is no guai
You're using these other cot
ompiler was used to test all
(a). The basic steps
Where to store your
It’s important to first note oerams
secondary storage device (¢ ane pr
decide the directory where,good © create your directory where you will st
s3 a : Z store ‘
s are well organized. You do so nea. Programs so
¢ system you are using e.g So
8. ows
your
chat } ~ of the operating
, of Windows or MkDir command (if y
you are using
com
pxploret program
Linus
= execution steps
The pasic SEEPS of executing a C program are;
@ Create the source program using the editor of the compiler you're
using. Also save your program in the appropriate directory.
(i Compile the program using the compiler you are using. This
checks and reports any errors in the program. If there are no errors,
the abject program is produced.
(iid- Execute (oF run) the object program. This makes the computer to
obey the instructions In the program.
These steps are common to all operating systems, but the commands for
mm operating systems to another.
doing so vary fro"
he execution steps using Microsoft Visual C++ 6.0
rosoft Visual C++ 6.0 interface
'
(b). T
@. Open the Mic
(ii). From the File Menu, select New sub menu.
ed (Ww indow titled
ndow that is displa
he listing shown. Also
le, int
f the program’s file (e.g.
ei). Select Files tab in the wi
New), and then select C++ Source Fil
in the right hand side write the name ©
Progl.cpp) in the text box just below File name:. Also select the
ditectory you want to store the file in the text box just below
Location:. The interface should now appear as the one below.snouos au Joy adenduyy 189q O49 St Qui,, ound
{
J
Qzeuny pion
{
4
3
(1aung pio*
<(, oBenBuel 2 Suisn USM Sem IIA, )yuud
/ <(_curesBoid puooas Aut st siypm,,.yraud
ctyorpis> apniuie
mojaq unoys se Yoo] {1!m wiEsBosd aU “SHORES
dot) ou JO saueU ay) Se goUNy puy ‘Zouny “Joung sn [fim aan
SUP Uy ‘eBessow Jo aut] 210 Buryndyno soy yoea ‘suonouny 29403 oa
wants 9q Ajaaneuoye Wed |'7'7 HONDAS Jo 7 ajdumexg Ut westoxd
VTT woysas Jo 7 adurexy Bunuimay :ajdwexd 0)
: onus
-gaoge paresisnii! 9°
Qureur oy) 10f au0 ay) 07 ARIUS SI UORSUNy YoRD jo Aan(d), Basie #
This prog!
following.
Other fune
The struel
main() fam
function
enclosed
start the
statement. —
(e). What is me
In this case, mail
tell the computer
then return. A
() brackets. For exal
named funel i.e
follows the call.
fune3(); Thus, we exes
When the program is
the function main().
(starting point of the pi
calls in main().
It’s mandatory for a prog
(f). Functions that ri
Some functions however
something. When we are
the required value(s), The
For example, we can hay
an integer as a paramete,
must pass to it an integer
follows.include
int main)
{
int num1, num2, sum;
scanf(“%d”, &num 1);
scanf(‘%d”, &num2); |
|
sum=num 1+num2;
printf(“%d”, sum);
return(0);
}
Discussion
ts the computer to declare three integers
The first statement instruc
named num1, num2, sum. Declarations will be covered later.
+ nam wiile .
The second statement instructs the computer to inpu!
third statement instructs the computer to input num2.
|e fi s ieee
= a ‘sian assigns a variable sum the sum of num1 and
~ Second last statement outputs the value of the variable sum.
s :
‘uppose the user inputs values 4 and 7. The program should output
value 11,
(c). Type identifiers
Type identifiers for both inputting and outputting include the
following.
Identifier Data type
%e
%s
%d
i
%u
%o
YX
. character (any single keyboard key represents a
character)
string (sequence of characters)
integer (whole number)
decimal, octal or hexadecimal integer
In outputting, value displayed as a signed decimal integer
floating point number
In outputting, value displayed with an exponent
floating point number
In outputting, value displayed without an exponent
floating point number
In outputting, value displayed using either %e or %f
format depending on the value. Trailing zeros and
trailing decimal points are not displayed
unsigned decimal integer (a positive integer)
octal number (for base 8 numbers)
In outputting. leading 0 not displayed
hexadecimal number (for base 16 numbers)
In outputting, Leading 0x not displayed.
The following may be used as a prefix of the above characters (i.e.
between % and the corresponding character).
h
I
for short
for long
For example, %ld refers to a long integer, “hd refers to a short
integer, while lf refers to a double (equivalent of a long float).
t2.3.4: More on Inputting and ©:
When outputting a variable’s value in an o
H output stateme
can contain not just the type identifier. bia taeh cones too
of the type identifier in this string will determine where the “a
value will be placed in the output ‘i
Example 1
‘Assuming integer x has value 5,
printf(“The value of x is Yd”, x);
outputs The value of x is 5, while
printf(“%d is the value of x”, x);
outputs Sis the value of x, whereas
printf(“The value %d is the output”, x):
outputs The value 5 is the output
(b). Outputting many variables usin:
We can also output many variables using the same statement Here, the
variables should be written after the string parameter (just as above) and
with commas, and their type identifiers written imthe strmg =
the sequence that the variables are written in.
ite. a string followed by the variables.
¢ the samre Statement
4
Thus, we pass many parameters
Example 2
eye the program shown in section 23.3 for computing sum of he #
sronars, Suppose that the user inputs 4 and 7 asthe values fox wud '
ively. The output statement used in the program +
and num2
printf(%d sum); wil just output the value of sam ie il
To improve usability of the program, we ean change the OP
statement to be either of the following.
(@)._ printf(“The sum is %d”, sum); to output the sum!(ii). printf“%d is the sum”, sum); to OUutpyr li,
F is
ey
im f Yd g I Nm
(iii). printf(*%d is the sum of %d ang %a ae
» ny,
i: n of 4 and 7 re
to output 11 is the sum of 4 and 7 %
intf(“ of Yd and %d jg 07 a
eee ee hey
: sy
to output The sum of 4 and 7 jg 1] hy,
Example 3 .
What ee would output 4+7=] 1
Answer
Printi(“%d+%d="%d”, numt, num2, sum);
(c). Specifying the input and the output width
A non-negative number may be written between % and the ¢|
that follows in the type identifier, to Specify the width Of the
Output i.e. the number of character locations (along the width
screen) allocated for the input or the output.
In seanf() Statement
If the number is in Seanf() statement, it Specifies the maximum number
of characters allowed for the input. Thus, you can input less, Ifyou
input more characters/digits, the extra characters will be cut off
Tn printfy) statement
If the number ig in printf) statement, it specifies the minimum width of
the piece of, cutput i.e. the number of Character positions allocated for
the Output. If the output occupies less character Positions, then the
output will be Preceded by blank spaces to fill the extra
a °y enough ;
Positions, If the character ©ccupies more positions, then it’s
ed as it is,
¢ Number may al
also iting. 50 be a float
e fractiona
ting point number in which
! part positions allocated,
4
/hen used in “
of not more wonton Specifies that we can input anii), %5d when i
( = n used in printf) statement specifies that the output
integer is allocated five character positions,
iii). % 7.28 when used in pri
(ii). > = = hen used in printfQ) statement specifies that the output is
Seven character positions two of which are fractional part
Positions (note that character . is included).
Examples 5: Some codes and their outputs
@. mtx;
scanf{“%3d”, &x);
printi(“%ed”, x);
‘The scanf{) statement specifies that only three digits are accepted
as the input of x. If you try to input 12345 (five digits), the output
is 123, so the extra two digits are not accepted by scanf(). If
however you input 123, the output is 123, while if you input 1, the
output is 1.
(ii). int x= 100;
printf(“in%3d”, x);
printf("\n%4d”, x):
printf(“\n%5d”, x);
outputs the following (assuming the screen’s left margin is the left
margin of the immediate above code),
100
100
100
In the second statement, the output is allocated three spaces along
the sereen’s length, and these are filled by value 100 (with three
digits). In the third statement, the output is allocated four character
positions, and so ‘outputting value 100 will cause the extra one
position to be filed with a preceding single space. Similarly, two
spaces start the display of value 100 in the fourth statement, since
the output is allocated five character positions.
i
(iii), int x=100, y=2, 2=3000, n=10000;
|outputs
VALUES
£10000
100
2
: 3000
x=10.0
5
esi %7-3f
i) 8 97.38" % Y)5
print
outputs
- 10.000 5.000
tifier %7-3f SP
the value of x (10.0) seven ch
fractional part positions. So the outpul
these total Six positions. We precede the displa
space to fill this difference (notice that there is one space displayeg
between : and 10.000). Then to display 5.000 (that has five
character positions), We start by outputting a space (note that there
is a space specified between the two identifiers in the statement),
then displaying two empty spaces and then the value, so as to make
this seven character positions.
ecifies that we allocate the display of
haracter positions. three of them
t should be 10.000, but since
y with one empty
The type iden!
(d). Specifying @ flag
also include a flag i.e. a charac!
t. A flag must be placed imme
d include the following.
e left justified, and so the empty
) above, will be
‘The type identifier can ter that affects the
appearance of the outpu diately after the
character %. The flags use
Os (that causes data item to b
spaces required to fill an output — in part (c
an after the data item and not aie
fat causes the output number to be : i
; 2 preceded with
either - or +). Without the sign, only negative numbe
ois ea byasign. ~ y
ili). jat causes Zeros to insteac ;
(iv). # (ith 0 or x) Seer eae tsattng Olanks).
- (causes octal and hexadecimal i
(herahaeveh, imal items to be preceded by ° and
a sign ie.
(ii). +
rs are(y), # (with ©, f, or gy
Examples 6:
@.
(ii).
©)
Though output inside doubl
Use of.
(causes a fractional point to be present in all floating point
fumbers, even if it is a whole number, Also prevents the
(runcation of trailing zeros in g-type conversion),
Some codes and their outputs
1 declare integer x with value 123.
Printf("\n:%45d", x); // output 123 with five character positions
Brintf("\n:%-5d”, x); // Left justify value 123
Printf(\n:%-+d”, x); // 123 is left justified and has a sign
Output
123
123
+123
int x123;,
float x=355.5, y=455.5,
Printt(“%-7.26%0+7 26 %-
e", X,Y, 2);
Output
355.50 +00455,50,1.22e+002
Discussion
The type identifier %-7.2f displays the value of x (355.5) with two
even character positions allocated. The
the display starts immediately after the
previous one,
. Escape sequences
16 Quotes inthe printf statement dplys
i specified, there are some xo
modifies the way the output is presen
string exactly the way
escape sequences
5
ie—
Pag
Ww
tb
¥
\a
v
single quote
r double quote
y question mark
‘The mostly used escape sequence is \n that takes the cursor (© the neyy
~ Tine on the screen, Note that \n can be placed anywhere in the string \y
~ on the other hand leaves a horizontal tab space (the same tab spaces jy
‘word processing used to format text).(0) priwel' My fliest string\tMy second string");
te he ne My second string
(vO. prineea"); Rings the computer's bell
‘The other esoape sequences work as shown in Table 2.1 above, The
veader should ty them out to test how they work
2.3.5: Input and Output of Characters and Strings
(a). About characters
What is a character?
A character is any single element that can be typed on the keyboard e.g.
an alphabet, a digit, or a special symbol (including $, %, !, =, {, |, ete).
Declaring a character ad
A character is declared using the char data type. For example, to ea
declare a character-type variable named t, we write
char ts
Quoting a character's content *
A character's contents is referred to using the “’ quotes. F: le, to
assign a char-type variable named t contents ca
hdint ee the message\n”)
en niqijs”, &message)
cal aed
seal i -sirlen(message); aa =
ed saaTbe message contains %ed charac
pein
lengths
su Variables, Constants and Data Ty pes
<=
24d: Variables
(Whatisavariable?
A variable is a programming concept of a loc 1 the me
ring a value that may change from time to ¢ owas
that can be stored in a variable must be of
program must store the values it is using for con
or other advanced storage locations.
(b). Declaration of variables
Declaring a variable instructs the computer to
for storing a value of that type. A variable must t
ean be used. Also, a variable can not be declared man:
same section of the program (in the main() function or
function).
allocate a meme
‘The syntax for declaring a variable is Type Name;
Example
The following statement inst
tructs the computer to declare a variable
named x, for storing an integer (whole number),
int x;
Declaring many variables
can declare many Variables using the same Statement. In this case,
Separate the Variables with commas. For example, the following
ny Variables named a, b and ¢ of float type. These
can store numbers With decimal points,
Moat a,b, ¢;
wn‘This is alternative to writing the follow ng three Statement
float ay
oat by
Moat ¢;
(©). Initialization of variables
You can give a variable some initial vaiue during de
known as initializing a variable). For example t
ad ¢ to zero during declaration, we write
claratio
) initialize float &
float a=0, b=0, c= 0;
To initialize only b, we write
float a, beO, ¢;
To initialize a character-type variable, we use Single quotes to enelogg
the initial content. For example,
char @y’;
declares a character variable named t and initializes it with contents ‘y’
To initialize a string, we use the “ quotes. For example
char name[30|=“john”;
initializes the variable name with the string “john”;
char name[30]="";
initializes the variable name with empty string.
Points to Note
A variable must be declared before being used.
> A variable can not be declared more than once (in the same
Program or function),
A variable can be declared anywhere in the program i.e. it’s not a
must to declare it at the beginning of main(), We can declare it at
the middle of other statements,
92Yr.
‘ od programming technique to use meaningful name
pedi aname suggesting the type of contents stored
hese Ce eather r+ vortabe for Bovitsg salaries ret
a: _—
° ‘These notes apply also to other data structures i.e. constan
arrays, structs, and also pointers.
2.4.2: Constants
(a). What is a constant?
A constant, just like a variable, is used to store values in
constant’s value however, may not change. Constants are used to
values that do not change in any run of the program includi
cirele, the tax rate of a payroll processing program, the pas
examination processing program, etc.
(b). Declaration of constants
Just like a variable, a constant’s declaration instructs the computer to
allocate a space for storing the value. Two syritax for declaring a
constant are;
(i). #define Name Value
(ii). const Type Name=Value;
Example
Each of the following two lines declares a constant named pi for storing
value 3.14
define pi 3.14
const double pi
14;
(c). Why use constants?
The use of constants ensures that the Program is easy to read, write and
modify. For example, consider computing the tax for three salaries
based on a constant tax rate (8.5%). Two options for doing this are:
Without using a constant
double salaryA, salaryB, salaryC, taxA, taxB, taxC;
seanf(“%lf”, &salaryA); scanf(“%lf”, &salaryB);
93seanf(**%lf”, &salaryC);
taxA=8.5/100*salaryA;
taxB=8,5/100*salaryB;
taxC=8,5/100*salaryC;
Option2 —_ Using a constant for rate
const double rate=8.5;
double salaryA, salaryB, salaryC, taxA, taxB, taxC;
seanf{“%lt”, &salaryA); seanf(*%If”, &alaryB);
scanf(“%lf”, &salaryC);
taxA=rate/100*salaryA;
taxB=rate/100*salaryB;
taxC=rate/100*salaryC;
It is clearly easy for one to read or write the Program using option 2
rather than Option 1 since it is easier to remember ¢
rather than the value 8.5 every time he/she wants
value in the program
Also, suppose the tax rate changes. When the programmer is modifying
the program in Option 1, he/she will have to change al the oceurena
of the value 85 in the program. However using Option 2 the
Programmer just needs to change the value 8.5 once (in the statement
const double rate=8.5;). Thus, Option? is more modifiable.
2.4.3: Identifiers
(a).
An identifier is the name of any object in a program e.g. a variable, 2
constant, an array, a function, a pointer, etc.
What is an identifier?
(b). Rules for identifiers in C as
© The following are the characters that are allowed in an identifier:
letters, digits, underscore. You may use a combination of these
three types of valid characters,
* The first character must be either an alphabet or an underscore.
* An identifier can’t be a reserved word.
© — Cis case sensitive. For example, the following are different
identifiers: WAT, wat, Wat, wAt, waT, wAT, WaT, WA
94|
pxample following names are valid identifiers in C7
hie A COMPUTER (i) main
Oe pi Tid noms (vi) Rctiage
Oo)
Gv). Fitst_nume
(ili). John
ean ;
@, (i), (vill), (29).
i (iii) isa reserved word, (v) contains an invalid character ic
, (vi) begins with a digit, (vii) contains an invalid character
Fe eeibsteeeht nes (2)
2.4.4: Data Types
ee
(a). General data types = :
There are four types of data used in Computing. They are as follo
(i). Integers
Meaning of integers and number systems
An integer is a sequence of digits representing a whole numbe
example 3, 10, 115, etc. Integers and float point numbers are
values (numbers). There are four umber systems used to represen
integers. They are decimal, binary, octal and hexadecimal systems
@. Decimal number system (base 10 number system)
The digits used im this system are 0 up to 9. It is the mostly
used number system — the other systems are rarely used by
Programmers, and so this book uses this system.
(QD). Binary number systems (base 2 number systems)
Ituses digits 0 and 1 to represent any number.
(MD). Octal number system (base § number system)
It uses digits 0 up to 7 to represent any number.
(IV). Hexadecimal number system (base 16 number system)
Ttuses digits 0 up to 9, then letters A, B, C, D, E, Fto
represent decimal numbers 0 up ta 15. Thus, letters A, B, C,
D, E, F represent decimal numbers 10 up to 15. ‘The system is
ot case sensitive, so you can still use a, b, c, d,e, f
. 95
ia
Some decimal numbers and the e
quivalents in the
systems are as follows,
Other n Umber
Decimal number Base 2 Base §
; 1 1 Base 16
3 ul 3 Fi
3 1000 10 8
13 1101 Is i"
21 10101
15
We do not usually use the binary number
high level programs. For more information a,
systems including conversion of num
another, the leamer should read intro,
computing,
ems when Writing
out the number
bers from one System to
ductory materials in
Representing octal and hexadecimal constant
Octal numbers must be preceded by the digit 0
fumbers onthe other hand, must be preceded by cin Ox oro
For example, 05 (an octal) is the decimal number §
is the decimal number .
Values in ©
Texadecimal
Examples 2
Some C language codes and their Outputs for the number systems
f are as shown below
(©. (Outputting a decimal number as a decimal, as an octal and as
| an hexadecimal)
int x=21;
Printi(‘\n%d”, x);
Printf(“in%o”, x);
Printf(‘“\n%x”, x};
Output
21
25
15
// output x as a decimal number
“output x as an octal number
“output x as an hexadecimal numberre
Outpatting a" hexadecimal number as & decimal, as an octal
a. S ‘5 an hexadecimal)
iat wet Ht declare an hexadecimal member x
ed”, 4); // output x as a decimal number
printtin%Go", x); // output 1 a5 an octal number
printf("\n%x", x); // output x as am hexadecimal
Qutpat
n
5
ad
(i). (Adding two octal numbers)
int 0345, yO233, 2;
meaty}
printf(“\nThe sum in octal form: %o”, 2);
printf(‘“\nThe sum in decimal form: Yd”, 2);
‘The sum in octal form: 600
‘The sum in decimal form: 384
(IV). (Adding two hexadecimal numbers)
int x=0x3, y=Oxe, 25
mextys
printf(*\nThe sum in hexadecimal form: %x", 2):
print{(*\nThe sum in decimal form: Yd”, 2);
‘The sum in hexadecimal form: 11
‘The sum in decimal form: 17
(ii). Floating point numbers
A floating point number is a base 10 number that contains a
fractional part e.g. 25.5, A floating point number can also be
in exponential form, For example, 25.5 can be written as
2.55el or 2.55e+1
Floating point numbers generally have much greater range of
values than integers,
Characters
character is any single clement that can be typed through the
¢.g. an alphabet, a special symbol (e.g. #, %, &, “), ora
7tA om 00 be td oor
dig Bt “he
‘ Aer is quoted by enclosing it ip Siigle Guites
nF, 9,9. Bach character has 4 unig al
— it based on the ASC) Coding system, (the on ey,
— Wiple, the Age Il value for
*A is 65, while for Character 4 97. The a a
ASCII values are shown in the Appendix section
(iv), Strings
A string is 4 sequence of individual characters for example, 4
name of 4 person,
A string is quoted using double quotes, for cxample, “Peterson
Jobnt” (note that a Space is also a character as used in thig string).
The null string (or empty string) can be quoted as”
example the following C
the names “Peterson and “Johnt” but on
betwee tes sitOe We lave sed the eseape sequene a,
between string “Peterson Johnt”.
Print{(“Peterson\nJohnt”),
(b). The data types in C
C uses various‘gable 2.2: Data types in C
Size (bytes) Range
a signed char | -128 to 127 e
unsigned char 7 0 to 255 s
int or signed int 4 -2,147,483,648 to 2,147,483,647
unsigned int 4 0 to 4,294,967,295
short int or
signed short int 2 ~32,768 to 32,767
unsigned short int 2 0 to 65,535
Jong int or
signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
float 4 3.4E-38 to 3.4E+38
double 8
long double 8 1.7E-308 to 1.7E+308
bool 1
True or False (or | or 0)
char data type stores characters e.g, alphabets (a-z, A-Z). digits (0-9) —
but can’t be used in expressions ie. are considered non-values in this
case, or special literals e.g. ?,-,*, {,.
int data type stores whole numbers (or integers). An int type variable
occupies four bytes (based on the compiler used in this book).
float data type stores numbers with fractional part. A float type variable
occupies four bytes (based on the compiler used in this book).
double data type stores numbers with fractional part just like float, but
can store a very large value e.g. a trillion. For example, if you try to
input the value 1,000,000,000,000 into a float type variable, you will
get errors unlike when you input into a double type variable.
long keyword in this compiler, has no effect on the storage capacity.
However, in some other compilers, it makes the storage Space bigger. In
that case, it can be used together with int or double. The data type long
int for example, can store very large integers, while long double can
store even larger numbers with fractional parts than double data type.
short keyword halves the storage space allocated for an int-type
variable (into two ‘You can for example declare a variable of
type short int, and this ls so as to spare the computer’s memory.keyword is used for both negatives and positives inte,
sally has no effect on the variable’s storage size. For cane
type is the same as a signed int type. 2D inp
wu keyword is used for non-negative numbers. Making q Vari
unsigned has the effect that the same storage space is used but the
of the positive values is twice that of signed (or normal) variables, g
example, a variable of type unsigned int has the same storage size =
int type variable. However, the former can store twice the maximum an
positive value that the later can store.
How are the above ranges of data types obtained?
The mathematical rule on combinations is used in obtaining the range of
values that a variable of a particular type can store. The rule shows that
if we have n objects, whereby each object can take any of the x possible
values, then the total number of ways we can have a combination of the
n objects is x”.
For example, the possible values a coin can have is 2 (Head or Tail, or
just H or T). The number of ways we can arrange 3 coins is 2°=8 i.e.
‘TTT, TTH, THT, THH, HTT, HTH, HHT, HHH.
Similarly, a decimal digit can take 10 possible values (i.e. 0, 1, 2, ...,9).
Two digits can thus be used to represent 107=100 total numbers (i.e. the
numbers 00, 01, 02, ..., 99). Similarly, 3 digits can be used to represent
a total of 10°=1000 numbers (j,e. the numbers 0, 1, 2, ..., 999).
In binary number systems, a bit has two possible values (i.e. 0 or 1).
One bit can thus represent 2'=2 numbers (i.e. 0, or 1). A sequence of
two bits can represent a total of 27=4 numbers (i.e. 00, 01, 10, or 11),
which in decimal form are 0, 1, 2, and 3 (note that we start with 0 and
not 1, so we don’t have number 4). Three bits can represent 2 =8
numbers (i.e. 000, 001, 010, 011, 100, 101, 110, or 111). In decimal
form, these eight numbers are 0, 1, 2, 3, 4, 5, 6, and 7 (note that we start
with 0 and not 1, so we don’t have number 8).
‘Thus, x bits can be used to represent 2* numbers. In decimal form, and
considering only positive integers, this represents value 0 followed by
the first 2*-1 integers i.e. the positive integers 0, 1, 2, ..., 2-1.
Examples
(i). A char type variable occupies one byte (or 8 bits). The computer is
thus able to represent 2°=256 characters (including all characters in
Appendix A at the end of this book). For example, the null
ee.a
4
x has ASCH value 0, and is thus stored as 0000000. ‘Th, |
PsA tas the ASCH values 65, and is thus stored ag” ne kaie
01000001.
(ji). Ashort int type variable occupies 2 bytes (or 16 bits), and can
and negatives, the computer dedicates half of this capacity to
negatives (i.e. the range -32,768 to -1) and the other half to
positives (ie. the range 0 to 32,767),
example, if you run the following code, you will notice that
ua input any value in the range (-32,768 t0 32.767) to be a's
value, I'you input any value outside this range, you got «logical
error (the computer can’t store the input value into the variable, so
it will output wrong values).
short int a;
scanf(“%hd”, &a);
printf(“\n%ha”, a);
(ii), An unsigned short int type variable occu,
and can thus store 2'°=65,536 numbers. §
allow negatives, we can thus store the val
pies 2 bytes (or 16 bits),
ince this type doesn’t
lues 0, 1,2, 3, ..., 65,535.
For example, if you run the following code, you will notice that
You can input any value in the range (0 to 65,535) to be a’s value.
If you input any value outside this Tange, you get a logical error.
unsigned short int a;
seanf(“Youh”, &a);
Printf(“\n%uh”, a);
(iv), ane Variable occupies 4 bytes (or 32 bits), and can thus
‘Store 2"°=4,294,967,296 numbers. Since we must cater for
Positives
and negatives, the computer dedicates half of this
fo negatives (i.e. the range -2,147,483,648 to ~1) and the
the range 0 to 2,147,483,647),ennigne supe variatile compos 4 leyles : VF hee
" Ae oe Tink 29486298 rambo Hide Die yg
pene wwe ns Chawe stews thee vateinn 9)
—
woop, pan the following onde, you
er ese ant te ange (0 0 4.2 4
‘eal. If you input any value cutside this range
ane.
on oy
peteete na", a)
Deciding on the type to use
‘The dasa type you to use for a variable will depen!
gplications of the program you are developing
‘Fer example, if you are developing an examimation system: ah.»
‘exams’ marks are expected to be smal! and posit:
Ww ose the wasigned short int (ype, as well as the char’to define an identifier that will he
used tes
data type. The syntax ie
Be asin the data type Unsigned long int You can
declare a variable x of this type as
unsigned long int x;
However, since the name of the dats type is quite long, you oan use the
identifier Ulint to represent the data type, and dofine it ax
typedef unsigned long int Ulin;
Any time you use Ulint, you will be referring 1 that data type. For
‘example you can now declare x ay
Ulint x;
(i. The enum keyword
‘he enum keyword is used t0 declare a user defined
specifying the
of its type ean lke, The mean of fing nn
{walues) ;subject is 2 variable of type subject, and can yay,
Hore, james. :
San at em tr ea
james_subject=Mathss
245: Example
, x%y); will Output | (the remainder
byy).
2.5.2: Relational Operators
Relatioy
wie ores @. nl i Boolean expressions to compare
Boolean expressine ‘0 Produce a value of either True or False 4
False. It's algy jon San ©xpression whose value can either be Tree
Possible relational gn’ ®S @ conditi
nal or a logical expression.
f° as shown in the table below.
pped)
of dividingRelational operators
Operator ___ Meaning
ater than
is Breater than or equal to
‘ less than
‘ee less than or equal to
ss equal to
not equal to
Examples of some Boolean expressions and their values ar
below.
Table 2.5: Some Boolean expressions
Expression
ae |
3>7
has
3:
+3)
Point to Note
‘When the computer evaluates the expression, it substitutes it with
the value obtained. Also, in C, value 1 is used to represent
True
value, and 0 to represent False value
Example
Assume the declaration
int x=9, y=2;
printf(“%d”, (x>y)); outputs 1 (for True)
printf(“%d”, (x<=y)); outputs 0 (for False)
:
¢
(ii). printf“%a”, (x1=y)); outputs | (for True)
2.5:3: Logical Operators
Logical operators are used to combine two Boolean expressions info @
compound Boolean expression (or just compound expressions). The
Tules of truth table are used to test the truth or false of compound
ressions depending on the truth or false of each expression in
und expression. Logical operators include the following.
107Table 2.6: Logical 0) ators
Operator Meaning
gk and
‘| or
1 not
The truth table is shown below.
Table 2.7; The truth table :
P Q P&&Q|PIQ P :
[F F F F a z
F x F T T
r F Fo ie FE 5
LT {T. be rT F ES
Where T stands for True, F stands for False, and both P and Q stangs
for simple expressions.
Example:Some compound expressions and their values.
Expression Value
BI) && a FALSE
G3) TRUE
ef eae
Here, using P to represent the expression (3<7) and Q to represent
(1>3), we find that P is True while Q is False. Thus from Table 2.7,
(G3) is False (using row 4 and column 3 of Table 2.7) while
(3<7) | (1>3) is True (using row 4 and column 4 of Table 2.7).
2.5.4: The Assignment Operator (=)
‘The assignment operator is used to assi i
; u ign the variable on the left hand
side the value of the expression which is on the right hand side.
ae of b and store it in variable a”.
the result in seater NEO and stow
ey ota oS one to it, and store the
one or just increment x”. metementthe value of x bY
E means “ le Value o}
a ‘decrement the valy fx by one (dec
: rement x)”.
108means “multiply the values of x and y
xextyh -
inx
and store the result
Points (0 Note
The assignment operator is a replacement operator as discussed
Chapter one, For example, the statement ab; replaces "|
(overwrites) the previous value of variable a,
4 The assignment statement is a copying process. For example,
when a=b; is executed, variable b does not lose its original value
Example 2
What is the output of the following section of code?
int and, b6;
ach; printi(‘a=%d,
%d", a, b);
Answer
.b=6
ignments can be done in a single statement
igns both x and y value 10.
Note also that multiple
For example, the following statement as
reyes
In this case, the assignment operator is right associative, ie. in the
above statement, we assign y value 10, then x.the value of y
2.5.5: Shortcut Operators
ions. The shorteut operators
=. These operators will be
Chas shortcuts for writing some expre
include the following: ++, —, +=, =*
explained by using the examples below
‘Table 2.8: Some shortcut expressions
Expression Equivalent to
ach or Hex xextl
x=x-
_y\ xSxXty.
om xy
xex"y
x=x/y
109noth ++ and
2 4+ and = operators van be written :
ca pore is difference between the two ware 4
compound statements (0taleMments Wilh many they ang
in Chapter one og. wey; which has tim
addition of | © Y, and assignment of the result 4
difference 18 8 anew _—
- “use the value of * in the expression and then
increment x" (past increment)
sii “inerement «and then use it in the expression”
increment). .
Example 3
‘What are the outputs of the following sections of code?
@, intx, ys
si
pela, y=, 9
ints, yhHow to create an alias variable
. ’ 7
& operator just before the
We use the
variable
‘Also, the new variable should be
declaration.
name
initialized to the other
one.
during
For example, the following statement declares y as an al
For ,
ias of x
int &y=%5
In this case, y is also known as a reference variable of x
Example :
‘What is the output of the following statements?
printf(“\nx="d, y="od”, x, y);
Ee
printf(“\nx=%od, y=%d”, x, y);
| hes
printf(“\nx=%d, y="%d”, x, y);
Answer
x=5, y=5
x=6, y=6
x=30, y=30
Here, changing the value of either x or y results to the other variable
being changed to the same value.
2.5.7: The Ternary Operator (2:)
i = a en
This operator is used indecision making. Jt takes the following syntax;
expression! ° expression2 : expression3
that is expression! is evaluated, If it is True, then expression? is
evaluated and becomes the value of the whole expression. Otherwise.
®xpression3 js evaluated and becomes the value of the expression.
ample
a=10; b=15;
= (>) 2 a:b;
“ho Ry
nas Ht 9 MWVariable x attains the value of by ie 15 This is because the
(a>b) fails and therefore the value of expression b becomes the
the expression ((a>b) Pash) which is then assigned to x Yalu”
2.5.8; Operator Precedence
The following is a list Fihe commonly used operators and their ~~
precedence (pt jority) levels. Note that some have not yet been ¢o
up to this chapter, but ‘will be explained in later chapters very
recedence of operators —_
{Rank |
! (Logical negation)
_ (Pointer reference)
& (Address of)
sizeof)
* =
/
a
=
i aa Ee
: 5
>2 1. ‘Type Conversion
Jou can mix constants and variables of different types in an canoes
For example, (vty), Where x is an int, while y is a double Cone
(a). Implicit type conversion
To avoid any logic errors (resulting from loss of significance) due to
mixing of variables of different types in an expression, the compiler
automatically converts some of the operands to the type of the other
before evaluating the expression using some rules that depend from a
compiler to a compiler. The basic tule is to convert the lower types to
the higher types. The following lists the levels based on this basic rule
Highest level: long double
double
float
unsigned long int
Jong int
unsigned int
int
Lowest level: short, char
(b). Explicit type conversion
‘The programmer can also force the conversion of some operands in an
expression by specifying the new type just before an operand’s name,
and putting the operand’s name inside the brackets (). For example
double(nt) converts a variable m into a double type.
Example
Consider the code
int a=3; float b=14.5, e3
c=b/float(a); printf(“%f”, ©);
In the statement e=b/Moat(a);, the programmer has converted the value
of variable a from an int into a float (so the new value is 3.0), so that he
‘can comfortably divide a float with another float to avoid any possible
logic errors, Note that this converts the value of variable a (as currently
being used) but not the variable a, Variable a in the memory remains am
integer. Note that converting into a higher type does not lose any :
precision, unlike converting into a lower type.
i us ee.Note: that you could also write the statement as c=b/a; j ¢
conversion, because by default, the compiler will do implicit »,
SOmversion when it encounters a fleat (b) being divided by an ime
this case, it will automatically convert a into a float ay
Se
2.6: Documentation Lines
—
(a). What are documentation lines?
Documentation lines are lines used to explain what the
Program are doing. They help one to be able to read and
Program. They also make the program easy to write and
another programmer can understand the code easier,
There are various techniques that are usually recommended (o he us
by the programmer when coding his program to ensure that the
Programs produced are of good quality. They include the following
and eng,
Seq
(a). Documentation lines
Documentation lines have been explained above in sub-chapter 2.6,
(b). Line spacing
Line spacing is leaving empty lines between sections of codes so as to
Visibly distinguish among the individual sections,
(c). Indenting code
The use of the word Processing feature of leaving indents is also
recommended in programming
Sub-sections of code inside a Particular sect
make them clearly identifiable
this book, all the code insi
1on should be indented 10
For example, in the Programs written it
in() is indented between { and }. In
are identifiable inside a particuli!
© 18 Sy 10 read, debug, wi”ood programming techniques are used below (in sub-
ll se yaa also through out this book a
chapte 2
ao Solved Problems
2.9.1: Problem 1
eS ae
fae mame or the debiigs of the two programs shown in Chapter
one in sections 1.4.3, and 1.6
Solutions
(@), Program to compute area and circumference of a circle.
7 program to compute the area circumference of a circle. *
#include |
ddefine Pi3.14 _// Declare a constant for pi=3.14
void main() |
/( Declare variables to hold the radius, area, circu’
double Radius, Area, Circumference;
ence |
(Input the radius |
printf(“\nlnput the radius”); scanf(“%lf”, &Radius);
/ Compute the area and the circumference
Area=Pi*Radius*Radius; Circumference=2*Pi*Radius;
// output area, circumference
printf(“\nArea: %lf, Circumference: %f”, Area,
Circumference);
) :
0). Program to compute the mean mark of a stude:
/* program to compute the mean mark */
#inelude
Void main()
{ 1 Declarations
double mark1, mark2, mark3, mean;
Input the marks
the first mark ”); scanf(“%If”,
M7fC%IE”, &marid),
“lf”, &mark3);
‘the seeond mark ”
‘printi(\ninput Th nd mark ") sean
printf(“\ninpat
a k
// Compute the mean mar
eres! +mark2+mark3)/3;
ik
// Output the mean mart : 5
oeatie mean mark is %If’, mean);
ja are eer aes
2.9.2: Problem 2
Give all the programming errors in the program below. ag
/* program to compute the mean of three numbers using C an) lage
}Alnclude
void main(); |
{ declare three numbers and the mean
double num1, num2, num3, mean
// input the three numbers
Print{(Input the three numbers”);
seanf(“%IP?, &numt);
seanf(“%If”, &num2);
Seanf(“%6lF”, &num3);
// compute mean
meannum | snum2+num3/3.
// output the sum
Printf“\nThe mean is “Alf”, Mean);
Solution
LINE EREOR
: is a fee should end With 4/ ang t /*
inctegee ot Belude is nor 4 Teserved word, It should be
Syntax errop 1;
«Line shy ‘
Syntax. Ine should not i
error, end with a ‘
Sy Ane should e ae Semi colon.
Logie error. igen smi colon.
be insid
Only num, i the *> quotes,
ded by three. Tt shouldbesyntias error, Mean is not declared. ty
Syntax error: Program does not end with a}
yet Problem 3
Fate & program to input the price and the quantity
Siaien une
¢an item. The program then compute
sel
cio be pale Assume a discount of 5°
* the discount and the
Solution
(a) Problem analysis
Outputs
ey Tee nouns for the sale
Variables
amount
The discount given discount
The total amount to be paid total
). Inputs
Price of an item price
Quantity purchased quantity
(iit). Tasks
1 Input the price and the quantity
HL. Compute the amount, the discount, and the total amount
ME Output the amount, the discount, and the total amount
v). Constant
The discount rate discount_rate=5
(b). Algorithm
@. Pseudo code
Begin
discount_rate=5
Input price, quantity
amount=(price* quantity)
discount=amount*discount_rate/100
‘otl=amount-discount
Output amount, discount, total
19(i, Floweharts
Input price, quantity
amount=price* quantity
discount=amount*discount_rate/100
total=amount-discount
Output amount, discount, total
(c). The program a
/* PROGRAM TO COMPUTE THE SALES AMOUNT Any
THE DISCOUNT */
#include
void main()
{
// Declarations
double price, discount, amount, total;
const float discount_rate=5
int quantity;
I Input the price and the quantity
Print{(“\ntnput the price: ”); scanf(“%lf”, &price);
Print{(“\nlnput the quantity: »); scanf(“%d”, &quantity)
// Computations
amount=price* quantity;
discount= + di :
total=amountedi oo 100;
// Outputtiny— ‘ells the compiler to _
(b), The work of the braces { and } is to __@*\
(©). In, words like main, include are known as
@
The main difference between a variable and a constant is that
(©). The keyword unsigned is used to
(. State the work of the following operators
@. % =p Gill. 4
: (iv). !
@). & ys"
(@. What types of programming errors are the following?
(@. Endless loop
. Using undeclared variable \
ii), Division by zero
(iv), Use of opening double quotes without corresponding
ending quotes
(v). Using wrong formulae to>\°
(h). The keyword bool means
pee ee
(What is the work of the following keywords?
(. char (I). unsigned (UD. const
(V). main (Vb. include
©). What types of data do the following type identifiers represent?
@. %s (ii). %ef (iii). %0
(iv). %i (¥). %[abed}s (vi). %f" Is
(vii). sate (viii). %8.3f (ix), 9054
0). 6d (xi). %09.21F
121