[go: up one dir, main page]

0% found this document useful (0 votes)
29 views82 pages

COS201_2024-25

Uploaded by

ayigbolafausat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views82 pages

COS201_2024-25

Uploaded by

ayigbolafausat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

OLABISI ONABANJO UNIVERSITY

DEPARTMENT OF COMPUTER SCIENCES

Harmattan Semester, 2024/2025 Academic Session

COS201: Computer Programming I


(Using C Programming Language)

THIS DOCUMENT IS NOT FOR SALE!


LABORATORY ONE

1.1 Computer Programming


A computer isn’t smart. Believe it or not, on your worst days, you are still light-years ahead
of your computer in intelligence. Computers are really very dumb machines indeed because they do
only what they are told to do. The computer can’t decide what to do on its own. Computers can’t
think for themselves, so programmers (people who tell computers what to do) must give computers
extremely detailed instructions. Without instructions, a computer is useless; with incorrect
instructions, a computer will not successfully execute your desired task.
A computer program is a series of instructions which enables the computer to perform a
designated task. As this text will demonstrate, a computer must be told what to do in precise, step-
by-step detail. These steps might include obtaining data, arithmetic operations (addition,
subtraction, multiplication, division, etc.), data storage, and information output. The computer will
perform these tasks as instructed, even if they don't always make sense. Consequently, it is the
programmer who must develop a solution to the problem.
To solve a problem using a computer, you must express the solution to the problem in terms
of the instructions of the particular computer. A computer program is just a collection of the
instructions necessary to solve a specific problem. The approach or method that is used to solve the
problem is known as an algorithm. For example, if you want to develop a program that tests if a
number is odd or even, the set of statements that solves the problem becomes the program. The
method that is used to test if the number is even or odd is the algorithm. Normally, to develop a
program to solve a particular problem, you first express the solution to the problem in terms of an
algorithm and then develop a program that implements that algorithm.

1.2 Introduction to Structured Programming


Software engineering is a discipline that is concerned with the construction of robust and
reliable computer programs. Just as civil engineers use tried and tested methods for the construction
of buildings, software engineers use accepted methods for analyzing a problem to be solved, a
blueprint or plan for the design of the solution and a construction method that minimizes the risk of
error. The structured programming approach to program design was based on the following method.
a) To solve a large problem, break the problem into several pieces and work on each piece
separately.
b) To solve each piece, treat it as a new problem that can itself be broken down into smaller
problems;
c) Repeat the process with each new piece until each can be solved directly, without
further decomposition.
This approach is called top-down programming.

1.3 The Birth of Modern Programming: C


The C language shook the computer world. Its impact should not be underestimated, because
it fundamentally changed the way programming was approached and thought about. C is a “higher-
level programming language” developed at AT and T’s Bell Laboratories of USA in 1972. It was
designed and written by a man named Dennis Ritchie. The creation of C was a direct result of the
need for a structured, efficient, high-level language that could replace assembly code when creating
systems programs. As you probably know, when a computer language is designed, trade-offs are
often made, such as the following:
i. Ease-of-use versus power
ii. Safety versus efficiency
iii. Rigidity versus extensibility
Prior to C, programmers usually had to choose between languages that optimized one set of
traits or the other. For example, although FORTRAN could be used to write fairly efficient
programs for scientific applications, it was not very good for system code. And while BASIC was
easy to learn, it wasn’t very powerful, and its lack of structure made its usefulness questionable for
large programs. Assembly language can be used to produce highly efficient programs, but it is not
easy to learn or use effectively. Further, debugging assembly code can be quite difficult.
Another compounding problem was that early computer languages such as BASIC, COBOL,
and FORTRAN were not designed around structured principles. Instead, they relied upon the
GOTO as a primary means of program control. As a result, programs written using these languages
tended to produce “spaghetti code”—a mass of tangled jumps and conditional branches that make a
program virtually impossible to understand. While languages like Pascal are structured, they were
not designed for efficiency, and failed to include certain features necessary to make them applicable
to a wide range of programs. (Specifically, given the standard dialects of Pascal available at the
time, it was not practical to consider using Pascal for systems-level code.)
The creation of C is considered by many to have marked the beginning of the modern age of
computer languages. It successfully synthesized the conflicting attributes that had so troubled
earlier languages. The result was a powerful, efficient, structured language that was relatively easy
to learn. It also included one other, nearly intangible aspect: it was a programmer’s language. Prior
to the invention of C, computer languages were generally designed either as academic exercises or
by bureaucratic committees. C is different. It was designed, implemented, and developed by real,
working programmers, reflecting the way that they approached the job of programming. Its features
were honed, tested, thought about, and rethought by the people who actually used the language. The
result was a language that programmers liked to use. Indeed, C quickly attracted many followers
who had a near-religious zeal for it. As such, it found wide and rapid acceptance in the programmer
community. In short, C is a language designed by and for programmers, especially system
programming.
Some examples of the use of C might be:
a) Operating Systems
b) Language Compilers
c) Assemblers
d) Text Editors
e) Print Spoolers
f) Network Drivers
g) Modern Programs
h) Databases
i) Language Interpreters
j) Utilities

1.4 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.
j) C is the most widely-used portable language for low-level coding (compilers, and libraries,
and kernels).

1.5 Strengths and Weaknesses of C


Like any other programming language, C has strengths and weaknesses. Both stem from the
language’s original use (writing operating systems and other system software) and its underlying
philosophy:
a) C is a low-level language. To serve as a suitable language for system programming, C
provides access to machine-level concepts (bytes and addresses, for example) that other
programming languages try to hide. C also provides operations that correspond closely to a
computer’s built-in instructions, ao that programs can be fast. Since application programs
rely on it for input/output, storage management, and numerous other services, an operating
system can’t afford to be slow.
b) C is a small language. C provides a more limited set of features than many
languages. To keep the number of features small, C relies heavily on a “library” of standard
functions. (A “function” is similar to what other programming languages might call a
“procedure”, “subroutine”, or “method”)
c) C is a permissive language. C assumes that you know what ypu are doing. So it allows you
a wider degree of latitude than many languages. Moreover, C doesn’t mandate the detailed
error-checking found in other languages.

1.5.1 Strengths
C’s strengths help explain why the language has become so popular:
i) Efficiency. Efficiency has been one of C’s advantages from the beginning. Because C
was intended for applications where assembly language had traditionally been used, it was
crucial that C programs could run quickly and in limited amounts of memory.
ii) Portability. Although program portability wasn’t a primary goal of C, it has turned out to
be one of the language’s strengths. When a program must run on computers ranging from
PCs to supercomputers, it is often written in C. One reason for the portability of C is that –
thanks to C’s early association with UNIX. Another is that C compilers are small and easily
written, which has helped make them widely available. Finally, C itself has features that
support portability (although there’s nothing to prevent programmers from writing non-
portable programs).
iii) Power. C’s large collection of data types and operators help make it a powerful
language. In C, it’s often possible to accomplish quite a bit with just a few lines of code.
iv) Flexibility. Although C was originally designed for systems programming, it has no
inherent restrictions that limit it to this area. C is now used for applications of all kinds, from
embedded systems to commercial data processing. Moreover, C imposes very few
restrictions on the use of its features; operations that would be illegal in other languages are
often permitted in C. For example, C allows a character to be added to an integer value (or,
for that matter, a floating-point number). This flexibility can make programming easier,
although it may allow some bugs to slip through.
v) Standard library. One of C’s great strngths is its standard library, which contains
hundreds of functions for input/output, string handling, storage allocations, and other useful
operations.
vi) Integration with UNIX. C is particularly powerful in combination with UNIX
(including the popular variant known as Linux). In fact, UNIX tools assume that the user
knows C.

1.5.2 Weaknesses
C’s weaknesses arise from the same source as many of its strengths: C’s closeness to the
machine. Here are a few of C’s most notorious problems:
i) C programs can be error-prone. C’s flexibility makes it an error-prone language.
Programming mistakes that would be caught in many other languages can’t be detected by a
C’s compiler. In this respect, C is a lot like assembly language, where most errors aren’t
detected until the program is run.
ii) C programs can be difficult to understand. Although C is a small language by most
measures, it has a number of features that aren’t found in all programming languages (and
that consequently are often misunderstood). These features can be combined in a great
variety of ways, many of which – although obvious to the original author of a program – can
be hard for others to understand. Another problem is the terse nature of C programs. C was
designed at a time when interactive communications with computers was tedious at best. As
a result, C was purposefully kept terse to minimize the time required to enter and edit
programs. C’s flexibility can also be a negative factor; programmers who are too clever for
their own good can make programs almost impossible to understand.
iii) C programs can be difficult to modify. Large programs written in C can be hard to
change if they haven’t been designed with maintenance in mind. Modern programming
languages usually provide features such as classes and packages that support the division of
a large program into more manageable pieces. C, unfortunately, lacks such features.

1.6 Operating System


The Operating System, or OS, is an interface between the user and the hardware (CPU, memory,
screen, disk drive, etc.). The OS is responsible for the management of the hardware, coordination of
activities, and the sharing of the resources of the computer that acts as a host for computing
applications run on the machine. The common operating systems include various versions of
Windows, MAC OS X, and UNIX/Linux. Programs written in Fortran programming language will
work on these operating systems.

1.7 Computer Organization


Before writing programs, it is useful to understand some basics about how a computer is
organised. This section provides a brief, high-level overview of the basic components of a computer
and how they interact.

1.7.1 Architecture overview


The basic components of a computer include a Central Processing Unit (CPU), Primary Storage or
Random Access Memory (RAM), Secondary Storage, and Input/Output devices (i. e., screen,
keyboard, and mouse), and an interconnection referred to as BUS. The secondary storage may be a
Solid-State Drive (SSD), disk drive, or other type of secondary storage media. A very basic diagram
of a computer architecture is pictured in Figure 1.1.

