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

c-lecture-notes-2023

C programming

Uploaded by

AbdulGafar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

c-lecture-notes-2023

C programming

Uploaded by

AbdulGafar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

lOMoARcPSD|3603662

C Lecture Notes 2023

computer science- introduction to C language (Olabisi Onabanjo University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Abdulgafar Usman ([email protected])
lOMoARcPSD|3603662

OLABISI ONABANJO UNIVERSITY

DEPARTMENT OF MATHEMATICAL SCIENCES

Harmattan Semester, 2022/2023 Academic Session

CMP 201/211: Computer Programming I (Using C Programming Language)

THIS DOCUMENT IS NOT FOR SALE!

Teaching Team:
Dr. T. J. Odule (Lead)
(Room 12, Department of Mathematical Sciences, Faculty of Science Building)
E-mail: [email protected]

Dr. S. O. Folorunso
(Room 2, Department of Mathematical Sciences, Faculty of Science Building)
E-mail: [email protected]

Dr. L. A. Ogundele
(Room 19, Department of Mathematical Sciences, Faculty of Science Building)
E-mail: [email protected]

Dr. S. O. Hassan
(Room 10, Department of Mathematical Sciences, Faculty of Science Building)
E-mail: [email protected]

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

CHAPTER ONE

INTRODUCTION TO C PROGRAMMING LANGUAGE

1.1 Computer Programming


A computer isn’t smart. Believe it or not, on your worst days, you are still light-years ahead
of your computer in intelligence. Computers are really very dumb machines indeed because they do
only what they are told to do. The computer can’t decide what to do on its own. Computers can’t
think for themselves, so programmers (people who tell computers what to do) must give computers
extremely detailed instructions. Without instructions, a computer is useless; with incorrect
instructions, a computer will not successfully execute your desired task.
A computer program is a series of instructions which enables the computer to perform a
designated task. As this text will demonstrate, a computer must be told what to do in precise, step-
by-step detail. These steps might include obtaining data, arithmetic operations (addition,
subtraction, multiplication, division, etc.), data storage, and information output. The computer will
perform these tasks as instructed, even if they don't always make sense. Consequently, it is the
programmer who must develop a solution to the problem.
To solve a problem using a computer, you must express the solution to the problem in terms
of the instructions of the particular computer. A computer program is just a collection of the
instructions necessary to solve a specific problem. The approach or method that is used to solve the
problem is known as an algorithm. For example, if you want to develop a program that tests if a
number is odd or even, the set of statements that solves the problem becomes the program. The
method that is used to test if the number is even or odd is the algorithm. Normally, to develop a
program to solve a particular problem, you first express the solution to the problem in terms of an
algorithm and then develop a program that implements that algorithm.

1.2 C Programming Language


C is a “higher-level programming language” developed at AT and T’s Bell Laboratories of
USA in 1972. It was designed and written by a man named Dennis Ritchie. C was initially used for
system development work, particularly the programs that make-up the operating system. C was
adopted as a system development language because it produces code that runs nearly as fast as the
code written in assembly language. Some examples of the use of C might be:
a) Operating Systems
b) Language Compilers

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

c) Assemblers
d) Text Editors
e) Print Spoolers
f) Network Drivers
g) Modern Programs
h) Databases
i) Language Interpreters
j) Utilities

1.3 Features of C
a) A knowledge of C will give you deep knowledge of what is going on beneath the surface of
higher- level languages like Java. The syntax of C pretty-well guarantees you will easily
understand other languages that came afterwards like C++, Java, Javascript, and C#.
b) A knowledge of C is now and has been for years a prerequisite for serious software
professionals and with the recent popularity and maturity of Open Systems this is even more
true.
c) C gives you access to the heart of the machine and all its resources at a fine-grained bit-
level.
d) C has been described as like “driving a Porsche with no brakes” - and because it is fast as
well this can be exhilarating. C is often the only option when speed and efficiency is crucial.
e) C has been called “dangerous” in that it allows low-level access to the machine but this
scariness is exactly what you need to understand as it gives you respect for the higher-level
languages you will use.
f) Many embedded miniaturised systems are all still written in C and the machine-to-machine
world of the invisible Internet for monitoring and process control often uses C.
g) C is more efficient than most programming languages.
h) The Linux kernel is scripted using C programming language.
i) When it comes to performance (speed of execution) nothing beats C.

1.4 Operating System


The Operating System, or OS, is an interface between the user and the hardware (CPU, memory,
screen, disk drive, etc.). The OS is responsible for the management of the hardware, coordination of
activities, and the sharing of the resources of the computer that acts as a host for computing
applications run on the machine. The common operating systems include various versions of
Windows, MAC OS X, and UNIX/Linux. Programs written in Fortran programming language will
work on these operating systems.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

1.5 Computer Organization


Before writing programs, it is useful to understand some basics about how a computer is
organised. This section provides a brief, high-level overview of the basic components of a computer
and how they interact.

1.5.1 Architecture overview


The basic components of a computer include a Central Processing Unit (CPU), Primary Storage or
Random Access Memory (RAM), Secondary Storage, and Input/Output devices (i. e., screen,
keyboard, and mouse), and an interconnection referred to as BUS. The secondary storage may be a
Solid-State Drive (SSD), disk drive, or other type of secondary storage media. A very basic diagram
of a computer architecture is pictured in Figure 1.1.

Figure 1.1: Computer Architecture


Programs and data are typically stored on the disk drive. When a program is executed, it must be
copied from the disk drive into the RAM memory. The CPU executes the program from RAM. This
is similar to storing a term paper on the disk drive, and when writing/editing the term paper, it is
copied from the disk drive into memory. When done, the updated version is stored back to the disk
drive.

1.6 Compiler
Programs can be written in the Fortran programming language. However, the CPU does not read C
directly. Instead, the C program that we create will be converted into binary (1's and 0's) by the
compiler. These 1's and 0's are typically referred to as machine language. The CPU will read the
instructions and information, represented in binary as machine language, and perform the
commands from the program.
The compiler is a program itself and is required in order to create the files needed to execute
programs written in C.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

1.7 Program Environment Setup


Programs produce output when you run or execute them. Before you can write and execute a
C program on your computer, you need a C compiler. The C compiler takes the C program you
write and builds or compiles it (technical terms for making the program computer-readable),
enabling you to run the compiled program when you’re ready to look at the results. Luckily, many
excellent free software packages such as Geany, NetBeans, Eclipse are freely available in which
you can edit and compile your C programs.
In this course, we will be using Code::Blocks (available from www.codeblocks.org) is a
single integrated application known as an Integrated Development Environments (IDE). The IDE
allows for processing, editing, compiling, running, and debugging programs.
Though, if you run a search for “C Programming Compilers,” you’ll see a number of
freeware options, including offerings from Borland and Microsoft. In particular, under Windows,
Microsoft Visual Studio is a good example of a popular IDE. Kylix is a popular IDE for developing
applications under Linux.
One good reason for using Code::Blocks however is because it offers versions for Windows,
Macs, and Linux, so you can use a version of the software no matter what operating system you use.
However, feel free to pick whichever programming environment looks best to you.
Code::Blocks is a free, open-source, cross-platform C, C++ and Fortran IDE built to meet
the most demanding needs of its users. It is designed to be very extensible and fully configurable.
The term “open source” refers to software code that users can alter or improve. The term
“cross-platform” is an adjective that means the software can run on different operating systems—as
a beginner, however, you need concern yourself with only your own platform. I think free is a term
we can all get behind, and IDE is short for integrated development environment, which just means
you can write, edit, and debug your programs without having to switch software to do so.

1.7.1 How to download and install Code::Blocks


i. Visit www.codeblocks.org
ii. From the home page, to download the C/C++ IDE, click the Downloads choice under the
Main section in the left column.
iii. After you select Downloads, you are taken to a page that further discusses three options:
Binaries, Source, and SVN. The latter two options are advanced, so you can ignore them.
Click Download the binary release.
iv. The next page presents a variety of options, depending on your operating system. If you
select the Windows option, choose the second option. Having the full compiler and
debugger will come in handy.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

