0% found this document useful (0 votes)
4 views34 pages

Programming Methodology Lecture Notes

The document provides an overview of computer programming, focusing on the C programming language, its structure, and characteristics of good programs. It explains the roles of compilers and interpreters, outlines the development cycle of a C program, and details the components of C programs, including variables, functions, and control flow constructs. Additionally, it emphasizes the importance of readability, maintainability, and usability in programming, along with the significance of comments and variable naming conventions.

Uploaded by

vincent mugendi
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)
4 views34 pages

Programming Methodology Lecture Notes

The document provides an overview of computer programming, focusing on the C programming language, its structure, and characteristics of good programs. It explains the roles of compilers and interpreters, outlines the development cycle of a C program, and details the components of C programs, including variables, functions, and control flow constructs. Additionally, it emphasizes the importance of readability, maintainability, and usability in programming, along with the significance of comments and variable naming conventions.

Uploaded by

vincent mugendi
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

INTRODUCTION

Most often we use computers to perform certain tasks to solve problems. At its most
basic level, programming a computer simply means telling it what to do. This can be
achieved through writing concise instructions for the computer in form of a program.
Therefore, a computer program is a set of instructions written by a programmer to solve
user problems on the computer. In general, a program consists of a sequence of
statements (instructions) that commands a computer to carry out a defined task or job.

It is important to note that computers can only understand a machine (object) language.
Therefore, to run the program, the source code has to be translated into terms the
computer can understand. In this case, interpreters and compilers are used to translate
these instructions into the computer language.

An interpreter translates a program as it reads it, turning the program instructions or code,
directly into actions. On the other hand, a compiler translates the code into an
intermediary form. This step is called compiling, and it produces an object file. The
compiler then invokes a linker, which turns the object file into an executable program.

Some languages such as Visual Basic, call the interpreter the runtime library. Java calls
its runtime interpreter a Virtual Machine (VM), which is provided by the browsers (such
as Internet explorer or Netscape).

Both C and C++ are compiled languages. This means that the programs you write are
translated, by a program called a compiler, into executable machine-language programs
which you can actually run. Executable machine-language programs are self-contained
and run very quickly. Since they are self-contained, you don't need copies of the source
code (the original programming-language text you composed) or the compiler in order to
run them; you can distribute copies of just the executable and that's all someone else
needs to run it. Since they run relatively quickly, they are appropriate for programs which
will be written once and run many times.

A compiler is a special kind of program that builds other programs. When you invoke the
compiler (which is a program), it reads the programming language statements that you
have written and turn them into a new, executable program. The executable program runs
without a compiler. However, if you give a copy of an interpreted program to someone
else, they would also need a copy of the interpreter to run it.

The big advantage of an interpreted language is that your program runs right away; you
don't have to perform--and wait for--the separate tasks of compiling and then running
your program. (Actually, on a modern computer, neither compiling nor interpreting takes
much time, so some of these distinctions become less important.)

Actually, whether a language is compiled or interpreted is not always an inherent part of


the language. There are interpreters for C, and there are compilers for Java.
Characteristics a “good ‘’program

When writing a computer program, one needs to make programs that are easier users use,
because most people use computers as tools for solving their business problems without
any technical knowledge about how computers and programs work. Therefore, a “good”
should have the following characteristics:

1. Readability

The code in the program must be well laid out and explained using comments.

2. Maintainability

The program must be easy to modify, having good structuring and documentation.

3. Usability

The program must be easy to use and self-documenting.

4. Robustness

The program should cope with invalid data without creating errors or stopping
without any indication of the cause.

5. Efficiency

The program must utilize available storage space and resources in such a way that
the systems speed is not wasted.

6. Reliability

The program must ALWAYS do what its supposed to do without failing.

7. Accuracy

The program must do what it is supposed to do, and meet the criteria laid down in
its specification
About C Language

C is a general-purpose, structured programming language. The principal idea behind


structured programming is as simple as the idea of divide and conquer. In a C program
can be thought of as consisting of a set of tasks. Any task that is too complex to be
described simply is broken down into a set of smaller component tasks, until the tasks are
sufficiently small and self-contained enough that they are easily understood.

The C language is very flexibe, allowing it to be used for systems programming (e.g. for
writing operating systems) as well as for applications programming (e.g. for writing
programs to solve real-life problems).

The ANSI Standard

The Accredited Standards Committee, operating under the procedures of the American
National Standards Institute (ANSI), has created an international standard for C. This
standard is an attempt to ensure that C is portable (ensuring, for example, that ANSI-
standard-compliant code compiles without errors on any compiler). We will ensure that
all written codes in this course are ANSI compliant.

The development cycle of a C program

The following are steps outlined in the development of a C program:

Writing the program


Compiling the source code
Linking the program
Run program.

Writing a C program

To create a source file (a text file containing a program, written in a programming


language), you need a text editor (a software system that allows you to create and edit
text files on your computer) such a WordPad, Notepad, Brief, Epsilon, EMACS, the DOS
edit command and vi. Note that using a full-fledged text editor makes it difficult for the
compiler to understand its formatting codes. However, some compilers such as Turbo C,
Borland C++ Builder, Metrowerks CodeWarrior, and Microsoft Visual C++ are IDE
(Integrated Development Environments) because they include their own specialized text
editors and debuggers.
Compiling a C program

