c-lecture-notes-2023
c-lecture-notes-2023
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]
CHAPTER ONE
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.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.
After a successful download and installation, you should be left with the opening screen of the
software, pictured in Figure 1.1.
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.
CHAPTER TWO
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 */
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.
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.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
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 */
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.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.
CHAPTER THREE
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.
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 */
(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.
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
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.
#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);
integerVar = 100
floatingVar = 331.790009
doubleVar = 8.440000e+11
doubleVar = 8.44e+11
charVar = W
boolVar = 0;
Figure 3.1 Storing floating-point values often takes more memory than integers.
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.
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.
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)
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.
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;
}
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.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 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.
return 0;
}
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
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.
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.
int count = 1;
while ( count <= 5 ) {
printf ("%i\n", count);
++count;
}
return 0;
}
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
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.
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.
CHAPTER FIVE
DECISION MAKING IN C
5.1 One of the fundamental properties of a computer is its capability to make decisions
printf ("\n");
return 0;
}
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.
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.
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.
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.
CHAPTER SIX
POINTERS IN C
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.
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.
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
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.
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.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 };
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;
}
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.
CHAPTER EIGHT
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.
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.
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.
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.
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():
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.
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.
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.
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
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:
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>
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;
free(ptemps);
return 0;
}
CHAPTER NINE
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.
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:
Syntax:-
return_type function(type 1 arg1, type2 arg2, type3 arg3) /*function header*/
{
Local variable declaration;
Statement 1;
Statement 2;
Return value;
}
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.
main()
{
function(arg1,arg2,arg3); /* calling function */
}
{
Local variable declaration;
Statement;
Return value;
}
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.
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.
{
int scores[10], i, minScore;
return 0;
}