After a successful download and installation, you should be left with the opening screen of the
software, pictured in Figure 1.1.

1.8 The Programming Process


Most people follow these basic steps when writing a program:
(1) Decide exactly what the program should do.
(2) Use an editor to write and save your programming language instructions. An editor is a lot
like a word processor (although not usually as fancy) that lets you create and edit text. All
the popular C compilers include an integrated editor along with the programming language
compiler. All C program filenames end in the .c file extension.
(3) Compile the program.
(4) Check for program errors. If any appear, fix them and go back to step 3.
(5) Execute the program.

Figure 1.1: Welcome to your programming home!

Take some time to explore Code::Blocks or whatever compiler you choose to install on your
computer. A robust IDE lets you perform these five steps easily, all from within the same
environment. You can compile your program, view any errors, fix the errors, run the program, and
look at the results, all from within the same screen and using a uniform set of menus.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

CHAPTER TWO

COMPILING AND RUNNING YOUR FIRST PROGRAM

2.1 Introduction
Here, you are introduced to the C language so that you can understand what actually
programming in C is all about. What better way to gain an appreciation for this language
than by taking a look at an actual program written in C?
To begin with, let us consider an actual program written in C, which is a rather simple
example—a program that displays the phrase “Hello World!” in your window. The C program
below shows how to accomplish this task.
Program 2.1
#include <stdio.h>
int main()
{
/* my first program in C */

printf("Hello, World! \n");

return 0;
}
In the C programming language, lowercase and uppercase letters are distinct. In addition, in
C, it does not matter where on the line you begin typing—you can begin typing your statement at
any position on the line. This fact can be used to your advantage in developing programs that are
easier to read. Tab characters are often used by programmers as a convenient way to indent lines.
Let us take a look at the various parts of the above program:
a) The first line of the program #include <stdio.h> is a preprocessor command which is
usually placed at the beginning of programs, tells a C compiler to include stdio.h
(standard input output header) file (which contains definition and declaration of system
defined function such as printf( ), scanf( ))before going to actual compilation. That is,
information about the standard input/output library will be included.
b) The next line int main() is the main function where the program execution begins and it is
encloses within the pair of curly braces. The abbreviation “int” implies that the main
function returns an integer. The main( ) function can be anywhere in the program but in
general practice it is placed in the first position.
c) The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments (details later) in the program.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

d) The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on your screen. The printf() function is defined in the
C Library - stdio.h include file. The last two characters in the string, namely the backslash
( \ ) and the letter n , are known collectively as the newline character. A newline character
tells the system to do precisely what its name implies — that is, go to a new line. Any
characters to be printed after the newline character then appear on the next line of the
display. In fact, the newline character is similar in concept to the carriage return key on a
typewriter.
All program statements in C must be terminated by a semicolon ( ; ).This is the reason for
the semicolon that appears immediately following the closing parenthesis of the printf call.
e) The next line return 0; terminates the main() function and return to the system a status value
of 0. You can use any integer here. Conventionally, zero is used to indicate that the program
completed successfully — that is, without running into any errors.

2.2 Writing Your First C Program


Open your Code::Blocks programming software. To create your program, Click the File
Menu and select New. Choose Empty File from the options that appear on the submenu. Now
you’ve got a nice clean file to start writing your program. The first (seven-line) program is
extremely simple - a short but complete C program:
Program 2.2
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
After you type in your program, you will need to compile or build your program. To do this,
click the little yellow gear icon in the upper-left corner. If you’ve typed the program in exactly and
had no errors, you can then run the program by clicking the green right-facing arrow next to the
gear. (The next icon in that row, with a gear and arrow, will do both the compiling and running of
the program, simplifying your life by reducing the number of arduous clicks you must perform from
two to one). When you compile (or build) the program and run it, you should see something like
Figure 2.1.

2.3 Comments in C
Throughout a C program, you should add comments. Comments are messages scattered
throughout your programs that explain what’s going on. Comments are not C commands. C ignores

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

every comment in your program. Comments are for people, and the programming statements
residing outside the comments are for the computer. C programs can be cryptic, and comments
eliminate lots of confusion.

2.3.1Specifying Comments in C
(1) Multiline comment style: C multiline comments begin with /* and end with */.
Comments can span several lines in a program, and they can go just about anywhere in a
program. All of the following lines contain C comments:
(a) /* This is a comment that happens to span two lines
before coming to an end */

(b) /* This is a single-line comment */


for (i = 0; i < 25; i++)
/* Counts from 0 to 25 */

Figure 2.1: The output of your first program.


(2) Single line comment style: This style of comment begins with two slashes (//) and ends
only at the end of the line. C ignores the rest of the line after that point.. This kind of
comment was originally developed for C++ programs.
Here is an example of the new style of comment:

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

Program 2.3
// Another Code Example, just with a different commenting style
#include <stdio.h>
main()
{
printf("I like these new comments!"); // A simple statement
}

2.3.2 Importance of Comments in Program Maintenance


Program maintenance is the process of changing a program over time to fix hidden bugs and
to adapt the program to a changing environment.
If you write a program to calculate payroll, the program’s comments explain the gross pay
calculations, state tax calculations, federal tax calculations, social security calculations, deductions,
and all the other calculations that are going on.
The company could eventually change the way it does payroll (to go from biweekly to
weekly, as an example), and you (or another programmer) will have to modify the payroll program
to conform to the company’s new payroll procedures. Commenting speeds program maintenance.
With comments, you or another programmer can quickly scan through a program listing to find the
areas that need changing.
Many programmers like to place a multiline comment before a section of code and then
insert a few smaller comments on lines that need them. Many companies require that their
programmers embed their own names in comments at the top of programs they write. If changes
need to be made to the program later, the original programmer can be found to help.

2.3.4 Whitespace
Whitespace is the collection of spaces and blank lines you find in many programs. In a way,
whitespace is more important than comments in making your programs readable. People need
whitespace when looking through a C program because those programs are more readable than
programs that run together too much.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

CHAPTER THREE

VARIABLES, DATA TYPES, AND


ARITHMETIC EXPRESSIONS IN C

3.1 Variables
The basic concept in a program is the concept of a variable. Today’s programming
languages allow you to concentrate more on solving the particular problem at hand than worrying
about specific machine codes or memory locations. They enable you to assign symbolic names,
known as variable names, for storing program computations and results. A variable name can be
chosen by you in a meaningful way to reflect the type of value that is to be stored in that variable.
The rules for forming variable names are quite simple:They must begin with a letter or
underscore ( _ ) and can be followed by any combination of letters (upper- or lower-case),
underscores, or the digits 0–9.The following is a list of valid variable names.
sum
pieceFlag
i
J5x7
Number_of_moves
_sysflag

On the other hand, the following variable names are not valid for the stated reasons:
sum$value $ is not a valid character.
piece flag Embedded spaces are not permitted.
3Spencer Variable names cannot start with a number.
int int is a reserved word.

It is important to note that there are certain words reserved for doing specific task, these
words are known as reserved word or keywords. These words are predefined and always written in
lower case or small letter. These keywords has special significance to the C compiler and cannot be
used as a variable name as it assigned with fixed meaning. Some examples are int, short,
signed,unsigned, default, volatile, float, long, double, break, continue,
typedef, static, do, for, union, return, while, do, extern, register, enum,
case, goto, struct, char, auto, const etc.
It should be noted that upper- and lowercase letters are distinct in C. Therefore, the variable
names sum , Sum , and SUM each refer to a different variable.

3.2 Storing Data in Variables


The assignment operator puts values in variables. The assignment operator is simply the
equals sign (=). The format of putting data in variables looks like this:

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

variable = data;
The variable is the name of the variable where you want to store data. You must have
defined the variable previously. The data can be a number, character, or mathematical expression
that results in a number. Here are examples of three assignment statements that assign values to the
variables:
answer = 'B';
quantity = 14;
price = 7.95;
You also can store answers to expressions in variables:
price = 8.50 * .65; // Gets price after 35% discount
You can even use other variables in the expression:
totalAmount = price * quantity; /* Uses value from another variable */

3.3 Data Types


The C programming language provides five basic data types: int, float, double, char, and
_Bool.
A variable declared to be of type int can be used to contain integral values only—that is,
values that do not contain decimal places.
A variable declared to be of type float can be used for storing floating-point numbers (values
containing decimal places).
The double type is the same as type float , only with roughly twice the precision.
The char data type can be used to store a single character, such as the letter a, the digit
character 6, or a semicolon (more on this later).
Finally, the _Bool data type can be used to store just the values 0 or 1. Variables of this type
are used for indicating an on/off, yes/no, or true/false situation.
In C, any number, single character, or character string is known as a constant. For example,
the number 58 represents a constant integer value. The character string "Hello World!\n" is an
example of a constant character string.

3.3.1 The Basic Integer Type int


In C, an integer constant consists of a sequence of one or more digits. A minus sign
preceding the sequence indicates that the value is negative. The values 158, –10, and 0 are all valid
examples of integer constants. No embedded spaces are permitted between the digits, and values
larger than 999 cannot be expressed using commas. (So, the value 12,000 is not a valid integer
constant and must be written as 12000).

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

3.3.2 The Floating Number Type float


A variable declared to be of type float can be used for storing values containing decimal
places. A floating-point constant is distinguished by the presence of a decimal point. You can omit
digits before the decimal point or digits after the decimal point, but obviously you can’t omit both.
The values 3. , 125.8 , and –.0001 are all valid examples of floating-point constants.
Floating-point constants can also be expressed in scientific notation. The value 1.7e4 is a
floating-point value expressed in this notation and represents the value 1.7 × 10 –4. The value
before the letter e is known as the mantissa, whereas the value that follows is called the exponent.
This exponent, which can be preceded by an optional plus or minus sign, represents the power of 10
by which the mantissa is to be multiplied. So, in the constant 2.25e–3 , the 2.25 is the value of the
mantissa and –3 is the value of the exponent. This constant represents the value 2.25 × 10 –3 , or
0.00225. Incidentally, the letter e , which separates the mantissa from the exponent, can be written
in either lowercase or uppercase.

3.3.3 The Extended Precision Type double


Type double is very similar to type float, but it is used whenever the range provided by a
float variable is not sufficient. Variables declared to be of type double can store roughly twice as
many significant digits as can a variable of type float. Most computers represent double values
using 64 bits. Unless told otherwise, all floating-point constants are taken as double values by the C
compiler. To explicitly express a float constant, append either an f or F to the end of the number, as
follows:
12.5f

3.3.4 The Single Character Type char


Your computer knows 256 different characters. Each of them is found in something called
the ASCII (American National Standards Institute) table. Anything your computer can represent can
be a character. Any or all of the following can be considered characters:
A a 4 % Q ! + = ]
In C, a char variable can be used to store a single character. A character constant is formed
by enclosing the character within a pair of single quotation marks. So 'A', 'a', '4', '%', '+
', '-' , and '0' are all valid examples of character constants.
None of the following can be character data because they have no apostrophes around them:
A, a, 4, %, and -
Do not confuse a character constant, which is a single character enclosed in single quotes,
with a character string, which is any number of characters enclosed in double quotes. None of the
following are valid characters.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