To turn your source code into a program, you use a compiler (a system software that
translates programs in a programming language into the machine language called binary
code). The computer’s operating system can then run this compiled program. When your
press ctrl+F9 you supply the source file to the compiler, which creates an object file
containing machine-language instructions corresponding to your program. Your program
is not ready to run yet, however: if you called any functions which you didn't write (such
as the standard library functions provided as part of a programming language
environment), you must arrange for them to be inserted into your program, too.
Therefore, an object file contains “holes” that needs to be filled up.

Creating an Executable File with the Linker

Linking the object files with one or more libraries typically creates C programs. The task
of combining object files together, while also locating and inserting any library functions,
is the job of the linker. The linker puts together the object files you give it, noticing if you
call any functions which you haven't supplied and which must therefore be library
functions. It then searches one or more library files (a library file is simply a collection of
object files) looking for definitions of the still-unresolved functions, and pulls in any that
it finds. When you run the linker to turn the object file into an executable program, it
either builds the final (executable file) or if there were any errors (such as a function
called but not defined anywhere) complains.

The Anatomy of a C Program

C programs are essentially constructed in the following manner, as a number of well


defined sections.
/* HEADER SECTION */
/* Contains name, author, revision number*/

/* INCLUDE SECTION */
/* contains #include statements */

/* CONSTANTS AND TYPES SECTION */


/* contains types and #defines */

/* GLOBAL VARIABLES SECTION */


/* any global variables declared here */

/* FUNCTIONS SECTION */
/* user defined functions */

/* main() SECTION */
int main()
{
}
The reasons for using a well defined structured layout when writing programs are to
make them
easy to read
easy to modify
consistent in format
self documenting

Elements/features of a C Language

Programs written in a C language typically contains several elements. If you understand


these elements and what they're for, not only will you understand C better, but you'll also
find learning other programming languages, and moving between different programming
languages, much easier.

1. There are variables, in which you can store the pieces of data that a program is
working on. Variables are the way we talk about memory locations (data).
Variables may be global (that is, accessible anywhere in a program) or local (that
is, private to certain parts of a program).

2. There are expressions, which compute new values from old ones.

3. There are assignments which store values (of expressions, or other variables)
into variables. In C language, an equals sign indicates an assignment statement.
Note that, in C, assignments are just another kind of expression.

4. There are conditionals which can be used to determine whether some condition
is true, such as whether one number is greater than another. In C, conditionals are
actually expressions which compare two values and compute a ``true'' or ``false''
value.

5. Variables and expressions may have types, indicating the nature of the expected
values. In C, declarations of the names of the variables to be used and their types
must be done explicitly. Note that ALL variables must be declared before being
used in an expression.

There are all sorts of data types handled by C language. There are single
characters, integers, and ``real'' (floating point) numbers. There are text strings
(i.e. strings of several characters), and there are arrays of integers, reals, or other
types. There are types (pointers) which reference (point at) values of other types.
Finally, there may be user-defined data types, such as structures, which allow the
programmer to build a more complicated data structure, describing a more
complicated object, by accreting together several simpler types (or even other
user-defined types).
6. There are statements which contain instructions describing what a program
actually does. Statements may compute expressions, perform assignments, or call
functions.

7. There are control flow constructs which determine what order statements are
performed in. A certain statement might be performed only if a condition is true.
A sequence of several statements might be repeated over and over, until some
condition is met; this is called a loop.
8. An entire set of statements, declarations, and control flow constructs can be
lumped together into a function (also called routine, subroutine, or procedure)
which another piece of code can then call as a unit.

When you call a function, you transfer control to it and wait for it to do its job,
after which it returns to you; it may also return a value as a result of what it has
done. You may also pass values to the function on which it will operate or which
otherwise direct its work.

Placing code into functions not only avoids repetition if the same sequence of
actions must be performed at several places within a program, but it also
makes programs easy to understand, because you can see that some function is
being called, and performing some (presumably) well-defined subtask, without
always concerning yourself with the details of how that function does its job.

9. A set of functions, global variables, and other elements makes up a program. A


source code/program is a set of instruction written in a programming language.

A simple C program

The following program is written in the c programming language

#include <stdio.h>
int main()
{
printf(“Programming in C language made easy! \ n ‘’); /*Displays on the
computer screen the string of characters marked by double quotes*/
}

The output

Programming in C language made easy!


A note about C programs

C language is case sensitive. That is, lower and uppercase characters are very important.
For this reason, all instructions in C must be in a lower case.

The starting point for C programs is identified by the word main(), which informs the
computer as to where the program actually starts. The brackets that follow the keyword
main indicate that it is a C function.

This function is required in all C programs. It indicates where a C program starts to


execute. Hence, it MUST be used at the beginning of all C programs.

The two braces, {and}, signify the beginning and end segment of a program or function.

The purpose of the statement

#include <stdio.h>

is to allow the use of the printf statement to provide program output.

This statement is commonly known as preprocessor directive and is usually written at the
beginning of the program. In this case, it commands that the contents of the file stdio.h
should be included in the object file (compiled machine code) at the place where #include
appears. The file stdio.h contains the standard input/output functions. Note that ALL
preprocessor directives:
Begins with the # sign, which must be entered in the first column
Must not end with semicolon
Only one preprocessor directive can appear in one line.

