Chapter 1: Fundamentals of C Programming AIMS Objectives 1

DT089/2
Software Systems
2005/2006
Chapter 1: Fundamentals of C Programming
AIMS
To review the fundamentals of the C language with emphasis on I/O, Data Types and operations
on data.
Objectives
When you have completed this unit, you should be able to:
 Write simple sequential C programs.
 Perform mathematical calculations in C.
 Perform basic input and output.
1.
Introduction to C Programming
1.1
What is C?
C is a `programming language'. That is, it is a language that allows you to specify exactly what
you want your computer to do and explain clearly for other people what you are doing.
C has been closely associated with the UNIX operating system for which it was developed since the system and most of the programs that run it are written in C.
C is a high level multi-purpose programming language that can be run across a number of
different platforms. For example, it can run on:
 MS DOS
 WINDOWS
 UNIX
A high level programming language uses keywords and symbols that humans are familiar with.
High level programming languages were developed to make it easier for humans to program
computers. Remember all the information inside a computer is in binary form, including the
program instructions. It would be tedious for humans to enter this so-called low-level code, so
different high level programming languages were developed, for example Visual Basic,
PASCAL and C.
A high level language can not run directly on your computer, it must be compiled (converted)
into a set of simple instructions that a computer can use. Each instruction is used to instruct the
computer to perform a specific operation.
C is often called a "Middle Level" programming language. This is not a reflection on its lack of
programming power but more a reflection on its capability to access the system's low level
functions. Most high-level languages (e.g. Visual Basic) provides everything the programmer
might want to do already built into the language. A low level language (e.g. assembler) provides
nothing other than access to the machines basic instruction set. A middle level language, such as
C, probably doesn't supply all the constructs found in higher level languages - but it provides you
with all the building blocks that you will need to produce the results you want.
DT089-2-CNotes01.doc
Page 1-6
05/10/2005
DT089/2
1.1.1
Software Systems
2005/2006
Why use C?
C has been used successfully for every type of programming problem imaginable from operating
systems to spreadsheets to expert systems - and efficient compilers are available for machines
ranging in power from the Apple Macintosh to the Cray supercomputers.
The largest measure of C's success seems to be based on purely practical considerations:
 the portability of the compiler;
 the standard library concept;
 a powerful and varied repertoire of operators;
 an elegant syntax;
 ready access to the hardware when needed;
 and the ease with which applications can be optimised by hand-coding isolated
procedures
C was initially used for system development work, in particular the programs that make-up the
operating system. Why use C? Mainly because it produces code that runs nearly as fast as code
written in assembly language.
Some examples of the use of C might be:
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Data Bases
 Language Interpreters
 Utilities
In recent years C has been used as a general-purpose language because of its popularity with
programmers.
DT089-2-CNotes01.doc
Page 2-6
05/10/2005
DT089/2
1.1.2
Software Systems
2005/2006
C and Personal Computers
With regards to personal computers Microsoft C for IBM (or clones) PC's. and Borlands C are
seen to be the two most commonly used systems. However, the latest version of Microsoft C is
now considered to be the most powerful and efficient C compiler for personal computers.
Figure 1
1.1.3
Example: Microsoft Visual C++ IDE
C and UNIX environments
There are many C compilers around. For example, the cc is the default Sun compiler and the
GNU C compiler gcc is popular and available for many platforms.
DT089-2-CNotes01.doc
Page 3-6
05/10/2005
DT089/2
Software Systems
2005/2006
2.
Developing C Programs
2.1
The Edit-Compile-Link-Execute Process
Developing a program in a compiled language such as C requires at least four steps:
1. editing (or writing) the program
2. compiling it
3. linking it
4. executing it
ASCII Editor
USER
C Source
[.c]
Header files
[.h]
C Preprocessor
Syntax
Errors
C Compiler
Object Code
[.obj]
Run Time
Errors
Other Object
Code
Linker
Errors
Linker
Run Time Code
Debugger
[.exe]
Figure 2
Edit-Compile-Link-Execute Process
2.1.1
Editing
You write a computer program with words and symbols that are understandable to human beings.
This is the edit part of the development cycle. You type the program directly into a window on
the screen and save the resulting text as a separate file. This is often referred to as the source file
(you can read it with the TYPE command in DOS or the cat command in UNIX). The custom is that
the text of a C program is stored in a file with the extension .c for C programming language
2.1.2
Compiling
You cannot directly execute the source file. To run on any computer system, the source file must
be translated into binary numbers understandable to the computer's Central Processing Unit. This
process produces an intermediate object file - with the extension .obj, the .obj stands for
Object.
DT089-2-CNotes01.doc
Page 4-7
05/10/2005
DT089/2
2.1.3
Software Systems
2005/2006
Linking
The main reason for linking is that many compiled languages come with library routines that can
be added to your program. Theses routines are written by the manufacturer of the compiler to
perform a variety of tasks, from input/output to complicated mathematical functions. In the case
of C the standard input and output functions are contained in a library (stdio.h) so even the
most basic program will require a library function. After the linking stage, the file extension is
.exe which are executable files.
2.1.4
Executable files
We have seen that the text editor produces .c source files, which go to the compiler, which
produces .obj object files, which go to the linker, which produces .exe executable file. You can
then run .exe files as you can other applications. For example, if working on a PC the
executable can be run simply by typing its name at the DOS prompt or run using windows menu.
If working from a workstation, the executable can be run by typing their name from a terminal
emulator window at the shell prompt or from the file manager window.
DT089-2-CNotes01.doc
Page 5-8
05/10/2005
DT089/2
Software Systems
3.
Structure of C Programs
3.1
C's Character Set
2005/2006
C does not use, nor requires the use of, every character found on a modern computer keyboard.
The only characters required by the C Programming Language are as follows:
 A - Z
3.2

a -z

0-9

space . , : ; ' $ "

# % & ! _ {} [] () < > |

+-/*=
The form of a C Program
Main Program
Function 1
Function 1.1
Figure 3
Function 2
Function 1.2
Function 2.1
Function 3
Function 2.2
Block Diagram of C Program
All C programs will consist of at least one function, but it usually comprises several functions.
The main function acts as a controlling function calling other functions in their turn.. The main
function is the first function that is called when your program executes.
C makes use of only 32 keywords that combine with the formal syntax to the form the C
programming language. Note that all keywords are written in lower case - C, like UNIX, uses
upper and lowercase text to mean different things. A keyword may not be used for any other
purposes. For example, you cannot have a variable called char.
DT089-2-CNotes01.doc
Page 6-9
05/10/2005
DT089/2
3.3
Software Systems
2005/2006
The layout of C Programs
The general form of a C program is as follows (don’t worry about what everything means at the
moment - things will be explained later):
preprocessor directives
global declarations
main()
{
local variables to function main ;
statements associated with function main ;
calls to other functions
}
function1()
{
local variables to function 1 ;
statements associated with function 1 ;
}
function2()
{
local variables to function f2 ;
statements associated with function 2 ;
}
.
.
.
etc
Note the use of the bracket set () and {}. () are used in conjunction with function names whereas
{} are used as to delimit the C statements that are associated with that function. Also note the
semicolon; a semicolon (;) is used to terminate C statements. C is a free format language and
long statements can be continued, without truncation, onto the next line. The semicolon informs
the C compiler that the end of the statement has been reached. Free format also means that you
can add as many spaces as you like to improve the look of your programs.
A very common mistake made by everyone, who is new to the C programming language, is to
miss off the semicolon. The C compiler will concatenate the various lines of the program
together and then tries to understand them - which it will not be able to do. The error message
produced by the compiler will relate to a line of you program which could be some distance from
the initial mistake.
DT089-2-CNotes01.doc
Page 7-10
05/10/2005
DT089/2
3.4
Software Systems
2005/2006
Preprocessor Directives
A preprocessor processes a C program before it is read by the compiler. A C program is read by
the preprocessor and modified by preprocessor directives. The preprocessor directives are placed
in a C program to tell the preprocessor how to modify the program.
All preprocessor directives begin with a # and the must start in the first column. The #include
directive is used to include a specified source file. C uses libraries of standard functions that can
be included when we build our programs. For example C provides the stdio.h standard library
to deal with standard inputting and outputting of data. The .h extension indicates that this is a
header file.
#include <stdio.h>
/* include stdio.h from standard
*/
/* include directory */
The angle brackets (< and >) around the header’s name instructs the preprocessor to search for
the specified file in the standard include directory only.
#include "myfunctions.h"
/* include myfunctions.h from current
*/
/* directory or if not found there from */
/* standard include directory */
The double quotation marks in the second format instruct the preprocessor to search for the file
in the current directory and if not found there to search the standard the standard include
directory. However, if a directory is specified within the double quotation marks, then this
directory only is searched.
Another useful preprocessor directive is #define is used to define symbolic constants, for
example:
#define PI 3.141592653
Where PI is the symbolic name. By convention, PI is usually in uppercase characters. The
preprocessor replaces all occurences of PI within the program by the value defined before the
program is compiled.
Note C program generally use the const data type (see later) for constants rather than #define.
DT089-2-CNotes01.doc
Page 8-11
05/10/2005
DT089/2
4.
Software Systems
2005/2006
C Fundamentals
To view the fundamentals of C programming, we will look at examples of simple C programs,
breaking these into the following three main functional blocks:
1. Get input data,
for example, asking the user to enter the data from the keyboard. Some data required
for the program may be assigned a value within the program.
2. Processing that data,
for example, the program may perform a mathematical operation on the input data.
3. Displaying output to the user
for example the result of the processing step may be displayed.
4.1
Simple Text Display Program: “Hello World”
The first C program introduced in many C text books is the “Hello World” program. This
program has just one function, i.e. to print the message “Hello World” on the screen.
#include <stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
Lines beginning with a # are Pre-Processor Directives. - used to tell the compiler of header files
that have to be included, and to declare constants and global variables. In this example, the
#include tells the preprocessor to include in the program the contents of the standard
input/output header file stdio.h. This file is required for data output to the screen or data input
from the keyboard.
The next line is the standard start for all C programs
int main() is the start of the function
main. This indicates the starting point of your program and can only appear once in any program
and must be in lower case. The curly brackets mark the start and end of the list of instructions
that make up the program. The int indicates that the function returns an integer value. The
return 0 before the closed curly bracket } indicates the program has ended successfully.
The printf function is provided in the C standard input/output library (stdio) and this library
must therefore be included in the preprocessor directives (#include <stdio.h>). The
printf function prints, on the screen, whatever is enclosed within the double quotes (“Hello
World\n”). The "\n" is a special symbols that forces a new line on the screen.
Note: as this program only requires a “display output” function, there is no need for data to be
fetched or assigned to memory.
DT089-2-CNotes01.doc
Page 9-12
05/10/2005
DT089/2
Software Systems
2005/2006
Adding Comments to a Program
A comment is used primarily to document the meaning and purpose of the source code. All
comments are ignored by the compiler and exist solely for information purposes.
In C, the start of a comment is signalled by the /* character pair. A comment is ended by */. For
example, this is a syntactically correct C comment:
/* This is a comment. */
Comments can extend over several lines and can go anywhere except in the middle of any C
keyword, function name or variable name. In C you can’t have one comment within another
comment. That is comments may not be nested. Lets now look at our first program one last time
but this time with comments:
#include <stdio.h>
/* PROGRAM NAME:
DESCRIPTION:
DEVELOPER:
DATE:
REVISION:
HelloWorld.c
prints “Hello World” to screen
Joe Bloggs
21/1/03
1.0
*/
int main()
{
printf(“\n Hello, World! \n”);
/* Display message on */
/* the screen
*/
return 0;
}
Programs should contain a programmer’s comment block at the start of each program stating
details such as the program function, author, date and revision.
DT089-2-CNotes01.doc
Page 10-13
05/10/2005
DT089/2
4.2
Software Systems
2005/2006
Program with Data Processing
Now we will look at a program that processes data. For example, consider the following
program that calculates the sum of two numbers assigned values in the program, i.e. not user
inputted.
/* program to calculate the sum of two integer numbers */
#include <stdio.h>
int main()
{
/* Data Declaration */
int num1 = 0,
/* declare and initialise num1 */
num2 = 0,
sum = 0;
/* 1) Explain program to user */
printf("This program calculates the ");
printf("sum of two numbers.\n");
/* 2) Assign values to Data */
num1 = 10;
num2 = 5;
/* 3) Data Processing */
sum = num1 + num2;
/* 4) Data Output */
printf("The sum is = %d", sum);
return 0;
}
Main Memory
num1
10
num2
5
sum
15
Input
Keyboard
Output
printf
10
5
ALU
sum = num1+num2
15
Central Processing Unit
Figure 4
DT089-2-CNotes01.doc
Data read from memory, processed in CPU and result stored
Page 11-14
05/10/2005
DT089/2
4.2.1
Software Systems
2005/2006
Data Types
Firstly we see that the program uses two locations in memory to store the values of the two
numbers and another location to store the result. These locations in memory where data can be
stored and then retrieved for processing are known as variables. A variable is just a named area
of storage that can hold a single value (numeric or character).
C is very fussy about how you create variables and what you store in them. It demands that you
declare the name of each variable that you are going to use and its type, or class, before you
actually try to do anything with it.
In this section we are only going to be discussing local variables. These are variables that are
used within the current program unit (or function), later we will looking at global variables variables that are available to all the program’s functions.
C recognises the data types shown in the table below.
NAME
int
char
unsigned char
short
unsigned short
long
unsigned long
enum
float
double
long double
Size
*
1
1
2
2
4
4
*
4
8
10
Details
Signed integer
Unsigned character
Unsigned character
Signed short integer
unsigned short integer
signed long integer
unsigned long integer
Enumerated
Floating point
Double floating point
Long Double floating point
Coverage
System dependent
–128 to 127
0 to 255
–32,768 to 32,767
0 to 65,535
–2,147,483,648 to 2,147,483,647
0 to 4,294,967,295
0 to 65,535
3.4E +/- 38 (7 digits)
1.7E +/- 308 (15 digits)
1.2E +/- 4932 (19 digits)
There are five basic data types associated with variables:
 int - integer: a whole number.
 float - floating point value: i.e. a number with a fractional part.
 double - a double-precision floating point value.
 char - a single character.
 void - valueless special purpose type which we will examine closely in later sections.
One of the confusing things about the C language is that the range of values and the amount of
storage that each of these types takes is not defined. This is because in each case the ‘natural’
choice is made for each type of machine.
You can call variables what you like, however most programmers follow naming conventions
which give the variable sensible names making the program easier to read and debug.
DT089-2-CNotes01.doc
Page 12-15
05/10/2005
DT089/2
4.2.2
Software Systems
2005/2006
Integer Number Variables (int)
An int variable is a whole number, no fractional part is allowed.. The size in memory is system
dependent.
To declare an int you use the instruction:
int variable name;
For example:
int num1;
To assign a value to our integer variable we would use the following C statement:
num1=10;
The C programming language uses the “=” character for assignment. A statement of the form
num1=10; should be interpreted as take the numerical value 10 and store it in a memory location
associated with the integer variable num1.
sum=num1+num2;
This statement should be interpreted as read from memory the current value stored in num1; read
from memory the value stored in num2 and add the two numbers. Then write the resulting value
to the memory location associated with sum.
4.2.3
Decimal Number Variables (float/ double)
As described above, an integer variable has no fractional part. Integer variables tend to be used
for counting, whereas real numbers are used in arithmetic. C uses one of two keywords to
declare a variable that is to be associated with a decimal number: float and double. They are
each offer a different level of precision as outlined below.
A float, or floating point, number has about seven digits of precision. A float takes four bytes to
store.
A double, or double precision, number has about 13 digits of precision. A double takes eight
bytes to store.
For example:
float total;
double sum;
4.2.4
Character Variables (char)
To declare a variable of type character we use the keyword char. - A single character stored in
one byte. For example:
char myLetter;
To assign, or store, a character value in a char data type is easy - a character variable is just a
symbol enclosed by single quotes. For example, if myLetter is a char variable you can store the
letter A in it using the following C statement:
myLetter=’A’
DT089-2-CNotes01.doc
Page 13-16
05/10/2005
DT089/2
4.3
Software Systems
2005/2006
Program with Data Output
For most programs to be useful they have to be able to output information and data to the screen.
The most important screen output function used by the C language to display information on the
screen is the printf function.
The syntax of the printf function is :
printf( "format-string", argument list.);
For example, in the program above printf is called to read the value stored in the variable sum
and display this on the computer output screen.
printf("The sum is = %d", sum);
4.3.1
Format-string:
All printf functions must have a format string. The characters in the format string are displayed
on the screen exactly as they appear unless they are preceded by the % symbol or the \ symbol.
% symbol
is used for what is known as format specifiers. Format specifiers are used to tell the
printf function what the data types of the arguments following the format string are, and
how they should be displayed. The order that the format specifiers appear in, corresponds
to the order of the list of arguments arg1,arg2 etc.
the % specifiers that you can use in ANSI C are:
Usual variable type
%c
%d
%e
%f
%g
%o
%x
(%i)
(%E)
(%G)
(%X)
char
int
float or double
float or double
float or double
int
int
Display
single character
signed integer
exponential format
signed decimal
scientific npotation
unsigned octal value
unsigned hex value
Formatting Your Output
Each specifier can be preceded by a modifier which determines how the value will be printed.
The most general modifier is of the form:
flag width.precision
The flag can be any of:
flag
+
space
0
meaning
left justify
always display sign
display space if there is no sign
pad with leading zeros
The width specifies the number of characters used in total to display the value and
precision indicates the number of characters used after the decimal point.
DT089-2-CNotes01.doc
Page 14-17
05/10/2005
DT089/2
Software Systems
2005/2006
For example, %10.3f will display the float using ten characters with three digits after
the decimal point. Notice that the ten characters includes the decimal point, and a - sign if
there is one.
The specifier %-1Od will display an int left justified in a ten character space. The
specifier %+5d will display an int using the next five character locations and will add a +
or - sign to the value.
\ symbol
is used to indicate special control characters the most common one of which is \n ,the
newline character. When this is encountered in a format string it causes the cursor to go
onto the next line.
Special Character
\a
\n
\r
\t
\b
\f
\\
\”
\’
\0
Meaning
alert (bell)
new line
carriage return
horizontal tab
backspace
formfeed
\ single dash
double quote
single quote
null character
Argument list:
This is a mixed list of variables, constants, calculations (expressions) and literal values separated
by comas. The values of these arguments are displayed using the printf function.
The example below shows how format specifiers are used to display integers, floating point
numbers and characters. In the examples the integer variable amount has a value of 2000, the
float variable length has a value of 12.5 and the char variable ch has a value of 'y'.
/* program to display varaibles */
#include <stdio.h>
int main()
{
/* Data Declaration */
int amount = 2000;
float length = 12.5;
char ch = 'y';
/* Data Output */
printf("The whole number is %d\n", amount);
printf("The real number is %.2f\n", length);
printf("The character is %c\n", ch);
/* %d -> integer */
/* %f -> floating point number */
/* %c -> character */
return 0;
}
DT089-2-CNotes01.doc
Page 15-18
05/10/2005
DT089/2
4.4
Software Systems
2005/2006
Program with User Input
Now we will modify the last program to allow the user to enter data from the keyboard.
/* program to calculate the sum of two integer numbers */
#include <stdio.h>
int main()
{
/* Data Declaration */
int num1 = 0,
num2 = 0,
sum = 0;
/* 1) Explain program to user */
printf("This program calculates the ");
printf("sum of two numbers.\n");
/* 2) Ask user to input Data */
printf("Please enter the first number > ");
scanf("%d”,&num1);
printf("Please enter the second number > ");
scanf("%d",&num2);
/* 3) Data Processing */
sum = num1 + num2;
/* 4) Data Output */
printf("The sum is = %d", sum);
return 0;
}
Main Memory
Input
Keyboard
num1
10
num2
5
sum
15
printf
scanf
Output
10
5
ALU
sum = num1+num2
15
Central Processing Unit
Figure 5
DT089-2-CNotes01.doc
User Input scanned into memory
Page 16-19
05/10/2005
DT089/2
4.4.1
Software Systems
2005/2006
Input from Keyboard
The main function that is used to allow the user to input data to a program is the scanf function.
The syntax of this function is shown below:
scanf( format-specifiers,&var1,&var2,..);
Format-specifiers:
similar to the ones used in printf enclosed in double quotation marks. The format specifers
should normally not be separated by comas, spaces or any other characters.
var1,var2.. :
variables which are used to store the inputted data.
Examples
To read in a single integer from the keyboard and store it in a variable called num1 use the
following C statement
scanf("%d",&num1);
To read in a floating point number and store it in a variable called fMyWage and an integer store
it in a variable called fLength use the following C statement
scanf("%f%d",&iMyWage,&iLength);
The scanf function reads in values from the keyboard and associates them with the corresponding
variables in the variable list. The variable names must each be preceded with an ampersand (&).
Values being inputted to a program by the user must be separated by the space bar or by the enter
key. Usually the scanf function is preceded by a printf function which is used to prompt the user
to enter the required values. A example of this is shown below:
Example
Program Code
Display (italics is user i/p)
printf("What is the diameter: ");
scanf("%f", &fDiameter);
What is the diameter: 12.3<cr>
The floating point value 12.3 entered by the user is stored in the variable fDiameter .
Note: be careful using scanf to read characters from keyboard, as all keys hit by the user will be
read, including the enter key. You can use the fflush(stdin) function to flush the input buffer
before receiving input, for example:
char ch;
:
fflush(stdin);
printf("Enter a character >> ");
scanf("%c", &ch);
:
The getchar function is used to read a character from the keyboard and return it to the calling
program. For example:
ch = getchar();
This reads a character from the keyboard and stores it in variable ch. The function requires that
the user hits <return> after typing the character and like the scanf function, a newline ‘\n’
character is left in the input buffer, so fflush can be used to clear this character from the buffer.
The getch function in the conio.h library if available differs from getchar in that it does not
require the user to hit <return>, so no newline character is left in the input buffer.
DT089-2-CNotes01.doc
Page 17-20
05/10/2005
DT089/2
5.
Software Systems
2005/2006
Arithmetic Operators
Integers and Reals can be operated on by the following arithmetic operators:
Symbol
+
*
/
%
Meaning
addition
subtraction
multiplication
division
modulus (Integers only)
Consider four very simple mathematical operations: add, subtract, multiply and divide. Let us see
how C would use these operations on two float variables num1 and num2.
add
num1+num2
subtract
num1-num2
multiply
num1*num2
divide
num1/num2
What is the answer to this simple calculation?
var = 10.0/3.0;
The answer depends upon how var was declared. If it was declared as type int the answer will
be 3; if var is of type float then the answer will be 3.333333.
What is the answer to this simple calculation?
var = 10/3;
The answer will be 3 irrespective of type of var. Because 10 and 3 are both integers, means
integer division occurs.
Two points to note from the above calculations:
1. C ignores fractions when doing integer division!
2. when doing float calculations integers will be converted into float. We will see later
how C handles type conversions.
Example
Write a program that will calculate the average of two numbers given by the user.
Answer :
/* program to calculate the average of two numbers */
#include <stdio.h>
int main()
{
float num1, num2;
printf("This program calculates the ");
printf("average of two numbers.");
printf("Enter the first number : ");
scanf("%f",&num1);
printf("Enter the second number : ");
scanf("%f",&num2);
printf("The average is = %f",(num1 + num2)/2);
return 0;
}
DT089-2-CNotes01.doc
Page 18-20
05/10/2005
DT089/2
5.1
Software Systems
2005/2006
Arithmetic Ordering
Consider the following calculation:
a=10.0 + 2.0 * 5.0 - 6.0 / 2.0
What is the answer?. In the above calculation the multiplication and division parts will be
evaluated first and then the addition and subtraction parts. This gives an answer of 17.
Note: To avoid confusion use brackets. The following are two different calculations:
a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)
a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0
5.2
More on Initialising Variables
You can assign an initial value to a variable when you declare it. For example:
int var=1;
sets the int variable to one as soon as it’s created. This is just the same as:
int var;
var=l;
but the compiler may be able to speed up the operation if you initialise the variable as part of its
declaration. Don’t assume that an un-initialised variable has a sensible value stored in it. Some C
compilers store 0 in newly created numeric variables but nothing in the C language compels
them to do so.
5.3
Constants
Constants are pieces of data used in a program which keep the same value through out the
program. These constants can be literal values such as the integer 8 or the float 1.23 as described
above.
Sometimes instead of using literals it is a good idea to assign a name or identifier to a constant
piece of data so that the identifier instead of the literal can be used throughout the program.
Constants are declared at the top of the program after the opening brace "{". The following are
examples of constant declarations :
const int
const int
MONTHS_IN_YEAR = 12;
LETTERS_IN_ALPHABET = 26,
DIGITS_IN_PHONE_NUMBER = 7;
const float PI=3.14, VOLUME_OF_VAN=1023.45;
const char CURRENCY_SYMBOL = '$';
So to declare constants we use the const keyword followed by the data type e.g. int for integers,
char for characters or float for floating point numbers. We then list the constant identifiers and
the values they are equal to. The items on the lists are separated by comas and the list is
terminated by a semicolon.
Constants can make a program more readable and if in the future when the program was being
updated or modified the value of the constant would only have to be changed where it was
declared not where it was used. To distinguish constants as unchangeable, the C convention is to
use constant names that are entirely in uppercase characters.
DT089-2-CNotes01.doc
Page 19-20
05/10/2005
DT089/2
6.
Software Systems
2005/2006
Review Questions
1. Assuming the following:
int i;
char ch;
Which of the following are valid C statements:
ch = 'A';
i = "1";
i = 1;
ch = "A";
ch = '1';
2. Write the variable definitions for each of the following:
(i)
integer variable resister_1
(ii)
floating-point variable resistance_in_parallel
(iii)
character variable my_grade
(iv)
double precision floating-point variable number
3. Write a program that will calculate:
(i)
the volume
(ii)
the surface area
of a box with a height of 10cm, a length of 11.5 cm and a width of 2.5cm
4. Write a program to do the following:
(i)
calculate and display the sum of the integers 1 to 5;
(ii)
calculate and display of the floating-point numbers 1.0, 1.1, 1.2. to 1.5;
5. Write a program that will calculate the cube of a number given by the user.
6. Write a program that will calculate the area of a square when given the length of one side by
the user.
DT089-2-CNotes01.doc
Page 20-20
05/10/2005