(a) ‘C is fun’
(b) ‘C is hard’
(c) ‘I should be sailing!’
3.3.5 The Boolean Data Type _Bool
A _Bool variable is defined in the language to be large enough to store just the values 0 and
1 .The precise amount of memory that is used is unspecified. _Bool variables are used in programs
that need to indicate a Boolean condition. For example, a variable of this type might be used to
indicate whether all data has been read from a file.
By convention, 0 is used to indicate a false value, and 1 indicates a true value. When
assigning a value to a _Bool variable, a value of 0 is stored as 0 inside the variable, whereas any
nonzero value is stored as 1.
To make it easier to work with _Bool variables in your program, the standard header file
<stdbool.h> defines the values bool, true, and false.

3.4 Displaying the Value of Variable


The printf routine provides an easy and convenient means to display program results. Not
only can simple phrases be displayed, but the values of variables and the results of computations
can also be displayed. In fact, Program 3.1 uses the printf routine to display the results of adding
two numbers, namely 50 and 25.
Program 3.1 Displaying Variables
#include <stdio.h>
int main (void)
{
int sum;

sum = 50 + 25;
printf ("The sum of 50 and 25 is %i\n", sum);

return 0;
}

In Program 3.1, the first C program statement declares the variable sum to be of type integer.
C requires that all program variables be declared before they are used in a program. The declaration
of a variable specifies to the C compiler how a particular variable will be used by the program. This
information is needed by the compiler to generate the correct instructions to store and retrieve
values into and out of the variable. A variable declared as type int can only be used to hold integral
values; that is, values without decimal places.
The integer variable sum is used to store the result of the addition of the two integers 50 and
25. A blank line was intentionally left following the declaration of this variable to visually separate

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

the variable declarations of the routine from the program statements; this is strictly a matter of style.
Sometimes, the addition of a single blank line in a program can help to make the program more
readable.
The program statement
sum = 50 + 25;
reads as it would in most other programming languages:The number 50 is added (as indicated by
the plus sign) to the number 25 , and the result is stored (as indicated by the assignment operator,
the equal sign) in the variable sum.
The printf routine call in Program 3.1 now has two items or arguments enclosed within the
parentheses. These arguments are separated by a comma. The first argument to the printf routine
is always the character string to be displayed. However, along with the display of the character
string, you might also frequently want to have the value of certain program variables displayed. In
this case, you want to have the value of the variable sum displayed at the terminal after the
characters
“The sum of 50 and 25 is”
are displayed. The percent character inside the first argument is a special character recognised by
the printf function. The character that immediately follows the percent sign specifies what type of
value is to be displayed at that point. In the preceding program, the letter i is recognised by the
printf routine as signifying that an integer value is to be displayed.
Whenever the printf routine finds the %i characters inside a character string, it
automatically displays the value of the next argument to the printf routine. Because sum is the
next argument to printf, its value is automatically displayed after the characters “The sum of 50
and 25 is” are displayed.

3.5 Example on Data Types Usage


In Program 3.1, the basic C data types are used.

Program 3.1 Using the Basic Data Types

#include <stdio.h>
int main (void)
{
int integerVar = 100;
float floatingVar = 331.79;
double doubleVar = 8.44e+11;
charcharVar = 'W';
_Bool boolVar = 0;
printf ("integerVar = %i\n", integerVar);
printf ("floatingVar = %f\n", floatingVar);
printf ("doubleVar = %e\n", doubleVar);
printf ("doubleVar = %g\n", doubleVar);

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

printf ("charVar = %c\n", charVar);


printf ("boolVar = %i\n", boolVar);
return 0;
}

Program 3.1 Output

integerVar = 100
floatingVar = 331.790009
doubleVar = 8.440000e+11
doubleVar = 8.44e+11
charVar = W
boolVar = 0;

3.6 Integers Versus Floating-point Data Types


The choice of using integers or floating-point numbers depends on the data your programs
are working with. Some values (such as ages and quantities) need only integers; other values (such
as money amounts or weights) need the exact amounts floating-point numbers can provide.
Internally, C stores integers differently than floating-point values. As you can see from
Figure 3.1, a floating-point value usually takes twice as much memory as an integer. Therefore, if
you can get away with using integers, do so—save floating points for values that need the decimal
point.

Figure 3.1 Storing floating-point values often takes more memory than integers.

3.7 Working with Arithmetic Expressions


In C, just as in virtually all programming languages, the plus sign ( + ) is used to add two
values, the minus sign ( – ) is used to subtract two values, the asterisk ( * ) is used to multiply two

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

values, and the slash ( / ) is used to divide two values. These operators are known as binary
arithmetic operators because they operate on two values or terms.
Program 3.2 further illustrates the operations of subtraction, multiplication, and division.

Program 3.2 Using the Arithmetic Operators