The printf() function is used to provide program output. The text to be displayed by this
function must enclosed in double quotes. Therefore, double quotes mark out the text to be
displayed by the printf function.

Note that this program has only one statement. That is,

printf(“Programming in C language made easy! \ n ‘’);

In general, the printf() is actually a function in C that is used for printing values of
variables and text. Where the text appears in double quotes, “ ‘’, it is printed without
modification. There are some exceptions however. These has to do with \ and %
characters. These characters are modifier’s, and for the present \ followed by the n
character represents a new line character. Thus this program prints.
Programming in C language made easy!
and the cursor is set to the beginning of the next line.

As we shall see next on what follows the backslash character will determine what is
printed, i.e. a tab, clear screen and so on. Another important thing to remember is all C
statements are terminated by a semicolon (;).

Some of the formatters for printf are,

1. Cursor Control Formatters


\n newline
\t tab
\r carriage return
\f form feed
\v vertical tab

2. Variable Formatters
%d decimal integer
%c character
%s string or character array
%f float
%e double

COMMENTS

The addition of comments inside programs is desirable. In our C program we enclosed it


as follows,

/*Displays on the computer screen the string of characters marked by double quotes*/

Note that
The /* opens the comment field while */ closes the comment field
Comments may span multiple lines
Comments may not be nested one inside another. For example,

/* This is a comment. /* this comment is inside */ wrong */

In this example, the first occurrence of */ closes the comment statement for the entire
line, meaning that the text wrong is interpreted as a C statement or variable, and in this
example, generates an error.

Use of comments
Comments are useful in programs because they:
• Document of variables and their usage
• Explain difficult sections of code
• Describe the program, author, date, modification changes, revisions etc
• Are used for copyrighting

VARIABLES

A variable is a quantity which may not change during program execution. We use
variables store the pieces of data that a program is working on. Variables are the way we
talk about memory locations (data). Each variable has a specific storage location in the
memory where its numerical value is stored. The variable is a given name and the
variable name is the “name tag” for the storage location. When a variable contains only
one number, it is called a scalar variable.

Variables may be global (that is, accessible anywhere in a program) or local (that is,
private to certain parts of a program).

In C, the word identifier is used as the general terminology for names given to variable,
functions, constants, structures etc.

There are rules that MUST be followed when naming variables in C programs. The
following rule are used to create valid identifiers:
1. The first character of a variable name must either a character or underscore, but
not any other special character or digit.
2. If a variable name consists of two names then an underscore and not any other
special characters must join them.
3. Reserved keywords cannot be used as variable names.

For example, the following is a list of valid variable names,

summary
exit_flag
i
Jerry7
Number_of_moves
_valid_flag

In addition to the basic rules of naming variables, you should ensure that you use
meaningful names for your variables. The reasons for this are,
meaningful names for variables are self documenting (see what they do at a
glance)
they are easier to understand
there is no correlation with the amount of space used in the .EXE file
makes programs easier to read

CLASS EXERCISE C3

Why are the variables in the following list invalid?

value$sum
exit flag
3lotsofmoney
char

DECLARATION OF VARIABLES

Variables may have types, indicating the nature of the expected values. For instance, you
might declare that one variable is expected to hold a number, and that another is expected
to hold a piece of text. In C, declarations of the names of the variables you plan to use
and what types you expect them to hold must be explicit.

The basic format for declaring variables is

data_type var_name, var_name, ... ;

where data_type is one of the four basic types, an integer, character, float, or double
type.

DATA TYPES AND CONSTANTS

The four basic data types are

1. INTEGER

Integers are whole numbers and they may be either positive or negative. Unsigned
integers are those that can hold positive values only. In addition, there are short and long
integers.

The keyword used to define integers is,

int
An example of declaring an integer variable called sum is,

int sum;
sum = 20;

2. FLOATING POINT

These are real numbers (which contain fractional parts, both positive and negative). The
keyword used to define float variables is,

float

An example of declaring a float variable called money is,

float money;
money = 0.12;

3. DOUBLE

These are exponentional numbers, both positive and negative. The keyword used to
define double variables is,

Double
An example of a double value is 3.0E2.
An example of declaring a double variable called big is,

double big;
big = 312E+7;

4. CHARACTER

These are single characters. The keyword used to define character variables is,

char

An example of a character value is the letter A. An example of declaring a character


variable called letter is,

char letter;
letter = 'A';

Note the assignment of the character A to the variable letter is done by enclosing the value
in single quotes. Remember the golden rule: Single character - Use single quotes.
INITIALIZING DATA VARIABLES AT DECLARATION TIME

In C variables may be initialized with a value when they are declared. Consider the
following declaration, which declares an integer variable count and initializes it to 10.

int count = 10;

SIMPLE ASSIGNMENT OF VALUES TO VARIABLES

The = operator is used to assign values to data variables. Consider the following
statement, which assigns the value 32 an integer variable count, and the letter A to the
character variable letter

count = 32;
letter = 'A';

THE VALUE OF VARIABLES AT DECLARATION TIME

Lets examine what the default value a variable is assigned when its declared. To do this,
consider the following program, which declares two variables, count which is an integer,
and letter which is a character. Note that neither variable is pre-initialized.