Figure 1.1: Computer Architecture


Programs and data are typically stored on the disk drive. When a program is executed, it must be
copied from the disk drive into the RAM memory. The CPU executes the program from RAM. This
is similar to storing a term paper on the disk drive, and when writing/editing the term paper, it is
copied from the disk drive into memory. When done, the updated version is stored back to the disk
drive.

1.8 Tutorial Questions


a) Explain why C could be considered a good option for embedded systems
b) Who invented the C programming language?
c) What do you understand by structured programming?
d) Provide five features of C programming language.
e) Describe the three underlying philosophies of C.
f) Describe the strengths and shortcomings of C.
LABORATORY 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 */

printf("Hello, World! \n");

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.2 Compiler
Programs can be written in the C 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.

2.3 Compiling and Linking


Despite its brevity getting hello.c to run is more involved than you might expect. First, we
need to create a file named hello.c containing the program (any text editor will do). The name of the
file doesn’t matter, but the .c extension is often required by compilers.
Next, we’ve got to convert the program to a form that the machine can execute. For a C
program, that usually involves three steps:
i) Preprocessing. The program is first given a preprocessor, which obeys commands that
begin with # (known as directives). A preprocessor is a bit like an editor; it can add things to
the program and make modifications.
ii) Compiling. The modified program now goes to a compiler, which translates it into
machine instructions (object code). The program isn’t quite ready to run yet, however.
iii) Linking. In the final step, a linker combines the object code produced by the compiler
with any additional code needed to yield a complete executable program. This additional
code includes library functions like (printf) that are used in the program.
2.4 Program Environment Setup
Programs produce output when you run or execute them. Before you can write and execute a
C program on your computer, you need a C compiler. The C compiler takes the C program you
write and builds or compiles it (technical terms for making the program computer-readable),
enabling you to run the compiled program when you’re ready to look at the results.
The alternative is to use an integrated development environment (IDE), a software package that
allows us to edit, compile, execute, and even debug a program without leaving the environment.
The components of an IDE are designed to work together. There’s a great deal of variation among
IDE’s. Luckily, many excellent free software packages such as Geany, NetBeans, Eclipse are freely
available in which you can edit and compile your C programs.
In this course, we will be using Code::Blocks (available from www.codeblocks.org) is a
single integrated application known as an Integrated Development Environments (IDE). The IDE
allows for processing, editing, compiling, running, and debugging programs.
Though, if you run a search for “C Programming Compilers,” you’ll see a number of
freeware options, including offerings from Borland and Microsoft. In particular, under Windows,
Microsoft Visual Studio is a good example of a popular IDE. Kylix is a popular IDE for developing
applications under Linux.
One good reason for using Code::Blocks however is because it offers versions for Windows,
Macs, and Linux, so you can use a version of the software no matter what operating system you use.
However, feel free to pick whichever programming environment looks best to you.
Code::Blocks is a free, open-source, cross-platform C, C++ and Fortran IDE built to meet
the most demanding needs of its users. It is designed to be very extensible and fully configurable.
The term “open source” refers to software code that users can alter or improve. The term
“cross-platform” is an adjective that means the software can run on different operating systems—as
a beginner, however, you need concern yourself with only your own platform. I think free is a term
we can all get behind, and IDE is short for integrated development environment, which just means
you can write, edit, and debug your programs without having to switch software to do so.

2.4.1 How to download and install Code::Blocks


i. Visit www.codeblocks.org
ii. From the home page, to download the C/C++ IDE, click the Downloads choice under the
Main section in the left column.
iii. After you select Downloads, you are taken to a page that further discusses three options:
Binaries, Source, and SVN. The latter two options are advanced, so you can ignore them.
Click Download the binary release.
iv. The next page presents a variety of options, depending on your operating system. If you
select the Windows option, choose the second option. Having the full compiler and
debugger will come in handy.
After a successful download and installation, you should be left with the opening screen of the
software, pictured in Figure 2.1.

Figure 2.1: Welcome to your programming home!

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.

2.5 The Programming Process


Most people follow these basic steps when writing a program:
(1) Decide exactly what the program should do.
(2) Use an editor to write and save your programming language instructions. An editor is a lot
like a word processor (although not usually as fancy) that lets you create and edit text. All
the popular C compilers include an integrated editor along with the programming language
compiler. All C program filenames end in the .c file extension.
(3) Compile the program.
(4) Check for program errors. If any appear, fix them and go back to step 3.
(5) Execute the program.

2.6 Writing Your First C Program


Open your Code::Blocks programming software. To create your program, Click the File
Menu and select New. Choose Empty File from the options that appear on the submenu. Now
you’ve got a nice clean file to start writing your program. The first (seven-line) program is
extremely simple - a short but complete C program:
Program 2.2 Hello.c
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}

2.7 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.7.1 Specifying 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 */

(b) /* This is a single-line comment */


for (i = 0; i < 25; i++)
/* Counts from 0 to 25 */
Figure 2.2: The output of your first program.
(2) Single line comment style: This style of comment begins with two slashes (//) and ends
only at the end of the line. C ignores the rest of the line after that point.. This kind of
comment was originally developed for C++ programs.
Here is an example of the new style of comment:
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.7.2 Importance of Comments in Program Maintenance


Program maintenance is the process of changing a program over time to fix hidden bugs and
to adapt the program to a changing environment.
If you write a program to calculate payroll, the program’s comments explain the gross pay
calculations, state tax calculations, federal tax calculations, social security calculations, deductions,
and all the other calculations that are going on.
The company could eventually change the way it does payroll (to go from biweekly to
weekly, as an example), and you (or another programmer) will have to modify the payroll program
to conform to the company’s new payroll procedures. Commenting speeds program maintenance.
With comments, you or another programmer can quickly scan through a program listing to find the
areas that need changing.
Many programmers like to place a multiline comment before a section of code and then
insert a few smaller comments on lines that need them. Many companies require that their
programmers embed their own names in comments at the top of programs they write. If changes
need to be made to the program later, the original programmer can be found to help.

2.8 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.

2.9 Tutorial Questions


a) Describe the essential format of a C language
b) Following the steps highlighted in section 2.4.1, install Code::Blocks on your development
system.
c) Mention the benefits of writing a program using an IDE instead of word processors like
wordpad or word.
d) Write a C program to display “Programming in good” using the GEANY IDE
e) Provide illustrations on the various ways of including comments in a C program.
f) Provide an illustration of the usage of white spaces
LABORATORY 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.

3.2 Storing Data in Variables


The assignment operator puts values in variables. The assignment operator is simply the
equals sign (=). The format of putting data in variables looks like this:
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 */

3.3 Data Types


The C programming language provides five basic data types: int, float, double, char, and
_Bool.
A variable declared to be of type int can be used to contain integral values only—that is,
values that do not contain decimal places.
A variable declared to be of type float can be used for storing floating-point numbers (values
containing decimal places).
The double type is the same as type float , only with roughly twice the precision.
The char data type can be used to store a single character, such as the letter a, the digit
character 6, or a semicolon (more on this later).
Finally, the _Bool data type can be used to store just the values 0 or 1. Variables of this type
are used for indicating an on/off, yes/no, or true/false situation.
In C, any number, single character, or character string is known as a constant. For example,
the number 58 represents a constant integer value. The character string "Hello World!\n" is an
example of a constant character string.

3.3.1 The Basic Integer Type int


In C, an integer constant consists of a sequence of one or more digits. A minus sign
preceding the sequence indicates that the value is negative. The values 158, –10, and 0 are all valid
examples of integer constants. No embedded spaces are permitted between the digits, and values
larger than 999 cannot be expressed using commas. (So, the value 12,000 is not a valid integer
constant and must be written as 12000).
3.3.2 The Floating Number Type float
A variable declared to be of type float can be used for storing values containing decimal
places. A floating-point constant is distinguished by the presence of a decimal point. You can omit
digits before the decimal point or digits after the decimal point, but obviously you can’t omit both.
The values 3. , 125.8 , and –.0001 are all valid examples of floating-point constants.
Floating-point constants can also be expressed in scientific notation. The value 1.7e4 is a
floating-point value expressed in this notation and represents the value 1.7 × 10 –4. The value
before the letter e is known as the mantissa, whereas the value that follows is called the exponent.
This exponent, which can be preceded by an optional plus or minus sign, represents the power of 10
by which the mantissa is to be multiplied. So, in the constant 2.25e–3 , the 2.25 is the value of the
mantissa and –3 is the value of the exponent. This constant represents the value 2.25 × 10 –3 , or
0.00225. Incidentally, the letter e , which separates the mantissa from the exponent, can be written
in either lowercase or uppercase.

3.3.3 The Extended Precision Type double


Type double is very similar to type float, but it is used whenever the range provided by a
float variable is not sufficient. Variables declared to be of type double can store roughly twice as
many significant digits as can a variable of type float. Most computers represent double values
using 64 bits. Unless told otherwise, all floating-point constants are taken as double values by the C
compiler. To explicitly express a float constant, append either an f or F to the end of the number, as
follows:
12.5f

3.3.4 The Single Character Type char