// Illustrate the use of various arithmetic operators


#include <stdio.h>
int main (void)
{
int a = 100;
int b = 2;
int c = 25;
int d = 4;
int result;
result = a - b;
// subtraction
printf ("a - b = %i\n", result);
result = b * c;
// multiplication
printf ("b * c = %i\n", result);
result = a / c;
// division
printf ("a / c = %i\n", result);
return 0;
}

Program 3.2 Output


a - b = 98
b * c = 50
a / c = 4

3.8 Order of Operators


C doesn’t always compute math operations in the order you expect. Example:
ans = 5 + 2 * 3; /* Puts 11 in ans */
If you thought that C would store 21 in ans, you’re reading the expression from left to right.
However, C always computes multiplication before addition. It sounds crazy, but as long as you
know the rules, you’ll be okay. C is following the order of operators table. C first multiplies 2 and 3
to get 6, and then adds 5 to get 11.
In fact, each operator in C has a precedence associated with it. This precedence is used to
determine how an expression that has more than one operator is evaluated:The operator with the
higher precedence is evaluated first. Expressions containing operators of the same precedence are
evaluated either from left to right or from right to left, depending on the operator. This is known as
the associative property of an operator.
As you can see in the Table 3.1, *, /, and % appear before + and -. Therefore, if C sees an
expression with a combination of these operators, it evaluates *, /, and % before computing + and -.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

Here is a difficult expression. All the variables and numbers are integers. See if you can
figure out the answer by the way C would evaluate the expression:
ans = 5 + 2 * 4 / 2 % 3 + 10 – 3; /* What is the answer? */
Figure 3.2 shows how to solve for the answer, 13.

Figure 3.2 Solving the expression the way C would.

Table 3.1. Order of Operators

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

Program 3.3 Using the Arithmetic Operators Precedence


// Illustrate the use of various arithmetic operators precedence
#include <stdio.h>
int main (void)
{
int a = 100;
int b = 2;
int c = 25;
int d = 4;
int result;
result = a - b;
// subtraction
printf ("a - b = %i\n", result);
result = b * c;
// multiplication
printf ("b * c = %i\n", result);
result = a / c;
// division
printf ("a / c = %i\n", result);
result = a + b * c;
// precedence
printf ("a + b * c = %i\n", result);
printf ("a * b + c * d = %i\n", a * b + c * d);
return 0;
}

Program 3.2 Output


a - b = 98
b * c = 50
a / c = 4
a + b * c = 150
a * b + c * d = 300

3.9 Combining Operations with Assignment: The Assignment Operators


The C language permits you to join the arithmetic operators with the assignment operator
using the following general format: op=
In this format, op is any of the arithmetic operators, including + , – , × , / , and %.
Consider this statement:
count += 10;
The effect of the so-called “plus equals” operator += is to add the expression on the right side of
the operator to the expression on the left side of the operator and to store the result back into the
variable on the left-hand side of the operator. So, the previous statement is equivalent to this
statement:
count = count + 10;
A slightly more involved expression is:
a /= b + c
which divides a by whatever appears to the right of the equal sign—or by the sum of b and c —
and stores the result in a .The addition is performed first because the addition operator has higher

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

precedence than the assignment operator. In fact, all operators but the comma operator have higher
precedence than the assignment operators, which all have the same precedence.
In this case, this expression is identical to the following:
a = a / (b + c)

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

CHAPTER FOUR

PROGRAM LOOPING IN C

4.1 Introduction
A loop is simply a section of code that repeats a few times. You don’t want a loop to repeat
forever— that’s called an infinite loop. The loops you write (if you write them properly—and, of
course, you will) should come to a conclusion when they finish doing the job you set them up to do.
One of the fundamental properties of a computer is its ability to repetitively execute a set of
statements. These looping capabilities enable you to develop concise programs containing repetitive
processes that could otherwise require thousands or even millions of program statements to
perform. The C programming language contains three different program statements for program
looping. They are known as the for statement, the while statement, and the do statement. Each of
these statements are described in detail in this chapter.

4.2 The for Statement


The general format of the for statement is as follows:
for ( init_expression; loop_condition; loop_expression )
program statement;
The three expressions that are enclosed within the parentheses — init_expression,
loop_condition , and loop_expression — set up the environment for the program loop. The
program statement that immediately follows (which is, of course, terminated by a semicolon) can be
any valid C program statement and constitutes the body of the loop. This statement is executed as
many times as specified by the parameters set up in the for statement. The first component of the for
statement, labeled init_expression , is used to set the initial values before the loop begins. The
second component of the for statement the condition or conditions that are necessary for the loop to
continue. In other words, looping continues as long as this condition is satisfied.
Program 4.1 is a sample code to illustrate the usage of the for loop.

Program 4.1
/* Prints 1, 4, 7, 10, 13, 16 */
#include <stdio.h>
main()
{
for (int i = 1; i < 18; i += 3)
{
printf("%d ", i);
}
return 0;
}

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

Program 4.1 Output


1 4 7 10 13 16

Program 4.2
/* Program to calculate the sum of first 200 natural numbers
Introduction of the for statement
*/
#include <stdio.h>
int main (void)
{
int sum;
sum = 0;
for ( int counter = 1; counter <= 200; counter = counter + 1 )
sum = sum + counter;
printf ("The sum of first 200 natural numbers is %i\n", sum);
return 0;
}

Program 4.2 Output


The sum of first 200 natural numbers is 20100

Program 4.3 is an improvement on Program 4.2 whereby the result of each iteration is printed to
the screen
Program 4.3
/* Program to calculate the sum of first 200 natural numbers
Introduction of the for statement
*/
#include <stdio.h>
int main (void)
{
int sum;
sum = 0;
for ( int counter = 1; counter <= 200; counter = counter + 1 )
{ // added to print each iteration
sum = sum + counter;
printf ("The sum of first 200 natural numbers is %i\n", sum);
} // added to print each iteration
return 0;
}

Program 4.3 Output


The sum of first 200 natural numbers is 1
The sum of first 200 natural numbers is 3
The sum of first 200 natural numbers is 6
The sum of first 200 natural numbers is 10
The sum of first 200 natural numbers is 15
The sum of first 200 natural numbers is 21
------
------
The sum of first 200 natural numbers is 20100

4.3 Program Input


Program 4.2 calculates the sum of first 200 natural numbers—and nothing more. If you want
to calculate the sum of first 50 or 100 natural numbers instead, you have to go back and change the

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

program so that the for loop is executed the correct number of times. You also have to change the
printf statement to display the correct message.
An easier solution might be if you could somehow have the program ask the number of
natural numbers you want to calculate. Then, after you provide your answer, the program could
calculate the desired sum for you. Such a solution can be effected in C by using a routine called
scanf. The scanf routine is very similar in concept to the printf routine. Whereas the printf
routine is used to display values at the terminal, the scanf routine enables you to type values into
the program.
Program 4.4 asks the user the number of natural numbers should be calculated, proceeds to
calculate that the sum, and then displays the results.

Program 4.4 Asking the User for Input


/* Program to calculate the sum of first supplied natural numbers
Introduction of the for statement
*/
#include <stdio.h>
int main (void)
{
int sum, number;
sum = 0;

printf ("How many numbers do you want? ");


scanf ("%i", &number);

for ( int counter = 1; counter <= number; counter = counter + 1 )


sum = sum + counter;
printf ("The sum of %i natural numbers is %i\n", number, sum);

return 0;
}

Program 4.4 Output


How many numbers do you want? 200
The sum of 200 natural numbers is 20100

According to the output, the number 200 was typed in by the user. The program then proceeded to
calculate the sum of first 200 natural numbers and displayed the result of 20100 at the terminal. The
user could have instead typed in the number 10, or 30, if he desired to calculate those particular
sum of first natural numbers.

The first printf statement in Program 4.4 is used to prompt the user to type in a number. After
the message is printed, the scanf routine is called. The first argument to scanf is the format string
and is very similar to the format string used by printf. In this case, the format string doesn’t tell

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

