Programming Methodology Lecture Notes
Programming Methodology Lecture Notes
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.)
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
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
7. Accuracy
The program must do what it is supposed to do, and meet the criteria laid down in
its specification
About C Language
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 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.
Writing 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.
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.
/* INCLUDE SECTION */
/* contains #include statements */
/* 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
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.
A simple C program
#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
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.
The two braces, {and}, signify the beginning and end segment of a program or function.
#include <stdio.h>
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,
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 (;).
2. Variable Formatters
%d decimal integer
%c character
%s string or character array
%f float
%e double
COMMENTS
/*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,
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.
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
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.
where data_type is one of the four basic types, an integer, character, float, or double
type.
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.
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
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
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.
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';
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.
#include <stdio.h>
main()
{
int count;
char letter;
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,
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 means do the operation first followed by any assignment operation. POST means do
the operation after any assignment operation. Consider the following statements
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;
really means increment count first, then assign the new value of count to loop.
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.
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 );
}
• 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;
An integer called number is defined. A prompt to enter in a number is then printed using
the statement
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
main()
{
int sum;
char letter;
float money;
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");
printf("%c", letter);
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);
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.
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,
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.
C provides the condition operator (?:) which closely related to the if/else structure. For
example, the conditional expression
if (grade>=60)
printf(“Passed\n”);
else
printf(“Failed\n”);
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
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.
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
POINTERS
Definition
Uses of pointers
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
Generally if we write:
z = *y;
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 are related to arrays by the fact that an array name is a pointer to the first
element of the array.
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].
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
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]
temp = &count;
*temp = 20;
temp = ∑
*temp = count;
printf("count = %d, *temp = %d, sum = %d\n", count, *temp, sum );
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?
temp = &count;
*temp = 20;
temp = ∑
*temp = count;
printf("count = %d, *temp = %d, sum = %d\n", count, *temp, sum );
FUNCTIONS
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.
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.
void print_message(void);
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
main()
{
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
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
0! = 1,
n! = n(n-1)! For n>0
In the example,
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.
return nfac;
Says that the value returned to the caller is the value of nfac.
#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 */
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
Caution: There is no semicolon after the right bracket of the formal parameter list
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.