Your computer knows 256 different characters. Each of them is found in something called
the ASCII (American National Standards Institute) table. Anything your computer can represent can
be a character. Any or all of the following can be considered characters:
A a 4 % Q ! + = ]
In C, a char variable can be used to store a single character. A character constant is formed
by enclosing the character within a pair of single quotation marks. So 'A', 'a', '4', '%', '+
', '-' , and '0' are all valid examples of character constants.
None of the following can be character data because they have no apostrophes around them:
A, a, 4, %, and -
Do not confuse a character constant, which is a single character enclosed in single quotes,
with a character string, which is any number of characters enclosed in double quotes. None of the
following are valid characters.
(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.

3.4 Displaying the Value of Variable


The printf routine provides an easy and convenient means to display program results. Not
only can simple phrases be displayed, but the values of variables and the results of computations
can also be displayed. In fact, Program 3.1 uses the printf routine to display the results of adding
two numbers, namely 50 and 25.
Program 3.1 Displaying Variables
#include <stdio.h>
int main (void)
{

int sum;

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.

3.5 Example on Data Types Usage


In Program 3.1, the basic C data types are used.

Program 3.1 Using the Basic Data Types

#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);
printf ("charVar = %c\n", charVar);
printf ("boolVar = %i\n", boolVar);
return 0;
}

Program 3.1 Output

integerVar = 100
floatingVar = 331.790009
doubleVar = 8.440000e+11
doubleVar = 8.44e+11
charVar = W
boolVar = 0;

3.6 Integers Versus Floating-point Data Types


The choice of using integers or floating-point numbers depends on the data your programs
are working with. Some values (such as ages and quantities) need only integers; other values (such
as money amounts or weights) need the exact amounts floating-point numbers can provide.
Internally, C stores integers differently than floating-point values. As you can see from
Figure 3.1, a floating-point value usually takes twice as much memory as an integer. Therefore, if
you can get away with using integers, do so—save floating points for values that need the decimal
point.

Figure 3.1 Storing floating-point values often takes more memory than integers.
3.7 Working with Arithmetic Expressions
In C, just as in virtually all programming languages, the plus sign ( + ) is used to add two
values, the minus sign ( – ) is used to subtract two values, the asterisk ( * ) is used to multiply two
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.

Program 3.2 Using the Arithmetic Operators

// Illustrate the use of various arithmetic operators


#include <stdio.h>
int main (void)
{
int a = 100;
int b = 2;
int c = 25;
int d = 4;
int result;
result = a - b;
// subtraction
printf ("a - b = %i\n", result);
result = b * c;
// multiplication
printf ("b * c = %i\n", result);
result = a / c;
// division
printf ("a / c = %i\n", result);
return 0;
}

Program 3.2 Output


a - b = 98
b * c = 50
a / c = 4

3.8 Order of Operators


C doesn’t always compute math operations in the order you expect. Example:
ans = 5 + 2 * 3; /* Puts 11 in ans */
If you thought that C would store 21 in ans, you’re reading the expression from left to right.
However, C always computes multiplication before addition. It sounds crazy, but as long as you
know the rules, you’ll be okay. C is following the order of operators table. C first multiplies 2 and 3
to get 6, and then adds 5 to get 11.
In fact, each operator in C has a precedence associated with it. This precedence is used to
determine how an expression that has more than one operator is evaluated:The operator with the
higher precedence is evaluated first. Expressions containing operators of the same precedence are
evaluated either from left to right or from right to left, depending on the operator. This is known as
the associative property of an operator.
As you can see in the Table 3.1, *, /, and % appear before + and -. Therefore, if C sees an
expression with a combination of these operators, it evaluates *, /, and % before computing + and -.
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.

Figure 3.2 Solving the expression the way C would.

Table 3.1. Order of Operators


Program 3.3 Using the Arithmetic Operators Precedence
// Illustrate the use of various arithmetic operators precedence
#include <stdio.h>
int main (void)
{
int a = 100;
int b = 2;
int c = 25;
int d = 4;
int result;
result = a - b;
// subtraction
printf ("a - b = %i\n", result);
result = b * c;
// multiplication
printf ("b * c = %i\n", result);
result = a / c;
// division
printf ("a / c = %i\n", result);
result = a + b * c;
// precedence
printf ("a + b * c = %i\n", result);
printf ("a * b + c * d = %i\n", a * b + c * d);
return 0;
}

Program 3.2 Output


a - b = 98
b * c = 50
a / c = 4
a + b * c = 150
a * b + c * d = 300

3.9 Combining Operations with Assignment: The Assignment Operators


The C language permits you to join the arithmetic operators with the assignment operator
using the following general format: op=
In this format, op is any of the arithmetic operators, including + , – , × , / , and %.
Consider this statement:
count += 10;
The effect of the so-called “plus equals” operator += is to add the expression on the right side of
the operator to the expression on the left side of the operator and to store the result back into the
variable on the left-hand side of the operator. So, the previous statement is equivalent to this
statement:
count = count + 10;
A slightly more involved expression is:
a /= b + c
which divides a by whatever appears to the right of the equal sign—or by the sum of b and c —
and stores the result in a .The addition is performed first because the addition operator has higher
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)

3.10 Tutorial Questions


a) Explain why integers data type might be a better option than floating dtat types in embedded
systems.
b) Write a program that prints values from one to 100.
c) Which of the following are invalid variable names? Why?
Int Calloc floating ReInitialize char
Xx _1312 6_05 alpha_beta_routine z A$
d) Write a program that converts 27° from degrees Fahrenheit (F) to degrees Celsius
(C) using the following formula:
C = (F - 32) / 1.8
e) Which of the following are invalid constants? Why?
123.456 0001 0Xab05 123.5e2 98.6F 0996 1234uL
1.234L 0XABCDEFL 0x10.5 0xFFFF 0L
.0001 98.7U -12E-12 1.2Fe-7 197u
0xabcu 0X0G1 123L -597.25 +12
17777s 07777 15,000 100U +123
LABORATORY FOUR: FORMATTED INPUT/OUTPUT

4.1 Introduction
scanf and printf, which support formatted reading and writing, are two of the most
frequently used functions in C. As this laboratory section shows, both are powerful but tricky to use
proper

4.2 The printf Function


The printf function is designed to display the contents of a string, known as the format
string, with values possibly inserted at specified points in the string. When it’s called, printf must
be supplied with the format string, followed by any values that are to be inserted into the string
during printing:

printf (string, exp1, expr2, …);

The values displayed can be constants, variables, or more complicated expressions. There’s
no limit on the number of values that can be printed by a single call of printf.
The format string may contain both characters and conversion specifications, which begin
with the % character. A conversion specification is a place holder representing a value to be filled in
during printing. The information that follows the % character specifies how the value is converted
from its internal form (binary) to printed form (characters) – that’s where the term “conversion
specification” comes from. For example, the conversion specification %d specifies that printf is to
convert an int value from binary to a string of decimal digits, while %f does the same for a float
value.
Ordinary characters in a format string are printed exactly as they appear in the string;
conversion specifications are placed by the values to be printed. Consider the following example:

int i, j;
float x, y;

i = 10;
j = 20;
x = 43.2892f;
y = 5527.0f;
printf (“i = %d, j = %d, x = %f, y = %f\n”, i, j, x, y);
This call of printf produces the following output:
i = 10, j = 20, x = 43.289200, y = 5527.000000
The ordinary characters in the format string are simply copied to the output line. The four
conversion specifications are replaced by the values of the variables i, j, x, and y, in that order.

4.3 Escape Sequences


The \n code that we often use in format strings is called an escape sequence. Escape
sequences enable strings to contain characters that would otherwise cause problems for the
compiler, including non-printing (control) characters and characters that have a special meaning to
the compiler (such as ”). Here’s a sample:

alert (bell) \a
Backspace \b
New line \n
Horizontal tab \t

When they appear in printf format string, these escape sequences represent actions to
perform upon printing. Printing \a causes an audible beep on most machines. Printing \b moves the
cursor back one position. Printing \n advances the cursor to the beginning of the next line. Printing
\t moves the cursor to the next tab stop.
A string may contain any number of escape sequences. Consider the following example, in
which the format string contains six escape sequences:

printf(“Item \t Unit \t Purchase \n \t Price \t Date \n”);

Executing this statement prints a two-line heading:

Item Unit Purchase


Price Date

Another common escape sequence is \”, which represents the ” character. Since the ”
character marks the beginning and end of a string, it can’t appear within a string without the use of
this escape sequence. Here’s an example:

printf(“\” Hello!\””);

The statement produces the following output:


“Hello!”

4.4 The scanf Function


Just as printf prints output in a specified format. scanf reads input according to a
particular format. A scanf format string, like a printf format string, may contain both ordinary
characters and conversion specifications. The conversions allowed with scanf are essentially the
same as those used with printf.
In many cases, a scanf format string will contain contain only conversion specifications as
in the following example:

int i, j;
float x, y;
scanf (“ %d %d %f %f”, &i, &j, &x, &y);

Suppose that the user enters the following input line:


1 -20 -3 -4.0e3
scanf will read the line, converting its characters to the numbers they represent, and then assign 1, -
20, 0.3, and -4000.0 to i, j, x, and y respectively. Tightly packed” format strings like %d %d %f
%f” are common in scanf calls. printf format strings are less likely to have adjacent conversion
specifications.
scanf, like printf, contains several traps for the unwary. When using scanf, the
programmer must check that the number of conversion specifications matches the number of input
variables and that each conversion is appropriate for the corresponding variable – as with printf,
the compiler isn’t required to check for a possible mismatch. Another trap involves the & symbol,
which normally precedes each variable in a scanf call. The & is usually (but not always) required,
and it’s the programmer’s responsibility to remember to use it.