the system what types of values are to be displayed but rather what types of values are to be read in
from the terminal. Like printf , the %i characters are used to specify an integer value.
The second argument to the scanf routine specifies where the value that is typed in by the user is
to be stored. The & character before the variable number is necessary in this case. Don’t worry about
its function here, though. Chapter 11, “Pointers,” discusses this character, which is actually an
operator, in great detail. & is called “Pointers” and it is necessary to place it in front of the variable
name in the scanf function call. If you forget, it causes unpredictable results and might cause your
program to terminate abnormally.
Sequel to the fore-going discussion, it can be seen that the scanf call from Program 4.4 specifies
that an integer value is to be read from the terminal and stored in the variable number.
After this number has been typed in (and the “Return” or “Enter” key on the keyboard pressed to
signal that typing of the number is completed), the program then proceeds to perform the
computation.

NOTE:
To display a double value, the format characters %f , %e , or %g characters used to display a
float value, can be used.

4.4 The while Statement

The syntax of this frequently used construct is as follows:


while ( expression )
program statement

The expression specified inside the parentheses is evaluated. If the result of the expression
evaluation is TRUE, the program statement that immediately follows is executed. After
execution of this statement (or statements if enclosed in braces), the expression is once again
evaluated. If the result of the evaluation is TRUE, the program statement is once again executed.
This process continues until the expression finally evaluates as FALSE, at which point the loop is
terminated. Execution of the program then continues with the statement that follows the program
statement.
As an example of its use, Program 4.5 sets up a while loop, which merely counts from 1 to 5.

Program 4.5 Introducing the while Statement


// Program to introduce the while statement
#include <stdio.h>
int main (void)
{

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

int count = 1;
while ( count <= 5 ) {
printf ("%i\n", count);
++count;
}
return 0;
}

Program 4.5 Output


1
2
3
4
5

It is worth noting in passing that Program 4.4 could have readily be accomplished using a for
statement. In fact, a for statement can always be translated into an equivalent while statement,
and vice versa. For example, the general for statement

for ( init_expression; program statement loop_condition; loop_expression )


program statement

can be equivalently expressed in the form of a while statement as

init_expression;
while ( loop_condition )
{
program statement
loop_expression;
}

After you become familiar with the use of the while statement, you will gain a better feel as to
when it seems more logical to use a while statement and when to use a for statement.

4.5 The do-while Statement


The two looping statements discussed so far in this chapter both make a test of the conditions
before the loop is executed. Therefore, the body of the loop might never be executed at all if the
conditions are not satisfied. When developing programs, it sometimes becomes desirable to have
the test made at the end of the loop rather than at the beginning. Naturally, the C language provides
a special language construct to handle such a situation. This looping statement is known as the do-
while statement. The syntax of this statement is as follows:
do
program statement
while ( loop_expression );

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

Execution of the do-while statement proceeds as follows: the program statement is executed
first. Next, the loop_expression inside the parentheses is evaluated. If the result of evaluating the
loop_expression is TRUE, the loop continues and the program statement is once again
executed. As long as evaluation of the loop_expression continues to be TRUE, the program
statement is repeatedly executed. When evaluation of the expression proves FALSE, the loop is
terminated, and the next statement in the program is executed in the normal sequential manner.
The do-while statement is simply a transposition of the while statement, with the looping
conditions placed at the end of the loop rather than at the beginning.
Note that, unlike the for and while loops, the do-while statement guarantees that the body of the
loop is executed at least once.

4.6 Note:

A for loop offers more control than while and do-while. With a for loop, you can specify
exactly how many times you want to loop; with while loops, you must continue looping as long as
a condition is true.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

CHAPTER FIVE

DECISION MAKING IN C

5.1 One of the fundamental properties of a computer is its capability to make decisions

5.2 The if Statement


The C programming language provides a general decision-making capability in the form of a
language construct known as the if statement. The general format of this statement is as follows:
if ( expression )
program statement;

Program 5.1 illustrates the use of if statement.


Program 5.1 if statement usage
//Program to check if the value of x is less than 20
#include <stdio.h>
int main (void)
{
int x=10;
if (x<20);
{
printf("x is less than 20 \n");
}
printf("Value of x is %i", x);

printf ("\n");
return 0;
}

Program 5.1 Output


x is less than 20
Value of x is 10

5.3 The if-else Construct


If someone asks you whether a particular number is even or odd, you most likely make the
determination by examining the last digit of the number. If this digit is either 0, 2, 4, 6, or 8, you
readily state that the number is even. Otherwise, you claim that the number is odd.
An easier way for a computer to determine whether a particular number is even or odd is affected
not by examining the last digit of the number to see if it is 0, 2, 4, 6, or 8, but by simply determining
whether the number is evenly divisible by 2. If it is, the number is even; else it is odd.
The modulus operator % (which compute the remainder of one integer divided by another) is a
perfect operator to use in determining whether an integer is evenly divisible by 2. If the remainder
after division by 2 is zero, it is even; else it is odd.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

Look at Program 5.2—a program that determines whether an integer value typed in by the user is
even or odd and that displays an appropriate message at the terminal.

Program 5.2 Determining if a Number Is Even or Odd


//Program to determine if a number is even or odd
#include <stdio.h>
int main (void)
{
int number_to_test, remainder;
printf ("Enter your number to be tested: ");
scanf ("%i", &number_to_test);
remainder = number_to_test % 2; //modulus operator % in use
if ( remainder == 0 )
printf ("The number is even.\n");
if ( remainder != 0 )
printf ("The number is odd.\n");
return 0;
}

Program 5.2 Output


Enter your number to be tested: 55
The number is odd.

Program 5.2 Output (Rerun)


Enter your number to be tested: 12
The number is even.

After the number is typed in, the remainder after division by 2 is calculated. The first if
statement tests the value of this remainder to see if it is equal to zero. If it is, the message “The
number is even” is displayed.
The second if statement tests the remainder to see if it’s not equal to zero and, if that’s the case,
displays a message stating that the number is odd.
When writing programs, this “else” concept is so frequently required that almost all modern
programming languages provide a special construct to handle this situation. In C, this is known as
the if-else construct and the general format is as follows:
if
( expression )
program statement 1
else
program statement 2

The if-else is actually just an extension of the general format of the if statement. If the result of
the evaluation of expression is TRUE, program statement 1 , which immediately follows, is
executed; otherwise, program statement 2 is executed. In either case, either program statement 1 or
program statement 2 is executed, but not both.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

You can incorporate the if-else statement into Program 5.2, replacing the two if statements with a
single if-else statement. The use of this new program construct actually helps to reduce the
program’s complexity and also improves its readability, as shown in Program 5.3.

Program 5.3 Revising the Program to Determine if a Number Is Even or Odd


// Program to determine if a number is even or odd (Version 2)
#include <stdio.h>
int main ()
{
int number_to_test, remainder;
printf ("Enter your number to be tested: ");
scanf ("%i", &number_to_test);
remainder = number_to_test % 2;
if ( remainder == 0 )
printf ("The number is even.\n");
else
printf ("The number is odd.\n");
return 0;
}

Program 5.3 Output


Enter your number to be tested: 168
The number is even.

Program 5.3 Output (Rerun)


Enter your number to be tested: 57
The number is odd.

5.4 Compound Relational Tests


The if statements discussed so far in this chapter is used to set up a simple relational tests between
two numbers. Sometimes, it becomes desirable, if not necessary, to set up more sophisticated tests.
The C language provides the mechanisms necessary to perform these types of compound
relational tests. A compound relational test is simply one or more simple relational tests joined by
either the logical AND or the logical OR operator. These operators are represented by the character
pairs && and || (two vertical bar characters), respectively. As an example, the C statement
Example:
a) (5==5) &&(3>6) //False
b) (5==5) || (3>6) //True
c) (8 = = 6*2) || (12 > 15) // False
d) !True //means False
e) !False //means True
f) !(5==5) //False
g) !(6<=4) //True

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

5.5 The else if Construct