The value of each variable is printed out using a printf() statement.

#include <stdio.h>

main()
{
int count;
char letter;

printf("Count = %d\n", count);


printf("Letter = %c\n", letter);
}

Sample program output


Count = 26494
Letter = f

It can be seen from the sample output that the values which each of the variables take on
at declaration time are no-zero. In C, this is common, and programmers must ensure that
variables are assigned values before using them. If the program was run again, the output
could well have different values for each of the variables. We can never assume that
variables declare in the manner above will take on a specific value.

Some compilers may issue warnings related to the use of variables, and Turbo C from
Borland issues the following warning,

possible use of 'count' before definition in function main

Note that before variable are declared they cannot be used in a program. Since C is case
sensitive, I recommend that you get used to the habit of declaring variables using lower
cases.

PRE/POST INCREMENT/DECREMENT OPERATORS

PRE means do the operation first followed by any assignment operation. POST means do
the operation after any assignment operation. Consider the following statements

++count; /* PRE Increment, means add one to count */


count++; /* POST Increment, means add one to count */

Note that in the above example, because the value of count is not assigned to any
variable, the effects of the PRE/POST operation are not clearly visible.

Lets examine what happens when we use the operator along with an assignment
operation. Consider the following program,

#include <stdio.h>

main()
{
int count = 0, loop;

loop = ++count; /* same as count = count + 1; loop = count; */


printf("loop = %d, count = %d\n", loop, count);

loop = count++; /* same as loop = count; count = count + 1; */


printf("loop = %d, count = %d\n", loop, count);
}

Sample Program Output


loop = 1, count = 1
loop = 1; count = 2
If the operator precedes (is on the left hand side) of the variable, the operation is
performed first, so the statement

loop = ++count;
really means increment count first, then assign the new value of count to loop.

Which way do you write it?

Where the increment/decrement operation is used to adjust the value of a variable, and is
not involved in an assignment operation, which should you use,
++loop_count;
or
loop_count++;

The answer is, it really does not matter. It does seem that there is a preference amongst C
programmers to use the post form.

Something to watch out for

Whilst we are on the subject, do not get into the habit of using a space(s) between the
variable name and the pre/post operator.
loop_count ++;
Try to be explicit in binding the operator tightly by leaving no gap.

GOOD FORM

Perhaps we should say programming style or readability. The most common complaints
we would have about beginning C programmers can be summarized as,
• they have poor layout
• their programs are hard to read
Your programs will be quicker to write and easier to debug if you get into the habit of
actually formatting the layout correctly as you write it.
For instance, look at the program below

#include<stdio.h>
main()
{
int sum,loop,kettle,job;
char Whoknows;

sum=9;
loop=7;
whoKnows='A';
printf("Whoknows=%c,kettle=%d\n",whoknows,kettle);
}
It is our contention that the program is hard to read, and because of this, will be difficult
to debug for errors by an inexperienced programmer. It also contains a few deliberate
mistakes!
Okay then, lets rewrite the program using good form.

#include <stdio.h>

main()
{
int sum, loop, kettle = 0, job;
char whoknows;

sum = 9;
loop = 7;
whoknows = 'A';
printf( "Whoknows = %c, kettle = %d\n", whoknows, kettle );
}

We have also corrected the mistakes. The major differences are


• the { and } braces directly line up underneath each other
This allows us to check indent levels and ensure that statements belong to the
correct block of code. This becomes vital as programs become more complex

• spaces are inserted for readability