Note:
Forgetting to put the & symbol in front of a variable in a call of scanf will have
unpredictable – and possibly disastrous – results. A program crash is a common outcome. At the
very least, the value that is read from the input won’t be stored in the variable; instead, the variable
will retain its old value (which may be meaningless if the variable wasn’t given an initial value).
Omitting the & is an extremely common error – be careful!. Some compilers can spot this error and
produce a warning message such as “format arrangement is not a pointer” (The term pointer is
defined in Laboratory 7; the & symbol is used to create a pointer to a variable). If you get a
warning, check for a missing &.
4.5 Adding Fractions
To illustrate scanf’s ability to match patters, consider the problem of reading a fraction
entered by the user. Fractions are customarily written in the form numerator/denominator. Instead of
having the user enter the numerator and denominator a a fraction as separate integers, scanf makes
it possible to read the entire fraction. The following program, which adds two fractions, illustrates
this technique.

Program to add two fractions


#include <stdio.h>
int main (void)
{
int num1, demom1, num2, denom2, result_num, result_denom;

printf (“Enter first fraction: “);


scanf (“%d/%d, &num1, &denom1);

printf (“Enter second fraction: “);


scanf (“%d/%d, &num2, &denom2);

result_num = num1 * denom2 + num2 * denom1;

result_denom = denom1 * denom2;


printf(“The sum is %d/%d\n”, result_num, result_denom);

return 0;
}

Program output:
Enter first fraction: 5/6
Enter second fraction: ¾
The sum is 38/24

Note that the resulting fraction isn’t reduced to lowest terms.


4.6 Tutorial Questions

1. What output do the following calls of printf produce?


(a) printf (“%6d, %4d”, 86, 1040);
(b) printf (“%12.5e”, 30.253);
(c) printf (“%.4f”, 83.172);
(d) printf (“%-6.2g”, 0.0000009979);

2. For each of the following pairs of scanf format strings, indicate whether or not the two
strings are equivalent. If they are not, show how they can be distinguished.
(a) “%d” versus “ %d”
(b) “%d-%d-%d” versus “%d -%d -%d”
(c) “%f” versus “%f ”
(d) “%f, %f” versus “%f, %f”

3. Suppose that we call scanf as follows:


scanf (“%d%f%d”, &i, &x, &j);
If the user enters
10.3 5 6
What will be the values of i, x, and j after the call? (Assume that i and j are int variables
and x is a float variable).

4. Suppose that we call scanf as follows:


scanf (“%f%d%f”, &x, &i, &y);
If the user enters
12.3 45.6 768
what will be the values of x, i, and j after the call? (Assume that x and y are float
variables and i is an int variable).
LABORATORY FIVE: PROGRAM LOOPING IN C

5.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.

5.2 The for Statement


The general format of the for statement is as follows:

for ( init_expression; loop_condition; loop_expression )


program statement;

The three expressions that are enclosed within the parentheses — init_expression,
loop_condition , and loop_expression — set up the environment for the program loop. The
program statement that immediately follows (which is, of course, terminated by a semicolon) can be
any valid C program statement and constitutes the body of the loop. This statement is executed as
many times as specified by the parameters set up in the for statement. The first component of the for
statement, labeled init_expression , is used to set the initial values before the loop begins. The
second component of the for statement the condition or conditions that are necessary for the loop to
continue. In other words, looping continues as long as this condition is satisfied.
Program 5.1 is a sample code to illustrate the usage of the for loop.

Program 5.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 5.1 Output


1 4 7 10 13 16

Program 5.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 5.2 Output


The sum of first 200 natural numbers is 20100

Program 5.3 is an improvement on Program 5.2 whereby the result of each iteration is printed to
the screen
Program 5.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 5.3 Output


The sum of first 200 natural numbers is 1
The sum of first 200 natural numbers is 3
The sum of first 200 natural numbers is 6
The sum of first 200 natural numbers is 10
The sum of first 200 natural numbers is 15
The sum of first 200 natural numbers is 21
------
------
The sum of first 200 natural numbers is 20100
5.2.1 Omitting expressions in a for statement
The for statement is even more flexible than we’ve seen so far. Some for loops may not need all
three of the expressions that normally control the loop, so C allows us to omit any or all of the
expressions.
If the first expression is omitted, no initialization is performed before the loop is executed:

i = 10;
for ( ; i > 0; --i )
printf (“T minus %d and counting \n”, i);

In this example, i has been initialized by a separate assignment, so we’ve omitted the first
expression in the for statement. (Notice that the semicolon between the first and second
expressions remains. The two semicolons must always be present, even when we’ve omitted some
of the expressions.)
If we omit the third expression if a for statement, the loop body is responsible for ensuring
that the value of the second expression eventually becomes false. Our for statement example could
be written like this:

for (i = 10; i > 0; )


printf (“T minus %d and counting \n”, i - -);

To compensate for omitting the third expression, we

5.3 Program Input


Program 5.2 calculates the sum of first 200 natural numbers—and nothing more. If you want
to calculate the sum of first 50 or 100 natural numbers instead, you have to go back and change the
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 5.4 asks the user the number of natural numbers should be calculated, proceeds to
calculate that the sum, and then displays the results.

Program 5.4 Asking the User for Input


/* Program to calculate the sum of first supplied natural numbers
Introduction of the for statement
*/
#include <stdio.h>
int main (void)
{
int sum, number;
sum = 0;

printf ("How many numbers do you want? ");


scanf ("%i", &number);

for ( int counter = 1; counter <= number; counter = counter + 1 )


sum = sum + counter;
printf ("The sum of %i natural numbers is %i\n", number, sum);

return 0;
}

Program 5.4 Output


How many numbers do you want? 200
The sum of 200 natural numbers is 20100

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 5.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. Laboratory Seven, “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.

5.4 The while Statement

The syntax of this frequently used construct is as follows:

while ( expression )
program statement

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 5.5 sets up a while loop, which merely counts from 1 to 5.

Program 5.5 Introducing the while Statement


// Program to introduce the while statement
#include <stdio.h>
int main (void)
{
int count = 1;
while ( count <= 5 ) {
printf ("%i\n", count);
++count;
}
return 0;
}

Program 5.5 Output


1
2
3
4
5

It is worth noting in passing that Program 5.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

for ( init_expression; program statement loop_condition; loop_expression )


program statement

can be equivalently expressed in the form of a while statement as

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.

Illustration: Printing a Table of Squares


Let’s write a program that prints a table of squares. The program will first prompt the user to enter a
number n. It will then print n lines of output, with each line containing a number between 1 and n
together with its square:

This program prints a table of squares,


Enter number of entries in table: 5
1 1
2 4
3 9
4 16
5 25
Let’s have the program store the desired number of squares in a variable named n. We’ll need a loop
that repeatedly prints a number i and its square, starting with i equal to 1. The loop will repeat as
long as i is less than or equal to n. We’ll have to make sure to add 1 to i each time through the
loop.
We’ll write the loop as a while statement. Here’s the program:
Program: Prints a table of squares using a while statement
#include <stdio.h>
int main (void)
{
int i, n;
printf (“This program prints a table of squares. \n”);
printf (“Enter number of entries in table: ”);
scanf (“%d”, &n);

i = 1;
while (i < = n) {
printf (“%10d%10d\n”, i, i * i);
i++;
}
return 0;
}

Note how the program displays numbers aligned numbers in neatly aligned colums. The trick is to
use a conversion specification like %10d instead of just %d, taking advantage of the fact that printf
right-justifies numbers when a field width is specified.

Illustration: Summing a Series of Number


An another example of the while statement, let’s write a program that sums a series of integers
entered by the user. Here’s what the user will see:

This program sums a series of integers.


Enter integers (0 to terminate): 8 23 71 5 1
The sum is: 108

Clearly we’ll need a loop that uses scanf to read a number and then adds the number to a running
total.
Letting n represent the number just read and sum the total of all numbers previously read, we end
up with the following program:
Program 5.6 Summing a Series of Numbers
#include <stdio.h>
int main (void)
{
int n, sum =0;

printf(“This program sums a series of integers”);


printf(“Enter integers (0 to terminate): ”);

scanf (“%d”, &n);


while (n!=0)
{sum += n;
scanf (“%d”, &n);
}
printf(“The sum is: %d\n”, sum”);

return 0;
}

5.5 The do-while Statement


The two looping statements discussed so far in this chapter both make a test of the conditions
before the loop is executed. Therefore, the body of the loop might never be executed at all if the
conditions are not satisfied. When developing programs, it sometimes becomes desirable to have
the test made at the end of the loop rather than at the beginning. Naturally, the C language provides
a special language construct to handle such a situation. This looping statement is known as the do-
while statement. The syntax of this statement is as follows:

do
program statement
while ( loop_expression );

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.

5.5.1 Illustration: Calculating the Number of Digits in an Integer


Although the while statement appears in C programs much more often than the do
statement, the latter is handy for loops that must execute at least once. To illustrate this point, let’s
write a program that calculates the number of digits in an integer entered by the user:

Enter a nonnegative integer: 60


The number has 2 digits(s)

Our strategy will be to divide the user’s input by 10 repeatedly until it becomes 0; the number of
divisions performed is the number of digits. Clearly, we’ll need some kind of loop, since we don’t
know how many divisions it will take to reach 0. But should we use a while statement or do
statement? The do statement turns out to be more attractive, because every integer – even 0 – has at
least one digit. Here’s the program:

Program 5.7 Calculates the number of digits in an integer


#include <stdio.h>
int main (void)
{
int digits = 0, n;

printf (“Enter a nonnegative integer: ”);


scanf (“%d”, &n);

do {
n /= 10;
digits ++;
} while (n > 0);

printf(“The number has %d digit (s) .\n”, digits);

return 0;
}

To see why the do statement is the right choice, let’s see what would happen if we were to replace
the do loop by a similar while loop:
while (n > 0)
{
n /= 10;
digits ++;
}

If n is 0 initially, this loop won’t execute at all, and the program would print
The number has 0 digit (s).

5.6 Exiting from a Loop