As can be seen from the previous discussions that the else statement comes into play when a
decision is to be made between two possible conditions. However, real programming decisions are
not always so black-and-white.
Consider the task of writing a program that displays –1 if a number typed in by a user is less than
zero, 0 if the number typed in is equal to zero, and 1 if the number is greater than zero. (This is
actually an implementation of what is commonly called the sign function.) Obviously, you must
make three tests in this case—to determine if the number that is keyed in is negative, zero, or
positive. Our simple if-else construct does not work. Of course, in this case, you could always
resort to three separate if statements, but this solution does not always work in general—especially
if the tests that are made are not mutually exclusive.
You can handle the situation just described by adding an if statement to your else clause.
Because the statement that followed an else can be any valid C program statement, it seems logical
that it can be another if .Thus, in the general case, you could write
if ( expression 1 )
program statement 1
else
if ( expression 2 )
program statement 2
else
program statement 3

which effectively extends the if statement from a two-valued logic decision to a three-valued
logic decision. You can continue to add if statements to the else clauses, in the manner just shown,
to effectively extend the decision to an n-valued logic decision.
The preceding construct is so frequently used that it is generally referred to as an else if
construct and is usually formatted differently from that shown previously as
if ( expression 1 )
program statement 1
else if ( expression 2 )
program statement 2

else
program statement 3

This latter method of formatting improves the readability of the statement and makes it clearer
that a three-way decision is being made.
5.4 DIY:
(a) Write a program to implement the sign function explained
(b) Write a program to illustrate the grade of a student in an examination.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

CHAPTER SIX

POINTERS IN C

6.1 Introduction to Pointers

Pointer variables, often called pointers, let you do much more with C than you can with
programming languages that don’t support pointers. In fact, one of the most sophisticated features
of C programming is the pointer and provides the means for the true power of C.
Pointers operate based on the concept of indirection. A pointer provides an indirect means of
accessing the value of a particular data item.

6.2 Memory Addresses


Inside your computer is a bunch of memory. The memory holds your program as it executes, and
it also holds your program’s variables. Just as every house has a different address, every memory
location has a different address. Not coincidentally, the memory locations have their own addresses
as well. As with house addresses, the memory addresses are all unique; no two are the same.
When you define variables, C finds an unused place in memory and attaches a name to that
memory location. That’s a good thing. Instead of having to remember that an variable named
orderNum is stored at memory address 34532, you only have to remember the name orderNum. The
name orderNum is much easier to remember than a number.

6.3 Defining a Pointer Variable


As with any other type of variable, you must define a pointer variable before you can use it. Two
key operators are used:
a) & which represents “address-of” operator
b) * which represents “dereferencing” operator

Pointer variables hold addresses of other variables. That’s their primary purpose. Use the address-of
operator, &, to assign the address of one variable to a pointer. Until you assign an address of a
variable to a pointer, the pointer is uninitialized and you can’t use it for anything.
But enough talk—it’s time to see how pointers actually work. The following code defines an integer
variable named age and stores 19 in age. Then a pointer named variable pAge is defined and
initialized to point to age. The address-of operator reads just like it sounds. The second line that
follows tells C to put the address of age into pAge.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

int age = 19; /* Stores a 19 in age */


int *pAge = &age; /* Links up the pointer to another variable */

You have no idea exactly what address C will store age at. However, whatever address C uses, pAge
will hold that address. When a pointer variable holds the address of another variable, it essentially
points to that variable. Assuming that age is stored at the address 18826 (only C knows exactly
where it is stored), Figure 6.1 pictures this concept.

Figure 6.1 The variable pAge points to age if pAge holds the address of age.

It should be noted that the asterisk, * dereferencing operator isn’t part of a pointer variable’s
name. It is simply used to tell C that the variable is a pointer, not a regular variable. The following
four statements do exactly the same thing as the previous two statements. Notice that you don’t use
* to store the address of a variable in a pointer variable unless you are also defining the pointer at
the same time.
int age; // Defines a regular integer
int * pAge; // Defines a pointer to an integer
age = 19; //Stores 19 in age
pAge = &age; // Links up the pointer to another variable, age

6.4 Using the Dereferencing *


As soon as you link up a pointer to another variable, you can work with the other value by
dereferencing the pointer. Dereferencing just means that you use the pointer to get to the other
variable. When you dereference, use the * dereferencing operator. In a nutshell, here are two ways
to change the value of age (assuming that the variables are defined as described earlier):
a) age = 25; and

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

b) *pAge = 25; /* Stores 25 where pAge points */


This assignment tells C to store the value 25 at the address pointed to by pAge. Because pAge
points to the memory location holding the variable age, 25 is stored in age. Therefore, pAge
pointer variable is used in the program to indirectly access the content (or value) of age.
Program 6.1, which illustrates the two fundamental pointer operators: the address operator, & , and
the indirection operator, * .
Program 6.1 Illustrating Pointers
// Program to illustrate pointers
#include <stdio.h>
int main (void)
{
int x=70;
int *int_pointer;
int_pointer = &x;
*int_pointer =45;
printf ("The value of x is %i\n", x);
return 0;
}

Program 6.1 Output


The value of x is 45

6.5 Using Pointers in Expressions

Program 6.2 Using Pointers in Expressions


// More on pointers
#include <stdio.h>
int main (void)
{
int i1, i2;
int *p1, *p2;
i1 = 5;
p1 = &i1;
i2 = *p1 / 2 + 10;
p2 = p1;
printf ("i1 = %i, i2 = %i, *p1 = %i, *p2 = %i\n", i1, i2, *p1, *p2);
return 0;
}
Program 6.2 Output
i1 = 5, i2 = 12, *p1 = 5, *p2 = 5

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

CHAPTER SEVEN

ARRAYS IN C

7.1 Introduction
This chapter teaches how C’s array and pointer variables share a lot of principles. As a matter of
fact, an array is a special kind of pointer. Because of their similarities, you can use pointer notation
to get to array values, and you can use array notation to get to pointed-at values.

7.2 An Array
An array is a series of elements of the same type placed in contiguous memory locations that can
be individually referenced by adding an index to a unique identifier. An array of characters is a
string. An array can also be described as a data structure used to group together data items of the
same type. That is, a collection of variables of the same type. Each element has a different index
number known as subscript.
The format for representing an array is:
type array_name [arraySize];
The items in an array are called elements.
As an example, the declaration
int values [10];
reserves enough space for an array called values that could hold up to 10 integer elements. You
can better conceptualize this reserved storage space by referring to Figure 7.1.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

Figure 7.1 The array values in memory.


The elements of an arrays declared to be of type int , float , or char can be manipulated in
the same fashion as ordinary variables. You can assign values to them, display their values, add to
them, subtract from them, and so on.
It is important to note that an array variable can store more than one value at a time where other
variable can store one value at a time.

7.3 Initialisation of Arrays


Just as you can assign initial values to variables when they are declared, so can you assign initial
values to the elements of an array. Elements of an array can be initialised in either of two ways: one
by one or using a single statement.
Example:
a) int numbers [5] ={16, 2, 7, 4, 12};
b) int numbers [ ] = {16, 2, 7, 4, 12};
c) int numbers [5];
numbers [0] = 16;
numbers [1] = 2;
numbers [2] = 7;
numbers [3] = 4;
numbers [4] = 12;
It is important to state here that numbering of elements always starts at 0 in C programming.
Therefore, the five elements in the array above is indexed by the numbers 0, 1, 2, 3, 4.

7.4 Working with Arrays


Program 7.1 illustrates an array that stores five numbers and add them up

Program 7.1
//Program to stores five numbers and add them up

#include <stdio.h>
int main (void)
{
int array_values[5] = { 16, 1, 4, 9, 5 };
int sum=0;
for ( int i = 0; i < 5; ++i )
sum = sum + array_values[i];
printf ("Sum is %i\n", sum);
return 0;
}

Program 7.1 Output


Sum is 35

Program 7.2 illustrates an array that stores five numbers, add them up and find the average.