We as humans write sentences using spaces between words. This helps our
comprehension of what we read (if you dont believe me, try reading the following
sentence. wishihadadollarforeverytimeimadeamistake. The insertion of spaces
will also help us identify mistakes quicker.

• good indentation
Indent levels (tab stops) are clearly used to block statements, here we clearly see
and identify functions, and the statements which belong to each { } program
body.

• initialization of variables
The first example prints out the value of kettle, a variable that has no initial value.
This is corrected in the second example.

KEYBOARD INPUT

There is a function in C which allows the programmer to accept input from a keyboard.
The following program illustrates the use of this function,

#include <stdio.h>
main() /* program which introduces keyboard input */
{
int number;

printf("Type in a number \n");


scanf("%d", &number);
printf("The number you typed was %d\n", number);
}

Sample Program Output


Type in a number
23
The number you typed was 23

An integer called number is defined. A prompt to enter in a number is then printed using
the statement

printf("Type in a number \n:");

The scanf routine, which accepts the response, has two arguments. The first ("%d")
specifies what type of data type is expected (ie char, int, or float). See the list of
formatters for scanf() found.
The second argument (&number) specifies the variable into which the typed response
will be placed. In this case the response will be placed into the memory location
associated with the variable number.
This explains the special significance of the & character (which means the address of).

Sample program illustrating use of scanf() to read integers, characters and floats

#include < stdio.h >

main()
{
int sum;
char letter;
float money;

printf("Please enter an integer value ");


scanf("%d", &sum );

printf("Please enter a character ");


/* the leading space before the %c ignores space characters in the
input */
scanf(" %c", &letter );
printf("Please enter a float variable ");
scanf("%f", &money );

printf("\nThe variables you entered were\n");


printf("value of sum = %d\n", sum );
printf("value of letter = %c\n", letter );
printf("value of money = %f\n", money );
}

Sample Program Output


Please enter an integer value
34
Please enter a character
W
Please enter a float variable
32.3
The variables you entered were
value of sum = 34
value of letter = W
value of money = 32.300000

This program illustrates several important points.


• the c language provides no error checking for user input. The user is expected to
enter the correct data type. For instance, if a user entered a character when an
integer value was expected, the program may enter an infinite loop or abort
abnormally.
• its up to the programmer to validate data for correct type and range of values.

Practise Exercise 3: printf() and scanf()


1. Use a printf statement to print out the value of the integer variable sum
2. Use a printf statement to print out the text string "Welcome", followed by a newline.
3. Use a printf statement to print out the character variable letter
4. Use a printf statement to print out the float variable discount
5. Use a printf statement to print out the float variable dump using two decimal places
6. Use a scanf statement to read a decimal value from the keyboard, into the integer
variable sum
7. Use a scanf statement to read a float variable into the variable discount_rate
8. Use a scanf statement to read a single character from the keyboard into the variable
operator. Skip leading blanks, tabs and newline characters.
Answers: Practise Exercise 3: printf() and scanf()

1. Use a printf statement to print out the value of the integer variable sum

printf("%d", sum);

2. Use a printf statement to print out the text string "Welcome", followed by a newline.

printf("Welcome\n");

3. Use a printf statement to print out the character variable letter

printf("%c", letter);

4. Use a printf statement to print out the float variable discount

printf("%f", discount);

5. Use a printf statement to print out the float variable dump using two decimal places

printf("%.2f", dump);

6. Use a scanf statement to read a decimal value from the keyboard, into the integer
variable sum

scanf("%d", &sum);

7. Use a scanf statement to read a float variable into the variable discount_rate

scanf("%f", &discount_rate);

8. Use a scanf statement to read a single character from the keyboard into the variable
operator. Skip leading blanks, tabs and newline characters.
scanf(" %c", &operator);

THE RELATIONAL OPERATORS

These allow the comparision of two or more variables.

OperatorMeaning
==equal to
!=not equal
<less than
<=less than or equal to
>greater than
>=greater than or equal to

Control Structures in C

The basic component of a high level programming language such as C is its control
structures. By this we mean the way in which the programmer specifies the order in
which instructions should be executed. A program cannot in general achieve its function
simply by executing one instruction after another. Sometimes it is necessary to choose
whether or not to perform a particular action, or to perform the same action repeatedly.
Therefore, control structures gives programs more flexibility in the order of statement
execution. The order of statement execution is called the flow of control. The C language
supports three basic control structures:
o Sequence
o Selection
o Repetition
Sequence structure

This is usually the default action in C. If an instruction is not a control statement, then the
next instruction (statement) to be executed will simply be the next one in sequence. That
is, C executes one statement after another, in the order in which they occur in the source
file.

Selection structure

The selection structure simply means executing different sections of code depending on a
condition or the value of a variable. This is what allows a program to take different
courses of action depending on different circumstances. C provides three types of
selection structures.
o if
o if/else
o switch
The if selection structure
The if selection structure allows the programmer to specify that a section of code should
only be executed if a certain condition is true. Therefore, the if selection structure either
performs (selects) an action if a condition is true or skips the condition if the condition is
false.

The syntax for this statement is


if (condition)
statement;
condition is an expression that evaluates to either a true or false value and statement
is the statement that should only be executed if the expression is true.

For example,
if (num1 > num2)
printf("%d is greater than %d\n", num1, num2);

If more than one statement should be executed if the condition is true, then these may be
grouped together inside braces. For example,

if (num1 > num2)


{
printf("%d is greater than %d\n", num1, num2);
printf("%d is less than or equal to %d\n", num2, num1);
}

The if structure is called a single-selection structure because it selects or ignores a single


action.

The if/else selection structure


The if/else statement extends the idea of the if statement by specifying another section of
code that should be executed only if the condition is false. Thus, the if/else structure is
called a double-selection structure because it selects between two different actions.
The syntax is
if (condition)
statement 1;
else
statement 2;
where condition is an expression which has a true or false value, statement 1 is the
statement to be executed only if the condition is true, and statement 2 is the statement to
be executed only if the condition is false.

For example,
if (num1 > num2)
printf("%d is greater than %d\n", num1, num2);
else
printf("%d is not greater than %d\n", num1, num2);

As before, each of the statements may be compound statements consisting of more than
one simple statement enclosed within braces.

We may also make longer sequences as follows:


if (score >= 80)
printf("Distinction");
else if (score >= 60)
printf("Credit”);
else if (score >= 50)
printf("Pass”);
else{
printf("Fail");
printf("You must take this course again");
}

C provides the condition operator (?:) which closely related to the if/else structure. For
example, the conditional expression

Grade>=60 ? printf(“Passed\n”) : printf(“Failed\n”);

can be rewritten using an if/else statement as follows

if (grade>=60)
printf(“Passed\n”);
else
printf(“Failed\n”);

The switch selection structure


The switch statement provides a way to execute one of a number of different
sections of code, according to the value of an integer or character variable. Each
section of code is labeled with a case, which specifies the value(s) of the variable
for which that section of code should be executed. The variable whose value is to
be used is given at the top of the switch statement.

For example,
switch (num) {
case 1:
printf("I");
break;
case 2:
printf("II");
break;
case 3:
printf("III");
break;
case 4:
printf("IV");
break;
case 5:
printf("V");
break;
default:
printf("?");
break;
}

This section of code prints out the Roman numeral corresponding to any of the numbers
from 0 to 5. There are two main points to notice.
o A break statement is used after each case. This causes the program to skip
the rest of the cases. Without the break statement, execution would
continue through all the sections of code after the matching case.
o The last case is a default one. This will be executed if none of the other
cases match. It is generally good practice to give a default case.
The switch selection structure performs one of many different actions depending on the
value of an expression. It is therefore, called a multi-selection structure because it selects
among many different actions.

Repetition

This means executing the same section of code more than once. A section of code may
either be executed a fixed number of times, or while some condition is true. C provides
three repetition structures.
o while
o do/while
o for

1. The while repetition structure

The while statement in C specifies that a section of code should be executed while a
certain condition holds true. The syntax is
while (condition)
statement;
where condition is an expression which is either true or false, and statement is the
statement to be repeatedly executed while the condition is true. As with the if and if/else
statements, the statement inside the loop may be a compound statement. Note if the
condition is initially false, the loop statement will never be executed.
2. The do/while repetition structure

There is another repetition control structure which is very similar to the while statement -
the do/while statement. The only difference is that the expression which determines
whether to carry on looping is evaluated at the end of each loop.
do
statement;
while (condition);
This structure is used much more rarely than the while statement, but is occasionally
useful if we want to ensure that the loop statement is executed at least once.

3. The for repetition structure


Both the while and the do/while statement provide repetition until some condition
becomes false. Often we want to have loops which are executed a fixed number of
times, and C provides another specalised repetition structure for this - the for
statement. The for statement uses a loop variable to count the number of times that
the loop has been executed. There are three parts before the loop body: an inital
value for the loop variable, a condition which must be true for looping to
continue, and a statement which modifies the loop variable at the end of each
loop.
For example,
for (i = 0; i < 10; i++)
The initialiser (i = 0) is only executed once - before the first time around the loop.
The loop condition (i < 10) is tested each time before the loop is executed. The
loop step (i++) is executed after each execution of the loop. This means that the
above example will loop ten times - the first time i will be equal to 0, the last time
i will be equal to 9.

Example
The program below prints out a number of stars, specified by the user.
#include <stdio.h>
main()
{
int num, i;
printf("Enter the number of stars: ");
scanf("%d", &num);
for (i = 0; i < num; i++)
printf("*");
printf("\n");
}

Exercise 2
Extend the program above so that it prints out a triangle of stars, its base as wide
as the number entered. For example, if the user types 7, the program should print.
*
**
***
****
******
*******
If you finish this, try writing a program which prints a symmetric pyramid of
stars, for example,
*
***
*****
*******
4. The break and continue statements

Sometimes we may wish to stop a particular iteration of a loop early, for example if an
abnormal condition occurs. C provides the break and continue statements to do this.
A break statement inside the body of a loop breaks completely out of the loop. No more
instructions in the body of the loop are executed, and the next statement after the loop
will be executed.

The continue statement just skips any instructions after it on that iteration of the loop.
The current iteration of the loop is terminated, and the loop statement is executed again
as if the last instruction of the loop body has been reached.

Remark

C provides two commands to control how we loop:


break -- exit form loop or switch.
continue -- skip 1 iteration of loop.

POINTERS

Definition

A pointer is a variable that holds a memory address.

Uses of pointers

Pointers enable us to:


Effectively represent complex data structures,
Change values as arguments to functions,
Work with memory which has been dynamically allocated, and
More concisely and efficiently deal with arrays.
When we declare a variable name x as type integer we tell the compiler that a location in
memory where an integer can be stored should be found and it should be given a name x.
Thus, the variable name is a symbolic name for the address of the memory box. If we
write int x = 32 then the integer 32 is stored as contents of x as shown below.

Variable
name address contents

Memory box

In this case, the numeric value of the address corresponding to x is 2568. Note that
computer memory is divided into sequentially numbered memory locations. Each
variable is located at a unique location in memory, known as its address.

We have already encountered the operator and which was used in scanf function. The
operator and is called an address operator. If we write:

&x

the operator & tells the compiler to find the numeric value of the address of a memory
box whose symbolic name is x. Suppose that the address corresponding to x is 2568.
Thus &x is 2568. If we write

y = &x ;

then 2568 which is the an address is stored in y. When a variable stores an address we
declare that variable as a pointer data type. Thus y is declared as:

int *y;

This declaration says that y will store the address of an integer variable name.
In this case y is the address of the integer variable name x. The following figure shows
what happens when we write
y = &x ;

Variable
name address contents

Memory box

The effect of writing y = &x.


Observe that the address allocated by the compiler to store y is 8468 and it has no
relation to 2568 which is the address of x.

Generally if we write:

z = *y;

* is taken as an operator which is called an indirection operator. The indirection


operator, *, asks the compiler to:
1. Read the contents of y. [Since y is declared as a type pointer its contents will be
an address.]
2. Go to the address found in Step 1 and retrieve its contents
3. Store the value retrieved in Step 2 in z.

It is important to observe that in a statement * is taken as an indirection operator. A


pointer provides an indirect means of accessing the value of a particular data item. The
indirection operator can operate only on addresses. Thus the operand of an indirection
operation should be declared to be a pointer data type. The symbol * used in the
declaration has a different meaning from the * used in a statement. In the
declaration it only gives information that y will store an address whereas in a statement
it is an operator commanding that the address stored in y should be retrieved and used.

Null and Wild pointer

Consider
int *pAge = 0;

pAge is initialized to zero. A pointer whose value is zero is called a null pointer. All
pointers, when they are created, should be initialized to something. If you don’t know
what you want to assign to the pointer, assign 0. A pointer that is not initialized is called
a wild pointer. Wild pointers are very dangerous!

POINTERS AND ARRAYS

Pointers are related to arrays by the fact that an array name is a pointer to the first
element of the array.

Consider the following array declared in C:

int a[5]={8, 6, 4, 9, 11};


It states that a is an array of integers and consists of 5 elements i.e. a[0], a[1], a[2],
a[3] and a[4]. The array is stored in consecutive addresses in memory as shown in the
following table.
Illustrating storage of an array
NameAddressContentsa[0]26888a[1]26896a[2]26904a[3]26919a[4]269211

From the table, writing:

int *x;
x = &a[0];
results in
x = 2688;
Alternatively, writing
x = a;

gives also x as 2688. The reason is that in the C language the name of an array variable
is taken as the address of its first element. Thus, a is a pointer to the first element within
the array a[5].

DYNAMIC MEMORY ALLOCATION

Since an array name is actually a pointer to the first element within the array, it is
possible to define the array as a pointer variable rather than as a conventional array. For
example, suppose x is a one-dimensional, 10-element array of integers. It is possible to
define x as int *x rather than int x[10]. However, x is not automatically assigned a
memory block when it is defined as a pointer variable, though a block of memory large
enough will be reserved in advance when x is defined as an array. To assign sufficient
memory for x, we can make use of the library function malloc, as follows.
x = (int *) malloc(10sizeof(int));
This function reserves a block of memory whose size (in bytes) is equivalent to 10
integer quantities.
ASSIGNMENT

Given the following information

Variable name address contents


p 2568 425
q 4284 2568
r 6242 4284
a[0] 8468 232
a[10] 8478 2568

Determine:
1. &p
2. *q
3. **r
4. *p + 5
5. *(&q)
6. &a[0]
7. &q
8. *(&q)
9. (*r)
10. &a [0]
11. a
12. a[0]
13. &a[5]
14. a[10]
15. *a[10]

Practise Exercise 10: Pointers

1. Declare a pointer to an integer called address.


2. Assign the address of a float variable balance to the float pointer temp.
3. Assign the character value 'W' to the variable pointed to by the char pointer letter.
4. What is the output of the following program segment?

int count = 10, *temp, sum = 0;

temp = &count;
*temp = 20;
temp = &sum;
*temp = count;
printf("count = %d, *temp = %d, sum = %d\n", count, *temp, sum );

5. Declare a pointer to the text string "Hello" called message.

Practise Exercise 10: Pointers

1. Declare a pointer to an integer called address.

int *address;

2. Assign the address of a float variable balance to the float pointer temp.

temp = &balance;

3. Assign the character value 'W' to the variable pointed to by the char pointer letter.

*letter = 'W';
4. What is the output of the following program segment?

int count = 10, *temp, sum = 0;

temp = &count;
*temp = 20;
temp = &sum;
*temp = count;
printf("count = %d, *temp = %d, sum = %d\n", count, *temp, sum );

count = 20, *temp = 20, sum = 20

5. Declare a pointer to the text string "Hello" called message.

char *message = "Hello";

FUNCTIONS

A set of declarations, expressions, definitions and


statements that perform a specific task

A function in C can perform a particular task, and supports the concept of modular
programming design techniques. Functions enable a large task to be broken into smaller
subtasks, each of which is handled by one function. In this way, a complex problem can
be divided in such a way that each individual portion becomes manageable.

We have already been exposed to functions. Our programs so far have consisted of a
single function called main. The main body of a C program, identified by the keyword
main, and enclosed by the left and right braces is a function. It is called by the operating
system when the program is loaded, and when terminated, returns to the operating
system. In addition, we made use of predefined C functions such as printf, scanf.
Usually a function is written to perform a task and return a value to the function which
called it. Sometimes a task is performed but no value needs to be returned.

Functions have a basic structure. The ANSI C format is

return_data_type function_name (data_type var_name,


data_type var_name, .. )
{
function_body
}

This permits type checking by utilizing function prototypes to inform the compiler of the
type and number of parameters a function accepts. When calling a function, this
information is used to perform type and parameter checking. ANSI C also requires that
the return_data_type for a function which does not return data must be type void.
The default return_data_type is assumed to be integer unless otherwise specified,
but must match that which the function declaration specifies.

A simple function is,

void print_message( void )


{
printf("This is a module called print_message.\n");
}

Note the function name is print_message. No arguments are accepted by the


function, this is indicated by the keyword void in the accepted parameter section of the
function declaration. The return_data_type is void, thus data is not returned by the
function.

An ANSI C function prototype for print_message() is,

void print_message(void);

Function prototypes are listed at the beginning of the source file.

In short, there are TWO conditions that would prompt a programmer to use the void
keyword in a program with functions. This is when functions:
Are not expected to return a value
Used do not have parameters

Now lets incorporate this function into a program.

/* Program illustrating a simple function call */


#include <stdio.h>

void print_message(void); /* ANSI C function prototype */

void print_message(void) /* the function code */


{
printf("This is a module called print_message.\n");
}

main()
{
print_message();
}

Sample Program Output


This is a module called print_message.

To call a function, it is only necessary to write its name. The code associated with the
function name is executed at that point in the program. When the function terminates,
execution begins with the statement which follows the function name.
In the above program, execution begins at main(). The only statement inside the main
body of the program is a call to the code of function print_message(). This code is
executed, and when finished returns back to main().
As there is no further statement inside the main body, the program terminates by
returning to the operating system.

LOCAL AND GLOBAL VARIABLES

Local

These variables only accessible within a specific function that creates them and they are
unknown to other functions in the main program. That is, Local variables cease to exist
once the function that created them is completed. They are recreated each time a function
is executed or called.

Global

These variables can be accessed (i.e. known) by any function comprising the program.
They are implemented by associating memory locations with variable names. They do
not get recreated if the function is recalled.
An example - factorial

Let us write a function which, given n, calculates and returns n! where

0! = 1,
n! = n(n-1)! For n>0

For example 5! = [Link].1 = 120. We can write it as follows:

int factorial (int n) /*function definition; No ‘;’ after ‘)’*/


{
int nfac; /* local variable declaration */

if (n < 0) return 0; /*return 0 for an invalid argument*/


for ( nfac = 1; n > 0; n-- )
nfac = n; / equivalent to nfac = nfac * n */
return nfac; /* value returned to the calling function */
}

In the example,

int factorial (int n)

Declares the type of the result (int) the function returns, the name of the function
factorial, and the type (int) and name (n) of the parameter which will correspond to the
actual argument when the function is called. When the function is called, an interger
argument must be supplied. Note again that there is no semicolon after the right bracket.
The left brace, {, indicates the start of the body of the function. After the left brace
comes the declaration of variables used only within this function, i.e., local (also called
automatic) variables. In this function, there is one such variable, nfac, which will
hold the value of n!
When a function is entered, storage is allocated for all local variables. This storage is
released (hence the local variables cease to exist) when the function returns. After the
local variable declaration(s) come the statements to be executed by the function. The
statement says that if the negative, function will return a value of 0 to the caller. The
caller can decide what to do in this case. The for loop calculates the value of n! for valid
values of n (n>=0). You should verify that it returns the correct value for n = 0 and n = 1.

The for loop leaves the value of n! in nfac. The statement

return nfac;

Says that the value returned to the caller is the value of nfac.

A complete program to print the values of n! for n = 0, 1, …, 7.

#include <stdio.h>
main ()
{
int factorial (int n), num;

printf (“ n n!\n\n”);
for (num = 0; num <= 7; num+ +)
printf (“%2d %4d\n”, num, factorial (num));
}
int factorial (int n) /*function definition; no ‘;’ after ‘)’.*/
{
int nfac; /* local variables declaration */

if (n < 0) return 0; /* return 0 for an invalid argument */

for (nfac = 1; n > 0; n - - )


nfac = n; /* equivalent to nfac * n */
return nfac; /* value returned to the calling function */
}
Note that, in main, we declare the properties of factorial in a similar manner to the
function definition. This is accomplished by

int factorial (int n);

which is called a function prototype. A function prototype specifies the


type of value returned by the function, the name of the
function and the type(s) of argument(s) expected by the
function. This enables the compiler to check that, when the function is used, the
correct number and type of argument are supplied.

It is not necessary to use the same variable in the prototype as in the function definition;
any variable may be used, for example,
int factorial (int x);
In fact, it is not necessary to use any variable at all - the type alone is enough. Thus the
following is valid and acceptable as a function prototype:
int factorial (int );
Another important reason for using a function prototype is that if the function is called
with an argument which is a different type from the corresponding formal parameter, the
argument is automatically converted to the required type.

A function prototype is declared in the same manner as the header line of a function
definition, except that the prototype is terminated by a semicolon.

N/B, in C, a function is ‘called’ simply by using the name of the function with the
appropriate argument(s).

Function definition
The general form of a function definition is

Type_name (formal parameter list, if any)


{
declaration of local variables
statements
}

Caution: There is no semicolon after the right bracket of the formal parameter list

Passing parameters to functions

There are several methods used to pass parameters to functions. We shall discuss two
methods which are widely used. These are call by value and call by reference. We wish
to establish the difference between these methods

In call by value the call function is given value of its argument in temporary
variables rather than the original while in call by reference the call function
has access to the original and not local copy.
Call by value is slower than call by reference
For call by value the changes in formal parameters does not affect the actual
parameters whereas changes in formal parameters affects the actual
parameters in call by reference.
For call by value two memory spaces are required by the actual parameters
while in call by reference only one memory is required by the actual
parameters.
In call by values only values are passed whereas in call by reference only
address are passed.

You might also like