We have seen how to write loops that an exit point before the loop body (using while and
for statements) or after it (using do statements). Occasionally, however, we’ll need a loop with an
exit point in the middle. We may even want a loop to have more than one exit point. The break
statement makes it possible to write either kind of loop.
After we’ve examined the break statement, we’ll look at a couple of related statements:
continue and goto. The continue statement makes it possible to skip part of a loop iteration without
jumping out of the loop. The goto statement allows a program to jump from one statement to
another. Thanks to the availability of statements such as break and continue, the goto statement is
rarely used.

5.6.1 The break Statement


The break statement can be used to jump out of a while, do, or for loop.
Suppose that we’re writing a program that checks whether a number n is prime. Our plan is to write
a for statement that divides n by the numbers between 2 and n-1. We should break out of the loop as
soon as any divisor is found; there’s no need to try the remaining possibilities. After the loop has
terminated, we can use an if statement to determine whether termination was premature (hence n
isn’t prime) or normal (n is prime):

for (d =2; d < n; d++)


if (n % d == 0)
break;
if (d < n )
printf (“%d is divisible by %d\n”, n, d);
else
printf (“%d is prime \n”, n);
The break statement statement is particularly useful for writing loops in which the exit point is in
the middle of the body rather than at the beginning or end. Loops that read user input, terminating
when a particular value is entered, often fall into this category:

for ( ; ; ) {
printf (“Enter a number (enter 0 to stop): ”);
scanf (“%d”, &n);
if (n == 0)
break;
printf (“%d cubed is %d\n”, n, n * n);

The break statement transfers control out of the innermost enclosing while, do, for statement.

5.6.2 The continue Statement


The continue statement doesn’t really here, because it doesn’t exit from a loop. It’s similar
to break, although, so its inclusion in this section isn’t completely arbitrary. break transfers
control just past the end of a loop, while continue transfers control to a point just before the end of
the loop body. With break, control leaves the loop; with continue, control remains inside the loop.
The following example, which reads a series of numbers and computes their sum, illustrates
a series of continue. The loop terminates when 10 nonzero numbers have been read. Whenever the
number 0 is read, the continue statement is executed, skipping the rest of the loop body (the
statements sum +=i; and n++;) but remaining inside the loop.

n = 0;
sum = 0;
while (n < 10)
{
scanf (“%d”, &i);
if (i ==0)
continue;
sum += i;
n++;
/* continue jumps to here */

5.6.2 The goto Statement


break and continue are jump statements that transfer control from one point in the pogram
to another. Both are restricted: the target of a break is a point just beyond the end of the enclosing
loop, while the target of a continue is a point just before the end of the loop. The goto statement, on
the other hand, is capable of jumping to any statement in a function, provided that the statement has
a label.
A label is just an identifier at the beginning of a statement:
identifier : statement

A statement may have more than one label. The goto statement itself has the form

goto identifier ;

Executing the statement goto L; transfers control to the statement that follows the label L, which
must be in the same function as the goto statement itself.
If C didn’t have a break statement, here’s how we might use a goto statement to exit prematurely
from a loop:

for (d = 2; d < n; d++)


if (n % d == 0)
goto done;

done:
if (d < n)
printf (“%d is divisible by %d\n”, n, d);
else
printf (“%d is prime \n”, n);

5.7 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.

5.7 Tutorial Questions


a) Write a program that asks the user to type in two integer values at the terminal. Test these
two numbers to determine if the first is evenly divisible by the second, and then display an
appropriate message at the terminal.
b) Write a program that accepts two integer values typed in by the user. Display the result of
dividing the first integer by the second, to three-decimal-place accuracy. Remember to have
the program check for division by zero.
c) Write a program that read and average 6 integers using while loop, print the result.
LABORATORY SIX: DECISION MAKING IN C

6.1 Introduction

In Study Session 4, “Program Looping in C,” you learned that one of the fundamental properties of
a computer is its capability to repetitively execute a sequence of instructions. But another
fundamental property lies in its capability to make decisions. You saw how these decision-making
powers were used in the execution of the various looping statements to determine when to terminate
the program loop. Without such capabilities, you would never be able to “get out” of a program
loop and would end up executing the same sequence of statements over and over again,
theoretically forever (which is why such a program loop is called an infinite loop).

6.2 The if Statement


The C programming language provides a general decision-making capability in the form of a
language construct known as the if statement. The general format of this statement is as follows:
if ( expression )
program statement;

Program 6.1 illustrates the use of if statement.


Program 6.1 if statement usage
//Program to check if the value of x is less than 20
#include <stdio.h>
int main (void)
{
int x=10;
if (x<20);
{
printf("x is less than 20 \n");
}
printf("Value of x is %i", x);

printf ("\n");
return 0;
}

Program 6.1 Output


x is less than 20
Value of x is 10
6.3 The if-else Construct
If someone asks you whether a particular number is even or odd, you most likely make the
determination by examining the last digit of the number. If this digit is either 0, 2, 4, 6, or 8, you
readily state that the number is even. Otherwise, you claim that the number is odd.
An easier way for a computer to determine whether a particular number is even or odd is affected
not by examining the last digit of the number to see if it is 0, 2, 4, 6, or 8, but by simply determining
whether the number is evenly divisible by 2. If it is, the number is even; else it is odd.
The modulus operator % (which compute the remainder of one integer divided by another) is a
perfect operator to use in determining whether an integer is evenly divisible by 2. If the remainder
after division by 2 is zero, it is even; else it is odd.
Look at Program 6.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.

Program 6.2 Determining if a Number Is Even or Odd


//Program to determine if a number is even or odd
#include <stdio.h>
int main (void)
{
int number_to_test, remainder;
printf ("Enter your number to be tested: ");
scanf ("%i", &number_to_test);
remainder = number_to_test % 2; //modulus operator % in use
if ( remainder == 0 )
printf ("The number is even.\n");
if ( remainder != 0 )
printf ("The number is odd.\n");
return 0;
}

Program 6.2 Output


Enter your number to be tested: 55
The number is odd.

Program 6.2 Output (Rerun)


Enter your number to be tested: 12
The number is even.

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 6.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 6.3.

Program 6.3 Revising the Program to Determine if a Number Is Even or Odd


// Program to determine if a number is even or odd (Version 2)
#include <stdio.h>
int main ()
{
int number_to_test, remainder;
printf ("Enter your number to be tested: ");
scanf ("%i", &number_to_test);
remainder = number_to_test % 2;
if ( remainder == 0 )
printf ("The number is even.\n");
else
printf ("The number is odd.\n");
return 0;
}

Program 6.3 Output


Enter your number to be tested: 168
The number is even.

Program 6.3 Output (Rerun)


Enter your number to be tested: 57
The number is odd.

Note:
Don’t confuse = = (equality) with = (assignment). The statement
if (i = = 0) …..
tests whether i is equal to 0. However, the statement
if (i = 0) …
assigns 0 to i, then tests whether the result in nonzero. In this case, the tests always fails.
Confusing = = with = is perhaps the most common C programming error, probably because =
means “is equal to” in mathematics (and in certain programming languages). Some compilers issues
a warning if they notice = where = = would normally appear.
6.4 Compound Relational Tests
The if statements discussed so far in this chapter is used to set up a simple relational tests between
two numbers. Sometimes, it becomes desirable, if not necessary, to set up more sophisticated tests.
The C language provides the mechanisms necessary to perform these types of compound
relational tests. A compound relational test is simply one or more simple relational tests joined by
either the logical AND or the logical OR operator. These operators are represented by the character
pairs && and || (two vertical bar characters), respectively. As an example, the C statement
Example:
a) (5==5) &&(3>6) //False
b) (5==5) || (3>6) //True
c) (8 = = 6*2) || (12 > 15) // False
d) !True //means False
e) !False //means True
f) !(5==5) //False
g) !(6<=4) //True

6.5 The else if Construct


As can be seen from the previous discussions that the else statement comes into play when a
decision is to be made between two possible conditions. However, real programming decisions are
not always so black-and-white.
Consider the task of writing a program that displays –1 if a number typed in by a user is less than
zero, 0 if the number typed in is equal to zero, and 1 if the number is greater than zero. (This is
actually an implementation of what is commonly called the sign function.) Obviously, you must
make three tests in this case—to determine if the number that is keyed in is negative, zero, or
positive. Our simple if-else construct does not work. Of course, in this case, you could always
resort to three separate if statements, but this solution does not always work in general—especially
if the tests that are made are not mutually exclusive.
You can handle the situation just described by adding an if statement to your else clause.
Because the statement that followed an else can be any valid C program statement, it seems logical
that it can be another if .Thus, in the general case, you could write
if ( expression 1 )
program statement 1
else
if ( expression 2 )
program statement 2
else
program statement 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.

6.6 Tutorial Questions


(a) Write a program to implement the sign function explained
(b) Write a program to illustrate the grade of a student in an examination.
LABORATORY SEVEN: POINTERS IN C

7.1 Introduction to Pointers

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.

7.2 Memory Addresses


Inside your computer is a bunch of memory. The memory holds your program as it executes, and
it also holds your program’s variables. Just as every house has a different address, every memory
location has a different address. Not coincidentally, the memory locations have their own addresses
as well. As with house addresses, the memory addresses are all unique; no two are the same.
When you define variables, C finds an unused place in memory and attaches a name to that
memory location. That’s a good thing. Instead of having to remember that an variable named
orderNum is stored at memory address 34532, you only have to remember the name orderNum. The
name orderNum is much easier to remember than a number.

7.3 Defining a Pointer Variable


As with any other type of variable, you must define a pointer variable before you can use it. Two
key operators are used:
a) & which represents “address-of” operator
b) * which represents “dereferencing” operator

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.
int age = 19; /* Stores a 19 in age */
int *pAge = &age; /* Links up the pointer to another variable */

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 7.1 pictures this concept.