Program 7.2
//Program to stores five numbers, add them up and find the average
#include <stdio.h>
int main (void)
{
int array_values[5] = { 16, 1, 4, 9, 5 };

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

int sum=0;
int avg=0;
for ( int i = 0; i < 5; ++i )
sum = sum + array_values[i];
avg = sum /5;
printf ("Sum = %i, Average = %i\n", sum, avg);
return 0;
}

Program 7.2 Output


Sum = 35, Average = 7

7.5 Character Arrays


The purpose of Program 7.3 is to simply illustrate how a character array can be used. However,
one point is worthy of discussion.

Program 7.3 Introducing Character Arrays


#include <stdio.h>
int main (void)
{
char word[] = { 'H', 'e', 'l', 'l', 'o', '!' };
for ( int i = 0; i < 6; ++i )
printf ("%c", word[i]);
printf ("\n");
return 0;
}

Program 7.3 Output


Hello!

7.6 Multidimensional Arrays


The types of arrays that you have been exposed to so far are all linear arrays—that is, they all
dealt with a single dimension. The C language allows arrays of any dimension to be defined. In this
section, a two-dimensional arrays will be discussed.
One of the most natural applications for a two-dimensional array arises in the case of a matrix.
The format to declare a two-dimensional array of size x, y is as follows:
type array_name [x][y];
This array declares x number of rows and y number of columns. A two-dimensional integer array
called num which contains three rows and four columns is declared as:
int num [3][4];
Therefore, every elements in the array num is identified by an element name of the form num[i][j],
where i and j are the subscripts that uniquely identify each element in num.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

7.7 Initialising a Two-Dimensional Arrays


Just as you can assign initial values to elements of a single dimensional array, so can you assign
initial values to the elements of a 2-dimensional array. Elements of the array can be initialised in
either of two ways: one by one or using a single statement.
Example:
(a) int numbers [3][4] ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
(b) int numbers [3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12};
};

Therefore, elements of the 2-dimensional can be easily accessed. Example:

num[2][1] =5;

7.8 DIY
a) Write a program to compute the maximum and minimum of an array elements.
b) Write a program for an array that stores prime numbers up to 50
c) Write a program to sum up the diagonal elements of a square matrix A.
d) Write a program to display all elements of an initialised 2-dimensional array.
e) Write a program that display alphabets stored in a 2-dimensional array of size 3 by 4.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

CHAPTER EIGHT

HEAP: MAXIMIZING YOUR COMPUTER’S MEMORY

8.1 Introduction
The heap is the collection of unused memory in your computer. The memory left over—after
your program, your program’s variables, and your operating system’s workspace—comprises your
computer’s available heap space, as Figure 8.1 shows.

Figure 8.1 The heap is unused memory.

Many times you’ll want access to the heap, because your program will need more memory than
you initially defined in variables and arrays. The free heap memory is called free heap or
unallocated heap memory. The part of the heap in use by your program at any one time is called the
allocated heap. Your program might use varying amounts of heap space as the program executes.
You don’t assign variable names to heap memory. The only way to access data stored in heap
memory is through pointer variables. Aren’t you glad you learned about pointers already? Without
pointers, you couldn’t learn about the heap.

8.2 Thinking of the Heap


Heap is—the unused section of contiguous memory. If you allocate 10 bytes of heap memory at
once, those 10 bytes will be contiguous. You’ll more quickly grasp how to use the heap if you think
of the heap as just one big heap of free memory stacked up in a pile. You’ll be allocating (using) and
deallocating (freeing back up) heap memory as your program runs.
Your operating system uses heap memory along with your program. If you work on a networked
computer or use a multitasking operating environment such as Windows, other tasks might be
grabbing heap memory along with your program.
You have to keep track of the memory you allocate. You do this with pointer variables. For
instance, if you want to allocate 20 integers on the heap, you use an integer pointer. If you want to
allocate 400 floating-point values on the heap, you use a floating-point pointer. The pointer always
points to the first heap value of the section you just allocated. Therefore, a single pointer points to

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

the start of the section of heap you allocate. If you want to access the memory after the first value
on the heap, you can use pointer notation or array notation to get to the rest of the heap section you
allocated.

8.2 But Why Do I Need the Heap?


Okay, before learning exactly how you allocate and deallocate heap memory, you probably want
more rationalization about why you even need to worry about the heap. After all, the variables,
pointers, and arrays you’ve learned about so far have sufficed nicely for program data.
The heap memory does not always replace the variables and arrays you’ve been learning about.
The problem with the variables you’ve learned about so far is that you must know in advance
exactly what kind and how many variables you will want. Remember, you must define all variables
before you use them. If you define an array to hold 100 customer IDs, but the user has 101
customers to enter, yourprogram can’t just expand the array at runtime. Some programmers (like
you) have to change the array definition and recompile the program before the array can hold more
values. With the heap memory, however, you don’t have to know in advance how much memory you
need.

For one thing, memory is one of the most precious resources in your computer. As we move into
networked and windowed environments, memory becomes even more precious. Your programs
can’t allocate huge arrays for those rare occasions when a user might need that much memory. Your
program would solely use all that memory, and other tasks could not access that allocated memory.

8.3 How Do I Allocate the Heap?

You must learn only two new functions to use the heap. The malloc() (for memory
allocate)function allocates heap memory, and the free() function deallocates heap memory. Note:
be sure to include the stdlib.h header file in all the programs you write that use malloc() and
free().

Perhaps looking at an example of malloc() is the best place to start. Suppose you were writing a
temperature-averaging program for a local weather forecaster. The more temperature readings the
user enters, the more accurate the correct prediction will be. You decide that you will allocate 10
integers to hold the first 10 temperature readings. If the user wants to enter more, your program can
allocate another batch of 10, and so on.
You first need a pointer to the 10 heap values. The values are integers, so you need an integer
pointer. You need to define the integer pointer like this:
int * temps; /* Will point to the first heap value */

Here is how you can allocate 10 integers on the heap using malloc():

temps = (int *) malloc(10 * sizeof(int));

The previous line included the following malloc() function call:

malloc(10 * sizeof(int))

This part of the statement told malloc() to allocate, or set aside, 10 contiguous integer locations
on the heap. In a way, the computer puts a fence around those 10 integer locations so that
subsequent malloc() calls do not intrude on this allocated memory. Now that you’ve mastered that
last half of the malloc() statement, there’s not much left to understand. The first part of malloc()
is fairly easy.

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

malloc() always performs the following two steps (assuming that enough heap memory exists
tosatisfy your allocation request):
1. Allocates the number of bytes you request and makes sure no other program can overwrite
that memory until your program frees it
2. Assigns your pointer to the first allocated value

Figure 8.2 shows the result of the previous temperature malloc() function call. As you can see
from the figure, the heap of memory (shown here as just that, a heap) now contains a fenced-off
area of 10 integers, and the integer pointer variable named temps points to the first integer.
Subsequent malloc() function calls will go to other parts of the heap and will not tread on the
allocated 10 integers.

Figure 8.2 After allocating the 10 integers.

The malloc() allocation still has one slight problem. There is a need to explain the left portion
of the temperature malloc(). What is the (int *) for?
The (int *) is a typecast. To convert a float value to an int, you place (int) before the
floating-point value, like this:

aVal = (int)salary;

The * inside a typecast means that the typecast is a pointer typecast. malloc() always returns a
character pointer. If you want to use malloc() to allocate integers, floating points, or any kind of
data other than char, you have to typecast the malloc() so that the pointer variable that receives
the allocation (such as temps) receives the correct pointer data type. temps is an integer pointer; you
should not assign temps to malloc()’s allocated memory unless you typecast malloc() into an
integer pointer.
Therefore, the left side of the previous malloc() simply tells malloc() that an integer pointer, not
the default character pointer, will point to the first of the allocated values.

Here comes the big question. What do you do with the 10 integers you just allocated? Treat them
like an array! You can store data by referring to temps[0], temps[1], and so on. Also
remember that each set of allocated memory will be contiguous, so the 10 integers will follow each
other just as if you allocated temps as a 10-integer array.

