Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Into To C Programming
Description: Intro includes the basic structuring of courses.
Description: Intro includes the basic structuring of courses.
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Module 813
Fundamental Programming
Structures in C
M
...
Learning objectives
After working through this module you should be able to:
1
...
2
...
3
...
4
...
5
...
6
...
7
...
8
...
9
...
Content
Program structure and layout
...
Assignment and Conversion statements
...
Control structures
...
Functions
...
Recursion in C
...
Learning Strategy
Read the printed module and the assigned readings and complete the
exercises as requested
...
References & resources
Turbo C/C++ Manuals
...
Page 813-2
Module 813
Fundamental Programming Structures in C
Introduction to Module 813
In this module you will be introduced to the fundamental structures
used to build a C program
...
This module describes the essential
program elements that are common to all C programs
...
The concepts presented in this module provide the basic elements
needed to construct a working program
...
ASNS1101 (Introduction to Computing
and Numerical Processes) provided a general introduction to computer
systems and application software
...
ASCO2202 (Language Design and Computer Hardware)
developed an understanding of the architecture of machines and the
compilation process
...
It is a strong belief in computing that the best method for learning a
new language is practice
...
In this, and
future modules, you should attempt to write as many programs as
possible to develop a good understanding of C
...
The programs do not
need to be complex
...
Over time you will develop a familiarity
with the language constructs that will eventually lead to more complex
programs
...
You will find that many programs can
be converted into C quite easily
...
There are times, however, when this
conversion process is difficult, or it produces code which is more
complex than the original
...
These notes make use of a number of program examples
...
You
should load, compile and run these programs to discover how they
Page 813-3
Module 813
Fundamental Programming Structures in C
work
...
In order to conserve paper, the programs have
been written with a minimum of documentation
...
Page 813-4
Module 813
Fundamental Programming Structures in C
Objective 1
After working through this module you should be able to identify the
structural elements and layout of C source code
...
Consider
the sample program [TRIVIAL
...
There is no way to simplify this
program or leave anything out
...
The word main is very important, and must
appear once (and only once) in every C program
...
It does not have to
be the first statement in the program but it must exist as the entry point
...
Functions
must return a value and the term void is used to denote that the main
program does not return a value
...
As you will see, all
C programs consist essentially of a collection of functions
...
The actual program statements go between the two
braces, and in this case there are no statements because the program
does absolutely nothing
...
Keep in mind,
however, that it is a valid C program
...
C]:
#include "stdio
...
");
}
It is the same as the previous program except that it has one executable
statement between the braces
...
Once again, we will not worry about what a function
is, but only how to use this one
...
The definition of this function is defined in the STDIO
library (the Standard Input/Output library)
...
The end result is that
whatever is included between the quotation marks in the printf function
will be displayed on the monitor when the program is run
...
C uses a semi-colon as a statement
terminator, so the semi-colon is required as a signal to the compiler that
this line is complete
...
Program output
Look at the following program [WRTMORE
...
h"
void main()
{
printf("This is a line of text to output
...
\n\n");
printf("This is a third line
...
The top line will be
executed first, then the next, and so on, until the fourth line is complete
...
Notice the
character near the end of the first line, namely the backslash (\)
...
In this case, the ‘n’ indicates that a newline is
requested
...
It is commonly referred to as a
carriage return/line feed
...
The C compiler considers the combination
of the backslash and letter n as a single character
...
The first printf
outputs a line of text and returns the carriage
...
Finally the fourth printf outputs a line followed by a carriage
return and the program is complete
...
It would be a good idea at this
time for you to experiment by adding additional lines of printout to see
if you understand how the statements really work
...
C] for an example of how
comments can be added to a C program:
Page 813-6
Module 813
Fundamental Programming Structures in C
/* This is the first comment line */
#include "stdio
...
\n");
}
/* One more comment for effect */
Comments are added to make a program more readable but the
compiler must ignore them
...
*/) combination is used
in C for comment delimiters
...
It is a very sloppy looking program
...
Note that
this comment is prior to the beginning of the program illustrating that a
comment can precede the program itself
...
The next comment is after the
main() program entry point and prior to the opening brace for the
program code itself
...
This is perfectly legal because a
comment can continue for as many lines as desired until it is terminated
...
The last comment is located
following the completion of the program, illustrating that comments can
go nearly anywhere in a C program
...
Comment out one of the printf statements by
putting comment delimiters both before and after it and see that it does
not get printed out
...
It will be much
easier to modify or fix a well commented program a year from now than
one with few or no comments
...
Some compilers allow you to nest
comments which can be very handy if you need to comment out a
section of code during debugging; check your compiler documentation
for the availability of this feature with your particular compiler
...
C] of a well formatted program:
Page 813-7
Module 813
Fundamental Programming Structures in C
#include "stdio
...
\n");
printf("And bad form ");
printf
("can make a program ");
printf
("unreadable
...
With the experience you have already
gained in this module, you should be able to very quickly grasp the
meaning of the program in its entirety
...
Indenting and adding spaces
is entirely up to you and is a matter of personal taste
...
C]; how long would it take
you to discover what this program will do?
#include "stdio
...
\n")
;printf("And bad form ");printf("can make a program ");
printf("unreadable
...
Don’t get too
worried about formatting style yet; you will have plenty of time to
develop a style of your own as you learn the language
...
Exercise 1
Write a program to display your name on the monitor
...
Page 813-8
Module 813
Fundamental Programming Structures in C
Objective 2
After working through this module you should be able to recall the
rules for constructing C identifiers and using data types
...
An identifier is applied to any variable,
function, data definition, etc
...
Two rules must
be kept in mind when naming identifiers:
1
...
Using INDEX for a
variable is not the same as using index and neither of them is the
same as using InDeX for a variable
...
2
...
If more than 31 are used, they will be ignored by the compiler
...
You should not do this for the
duration of your study of this tutorial as you could get some odd
compiler diagnostics
...
It adds
greatly to the readability of a program to use descriptive names for
variables and it would be to your advantage to do so
...
Most of the example
programs in this unit use very short names for that reason
...
C provides for
two types of numbers - integers and floating point
...
Each data item used by a program must have a data type
...
Each data type
represents a different kind of number
...
Page 813-9
Module 813
Fundamental Programming Structures in C
Data Type
Data Range
Description
int
-32,768 to 32,767
integer value
long int
-2,147,483,648 to
2,147,483,647
integer value with an
extended range
short int
-32,768 to 32,767
exactly the same as int
unsigned int
0 to 65,535
integer value
char
0 to 255
character data
float
3
...
4×10+38
floating point number
double
1
...
7×10+308
double precision floating
point number
Table 1
Integer data types
The next example [ONEINT
...
#include "stdio
...
The int is a reserved
word in C, and can therefore not be used for anything else
...
The variable name index can be
any name that follows the rules for an identifier and is not one of the
reserved words for C
...
We will see later that additional integers could also be defined on the
same line, but we will not complicate the present situation
...
The first one assigns the value of 13 to index, and its value is
printed out
...
) Later, the value of 27 is
assigned to index, and finally 10 is assigned to it, each value being
printed out
...
Please note that the words ‘printed
out’ are usually used to mean ‘displayed on the monitor’
...
Much more will be covered at a later time on all aspects of input and
output formatting
...
It is not necessary to
understand everything about output formatting at this time, only a fair
understanding of the basics
...
C]
...
/* This file introduces additional data types
void main()
{
int a,b,c;
/* -32768 to 32767 with no decimal point
char x,y,z; /* 0 to 255 with no decimal point
float num,toy,thing;
/* 10E-38 to 10E+38 with
decimal point
a = b = c = -27;
x = y = z = 'A';
num = toy = thing = 3
...
00
a = toy;
/* a will now be 3
}
*/
*/
*/
*/
*/
*/
*/
*/
The char type of data is nearly the same as the integer except that it can
only be assigned values between zero and 255, since it is stored in only
one byte of memory
...
The text you are reading was
originally written on a computer with a word processor that stored the
words in the computer one character per byte
...
Data type mixing
It would be profitable at this time to discuss the way C handles the two
types char and int
...
Those
functions, when called on to use a char type variable, will actually
promote the char data into integer data before using it
...
The compiler will not get confused, but you might! It is good
not to rely on this too much, but to carefully use only the proper types
of data where they should be used
...
This is a data type which usually has a very large
range and a large number of significant digits, so a large number of
computer words (four in Turbo C) are required to store it
...
4×10-38 to 3
...
Using data types
The first three lines of the program assign values to all nine of the
defined variables so we can manipulate some of the data between the
different types
...
When going the other way, there is no standard, so
you may simply get garbage if the value of the integer variable is
outside the range of the “char” type variable
...
The third line illustrates the simplicity of translating an integer into a
float: simply assign it the new value and the system will do the proper
conversion
...
Since there may be a fractional part of the floating point
number, the system must decide what to do with it
...
This program produces no output, and we haven’t covered a way to
print out char and float type variables yet, so you can’t really get in to
this program and play with the results, but the next program will cover
this
...
C] contains every standard simple data
type available in the programming language C
...
e
...
#include "stdio
...
14159;
g = 3
...
3f\n",f); /*
printf("f = %12
...
5f\n",f);/*
*/
decimal output
octal output
hexadecimal output
decimal long output
decimal short output
unsigned output
character output
floating output
double float output
*/
*/
*/
*/
*/
*/
*/
*/
*/
simple int output
use a field width of 7
left justify width = 7
*/
*/
*/
simple float output
use field width of 12
use 3 decimal places
use 5 decimal places
left justify in field
*/
*/
*/
*/
*/
}
First we define a simple int, followed by a long int which has a range of
-2147483648 to 2147483647, and a short int which has a range that is
identical to that for the int variable, namely -32768 to 32767 (in most
compilers)
...
The unsigned int will usually therefore cover a
range of 0 to 65535
...
We have already covered the char and the float, which leaves only the
double
...
It also requires
more memory to store a value than the simple float
...
7×10-308 to 1
...
Note that other compounding of
types can be done such as long unsigned int, unsigned char, etc; see the
compiler manual for more details
...
Most C compilers have no
provision for floating point math, but only double floating point math
...
Of course, this is totally
transparent to you, so you don’t need to worry about it
...
A float variable requires 4 bytes of storage and
a double requires 8 bytes of storage, so if you have a large volume of
Page 813-13
Module 813
Fundamental Programming Structures in C
floating point data to store, the double will obviously require much
more memory
...
Exercises 2
Write a program which displays an integer value in a number of
formats, i
...
hexadecimal, binary and octal form
...
Create the following
source code program and ensure that it compiles and runs correctly
...
h"
void main()
{
int a, b, c;
a = 1;
b = 2;
c = 3;
printf("Some output: %d %d %d\n", a, b, c);
Now introduce each of the following programming errors in turn,
compile the program, and record the error messages generated
...
Module 813
Fundamental Programming Structures in C
Objective 3
After working through this module you should be able to use
assignment statements and operators to store and manipulate data in a
C program
...
In the first program
[INTASIGN
...
/* This program illustrates the assignment statement
void main()
{
int a,b,c;
/* Integer variables for examples
/* data assignment statements
a = 12;
b = 3;
/* data manipulation statements
c = a + b;
/* simple addition
c = a - b;
/* simple subtraction
c = a * b;
/* simple multiplication
c = a / b;
/* simple division
c = a % b;
/* simple modulo (remainder)
c = 12*a + b/2 - a*b*2/(a*c + b*2);
c = c/4+13*(a + b)/3 - a*b + 2*a*a;
a = a + 1;
/* incrementing a variable
b = b * 5;
a = b = c = 20; /* multiple assignment
a = b = c = 12*13/4;
}
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
The data assignment statements assign numerical values to a and b, and
the next four lines illustrate the five basic arithmetic functions and how
to use them
...
It can only be applied to int or char type
variables, and of course int extensions such as long, short, etc
...
All of the above
examples should require no comment except to say that none of the
equations are meant to be particularly useful except as illustrations
...
This leaves us with the last two lines which may appear very strange to
you
...
The compiler finds
the value 20, assigns it to c, then continues to the left finding that the
latest result of a calculation should be assigned to b
...
This is a very useful
Page 813-15
Module 813
Fundamental Programming Structures in C
construct when you are initialising a group of variables
...
The program has no output, so compiling and executing this program
will be very uninteresting
...
This would be a good time for a preliminary definition of a rule to be
followed in C
...
This is why the variables
are defined first in this program and in any C program
...
Arithmetic Operators
The basic arithmetic operators have been introduced in the previous
section
...
Modular division is
achieved using the % operator
...
For example, in the following statement:
x = 12
...
814 if x is defined as a float, and
164 if x is defined as an int
...
There are three constructs used in C that make no sense at all when first
encountered because they are not intuitive, but they greatly increase the
efficiency of the compiled code and are used extensively by experienced
C programmers
...
C] of their use:
void main()
{
int x = 0,y = 2,z = 1025;
float a = 0
...
14159,c = -37
...
2;
/* This multiplies a by 3
...
0;
/* This divides a by 10
...
0 ? 2
...
5 ); /* This expression
if (b >= 3
...
0;
/* are identical, both
else
/* will cause the same
a = 10
...
*/
c = (a > b?a:b);
/* c will have the max of a or b
c = (a > b?b:a);
/* c will have the min of a or b
}
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
In this program some variables are defined and initialised in the same
statements for later use
...
The next two
statements also add one to the value of x, but it is not intuitive that this
is what happens
...
Therefore, by
definition of the C language, a double plus sign either before or after a
variable increments that variable by 1
...
In the next statement, the value of y is assigned to the
variable z, then y is incremented because the plus signs are after the
variable y
...
The next group of statements illustrate decrementing a variable by one
...
If the minus signs are before the variable, the variable
is decremented, then used, and if the minus signs are after the variable,
the variable is used, then decremented
...
This
operator is used to modify any variable by some constant value
...
The second statement does the
same, but once again, it is not intuitive that they are the same
...
It should be
noted that the expression on the right side of the arithmetic operator
can be any valid expression; the examples are kept simple for your
introduction to this new operator
...
Page 813-17
Module 813
Fundamental Programming Structures in C
The conditional expression
The conditional expression is just as cryptic as the last two, but once
again it can be very useful so it would pay you to understand it
...
The expression prior to the question mark is
evaluated to determine if it is true or false
...
The result of the
evaluation is used for the assignment
...
This is illustrated by the second
example in this group
...
The final two lines of this example program are given to illustrate a very
compact way to assign the greater of two variables a or b to c, and to
assign the lesser of the same two variables to c
...
Many students of C have stated that they didn’t like these three cryptic
constructs and that they would simply never use them
...
I have found many functions that I wished
to use within a program but needed a small modification to use it,
requiring me to understand another person’s code
...
They
will be used in the remainder of this tutorial, so you will be constantly
exposed to them
...
C] has many examples of compare
statements in C
...
This initialisation is new to you
and can be used to initialise variables while they are defined
...
987,s = 12
...
987;
/* First group of compare statements
*/
if (x == y) z = -13;
/* This will set z = -13
if (x > z) a = 'A';
/* This will set a = 65
if (!(x > z)) a = 'B'; /* This will change nothing
if (b <= c) r = 0
...
0
if (r != s) t = c/2;
/* This will set t = 20
/* Second group of compare statements
if (x = (r != s)) z = 1000;
/* This sets x = some positive number and z = 1000
if (x = y) z = 222;
/* Sets x = y, and z = 222
if (x != 0) z = 333;
/* This sets z = 333
Page 813-18
*/
*/
*/
*/
*/
*/
*/
*/
*/
Module 813
Fundamental Programming Structures in C
if (x) z = 444;
/* This sets z = 444
/* Third group of compare statements
*/
x = y = z = 77;
if ((x == y) && (x == 77)) z = 33;
/* This sets z = 33
if ((x > y) || (z > 12))
z = 22;
/* This sets z = 22
if (x && y && z) z = 11; /* This sets z = 11
if ((x = 1) && (y = 2) && (z = 3)) r = 12
...
00
if ((x == 2) && (y = 3) && (z = 4)) r = 14
...
345; /* z always gets changed
if (x != x)
z = 27
...
345; /* Sets x = 0, z unchanged
}
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
The first group of compare statements represents the simplest kinds of
compares since they simply compare two variables
...
The first compare checks to see if x is
equal to y and it uses the double equal sign for the comparison
...
The second comparison checks to see if x is greater
than z
...
The fourth
checks for ‘b less than or equal to c’, and the last checks for ‘r not
As with other programming languages, if the result of the compare is
true, the statement following the if clause will be executed and the
results are given in the comments
...
It would be well to mention the different format used for the if
statement in this example program
...
A more
detailed discussion of the ‘if’ structure can be found in the next
objective
...
Starting
with the first compare, we find a rather strange looking set of
conditions in the parentheses
...
A false is defined as a value of zero, and
true is defined as a non-zero value
...
Look at the first compare of the second group of compare statements
...
0 above,
so the result will be a non-zero value, probably 1
...
There is no explicit variable to which it will be assigned so the
result of the compare is an implied integer
...
If double equal
signs were used, the phantom value, namely 1, would be compared to
the value of x, but since the single equal sign is used, the value 1 is
simply assigned to x, as though the statement were not in parentheses
...
Thus we accomplished two things in this statement: we assigned x a
new value, probably 1, and we assigned z the value of 1000
...
The important things to remember are the values that define
true and false, and the fact that several things can be assigned in a
conditional statement
...
The next
example should help clear up some of the above in your mind
...
The third example, in the second group, compares x to zero
...
The last example in this group illustrates the same
concept, since the result will be true if x is non-zero
...
The
third and fourth examples of this group are therefore identical
...
We assign the value of 77
to the three integer variables simply to get started again with some
defined values
...
The entire statement reads, if x
equals y AND if x equals 77 then the result is true
...
The next compare in this group introduces the || operator which is the
OR
...
Since z is greater than 12, it doesn’t matter if x is
greater than y or not, because only one of the two conditions must be
true for the result to be true
...
Page 813-20
Module 813
Fundamental Programming Structures in C
Logical evaluation
When a compound expression is evaluated, the evaluation proceeds
from left to right and as soon as the result of the outcome is assured,
evaluation stops
...
In the
case of an OR evaluation, if any of the terms is found to be true,
evaluation stops because it will be impossible for additional terms to
cause the result to be false
...
Operator precedence
The question immediately arises of the precedence of operators: which
operators are evaluated first and which last? There are many rules about
this topic, which your compiler will define completely, but I would
suggest that you don’t worry about it at this point
...
Parentheses always have the highest priority and will
remove any question of which operations will be done first in any
particular statements
...
Since all three are
non-zero, all three are true, and therefore the AND of the three
variables are true, leading to the result being true, and z being assigned
the value of 11
...
Continuing on to the fourth example of the third group we find three
assignment statements in the compare part of the if statement
...
The last example of the third group contains a bit of a trick, but since
we have covered it above, it is nothing new to you
...
The remaining parts of the
compare are not evaluated, because it is an AND and it will definitely
be resolved as a FALSE because the first term is false
...
Likewise, z will not be set to 4, and the variable
r will not be changed
...
All three have the common result that z will not get set
to the desired value, but for different reasons
...
The if
therefore has no effect because of the misplaced semicolon
...
The last statement
will always assign 0 to x and the compare will therefore always be false,
never executing the conditional part of the if statement
...
If any part of this
discussion is unclear in your mind, restudy it until you are confident that
you understand it thoroughly before proceeding onward
...
Compile and run this
program, then add some printout to see the results of some of the
comparisons
...
Locate, explain and
fix the error
...
assign the value 26
...
219 to height
calculate the height-to-weight ratio using the formula:
height
ratio =
weight
display a heading for the results
display the results in a suitable format, for example:
age
...
x years
weight
...
: xx
...
: xxx
...
Repetition structures
The C programming language has several structures for looping and
conditional branching
...
The WHILE loop
The while loop continues to loop while some condition is true
...
It therefore
does just what it says it does; the name of the loop being very
descriptive
...
C] for an example of a
while loop:
/* This is an example of a "while" loop*/
#include "stdio
...
The variable
is set to zero and we come to the while loop itself
...
The keyword while is followed by an
expression of something in parentheses, followed by a compound
statement bracketed by braces
...
In this case,
since the variable count is incremented by one every time the statements
are executed, it will eventually reach 6, the statement will not be
executed, and the loop will be terminated
...
We will cover the compare expression (the one in parentheses) soon;
until then, simply accept the expressions for what you think they should
do and you will probably be correct
...
First, if the
variable count were initially set to any number greater than 5, the
statements within the loop would not be executed at all, so it is possible
to have a while loop that is never executed
...
Finally, if
Page 813-23
Module 813
Fundamental Programming Structures in C
there is only one statement to be executed within the loop, it does not
need braces but can stand alone
...
This
program [DOWHILE
...
/* This is an example of a do-while loop
#include "stdio
...
When the expression in parentheses
becomes false, execution is terminated, and control passes to the
statements following this statement
...
Since the
test is done at the end of the loop, the statements in the braces will
always be executed at least once
...
Finally, just like for the while loop, if only one
statement will be executed within the loop, no braces are required
...
That is, one loop can be included within the compound statement of
another loop, and the nesting level has no limit
...
Examine the next program [FORLOOP
...
/* This is an example of a for loop */
#include "stdio
...
The first field contains the expression ‘index = 0’ and is an
initialising field
...
There is essentially no limit as to what can
go here, but good programming practice would require it to be kept
simple
...
The second field, in this case containing ‘index < 6’, is the test which is
done at the beginning of each loop through the program
...
(More will be said
about the actual value of true and false in the next section
...
This field, like the first, can also be
composed of several operations separated by commas
...
A compound statement
is any group of valid C statements enclosed in braces
...
You may be wondering why there are two statements available that do
exactly the same thing because the while and the for loop do exactly the
same thing
...
The for loop is also convenient because it moves all of the
control information for a loop into one place, between the parentheses,
rather than at both ends of the code
...
Selection structures
The IF statement
The next program [IFELSE
...
/* An example of the if and the if-else statements
#include "stdio
...
This is an example of how
statements can be nested
...
Consider the first if statement
...
If the expression is evaluated and found to
be true, the single statement following the if is executed, and if false,
the following statement is skipped
...
(The expression ‘data == 2’ is simply asking if the
value of data is equal to 2; this will be explained in detail in the next
section
...
)
The IF-ELSE statement
The second if is similar to the first with the addition of a new reserved
word, the else following the first printf statement
...
Thus, one of the two expressions will always be executed,
whereas in the first example the single expression was either executed
or skipped
...
The BREAK and CONTINUE statements
Now for a program [BREAKCON
...
Notice that in the first for, there is an if statement that calls
a break if xx equals 8
...
#include "stdio
...
In this
case, when xx reaches 8, the loop is terminated and the last value
printed will be the previous value, namely 7
...
When the
value of xx reaches 8 in this case, the program will jump to the end of
the loop and continue executing the loop, effectively eliminating the
printf statement during the pass through the loop when xx is eight
...
C] containing the
biggest construct we have so far come across in C - the switch
...
h"
void main()
{
int truck;
for (truck = 3; truck < 13; truck = truck + 1)
{
switch (truck)
{
case 3 : printf("The value is three\n");
break;
case 4 : printf("The value is four\n");
break;
case 5 :
case 6 :
case 7 :
case 8 : printf("The value is between 5 & 8\n");
break;
case 11
:
printf("The value is eleven\n");
break;
default
:
printf("The value is undefined\n");
break;
}
/*
end of switch */
}
/*
end of for loop
}
*/
It begins with the keyword switch followed by a variable in parentheses
which is the switching variable, in this case truck
...
The reserved word
case is used to begin each case entered followed by the value of the
variable, then a colon, and the statements to be executed
...
Once an entry point is found, statements will be executed until a break
is found or until the program drops through the bottom of the switch
braces
...
These are executed and the break
statement in the case 8 portion will direct the execution out the bottom
Page 813-27
Module 813
Fundamental Programming Structures in C
of the switch
...
It should be clear that any of the above constructs can be nested within
each other or placed in succession, depending on the needs of the
particular programming project at hand
...
Write
this program three times, once with each looping method
...
Write a program that will count from 1 to 12 and print the count, and
its square, for each count
...
Write a program that counts from 1 to 12 and prints the count and its
inversion to 5 decimal places for each count
...
1
1
...
50000
3
0
...
25000
etc
...
Page 813-28
Module 813
Fundamental Programming Structures in C
Objective 5
After working through this module you should be able to describe the
techniques for creating program modules in C
...
We have already seen that the main
module of a C program is a function (called main)
...
The type associated with each function is the data type of the
value being returned by the function
...
Examples of this situation include
modules which print headings to the screen
...
The data type is called void
...
All modules in a main program must be prototyped
...
The compiler can then use the
model to check each of your calls to the function and determine if you
have used the correct number of arguments in the function call and if
they are of the correct type
...
The ANSI standard for C
contains prototyping as part of its recommended standard
...
Standard function libraries
Every compiler comes with some standard predefined functions which
are available for your use
...
We
will cover most of these in subsequent sections
...
A few minutes spent studying your compiler’s
Reference Guide will give you an insight into where the prototypes are
defined for each of the functions
...
In the case of the IBM-PC and compatibles, most
of these functions allow the programmer to use the BIOS services
available in the operating system, or to write directly to the video
monitor or to any place in memory
...
One example of a library of this type is the CONIO library which is
provided as part of the Turbo C package
...
Page 813-30
Module 813
Fundamental Programming Structures in C
Objective 6
After working through this module you should be able to create C
functions
...
C] as an example of a C
program with functions
...
The printf function is a
library function that was supplied with your compiler
...
h"
int sum;
/* This is a global variable
/* define the prototypes for the functions used in this
/* program
...
*/
void square(int number)
/* The square function uses a
/* single integer parameter
...
void ending()
/* This function does not return
/* a value
...
The parentheses are
required because the C compiler uses them to determine that it is a
function call and not simply a misplaced variable
...
Continuing on we come to a for loop which will be executed 7
times and which calls another function named square each time through
the loop, and finally a function named ending will be called and
executed
...
) We have seen that this program therefore calls a header,
makes 7 calls to square, and a call to ending
...
Defining functions
Following the main program you will see another program that follows
all of the rules set forth so far for a main program except that it is
named header()
...
Each of these statements are executed, and when they
are all complete, control returns to the main program
...
Since the variable sum is defined as an
integer type variable prior to the main program, it is available to be used
in any of the following functions
...
More will be said about
the scope of variables at the end of this section
...
Program control then returns
to the main program since there are no additional statements to execute
in this function
...
This does not minimise the value of functions,
it merely illustrates the operation of this simple function in a simple
way
...
Passing a value to a function
Going back to the main program, and the for loop specifically, we find
the new construct from the end of the last section used in the last part
of the for loop, namely incrementing the index variable using index++
...
In the call to the function square, we have an added feature,
namely the variable index within the parentheses
...
Looking ahead at the function square, we find that another variable
name is enclosed in its parentheses, namely the variable ‘number’
...
We can call it anything we wish as long as it
follows the rules of naming an identifier
...
Thus the line containing ‘int number;’ tells the function
that the value passed to it will be an integer type variable
...
This is the classic style of defining
function variables and has been in use since C was originally defined
...
Following the opening brace of the function, we define another variable
numsq for use only within the function itself, (more about that later)
and proceed with the required calculations
...
We print the number and its square, and return
to the main program
...
We did not actually pass the value of
index to the function, we actually passed a copy of the value
...
We could have modified the variable number in any way
we wished in the function square, and when we returned to the main
program, index would not have been modified
...
We will find a well defined method of
returning values to the main program or to any calling function when
we get to arrays and another method when we get to pointers
...
We have already hinted at global
variables above, and will discuss them in detail later in this section
...
This call simply calls the last function which has no local
variables defined
...
The program ends by returning to
the main program and finding nothing else to do
...
I told you a short time ago that the only way to get a value back to the
main program was through use of a global variable, but there is another
way which we will discuss by reference to the next program
[SQUARES
...
h"
/* define the prototype for the function used in this
/* program
...
It returns an
/* integer value
...
But once again, it is true that to
return more than one value, we will need to study either arrays or
pointers
...
The first statement of the for loop
is ‘y = squ(x);’ which is a new and rather strange looking construct
...
Looking ahead to the function itself we find
that the function prefers to call the variable ‘in’ and it proceeds to
square the value of in and call the result square
...
The
value within the parentheses is assigned to the function itself and is
returned as a usable value in the main program
...
If x were therefore
assigned the value 4 prior to this call, y would then be set to 16 as a
result of this line of code
...
The values of x and y are then printed out
...
Floating point functions
Now for an example of a function with a floating point type of return
[FLOATSQ
...
It begins by defining a global floating point variable we
will use later; then in the main part of the program an integer is defined,
Page 813-34
Module 813
Fundamental Programming Structures in C
followed by two floating point variables, and then by two strange
looking definitions
...
h"
float z;
/* This is a global variable
/* define the prototype for the function used in this
/* program
...
It
/* returns a float value
...
4f\n",index,y);
}
for (index = 0; index <= 7;index++) {
z = index;
y = glsqr();
printf("The square of %d is %10
...
This is the proper way in C to define that a function will return a value
that is not of the type int, but of some other type, in this case float
...
This once again is the classic method
of defining functions
...
This is an
indication to the compiler that this function will return a value of type
float to any program that calls it
...
The line following the function name contains ‘float
inval;’, which indicates to the compiler that the variable passed to this
function from the calling program will be of type float
...
Exercise 6
Rewrite TEMPCONV
...
Write a program that writes your name on the monitor 10 times by
calling a function to do the writing
...
Page 813-35
Module 813
Fundamental Programming Structures in C
Objective 7
After working through this module you should be able to make use of
local and global parameters in functions
...
C] leads us to a discussion of the scope of
variables in a program
...
#include "stdio
...
In addition, it is always available because it does not come
and go as the program is executed
...
)
Further down in the program, another global variable named counter is
defined which is also global but is not available to the main program
since it is defined following the main program
...
Note that both of these
variables are sometimes referred to as external variables because they
are external to any functions
...
[Ignore the word register for the moment
...
In addition, it is an automatic variable, which means that it only
comes into existence when the function in which it is contained is
invoked, and ceases to exist when the function is finished
...
Another integer is defined within the for braces, namely stuff
...
The variable will be an automatic variable and will cease
to exist when execution leaves the braces
...
Automatic variables
Observe the function named head1, which looks a little funny because
void is used twice; the purpose of the word void will be explained
shortly
...
When the program is not actually executing
statements in this function, this variable named index does not even
exist
...
Keep in mind that this does not affect the variable of the
same name in the main program, since it is a completely separate entity
...
The important thing to remember is that from one call
to a function to the next call, the value of an automatic variable is not
preserved and must therefore be reinitialised
...
By putting the reserved word static in front of a variable
declaration within a function, the variable or variables in that
declaration are static variables and will stay in existence from call to call
of the particular function
...
This implies that it is
Page 813-37
Module 813
Fundamental Programming Structures in C
possible to refer to external variables in other separately compiled files,
and that is true
...
Reusing names
Refer to the function named head2
...
Even though count has already been defined as a
global variable, it is perfectly all right to reuse the name in this function
...
This allows you to write programs using
existing functions without worrying about what names were used for
variables in the functions because there can be no conflict
...
Register variables
Now to fulfil a promise made earlier about what a register variable is
...
A register is much
faster in operation than memory but there are very few registers
available for the programmer to use
...
Most C compilers allow you to use 2
register variables and will ignore additional requests if you request more
than 2
...
You can also
normally use register storage for two byte pointers - which we will
study later
...
When you have
variables brought to a function as arguments to the function, they are
defined immediately after the function name and prior to the opening
brace for the program
...
Returning to lines 2, 3 and 4 in the program, we have the prototypes for
the three functions contained within the program
...
The word void within the parentheses tells the compiler that this
function requires no parameters and if a variable were included, it
would be an error and the compiler would issue a warning message
...
This
Page 813-38
Module 813
Fundamental Programming Structures in C
allows you to use type checking when programming in C in much the
same manner that it is used in Pascal, Modula 2, or Ada
...
H which contains the prototypes for the standard input and
output functions so they can be checked for proper variable types
...
Exercise 7
Create a program that contains the following main program block
...
void main()
{
int a;
a = 2;
printf("%d\n", a);
{
int a;
a = 3;
printf("%d\n", a);
}
printf("%d\n", a);
}
Page 813-39
Module 813
Fundamental Programming Structures in C
Objective 8
After working through this module you should be able to create
recursive functions in C
...
C] should help to take some of the mystery out
of it
...
#include "stdio
...
*/
void count_dn(int count);
void main()
{
int index;
index = 8;
count_dn(index);
}
/* -- Function definition -------------------void count_dn(int count)
{
count--;
printf("The value of the count is %d\n",count);
if (count > 0)
count_dn(count);
printf("Now the count is %d\n",count);
}
*/
*/
Recursion is nothing more than a function that calls itself
...
In this program the
variable index is set to 8, and is used as the argument to the function
count_dn
...
etc
...
Finally, the variable will
reach zero, and the function will not call itself again
...
For purposes
of understanding you can think of it as having 8 copies of the function
count_dn available and it simply called all of them one at a time,
keeping track of which copy it was in at any given time
...
A better explanation of what actually happened is in order
...
The next time it called itself, it did the same thing, creating and storing
another block of everything it needed to complete that function call
...
The blocks were stored on an internal part of the computer called the
stack; this is a part of memory carefully organised to store data just as
described above
...
A stack is used in nearly all
modern computers for internal housekeeping chores
...
Indirect
recursion would be when a function A calls the function B, which in
turn calls A, etc
...
There is no reason why you could not have three
functions calling each other in a circle, or four, or five, etc
...
The thing you must remember about recursion is that at some point,
something must go to zero, or reach some predefined point, to
terminate the loop
...
Another example of recursion
The next program [BACKWARD
...
This program is similar to the last one except that it
uses a character array
...
Additionally, each time the function ends, one of the characters
is printed again, this time backwards as the string of recursive function
calls is retraced
...
h" /* Prototypes for Input/Output
#include "string
...
*/
void forward_and_backwards(char line_of_char[],int index);
void main()
{
char line_of_char[80];
int index = 0;
strcpy(line_of_char,"This is a string
...
The modern method of function
definition moves the types of the variables into the parentheses along
with the variable names themselves
...
Exercise 8
Write a recursive function that when given an integer will calculate the
sum of all the integers up to, and including, that integer
...
The greatest common divisor of two positive integers is the largest
integer that is a divisor of both of them
...
The following recursive function
computes the greatest common divisor of two integers
...
int gcd(int p, int q)
{
int r;
if ((r = p % q) == 0)
return (q);
else
return (gcd(q, r));
}
Page 813-42
Module 813
Fundamental Programming Structures in C
Objective 9
After working through this module you should be able to use the
#define statement to simplify code development
...
C] contains your
first look at some define and macro statements
...
h"
#define START 0
#define ENDING 9
#define MAX(A,B)
#define MIN(A,B)
/* Starting point of loop
/* Ending point of loop
((A)>(B)?(A):(B))
/* Max macro definition
((A)>(B)?(B):(A))
/* Min macro definition
*/
*/
*/
*/
void main()
{
int index,mn,mx;
int count = 5;
for (index = START; index <= ENDING;index++) {
mx = MAX(index,count);
mn = MIN(index,count);
printf("Max is %d and min is %d\n",mx,mn);
}
}
Notice the four lines starting with the word #define
...
Before the actual compilation starts, the
compiler goes through a preprocessor pass to resolve all of the defines
...
The compiler itself will never see the word
START, so as far as the compiler is concerned, the zeros were always
there
...
It should be clear to you by now that putting the word START in your
program instead of the numeral 0 is only a convenience to you and
actually acts like a comment since the word START helps you to
understand what the zero is used for
...
If, however, you had a 2000 line program
before you with 27 references to the START, it would be a completely
different matter
...
Page 813-43
Module 813
Fundamental Programming Structures in C
In the same manner, the preprocessor will find all occurrences of the
word ENDING and change them to 9, then the compiler will operate on
the changed file with no knowledge that ENDING ever existed
...
You can use any method you choose
since it is mostly a matter of personal taste
...
Since different compilers use different numerical values for this,
although most use either a zero or a minus 1, we will write the program
with a define to define the EOF used by our particular compiler
...
Macros
A macro is nothing more than another define, but since it is capable of
at least appearing to perform some logical decisions or some math
functions, it has a unique name
...
In this case, any time the preprocessor finds
the word MAX followed by a group in parentheses, it expects to find
two terms in the parentheses and will do a replacement of the terms into
the second definition
...
When line 10 of the program is reached, index will be
substituted for every A, and count will be substituted for every B
...
)
Remembering the cryptic construct we studied a couple of sections ago
will reveal that mx will receive the maximum value of index or count
...
The results are then printed out
...
We will discuss the extra parentheses in our
next program
...
Wrong macros
The next program [MACRO
...
The first line defines a macro named WRONG that appears to
get the cube of A, and indeed it does in some cases, but it fails
miserably in others
...
#include "stdio
...
If
i is 1, which it is the first time through, then we will be looking for the
cube of 1+5 = 6, which will result in 216
...
However, when
we use WRONG, we group them as 1+5*1+5*1+5 = 1+5+5+5 = 16
which is a wrong answer
...
It should be clear to you that
either CUBE or WRONG would arrive at a correct answer for a single
term replacement such as we did in the last program
...
Inspection of line 20 will reveal that we are evaluating 5*(i) + (i) which
is 6 if i is one, and in the second case 5*((i) + (i)) which is 10 if i is one
...
Exercise 9
1
...
Use
#define statements to define the limits
...
)
2
...
C to see the result of the
erroneous addition macro
Title: Into To C Programming
Description: Intro includes the basic structuring of courses.
Description: Intro includes the basic structuring of courses.