Figure 7.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

7.4 Using the Dereferencing *


As soon as you link up a pointer to another variable, you can work with the other value by
dereferencing the pointer. Dereferencing just means that you use the pointer to get to the other
variable. When you dereference, use the * dereferencing operator. In a nutshell, here are two ways
to change the value of age (assuming that the variables are defined as described earlier):
g) age = 25; and
h) *pAge = 25; /* Stores 25 where pAge points */
This assignment tells C to store the value 25 at the address pointed to by pAge. Because pAge
points to the memory location holding the variable age, 25 is stored in age. Therefore, pAge
pointer variable is used in the program to indirectly access the content (or value) of age.
Program 7.1, which illustrates the two fundamental pointer operators: the address operator, & , and
the indirection operator, * .

Program 7.1 Illustrating Pointers


// Program to illustrate pointers
#include <stdio.h>
int main (void)
{
int x=70;
int *int_pointer;
int_pointer = &x;
*int_pointer =45;
printf ("The value of x is %i\n", x);
return 0;
}

Program 7.1 Output


The value of x is 45

7.5 Using Pointers in Expressions

Program 7.2 Using Pointers in Expressions


// More on pointers
#include <stdio.h>
int main (void)
{
int i1, i2;
int *p1, *p2;
i1 = 5;
p1 = &i1;
i2 = *p1 / 2 + 10;
p2 = p1;
printf ("i1 = %i, i2 = %i, *p1 = %i, *p2 = %i\n", i1, i2, *p1, *p2);
return 0;
}

Program 7.2 Output


i1 = 5, i2 = 12, *p1 = 5, *p2 = 5

7.6 Tutorial Questions


a) Write a statement that displays the address of the variable testvar.
b) An address is a _____________, while a pointer is a ____________.
c) If a pointer testptr points to a variable testvar, write a statement that represents the
contents of testvar but does not use its name.
d) An asterisk placed after a data type means _________. An asterisk placed in front of a
variable name means __________.
e) What is the difference between intarr[3] and *(intarr+3)?
f) If intarr is an array of integers, why is the expression intarr++ not legal?
LABORATORY EIGHT: ARRAYS IN C

8.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.

8.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 8.1.

Figure 8.1: The array values in memory.


The elements of an arrays declared to be of type int , float , or char can be manipulated in
the same fashion as ordinary variables. You can assign values to them, display their values, add to
them, subtract from them, and so on.
It is important to note that an array variable can store more than one value at a time where other
variable can store one value at a time.

8.3 Initialisation of Arrays


Just as you can assign initial values to variables when they are declared, so can you assign initial
values to the elements of an array. Elements of an array can be initialised in either of two ways: one
by one or using a single statement.
Example:
a) int numbers [5] ={16, 2, 7, 4, 12};
b) int numbers [ ] = {16, 2, 7, 4, 12};
c) int numbers [5];
numbers [0] = 16;
numbers [1] = 2;
numbers [2] = 7;
numbers [3] = 4;
numbers [4] = 12;
It is important to state here that numbering of elements always starts at 0 in C programming.
Therefore, the five elements in the array above is indexed by the numbers 0, 1, 2, 3, 4.

8.4 Working with Arrays


Program 8.1 illustrates an array that stores five numbers and add them up

Program 8.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 8.1 Output


Sum is 35

Program 8.2 illustrates an array 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
#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;
}

Program 8.2 Output


Sum = 35, Average = 7

8.5 Character Arrays


The purpose of Program 8.3 is to simply illustrate how a character array can be used. However,
one point is worthy of discussion.

Program 8.3 Introducing Character Arrays


#include <stdio.h>
int main (void)
{
char word[] = { 'H', 'e', 'l', 'l', 'o', '!' };
for ( int i = 0; i < 6; ++i )
printf ("%c", word[i]);
printf ("\n");
return 0;
}

Program 8.3 Output


Hello!

8.6 Multidimensional Arrays


The types of arrays that you have been exposed to so far are all linear arrays—that is, they all
dealt with a single dimension. The C language allows arrays of any dimension to be defined. In this
section, a two-dimensional arrays will be discussed.
One of the most natural applications for a two-dimensional array arises in the case of a matrix.
The format to declare a two-dimensional array of size x, y is as follows:
type array_name [x][y];
This array declares x number of rows and y number of columns. A two-dimensional integer array
called num which contains three rows and four columns is declared as:
int num [3][4];
Therefore, every elements in the array num is identified by an element name of the form num[i][j],
where i and j are the subscripts that uniquely identify each element in num.

8.7 Initialising a Two-Dimensional Arrays


Just as you can assign initial values to elements of a single dimensional array, so can you assign
initial values to the elements of a 2-dimensional array. Elements of the array can be initialised in
either of two ways: one by one or using a single statement.
Example:
(a) int numbers [3][4] ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
(b) int numbers [3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12};
};

Therefore, elements of the 2-dimensional can be easily accessed. Example:

num[2][1] =5;

8.8 Tutorial Questions


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.
LABORATORY 9: FUNCTIONS IN C

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.

9.3 Types of Function in C

There are basically two types of function. They are:


a) Standard (or library or system defined) function and
b) User defined function

9.3.1 System defined function


The system defined function can’t be modified, it can only read and can be used. These
function are supplied with every C compiler Source of these library function are precomplied and
only object code get used by the user by linking to the code by linker
Here the system defined function consists of three components:
i. Function definition : predefined, precompiled, stored in the library
ii. Function declaration : In header file with or function prototype.
iii. Function call : By the programmer

9.3.2 User defined functions


The user defined functions defined by the user according to its requirement and function
consists of three components:
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:

int function(type1 arg1, type2 arg2) /* 2 passed, one integer returned */


and
function(type1 arg1, type2 arg2); /* 2 passed, one integer returned */
Prototypes aren’t required if you don’t return a value or if you return an integer value,
but they are strongly recommended.
To prototype a function, place an exact duplicate of the function’s first line somewhere
before main().
If your program calls 20 functions, you should have 20 prototypes.

ii. Function definition:-


Function definition consists of the whole description and code of the function. It tells about
what function is doing what are its inputs and what are its output. It consists of two parts
function header and function body.

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.

iii. Function Call:


When the function get called by the calling function then that is called, function call. The
compiler execute these functions when the semicolon is followed by the function name.
Example:
function(arg1,arg2,arg3);
The argument that are used inside the function call are called actual argument
Example:
int S=sum(a, b); //actual arguments
Actual argument
The arguments which are mentioned or used inside the function call is knows as actual argument
and these are the original values and copy of these are actually sent to the called function. It can be
written as constant, expression or any function call like
Function (x);
Function (20, 30);
Function (a*b, c*d);
Function(2,3,sum(a, b));

9.4 Formal Arguments


The arguments which are mentioned in function definition are called formal arguments or dummy
arguments. These arguments are used to just hold the copied of the values that are sent by the
calling function through the function call. These arguments are like other local variables which are
created when the function call starts and destroyed when the function ends.
It is vital to note that the order number and type of actual arguments in the function call should
match with the order number and type of the formal arguments in the function definition.

These three user defined function components are illustrated as follows:

int function(int, int, int); /*function declaration*/

main()
{
function(arg1,arg2,arg3); /* calling function */
}

int function(type 1 arg 1,type2 arg2, type3, arg3) /* function definition */


{
Local variable declaration;
Statement;
Return value;
}
9.5 Return type
The C language provides you with a convenient mechanism whereby the results of a function can
be returned to the calling function. The general syntax of this construct is straightforward enough:

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.

Program 9.1 Writing a Function in C


#include <stdio.h>
void printMessage (void)
{
printf ("Programming is good.\n");
}

int main (void)


{
printMessage ();
return 0;
}

Program 9.1 Output

Programming is good.

Program 9.1 consists of two functions: printMessage and main. Program execution always
begins with main. Inside that function, the statement
printMessage ();
appears. This statement indicates that the function printMessage is to be executed. The open and
close parentheses are used to tell the compiler that printMessage is a function and that no
arguments or values are to be passed to this function (which is consistent with the way the function
is defined in the program). When a function call is executed, program execution is transferred
directly to the indicated function. Inside the printMessage function, the printf statement is
executed to display the message “Programming is good.” at the terminal. After the message has
been displayed, the printMessage routine is finished (as signaled by the closing brace) and the
program returns to the main routine, where program execution continues at the point where the
function call was executed. Note that it is acceptable to insert a return statement at the end of
printMessage like this:
return;

Program 9.2 More on Calling Functions


#include <stdio.h>
void printMessage (void)
{
printf ("Programming is good.\n");
}
int main (void)
{
int i;
for ( i = 1; i <= 5; ++i )
printMessage ();

return 0;
}

Program 9.2 Output


Programming is good.
Programming is good.
Programming is good.
Programming is good.
Programming is good.

Program 9.3 Maximum between two numbers


#include <stdio.h>

int max(int num1, int num2); //function prototype or declaration

int main ( ) // main function