8.4 If There’s Not Enough Heap Memory


In extreme cases, not enough heap memory might exist to satisfy malloc()’s request. The
user’s computer might not have a lot of memory, another task might be using a lot of memory, or

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

your program might have previously allocated everything already. If malloc() fails, its pointer
variable points to a null value, 0. Therefore, many programmers follow a malloc() with an if,
like this

temps = (int *) malloc(10 * sizeof(int));


if (temps == 0)
{
printf("Oops! Not Enough Memory!\n");
exit(1); // Terminate the program early
}
// Rest of program would follow...

Programmers often use the not operator, !, instead of testing a value against 0, as done
here. Therefore, the previous if test would more likely be coded like this:

if (!temps) /* Means, if not true */

8.4 Freeing Heap Memory

When you’re done with the heap memory, give it back to the system. Use free() to do that.
free() is a lot easier than malloc(). To free the 10 integers allocated with the previous
malloc(), use free() in the following manner:

8.5 Illustration
Program 8.2 illustrates a heap that stores five numbers, add them up and find the average.

Program 8.2
/*Program to stores five numbers, add them up and find the average
using heap */

#include <stdio.h>
#include <stdlib.h>

int main (void)


{

int *ptemps; //ptemp declared as a pointer variable

ptemps = (int *) malloc (100 * sizeof (int)); // malloc () function

if (!ptemps)
{
printf("Oops! Not Enough Memory! \n");
exit(1);
}
ptemps[0] = 197;
ptemps[1] = 100;
ptemps[2] = 350;
ptemps[3] = 153;
ptemps[4] = 453;

int sum=0, avg=0;

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

for ( int i = 0; i <= 5; ++i )


sum = sum + ptemps[i];
avg=sum/5;
printf ("Sum is %i\n", sum);
printf ("Average is %i\n", avg);

free(ptemps);

return 0;
}

Program 8.2 Output


Sum is 1253
Average is 250

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

CHAPTER NINE

FUNCTIONS IN C PROGRAMMING LANGUAGE

9.1 Introduction

Function is an essential component of the C programming language. In fact, every C program has
a function therein, at least the main () funcion. The scanf () and printf () routines used so far
are also functions. Basically, program function provides the mechanism for producing programs that
are easy to write, read, understand, debug, modify, and maintain.

9.2 Functions

A function is a self contained block of codes or sub programs with a set of statements that
perform some specific task or coherent task when it is called. It can be described as hiring a person
to do some specific task like, every six months servicing a car and hand over to it.
By using functions, large and difficult program can be divided in to sub programs and solved.
When we want to perform some task repeatedly or some code is to be used more than once at
different place in the program, then function avoids this repetition or rewritten over and over.

9.3 Types of Function in C

There are basically two types of function. They are:


a) Standard (or library or system defined) function and
b) User defined function

9.3.1 System defined function


The system defined function can’t be modified, it can only read and can be used. These
function are supplied with every C compiler Source of these library function are precomplied and
only object code get used by the user by linking to the code by linker
Here the system defined function consists of three components:
i. Function definition : predefined, precompiled, stored in the library
ii. Function declaration : In header file with or function prototype.
iii. Function call : By the programmer

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

9.3.2 User defined functions


The user defined functions defined by the user according to its requirement and function
consists of three components:

i. Function declaration:

Function declaration is also known as function prototype declaration. It inform the compiler
about three thing, those are name of the function, number and type of argument received by
the function and the type of value returned by the function.
While declaring the name of the argument is optional and the function prototype always
terminated by the semicolon.
If a function returns any value other than int, you should prototype that function. Actually,
you should prototype functions that return integers as well for clarity.
The word prototype means a model of something else. A prototype of a function is just a
model of the actual function.
The reason functions that return int values don’t need prototypes is that int is the default
prototyped return value unless you specify a different return value. Therefore, these two
prototypes both model the same function:

int function(type1 arg1, type2 arg2) /* 2 passed, one integer returned */


and
function(type1 arg1, type2 arg2); /* 2 passed, one integer returned */
Prototypes aren’t required if you don’t return a value or if you return an integer value, but
they are strongly recommended.
To prototype a function, place an exact duplicate of the function’s first line somewhere
before main().
If your program calls 20 functions, you should have 20 prototypes.
ii. Function definition:-
Function definition consists of the whole description and code of the function. It tells about
what function is doing what are its inputs and what are its output. It consists of two parts
function header and function body.

Syntax:-
return_type function(type 1 arg1, type2 arg2, type3 arg3) /*function header*/
{
Local variable declaration;
Statement 1;
Statement 2;
Return value;
}

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

The return_type denotes the type of the value that function will return and it is optional and if it
is omitted, it is assumed to be int by default. The body of the function is the compound statements
or block which consists of local variable declaration statement and optional return statement.
Note that the local variables declared inside a function is local to that function only. It can’t be
used anywhere in the program and its existence is only within this function. The arguments of the
function definition are known as formal arguments.

iii. Function Call:


When the function get called by the calling function then that is called, function call. The
compiler execute these functions when the semicolon is followed by the function name.
Example:
function(arg1,arg2,arg3);
The argument that are used inside the function call are called actual argument
Example:
int S=sum(a, b); //actual arguments
Actual argument
The arguments which are mentioned or used inside the function call is knows as actual argument
and these are the original values and copy of these are actually sent to the called function. It can be
written as constant, expression or any function call like
Function (x);
Function (20, 30);
Function (a*b, c*d);
Function(2,3,sum(a, b));

9.4 Formal Arguments


The arguments which are mentioned in function definition are called formal arguments or dummy
arguments. These arguments are used to just hold the copied of the values that are sent by the
calling function through the function call. These arguments are like other local variables which are
created when the function call starts and destroyed when the function ends.
It is vital to note that the order number and type of actual arguments in the function call should
match with the order number and type of the formal arguments in the function definition.

These three user defined function components are illustrated as follows:

int function(int, int, int); /*function declaration*/

main()
{
function(arg1,arg2,arg3); /* calling function */
}

int function(type 1 arg 1,type2 arg2, type3, arg3) /* function definition */

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

{
Local variable declaration;
Statement;
Return value;
}

9.5 Return type


The C language provides you with a convenient mechanism whereby the results of a function can
be returned to the calling function. The general syntax of this construct is straightforward enough:

return expression;

This statement indicates that the function is to return the value of expression to the calling
routine. Parentheses are placed around expression by some programmers as a matter of
programming style, but their use is optional.

Example:

return a;
return a*b;
return (a*b+c);

An appropriate return statement is not enough. When the function declaration is made, you must
also declare the type of value the function returns. This declaration is placed immediately
before the function’s name.
Each of the previous examples discussed hitherto defined the function main to return an integer
value, which is why the keyword int is placed directly before the function name.
In a sense, the void data type is actually defining the absence of a data type. Therefore, a
function declared to be of type void has no value and cannot be used as if it does have a value in
an expression.

9.6 Functions and Arrays

For your first program that illustrates a function that takes an array as an argument, you can write
a function minimum to find the minimum value in an array of 10 integers. This function, together
with a main routine to set up the initial values in the array, is shown in Program 8.9.

Program 9.9 Finding the Minimum Value in an Array


// Function to find the minimum value in an array
#include <stdio.h>
int minimum (int values[10])
{
int minValue, i;
minValue = values[0];

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

for ( i = 1; i < 10; ++i )


if ( values[i] < minValue )
minValue = values[i];
return minValue;
}
int main (void)

{
int scores[10], i, minScore;

int minimum (int values[10]);


printf ("Enter 10 scores\n");

for ( i = 0; i < 10; ++i )


scanf ("%i", &scores[i]);
minScore = minimum (scores);
printf ("\nMinimum score is %i\n", minScore);

return 0;
}

Program 9.9 Output


Enter 10 scores
1
2
3
4
5
6
7
8
9
10
Minimum score is 1

Downloaded by Abdulgafar Usman ([email protected])


lOMoARcPSD|3603662

Downloaded by Abdulgafar Usman ([email protected])

You might also like