{
int a = 100;
int b = 200;
int answer;

answer=max (a, b); //calling a function to get maximum value


printf ("The value is %i\n", answer);

return 0;

int max(int num1, int num2) // function definition


{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

Program 9.3 Output


max value is 200

Program 9.4 Another way of writing Program 9.3


#include <stdio.h>

int max(int num1, int num2) // function definition


{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

int max(int num1, int num2); //function prototype or declaration


int main ( ) // main function
{
int a = 100;
int b = 200;
int answer;

answer=max (a, b); //calling a function to get maximum value


printf ("The value is %i\n", answer);
return 0;

Program 9.4 Another way of writing Program 9.3


#include <stdio.h>

float max(float firstSide, float secondSide); /*function prototype or


declaration*/
int main ( ) // main function
{
float firstSide, secondSide;

float answer;

printf ("Enter the value for the first side: ");


scanf ("%f", &firstSide);

printf ("Enter the value for the second side: ");


scanf ("%f", &secondSide);

answer=max (firstSide, secondSide); //calling a function to get maximum value


printf ("The maximum value is %f\n", answer);

return 0;

float max(float firstSide, float secondSide) // function definition


{

if (firstSide > secondSide)

return firstSide;

else

return secondSide;

9.6 Functions and Arrays

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 9.5.

Program 9.5 Finding the Minimum Value in an Array


// Function to find the minimum value in an array
#include <stdio.h>
int minimum (int values[10])
{
int minValue, i;
minValue = values[0];
for ( i = 1; i < 10; ++i )
if ( values[i] < minValue )
minValue = values[i];
return minValue;
}
int main (void)

{
int scores[10], i, minScore;

int minimum (int values[10]);


printf ("Enter 10 scores\n");

for ( i = 0; i < 10; ++i )


scanf ("%i", &scores[i]);
minScore = minimum (scores);
printf ("\nMinimum score is %i\n", minScore);

return 0;
}

Program 9.5 Output


Enter 10 scores
1
2
3
4
5
6
7
8
9
10
Minimum score is 1

9.7 Tutorial Questions


a) A function’s single most important role is to
i) give a name to a block of code.
ii) reduce program size.
Iii) accept arguments and provide a return value.
iv) help organize a program into conceptual units.
b) A function itself is called the function d_________.
c) Write a function called goal( ) that displays the word goal.
d) The statements that carry out the work of the function constitute the function _________.
e) A program statement that invokes a function is a function _________.
f) The first line of a function definition is referred to as the _________.
g) A function argument is
i) a variable in the function that receives a value from the calling program.
ii) a way that functions resist accepting the calling program’s values.
iii) a value sent to the function by the calling program.
iv) a value returned by the function to the calling program.
h) True or false: When arguments are passed by value, the function works with the original
arguments in the calling program.
i) What is the significance of empty parentheses in a function declaration
j) How many values can be returned from a function?
k) True or false: When a function returns a value, the entire function call can appear on the
right side of the equal sign and be assigned to another variable.
l) Here’s a function:
int times2(int a)
{
return (a*2);
}
Write a main() program that includes everything necessary to call this function.
m) Write a function called hms_to_secs() that takes three int values—for hours, minutes, and
seconds—as arguments, and returns the equivalent time in seconds (type long). Create a
program that exercises this function by repeatedly obtaining a time value in hours, minutes,
and seconds from the user (format 12:59:59), calling the function, and displaying the value
of seconds it returns.
LABORATORY TEN: HEAP: MAXIMIZING YOUR COMPUTER’S MEMORY

10.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 10.1 shows.

Figure 10.1: The heap is unused memory.

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.

10.2 Thinking of the Heap


Heap is—the unused section of contiguous memory. If you allocate 10 bytes of heap memory at
once, those 10 bytes will be contiguous. You’ll more quickly grasp how to use the heap if you think
of the heap as just one big heap of free memory stacked up in a pile. You’ll be allocating (using) and
deallocating (freeing back up) heap memory as your program runs.
Your operating system uses heap memory along with your program. If you work on a networked
computer or use a multitasking operating environment such as Windows, other tasks might be
grabbing heap memory along with your program.
You have to keep track of the memory you allocate. You do this with pointer variables. For
instance, if you want to allocate 20 integers on the heap, you use an integer pointer. If you want to
allocate 400 floating-point values on the heap, you use a floating-point pointer. The pointer always
points to the first heap value of the section you just allocated. Therefore, a single pointer points to
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.

10.3 But Why Do I Need the Heap?


Okay, before learning exactly how you allocate and deallocate heap memory, you probably want
more rationalization about why you even need to worry about the heap. After all, the variables,
pointers, and arrays you’ve learned about so far have sufficed nicely for program data.
The heap memory does not always replace the variables and arrays you’ve been learning about.
The problem with the variables you’ve learned about so far is that you must know in advance
exactly what kind and how many variables you will want. Remember, you must define all variables
before you use them. If you define an array to hold 100 customer IDs, but the user has 101
customers to enter, your program can’t just expand the array at runtime. Some programmers (like
you) have to change the array definition and recompile the program before the array can hold more
values. With the heap memory, however, you don’t have to know in advance how much memory you
need.
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.

10.4 How Do I Allocate the Heap?

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():

temps = (int *) malloc(10 * sizeof(int));

The previous line included the following malloc() function call:

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 to
satisfy 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 10.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.

Figure 10.2: After allocating the 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.

10.5 If There’s Not Enough Heap Memory


In extreme cases, not enough heap memory might exist to satisfy malloc()’s request. The
user’s computer might not have a lot of memory, another task might be using a lot of memory, or
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

temps = (int *) malloc(10 * sizeof(int));


if (temps == 0)
{
printf("Oops! Not Enough Memory!\n");
exit(1); // Terminate the program early
}
// Rest of program would follow...

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:

if (!temps) /* Means, if not true */

10.6 Freeing Heap Memory


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:

10.5 Illustration
Program 10.2 illustrates a heap that stores five numbers, add them up and find the average.

Program 10.2
/*Program to stores five numbers, add them up and find the average
using heap */

#include <stdio.h>
#include <stdlib.h>

int main (void)


{

int *ptemps; //ptemp declared as a pointer variable

ptemps = (int *) malloc (100 * sizeof (int)); // malloc () function

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;

int sum=0, avg=0;


for ( int i = 0; i <= 5; ++i )
sum = sum + ptemps[i];
avg=sum/5;
printf ("Sum is %i\n", sum);
printf ("Average is %i\n", avg);

free(ptemps);

return 0;
}

Program 10.2 Output


Sum is 1253
Average is 250
LABORATORY ELEVEN: WORKING WITH STRUCTURES IN C

11.1 Introduction
A structure is the collection of dissimilar data types or heterogeneous data types grouped together.
It means the data types may or may not be of same type.
The format for a Structure is as follows:
struct tagname
{
Data_type member_1;
Data_type member_2;
Data_type member_3;
. . . . . . . . . .
. . . . . . . . . .
Data_type member_n;
};

11.2 A Structure for Storing the Date


You can define a structure called date in the C language that consists of three components that
represent the month, day, and year. The syntax for such a definition is rather straightforward, as
follows:
struct date
{
int month;
int day;
int year;
};

The date structure just defined contains three integer members called month, day, and year. The
definition of date in a sense defines a new type in the language in that variables can subsequently be
declared to be of type struct date, as in the declaration
struct date today;

You can also declare a variable purchaseDate to be of the same type by a separate declaration,
such as
struct date purchaseDate;
Or, you can simply include the two declarations on the same line, as in
struct date today, purchaseDate;
Unlike variables of type int, float, or char, a special syntax is needed when dealing with
structure variables. A member of a structure is accessed by specifying the variable name, followed
by a period, and then the member name. For example, to set the value of the day in the variable
today to 25, you write
today.day = 25;

11.3 Initializing Structures


Initializing structures is similar to initializing arrays—the elements are simply listed inside
a pair of braces, with each element separated by a comma.
To initialize the date structure variable today to July 2, 2005, the statement
struct date today = { 7, 2, 2005 };
can be used. The statement
struct time this_time = { 3, 29, 55 };
defines the struct time variable this_time and sets its value to 3:29:55 a.m. As with other
variables, if this_time is a local structure variable, it is initialized each time the function is
entered. If the structure variable is made static (by placing the keyword static in front of it), it is
only initialized once at the start of program execution. In either case, the initial values listed inside
the curly braces must be constant expressions.
You can also specify the member names in the initialization list. In that case, the general format is
.member = value

Program 11.1: Illustrating the initialization of a Structure

#include <stdio.h>

int main (void)


{
struct date
{
int month;
int day;
int year;
};
struct date today;

today = {.day = 25, .month = 9, .year = 2024};

printf ("Today's date is %i/%i/%.2i.\n", today.month, today.day, today.year %


100);

return 0;

}
Program 11.1 Output

Today's date is 9/25/04.

Program 11.2: Illustrating a Structure


// Program to illustrate a structure
#include <stdio.h>

int main (void)


{
struct date
{
int month;
int day;
int year;
};
struct date today;
today.month = 9;
today.day = 25;
today.year = 2004;

printf ("Today's date is %i/%i/%.2i.\n", today.month, today.day, today.year %


100);

return 0;

Program 11.2 Output

Today's date is 9/25/04.

The first statement inside main defines the structure called date to consist of three integer
members called month, day, and year. In the second statement, the variable today is declared to
be of type struct date. The first statement simply defines what a date structure looks like to the C
compiler and causes no storage to be reserved inside the computer. The second statement declares a
variable to be of type struct date and, therefore, does cause memory to be reserved for storing the
three integer values of the variable today. Be certain you understand the difference between
defining a structure and declaring variables of the particular structure type.

After today has been declared, the program then proceeds to assign values to each of the three
members of today, as depicted in Figure 11.1.
Figure 11.1. Assigning values to a structure variable.

After the assignments have been made, the values contained inside the structure are displayed by an
appropriate printf call. The remainder of today.year divided by 100 is calculated prior to being
passed to the printf function so that just 04 is displayed for the year. Recall that the format
characters %.2i are used to specify that two integer digits are to be displayed with zero fill. This
ensures that you get the proper display for the last two digits of the year.

Suppose you want to write a simple program that accepts today’s date as input and displays
tomorrow’s date to the user. Now, at first glance, this seems a perfectly simple task to perform. You
can ask the user to enter today’s date and then proceed to calculate tomorrow’s date by a series of
statements, such as

tomorrow.month = today.month;
tomorrow.day = today.day + 1;
tomorrow.year = today.year;

Of course, the preceding statements work just fine for the majority of dates, but the following two
cases are not properly handled:

If today’s date falls at the end of a month.


If today’s date falls at the end of a year (that is, if today’s date is December 31).

One way to determine easily if today’s date falls at the end of a month is to set up an array of
integers that corresponds to the number of days in each month. A lookup inside the array for a
particular month then gives the number of days in that month. So the statement
int daysPerMonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

defines an array called daysPerMonth containing 12 integer elements. For each month i, the value
contained in daysPerMonth[i - 1] corresponds to the number of days in that particular month.
Therefore, the number of days in April, which is the fourth month of the year, is given by
daysPerMonth[3], which is equal to 30. (You could define the array to contain 13 elements, with
daysPerMonth[i] corresponding to the number of days in month i. Access into the array could
then be made directly based on the month number, rather than on the month number minus 1.
If it is determined that today’s date falls at the end of the month, you can calculate
tomorrow’s date by simply adding 1 to the month number and setting the value of the day equal to
1.
To solve the second problem mentioned earlier, you must determine if today’s date is at the
end of a month and if the month is 12. If this is the case, then tomorrow’s day and month must be
set equal to 1 and the year appropriately incremented by 1.
Program 10.3 asks the user to enter today’s date, calculates tomorrow’s date, and displays
the results.

Program 11.3 Determining Tomorrow’s Date


// Program to determine tomorrow's date
#include <stdio.h>
int main (void)
{
struct date
{
int month;
int day;
int year;
};

struct date today, tomorrow;


const int daysPerMonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

printf ("Enter today's date (mm dd yyyy): ");


scanf ("%i%i%i", &today.month, &today.day, &today.year);

if ( today.day != daysPerMonth[today.month - 1] )
{
tomorrow.day = today.day + 1;
tomorrow.month = today.month;
tomorrow.year = today.year;
}
else if ( today.month == 12 )
{ // end of year
tomorrow.day = 1;
tomorrow.month = 1;
tomorrow.year = today.year + 1;
}
else { // end of month
tomorrow.day = 1;
tomorrow.month = today.month + 1;
tomorrow.year = today.year;
}

printf ("Tomorrow's date is %i/%i/%.2i.\n", tomorrow.month, tomorrow.day,


tomorrow.year % 100);

return 0;
}

Program 11.3 Output


Enter today's date (mm dd yyyy): 12 17 2004
Tomorrow's date is 12/18/04.

Program 11.3 Output (Rerun)


Enter today's date (mm dd yyyy): 12 31 2005
Tomorrow's date is 1/1/06.

Program 11.3 Output (Second Rerun)


Enter today's date (mm dd yyyy): 2 28 2004
Tomorrow's date is 3/1/04.

More explanation on Program 11.3


After the date structure is defined, two variables of type struct date, today and
tomorrow, are declared. The program then asks the user to enter today’s date. The three integer
values that are entered are stored into today.month, today.day, and today.year, respectively.
Next, a test is made to determine if the day is at the end of the month, by comparing today.day to
daysPerMonth[today.month - 1]. If it is not the end of the month, tomorrow’s date is calculated
by simply adding 1 to the day and setting tomorrow’s month and year equal to today’s month and
year.
If today’s date does fall at the end of the month, another test is made to determine if it is the
end of the year. If the month equals 12, meaning that today’s date is December 31, tomorrow’s date
is set equal to January 1 of the next year. If the month does not equal 12, tomorrow’s date is set to
the first day of the following month (of the same year).
After tomorrow’s date has been calculated, the values are displayed to the user with an
appropriate printf statement call, and program execution is complete.
Program 11.4

/* Program to generate the previous date given a date, assumes date given as dd mm yyyy
separated by space and performs error checking of the current date entered. */

#include <stdio.h>
#include <conio.h>

int main ()
{

int day month, year, validDate = 0;

/* Date Entry */

printf (“Enter the day value: ”);


scanf (“%d,”, $day);

printf (“Enter the month value: ”);


scanf (“%d,”, $month);

printf (“Enter the year value: ”);


scanf (“%d,”, $year);

if (year>= 1990 && year <= 2025) {


if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 ||
month == 10 || month == 12 ) {

if ( day > =1 && day <= 31)


{
validDate =1;
}
else
{
validDate = 0;
}
}
else if (month == 2}
{
int rval = 0;
if (year % 4 == 0)
{
rval = 1;
if ( (year % 100) == 0 && (year % 400)!= 0)
{
rval = 0;
}
}
if (rval == 1 && (day > = 1 && day <= 29) )
{
validDate = 1;
}
else if ( day >= 1 && day < = 28 )
{
validDate = 1;
}
else
validDate = 0;
}
}
else if ( (month >= 1 && month <= 12) && (day>= 1 && day <=30) )
{
validDate = 1;
}
else
{
validDate = 0;
}
}

/* Previous Date Calculation */

if (validDate) {
if (day == 1) {
if (month == 1) {
year --;
day = 31;
month =12;
}
else if (month == 3)
int rval = 0;
if (year %4 == 0)
{
rval =1;
if ((year % 100) == 0 && (year % 400) != 0)
{
rval = 0;
}
}
if (rval == 1)
{
day = 29;
month --;
}
else
{
day = 28;
month --;
}
}
else if (month ==2 || month == 4 || month == 6 || month == 9 || month == 11)
{
day = 31;
month --;
}
else
{
day = 30;
month --;
}
}
else
{
day --;
}

printf (“The next date is %d - %d - %d”, day. month, year);


}
else
{
printf(“The entered date (%d - %d - %d) is invalid”, day month, year);
}

getche ();

return 1;

11.4 Tutorial Question

a) Using the concept of structure, re-write the program in Program 11.4.


LABORATORY TWELVE: MORE ON DATA TYPES

12.1 Introduction
This laboratory session introduces you to a data type that has not yet been described: the
enumerated data type.

12.2 Enumerated Data Types


Wouldn’t it be nice if you could define a variable and specify the valid values that could be
stored into that variable? For example, suppose you had a variable called myColor and you wanted
to use it to store one of the primary colors, red, yellow, or blue, and no other values. This type
of capability is provided by the enumerated data type.
An enumerated data type definition is initiated by the keyword enum. Immediately
following this keyword is the name of the enumerated data type, followed by a list of identifiers
(enclosed in a set of curly braces) that define the permissible values that can be assigned to the type.
For example, the statement

enum primaryColor { red, yellow, blue };

defines a data type primaryColor. Variables declared to be of this data type can be assigned the
values red, yellow, and blue inside the program, and no other values. That’s the theory anyway!
An attempt to assign another value to such a variable causes some compilers to issue an error
message. Other compilers simply don’t check.
To declare a variable to be of type enum primaryColor, you again use the keyword enum,
followed by the enumerated type name, followed by the variable list. So the statement

enum primaryColor myColor, gregsColor;

defines the two variables myColor and gregsColor to be of type primaryColor. The only
permissible values that can be assigned to these variables are the names red, yellow, and blue. So
statements such as
myColor = red;

and
if ( gregsColor == yellow )

are valid. As another example of an enumerated data type definition, the following defines the type
enum month, with permissible values that can be assigned to a variable of this type being the
months of the year:

enum month { january, february, march, april, may, june, july, august,
september, october, november, december };

The C compiler actually treats enumeration identifiers as integer constants. Beginning with the first
name in the list, the compiler assigns sequential integer values to these names, starting with 0. If
your program contains these two lines:

enum month thisMonth;


. . .
thisMonth = february;

the value 1 is assigned to thisMonth (and not the name february) because it is the second
identifier listed inside the enumeration list.
If you want to have a specific integer value associated with an enumeration identifier, the
integer can be assigned to the identifier when the data type is defined. Enumeration identifiers that
subsequently appear in the list are assigned sequential integer values beginning with the specified
integer value plus 1. For example, in the definition

enum direction { up, down, left = 10, right };

an enumerated data type direction is defined with the values up, down, left, and right. The compiler
assigns the value 0 to up because it appears first in the list; 1 to down because it appears next; 10 to
left because it is explicitly assigned this value; and 11 to right because it appears immediately after
left in the list.
12.3 Illustration
Program 12.1 shows a simple program using enumerated data types. The enumerated data type
month sets january to 1 so that the month numbers 1 through 12 correspond to the enumeration
values january, february, and so on. The program reads a month number and then enters a
switch statement to see which month was entered. Recall that enumeration values are treated as
integer constants by the compiler, so they’re valid case values. The variable days is assigned the
number of days in the specified month, and its value is displayed after the switch is exited. A special
test is included to see if the month is February.

Program 12.1 Using Enumerated Data Types


// Program to print the number of days in a month
#include <stdio.h>
int main (void)
{
enum month { january = 1, february, march, april, may, june, july, august,
september, october, november, december };
enum month aMonth;
int days;

printf (“Enter month number: “);


scanf (“%i”, &aMonth);

switch (aMonth ) {
case january:
case march:
case may:
case july:
case august:
case october:
case december:
days = 31;
break;

case april:
case june:
case september:
case november:
days = 30;
break;
case february:
days = 28;
break;

default:
printf (“bad month number\n”);
days = 0;
break;
}

if ( days != 0 )
printf (“Number of days is %i\n”, days);

if ( amonth == february )
printf (“...or 29 if it’s a leap year\n”);

return 0;
}

Program 12.1 Output


Enter month number: 5
Number of days is 31

Program 12.1 Output (Rerun)


Enter month number: 2
Number of days is 28
...or 29 if it’s a leap yearP

You might also like