You are on page 1of 78

UNIVERSITY OF RWANDA

FACULTY OF APPLIED SCIENCE


FIRST YEAR

Course: C PROGRAMMING LANGUAGE

Academic year: 2013-2014


CHAP0: INTRODUCTION TO PROGRAMMING

0.1. DEFINITION

Computer programming (often shortened to programming or coding) is the process of writing,


testing, debugging/troubleshooting, and maintaining the source code of computer programs.

0.2. OVERVIEW OF PROGRAMMING LANGUAGES

We use programming languages to write computer programs. Although there are many different
programming languages, the mist commonly used today are called high-level languages because
it is close to the human languages.

0.2.1. Machine language

This is the native tongue of a computer. Each machine instruction is a binary string of 0s and 1s
that specifies an operation and identifies the memory cells involved in that operation. For
example, if we wanted to represent the algebraic formula:
Area = width*length
In a machine language program, we might need a sequence of instructions such as the following:
0001 0000 1110 0100
1010 1101 0011 0010
0101 0001 1101 0000
Although the computer would have no difficulty understanding the three machine languages
instructions above, they are unintelligible to most people.

0.2.2. Assembly Languages


Since it is very difficult for us to write instructions in binary language, assembly languages were
developed. Instead of using a set of 1s and 0s for a particular instruction, the programmer could
use some short abbreviations (called „mnemonics‟) to write the program (for example: ADD is a
mnemonic to add two numbers).

0.2.3. High-level language

Writing larger programs in assembly language is quite difficult and hence, high-level languages
were developed (like BASIC).For example, in C, you would use the instruction

2
C PROGRAMMING 2013-2014 UR
area = width * length
which closely resembles the original formula. This statement means “ multiply the value of width
by the value of length and store the result as area”.

Each language was designed with specific purpose in mind.

 The development of Ada was driven largely by the US Department of Defense, wich
sought a single high-level language to be used in the specialized program applications
area known as real-time, distributed systems.
 BASIC (Beginners All-purpose Symbolic Instruction Code) was designed to be easily
learned and used by students.
 COBOL (Common Business-Oriented Language) is primarily for business data-
processing operations.
 FORTRAN (FORmula TRANslator) is primarily used by engineers and scientists.
 Lisp ( LISt Processing) is a language used primarily in artificial intelligence applications.
 Pascal was developed primarily for teaching introductory programming by following a
particular approach often referred to as structured programming. This language was
named after the famous mathematician and philosopher Blaise Pascal. It was very popular
during the 80's and 90's.
 The C language, developed in 1972 by Dennis Ritchie of Bell Laboratories, is highly
versatile language that has been used in a wide variety of applications, from operating
systems implementation (such as UNIX) to database and large-scale, numeric-processing
applications. C++ is based on C; it is also a versatile programming language that is
rapidly gaining wide acceptance in the computing field. It is becoming increasingly
popular for teaching programming concepts, partly because it provides powerful features
useful for practicing modern approaches to software development.
 MATLAB (matrix laboratory) is a tool for doing numerical computations with matrices
and vectors. It can also display information graphically.
 PHP is a newer programming language with focus on web design.
 JAVA is an object oriented interpreted programming language. It has gained popularity in
the past few years for its ability to be run on many platforms, including Microsoft
Windows, Linux, Mac OS, and other systems. It was developed by Sun Microsystems.

3
C PROGRAMMING 2013-2014 UR
The following steps can be followed to prepare a program for execution:

1. Use the editor program to enter each line of the source program into memory and to save
it on disk as a source file.
2. Use a compiler program to translate the source program into machine language. If there is
any syntax errors (errors in grammar), the compiler displays these errors on the monitor.
Compile the program into machine-language. The machine language program produced is
called the object code. At this stage the compiler may find Syntax errors in the program.
3. Use the editor program to correct the errors by editing and resaving the source program.
When the source program is error free, the compiler saves its machine language as an
object file.
Use the Linker/loader program to combine the object file with additional object files that may be
needed for the program to execute ( for example , programs for input and output). The
linker/loader can also save the final machine language program as an executable file on disk.

CHAPTER I: OVERVIEW OF C

1.1. DEFINITIONS

1.1.1. Compiler

The compiler will read each and every character that has been typed in the program code. After
reading the entire code, the compiler will convert the code into machine level format (i.e. 0s and
1s). Technically speaking, the microprocessor in a computer can understand only binary numbers
(only 0s and 1s). It is not possible for us to write programs in binary numbers. Compilers will
convert the coding for a program into machine understandable form (i.e. it will convert the
instructions we type into machine understandable form). Compilation is the process of
converting the source code into machine language.

1.1.2. Keywords
Keyword is a word that the compiler already knows, i.e. when the compiler sees a keyword
somewhere in the program it knows what to do automatically.

4
C PROGRAMMING 2013-2014 UR
There are 32 words defined as keywords in C. These have predefined uses and cannot be used for
any other purpose in a C program. They are used by the compiler as an aid to compiling the
program. They are always written in lower case. A complete list follows;
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

1.1.3. Debugging
Debugging is the process of identifying bugs in the code. A bug is a programming term for an
„error‟.

1.1.4 Preprocessor
• Preprocessor statements begin with a # symbol, and are NOT terminated by a semicolon.
Traditionally, preprocessor statements are listed at the beginning of the source file.
• Preprocessor statements are handled by the compiler (or preprocessor) before the program is
actually compiled. All # statements are processed first

1.1.5. Preprocessor directives


Preprocessor directives are lines included in the code of our programs that are not program
statements but directives for the preprocessor. These lines are always preceded by a hash sign (#).
The preprocessor is executed before the actual compilation of code begins, therefore the
preprocessor digests all these directives before any code is generated by the statements.
Example: #include <stdio.h>

1.2. GENERAL FORM OF A C PROGRAM


The following program is written in the C programming language:
#include <stdio.h>
main()
{
printf("hello, world\n");
5
C PROGRAMMING 2013-2014 UR
}
C is case sensitive. All commands in C must be lowercase.
C has a free-form line structure. End of each statement must be marked
with a semicolon. Multiple statements can be on the same line. White space is
ignored. Statements can continue over many lines.
• The C program starting point is identified by the word main().
• This informs the computer as to where the program actually starts. The
parentheses that follow the keyword main indicate that there are no arguments
supplied to this program (this will be examined later on).
• The two braces, { and }, signify the begin and end segments of the
program. In general, braces are used throughout C to enclose a block of
statements to be treated as a unit. COMMON ERROR: unbalanced number
of open and close curly brackets!
• The purpose of the statement #include <stdio.h> is to allow the use of the printf statement to
provide program output. For each function built into the language, an associated header file must
be included. Text to be displayed by printf() must be enclosed in double quotes. The program
only has the one printf() statement.
• printf() is actually a function (procedure) in C that is used for printing variables and text.
Where text appears in double quotes "", it is printed without modification. There are some
exceptions however. This has to do with the \ and % characters. These characters are modifiers,
and for the present the \ followed by the n character represents a newline character.
• Thus the program prints Hello World!

1.3. DESCRIPTION OF ELEMENTS OF A C PROGRAM

1.3.1. Comments

Comments are parts of the source code disregarded by the compiler. They simply do nothing.
Their purpose is only to allow the programmer to insert notes or descriptions embedded within
the source code. They serve as internal documentation for program structure and functionality.
C supports two ways to insert comments:
// line comment
/* block comment */

6
C PROGRAMMING 2013-2014 UR
The first of them, known as line comment, discards everything from where the pair of slash signs
(//) is found up to the end of that same line. The second one, known as block comment, discards
everything between the /* characters and the first appearance of the */ characters, with the
possibility of including more than one line.
Why use comments?

• Documentation of variables and functions and their usage


• Explaining difficult sections of code
• Describes the program, author, date, modification changes, revisions…
Best programmers comment as they write the code, not after the fact.
Note:
• A C development environment includes
– System libraries and headers: a set of standard libraries and their header files. For
example see /usr/include and glibc.
– Application Source: application source and header files
– Compiler: converts source to object code for a specific platform
– Linker: resolves external references and produces the executable module
• User program structure
– there must be one main function where execution begins when the program is run.
This function is called main
• int main (void) { ... },
• int main (int argc, char *argv[]) { ... }

1.3.2. Header Files


• Header files contain definitions of functions and variables which can be incorporated into
any C program by using the pre-processor #include statement.
Standard header files are provided with each compiler, and cover a range of areas:
string handling, mathematics, data conversion, printing and reading of variables, etc.
• To use any of the standard functions, the appropriate header file should be included.
This is done at the beginning of the C source file. For example, to use the function
printf() in a program, the line
#include <stdio.h>
• should be at the beginning of the source file, because the declaration for printf() is

7
C PROGRAMMING 2013-2014 UR
found in the file stdio.h.
All header files have the extension .h and generally reside
in the /usr/include subdirectory.
#include <string.h>
#include <math.h>
#include "mylib.h"

1. Each function in the C standard library has its associated header.


2. The headers are included using #include.
3. Header Including obtains the Declarations for the standard library functions.

1.3.2.1. General form

#include<filename>

Example: #include<stdio.h>
#include<math.h>// allows to read mathematical functions: trigonometric functions(
tan(x),sin(x),cos(x);logarithmic functions (log(x)= ln(x),log10(x)), exp(x), pow(x,y)=xy,

Note: The line #include <stdio.h> must start in column one. It causes the compiler to
include the text of the named file (in this case stdio.h) in the program at this point. The
file stdio.h allows the compiler to read input/output streams. All your programs will
include this file.

1.3.2.2. Standard C libraries of filenames

 <assert.h> : Diagnostics
 <ctype.h> : Character Class Tests
 <errno.h> : Error Codes Reported by (Some) Library Functions
 <float.h> : Implementation-defined Floating-Point Limits
 <limits.h> : Implementation-defined Limits
 <locale.h> : Locale-specific Information
 <math.h> : Mathematical Functions
 <setjmp.h> : Non-local Jumps
 <signal.h> : Signals
 <stdarg.h> : Variable Argument Lists
 <stddef.h> : Definitions of General Use

8
C PROGRAMMING 2013-2014 UR
 <stdio.h> : Input and Output
 <stdlib.h> : Utility functions
 <string.h> : String functions
 <time.h> : Time and Date functions

1.3.3. Function main


All programs must have a function main, also called main program. Note that the
opening brace ({) marks the beginning of the body of the function, while the closing brace (})
indicates the end of the body of the function. In the function header line, the word int indicates
that the main function returns an integer value to the operating system.
A block is a group of statements and optionally declarations enclosed in braces { }. The body of
any function is a block.
Note:
1. Every statement which instructs the computer to do something is terminated by a semi-colon
(;). Symbols such as main (), { } etc. are not instructions to do something and hence are not
followed by a semi-colon.
2. The word void indicates that main does not return a value. Therefore it does not end in return
0 statement.
3. Use consistent indentation to indicate intended program structure
4. Note that it makes complex programs much easier to interpret if, as above, closing braces }
are aligned with the corresponding opening brace {.

9
C PROGRAMMING 2013-2014 UR
10
C PROGRAMMING 2013-2014 UR
1.4. Data types
1.4.1. Definition

A data type provides a method of modeling or representing a particular set of values and
determines what operations can be performed on those values. For the moment only four variable
types are considered, namely, int, float, double and char. These types hold values as follows:

int: variables can represent negative and positive integer values (whole numbers). There is a limit
on the size of value that can be represented, which depends on the number of bytes of
storage allocated to an int variable by the computer system and compiler being used. On a
PC most compilers allocate two bytes for each int which gives a range of -32768 to
+32767. On workstations, four bytes are usually allocated, giving a range of -2147483648
to 2147483647. It is important to note that integers are represented exactly in computer
memory.

float :variables can represent any real numeric value, that is both whole numbers and numbers
that require digits after the decimal point.Usually four bytes are allocated for float
variables, this gives an accuracy of about six significant figures and a range of about -1038
to +1038. It is important to note that float values are only represented approximately.
char variables represent a single character -- a letter, a digit or a punctuation character. They
usually occupy one byte, giving 256 different possible characters. The bit patterns for characters
usually conform to the American Standard Code for Information Interchange (ASCII).
Examples of values for such variables are:
int 123 -56 0 5645
float 16.315 -0.67 31.567
char '+' 'A' 'a' '*' '7'

1.4.2. built-in types

Built in Types -

Void A generic "nontype."


Char Characters (usually 1 byte).

11
C PROGRAMMING 2013-2014 UR
Int Integers (2 or 4 byte).
Single precision real (floating point) numbers. Usually 4 bytes and not typically
Float
used.
Double Double precision real (floating point) numbers. Usually 8 bytes and typically used.

Type Modifiers -

unsigned Doesn‟t use sign bit (assumes int if base type is omitted).
Long May have twice as many bytes as base type (assumes int if base type is omitted).
Short May have half as many bytes as base type (assumes int if base type is omitted).
Const Constant (values can‟t be changed during execution).

Note that short int and long int are also available, and may be represented by fewer or
more bits than int. unsigned int, short unsigned int and long unsigned int can be
used to hold zero-or-positive whole numbers.

The data type defines:

1. the amount of storage allocated to variables.


2. the values that they can accept.
3. the operations that can be performed on variables.

1.5. Executable statement


1.5.1. Input statement with scanf

Scanf();

example: scanf(“%d”,&age);

1.5.2. output statement

A statement to print the value of a variable or a string of characters (set of characters enclosed
by double quotes) to the screen begins with printf, followed by the (. The data to be printed are
between “ ”:

Printf(”string of characters”);

12
C PROGRAMMING 2013-2014 UR
1.6. LOCAL AND GLOBAL VARIABLES
A global variable exists only once in a program, and is visible in every function. Modifications
to it in one function are permanent and visible to all functions.
A local variable, however, has a limited scope: it exists only within the block that it is declared
in. Once that block ends, the variable is destroyed and its values lost.
Any variable declared within a block are strictly local to that block (and any enclosed block),
and they are created each time the block is executed and destroyed when the block is exited
(unless declared static).

1.7. Formatted Input/Output


The following table show what format specifiers should be used:

e Type
%c character
%d decimal integer
%o octal integer (leading 0)
%x hexadecimal integer (leading 0x)
%u unsigned decimal integer
%ld long int
%f floating point
%lf double or long double
%e exponential floating point
%s character string

13
C PROGRAMMING 2013-2014 UR
• For floating-point values, in addition to specifying the field width, the number of decimal places
can also be controlled. A sample format specifier would look like this

%7.3f

Field width Number of decimal places


• Note that a period separates the two numbers in the format specifier. Don‟t forget to count the
column needed for the decimal point when calculating the field width.
S format
• For strings, the field length specifier works as before and will automatically
expand if the string size is bigger than the specification. A more sophisticated
string format specifier looks like this

%6.4 s

field width maximum number of characters printed

Example: printf("3.4s\n","Sheridan"); //displays sher

Formatted input
• Modifications can be made to the control string of the scanf function which enable more
sophisticated input. The formatting features that can be inserted into the control string are
– Ordinary characters (not just format identifiers) can appear in the scanf control string.
They must exactly match corresponding characters in the input.
These “normal” characters will not be read in as input.
– As with formatted output, a field width can be specified for inputting values.
The field width specifies the number of columns used to gather the input.

14
C PROGRAMMING 2013-2014 UR
Example:

#include <stdio.h>
main() {
int i; char lett; char word[15];
scanf("%d , %*s %c %5s",&i,&lett,word);
printf("%d \n %s \n %s\n",i,lett,word);

1.8. Character Escape Sequences


Escape ASCII
Name Description
Sequence value
\a Bell (alert) 007 Makes a sound from the computer
\b Backspace 008 Takes the cursor back
Horizontal
\t 009 Takes the cursor to the next tab stop
Tab
Takes the cursor to the beginning of the
\n New line 010
next line
\v Vertical Tab 011 Performs a vertical tab
Carriage
\r 013 Causes a carriage return
return
\" Double Quote 034 Displays a quotation mark (")
\' Apostrophe 039 Displays an apostrophe (')
Question
\? 063 Displays a question mark
mark
\\ Backslash 092 Displays a backslash (\)
\0 Null 000 Displays a null character

1.9. EXECUTING A PROGRAM

As we have seen, a computer has its own language known as the machine language. Therefore,
after writing a program in C, we need to translate it in a language the computer can understand. A
program was created to that effect and supplied to you with C. This is what we call a compiler.

15
C PROGRAMMING 2013-2014 UR
The words (or verbs) "execute" and "run" will be used interchangeably to mean the same
thing. Running the program consists of obeying the statements in the body of the function
main.

In the past, a program used to be created from various parts all over the computer; some of the
techniques are still used to "debug" a program to isolate problems or "bugs". Since this is a small
program, we will just ask the computer to "execute" it and see the result.

1.10. PROJECT CREATION

The C language doesn't define how to create a project. When you buy or acquire a c compiler, its
documentation should tell you how to create and execute a project. We describe here how to
create a project in most familiar environments.
The programs we will be creating on this course are called console applications. They can also
be called Bash programs (especially on Unix/Linux).

1.10.1. Creating and Executing a Dev-C++ 4 Application

Dev-C++ is a free programming environment. To get it, you can download it from
http://www.bloodshed.net. If you decide to use it, you should help the developers with a
financial contribution.

1. Start Dev-C++ 4

2.

16
C PROGRAMMING 2013-2014 UR
3. On the main menu, click File -> New Project...

4. On the New Project dialog box, click the Project property sheet if necessary.
Click Console Application

17
C PROGRAMMING 2013-2014 UR
5. On the subsequent New Project dialog box, type Exercise to change the name of the
project:

6. Click OK. You will be asked to create a location for the project.

7. Click the Create New Folder button.

8. Type Exercise1 and press Enter.

9. Double-click Exercise1 to display it in the Save In combo box:

10. Click Save.


18
C PROGRAMMING 2013-2014 UR
11. Because the project has already been saved, it is better to save your C files as you go.
As it happens, Dev-C++ has already created the first C file for you.
Change the contents of the file as follows:
#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[])

printf("hello world!");

system("PAUSE");

return 0;

12. Click Save.

13. To execute the program, on the main menu, click Execute -> Compile

14. After the program has been compiled, click Execute.

15. After viewing the program, press Enter to close the DOS window to return to Dev-C++

19
C PROGRAMMING 2013-2014 UR
CHAPETER TWO: VARIABLES, OPERATORS AND EXPRESSIONS

2.1. VARIABLES

2.1.1 Definition

A variable is a named memory location in which data of a certain type can be stored. The
contents of a variable can change, thus the name. User defined variables must be declared
before they can be used in a program. It is during the declaration phase that the actual memory
for the variable is reserved. All variables in C must be declared before use.
• Get into the habit of declaring variables using lowercase characters.
Remember that C is case sensitive, so even though the two variables listed
below have the same name, they are considered different variables in C.
sum Sum

2.1.2 Variable declaration

The basic format for declaring variables is

data_type var;

example: int sum; // declares a variable named sum having int as data type

2.1.3 Variable initialization

The format of variable initialization is the following:

Data_type var_name= value;

Integer (int) variables are used to store integer values like 34, 68704 etc. To declare a variable of
type integer, type keyword int followed by the name of the variable. You can give any name to a
variable but there are certain constraints, they are specified in Identifiers section. For example,
the statement

int sum;

20
declares that sum is a variable of type int. You can assign a value to it now or later. In order to
assign values along with declaration use the assignment operator (=).

int sum = 25;

assigns value 25 to variable sum.

There are three types of integer variables in C, short, int and long int. All of them store values of
type integer but the size of values they can store increases from short to long int. This is because
of the size occupied by them in memory of the computer. The size which they can take is
dependent on type of computer and varies. More is the size, more the value they can hold. For
example, int variable has 2 or 4 bytes reserved in memory so it can hold 2 32= 65536 values.
Variables can be signed or unsigned depending they store only positive values or both positive
and negative values. And short, variable has 2 bytes. Long int variable has 4 bytes.

Float data type

To store decimal values, you use float data type. Floating point data types comes in three sizes,
namely float, double and long double. The difference is in the length of value and amount of
precision which they can take and it increases from float to long double. For example, statement

float average = 2.34;

declares a variable average which is of type float and has the initial value 2.34

Character data type

A variable of type char stores one character. It size of a variable of type char is typically 1 byte.
The statement

char name = 'c';

declares a variable of type char (can hold characters) and has the initial values as character c.
Note that value has to be under single quotes.

21
2.1. 4.Constant
A constant is a variable whose value cannot be changed in the program.

2.1.4.1 Constant declaration

Often in programming numerical constants are used, e.g. the value of . It is well worthwhile to
associate meaningful names with constants.
General form

const datatype constant_identifier = constant_value


Example: -const float PI = 3.14159
-const int G = 9.81
Note: -Constant identifiers are generally in all uppercase.
-Constant definitions are, by convention, usually placed before variable declarations;
-Several constant identifiers of the same type can be declared in the same constant
declaration by separating each declaration by a comma.
e.g.: const int days_in_year = 365,days_in_leap_year = 366;

2.1.4.2. Constant declaration using preprocessor

Names given to values that cannot be changed. Implemented with the


#define preprocessor directive.
#define N 3000
#define FALSE 0
#define PI 3.14159
#define FIGURE "triangle"
In general, preprocessor constants are written in UPPERCASE. This acts as a
form of internal documentation to enhance program readability and reuse.

Example:
#include <stdio.h>
#include <stdlib.h>
#define TAXRATE 0.10

int main(int argc, char *argv[])


{
float balance;
float tax;

22
balance = 72.10;
tax = balance * TAXRATE;
printf("The tax on %.2f is %.2f\n",balance, tax);
system("PAUSE");
return 0;
}
Output of the above program

Note: An identifier (name of variable):

 Starts with an underscore “_” or a letter, lowercase or uppercase, such as a letter


from a to z or from A to Z. Examples are Name, gender, _Students, pRice ;

 Can include letters, underscore, or digits. Examples are: keyboard, Master, Junction,
Player1, total_grade, _Score_Side1 ;

 Cannot include special characters such as !, %, ], or $;

 Cannot include an empty space ;

 Cannot be any of the reserved words ;

23
 is case sensitive and can be of any length but typically only the first 31 characters are
significant. Objects names are generally all lowercase. Class names generally start with
an upper case letter.
Note:
 Represent storage units in a program
 Used to store/retrieve data over life of program
 Type of variable determines what can be placed in the storage unit
 Assignment – process of placing a particular value in a variable
 Variables must be declared before they are assigned
 The value of a variable can change; A constant always has the same value
 Name must begin with a letter; otherwise, can contain digits or any other characters. C is
CASE SENSITIVE! Use 31 or fewer characters to aid in portability
 All variables must be declared in a C program before the first executable statement!
Examples:
main(){
int a, b, c;
float d;
/* Do something here */
}

2.2 EXPRESSION
An expression in C is some combination of constants, variables, operators and function calls.
Sample expressions are:
a + b;
3.0*x - 9.66553;
A statement in C is just an expression terminated with a semicolon.

2.3. ARITHMETIC OPERATORS


• The primary arithmetic operators and their corresponding symbols in C are:
Negation -
Multiplication *
Division /
Modulus %
Addition +

24
Subtraction -
• When the / operator is used to perform integer division the resulting integer is obtained by
discarding (or truncating) the fractional part of the actual floating point value. For example:
1/2 0
3/2 1
• The modulus operator % only works with integer operands. The expression
a%b is read as “a modulus b” and evaluates to the remainder obtained after dividing a by b. For
example
7 % 2= 1
12 % 3= 0

2.4. Arithmetic assignment statement


Assignment is performed with the operator =. It means «take the right-hand side (often called
the rvalue) and copy it into the left-hand side (often called the lvalue). The general form is:
result = expression

This notation can be used with the arithmetic operators that are the same as the ones available in
most programming languages: addition (+), subtraction (-), division (/), multiplication (*) and
modulus (%, this produces the remainder from integer division). Integer division truncates the
result (it doesn't round). The modulus operator cannot be used with floating-point numbers.
Example: x= y+z+2.0;
Interpretation:
i) variable or object specifed by result is assigned the value of expression.
ii) The previous value of result is destroyed.
iii) The expression may be a single variable or abject or variables and constants using arithmetic
operations.

2.5. compound assignment statement


Another common situation that occurs is assignments such as the follows:
sum = sum + x;
in which a variable (sum) is increased by some amount (x) and the result assigned back to the
original variable. This type of assignment can be represented in C by compound assignment
operators:

example: sum += x;

The general form of compound assignment:


result op= expression // op means operator namely +,-,*,/,%
25
which is interpreted as being equivalent to: result = result op(expression)

The expression is shown in brackets to indicate that the expression is evaluated first before
applying the operator op. The following examples illustrate the use of compound assignment
operators:
total += value; or total = total + value;

prod *= 10; or prod = prod * 10;

x /= y + 1; or x = x/(y + 1);

n %= 2; or n = n % 2;

Except for the case of the compound modulus operator %= the two operands may be any
arithmetic type. The compound modulus operator requires that both operands are integer types.

2.6. EXAMPLE OF A SIMPLE C PROGRAM


Before looking at how to write C programs consider the following simple example program.

/* Sample program: done by students of civil Engineering at the


beginning of c programming*/
// Reads values for the length and width of a rectangle
// and returns the perimeter and area of the rectangle.

#include <stdio.h>
int main()
{
int length, width; // declaration of input variables
int perimeter, area; // declaration of output variables
printf( "Length = "); // prompt user
scanf(“ %d”,&length); // enter length
printf( "Width = "); // prompt user
scanf(“ %d”,&width); // input width
perimeter = 2*(length+width); // compute perimeter
26
area = length*width; // compute area
//output results
printf(“\nPerimeter is %d meters\n", perimeter);//output perimeter
printf(“\nArea is %d square meters\n,area");// output area
printf(”Thank you for your program ! \n”);
printf(”Enjoy this program! \n”);
return 0;
} // end of main program

The above program would produce:

Enter the value of breadth= 12


Enter the value of length= 25
perimeter is = 74 meters
area is = 300 square meters
Thank you for your program !
Enjoy this program !.
Press any key to continue

2.7. LOGICAL operators


It is possible to specify more complex conditions than those which can be written using only the
relational operators described above. Since the value of a condition has a numerical interpretation
it could be operated on by the usual arithmetic operators, this is not to be recommended. There
are explicit logical operators for combining the logical values true (1) and false (0).

The logical operators can be defined by truth tables as follows. Note that F is used for false and
T is used for true in these tables.

Not ! And && Or ||


A !A A B A && B A B A || B
F T F F F F F F
T F F TF F TT
T F F T F T
27
T TT T TT

These tables show that NOT reverses the truth value of the operand, that the AND of two
operands is only true if both operands are true and that the OR of two operands is true if either or
both of its operands are true. Using these logical operators more complex conditions can now be
written.

2.8. RELATIONAL OPERATORS


Operator Meaning Example Opposite
== Equality to a == b !=
!= Not equal to 12 != 7 ==
< Less than 25 < 84 >=
<= Less than or equal to Cab <= Tab >
> Greater than 248 > 55 <=
>= Greater than or equal to Val1 >= Val2 <

2.9. INCREMENT AND DECREMENT OPERATORS

There are some operations that occur so frequently in writing assignment statements that C has
shorthand methods for writing them.

One common situation is that of incrementing or decrementing an integer variable. For example:

n = n + 1;
n = n - 1;

C has an increment operator ++ and a decrement operator --. Thus

n++; can be used instead of n = n + 1;


n--; can be used instead of n = n - 1;

The ++ and -- operators here have been written after the variable they apply to, in which case
they are called the postincrement and postdecrement operators. There are also identical
preincrement and predecrement operators which are written before the variable to which they
apply. Thus
28
++n; can be used instead of n = n + 1;
--n; can be used instead of n = n - 1;

Both the pre- and post- versions of these operators appear to be the same from the above, and in
fact it does not matter whether n++ or ++n is used if all that is required is to increment the
variable n. However both versions of the increment and decrement operators have a side effect
which means that they are not equivalent in all cases. These operators as well as incrementing or
decrementing the variable also return a value. Thus it is possible to write

i = n++;

What value does i take? Should it take the old value of n before it is incremented or the new
value after it is incremented? The rule is that a postincrement or postdecrement operator delivers
the old value of the variable before incrementing or decrementing the variable. A preincrement or
predecrement operator carries out the incrementation first and then delivers the new value. For
example if n has the value 5 then

i = n++;
would set i to the original value of n i.e. 5 and would then increment n to 6. Whereas
i = ++n;
would increment n to 6 and then set i to 6.
For the moment this notation will only be used as a shorthand method of incrementing or
decrementing a variable.

Note:

 The unary increment and decrement operators are applied to integer variables to increase
or decrease the value by 1.
 If the increment (or decrement) operator is placed after the variable, the operation takes
place after the value has been returned.
 If the increment (or decrement) operator is placed before the variable, the operation takes
place before the value is returned.

29
2.10. PRECEDENCE & ASSOCIATIVITY OF OPERATORS
• The precedence of operators determines the order in which operations are
performed in an expression. Operators with higher precedence are employed
first. If two operators in an expression have the same precedence, associativity
determines the direction in which the expression will be evaluated.
• C has a built-in operator hierarchy to determine the precedence of operators.
Operators higher up in the following diagram have higher precedence. The
associativity is also shown.
- ++ -- R to L
* / % L to R
+ - L to R
= R to L
This is how the following expression is evaluated
1+2*3-4
1+6-4
7-4
3
NB:
The negation operator, !, has the highest precedence and is always performed
first in a mixed expression. The remaining logical operators have a precedence
below relational operators.

2.11TYPE CASTING
• Programmers can override automatic type conversion and explicitly cast
variables to be of a certain type when used in an expression. For example,
(double) i
• will force i to be of type double. The general syntax is (type) expression
• Some examples,
(char) 3 + 'A'
x = (float) 77;
(double) k * 57

30
Exercises

1. int c, a=2, b=1;


c = (a > b)
What is the value of c?
2. For the declaration
int a=1,b=2,c;
what is the value of the following expressions?
a > b; a<b; a>=b;a<=b
3. int a = 1, b = 2, c = 3, d;
d = ( a > b ) || ( c = = (b – 1) );
What is the value of d here?
4. Consider the given code:

#include <stdio.h>
using namespace std;
int main ( )
{
int i,j,k;
i = 10;
k = i++;
j = i+k;
i= ++j;
printf(“%d,%d,%d\n”, i, j , k);
return 0;
} The output is:
a. 10,21,10
b. 11,20,10
c. 21,21,10
d. 20,21,11
5. Given the following int a,b,c,d,e;
a=8,b=3,c=4,d=9;
e=a % b * c + a / b – c or abc*%83/+9-
The value of e is
1. -3
2. 1
3. -4
4. None

31
CHAPTER THREE: CONTROL STATEMENTS

Control statements determine the order in which nested statements are executed. They consist of
selection statements and repetition statements. Where more than one statement is required in a
control structure, a block should be used.

3.1. SELECTION STRUCTURES: ( IF and SWITCH STATEMENTS)

3.1.1. IF statement
The if-else statement can exist in two forms: with or without the else. The two forms are:

if(expression) // expression is Boolean expression or condition to be satisfied


statement; //executed only if expression is true
or
if(expression1)
statement1;
else if(expression2)
statement2;
else if(expressionn)
statementn
else
statement;// executed only if the previous expressions are false.

The "expression" evaluates to true or false. The "statement" means either a simple statement
terminated by a semicolon or compound statement, which is a group of simple statements
enclosed in braces { }. Note this statement can also be another if, so they can
be strung together.
Note:Pascal programmers should notice that the "then" is implied in C and C++, which are terse
languages. "Then" isn't essential, so it was left out.
Example 1.
#include <stdio.h>
int main() {
int i;

32
printf( "type a positive integer less than 10\n") ;
scanf(“%d”,& i);
if(i > 5)
printf( "the number was greater than 5 \n") ;
else if(i < 5)
printf("the number was less than 5\n ");
else
printf("the number must be equal to 5 \n");
return 0;
}

Example 2. Write a program that will tell you if a number was odd or even. You could use
modulus to quickly tell you by asking for the remainder of the number when divided by two.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int num;
printf(" Enter a number \n");
scanf("%d",& num);
// num % 2 computes the remainder when num is divided by 2
if ( num % 2 == 0 )
{
printf("%d is even",num);
}
else
{
printf("%d is odd",num);
}
system("PAUSE");
return 0;
}

33
3.1.2. SWITCH statement
The switch statement is a very clean way to implement multi-way selection (i.e., selecting
from among a number of different execution paths), but it requires a selector that evaluates to
an integral value at compile-time. If you want to use, for example, a string as a selector, it
will not work in a switch statement. For a string selector, you must use instead a series of if
statements and compare the string inside the conditional.
Its general form is as follows:

switch (selector)// selector variable that can have multiple choices


{
case choice1:
statement1; // statement1, statement2 are executed if selector == choice1
sstatement2;
break;
case choice2:
statement3; // statement3 executed if selector == choice2
break;

// ... more cases as required and corresponding choices or statements


default:
statement4; // statement4 executed only if none of the cases matches
break;
}//choice1, choice2, choicen are constants of the same type as variable i.

Note:
 A selector is an expression that produces an integral value (choice). The switch compares the result
of selector to each choice. Switch statement selects the next statement to be executed from many
possible statements. If it finds a match, the corresponding statement (simple or compound executes. If
no match occurs, the default statement executes.
 The selection is made depending on the value of a selector variable which can only be an integer or a
character.

34
 The default label is optional but if it is not included then a selector which does not match any of
the case labels causes the whole switch statement to be ignored.
 You will notice in the above definition that each case ends with a break, which causes
execution to jump to the end of the switch body. This is the conventional way to build a
switch statement, but the break is optional. If it is missing, the code for the following case
statements execute until a break is encountered. Although you don't usually want this kind of
behavior, it can be useful to an experienced C programmer.

Example 1: Menus often lend themselves neatly to a switch:


//: C03:Menu2.cpp
// A menu using a switch statment
#include <stdio.h>
int main() {
char response; // The user's response
int quit = 0; // Flag for quitting
while(quit == 0)
{
printf("Select a, b, c or q to quit: ");
scanf(“%c”,& response);
switch(response)
{
case 'a' :
printf( "you chose 'a'\n");
break;
case 'b' :
printf( "you chose 'b'\n”);
break;
case 'c' :
printf( "you chose 'c'\n");
break;
case 'q' :
printf( "quitting menu\n");

35
quit = 1; /*Notice that selecting 'q' sets the quit flag to 1. The next time the selector is
evaluated, quit == 0 returns false so the body of the while does not execute.*/
break;
default :
printf( "Please use a,b,c or q!\n");
}// end of switch
}//end of while
return 0;
}// end main
Note:
• The switch statement works as follows
1) Integer control expression is evaluated.
2) A match is looked for between this expression value and the case constants. If a match is
found, execute the statements for that case. If a match is not found, execute the default statement.
3) Terminate switch when a break statement is encountered or by “falling out
the end”.
• Some things to be aware of when using a switch statement:
– case values must be unique (How to decide otherwise?)
– switch statement only tests for equality
– The control expression can be of type character since they are internally treated as integers

3.2. REPETITION OR LOOPING


Definition
A loop is a sequence of instruction s that is continually repeated until a certain condition is
reached.
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional
exit so that it repeats indefinitely.
Repetition statements are comprised of while, do-while and for control looping.

36
3.2.1. WHILE statement

The while statement examines or evaluates a condition. The syntax of the while statement
is:

while(Condition)

Statements;

Increment or decrement;

Example1. /*NUR 2007/April


This program Prints first 10 integers*/

#include <stdio.h>

void main()
{
int i; // declaration of variable
i = 1;// initialization of the first integer=1
while (i <= 10)// testing the condition
{
printf(”%d”, i);
printf(” ”);
i++; // update
}
}

3.2.2. DO...WHILE statement


Its format is:

do {statements} while (condition);

Its functionality is exactly the same as the while loop, except that condition in the do-while loop
37
is evaluated after the execution of statement instead of before, granting at least one execution of
statement even if condition is never fulfilled.
Example 1
#include <stdio.h>
int main()
{
int Number = 0;//initializing the number

do
{
Printf("Number %d\n",Number);
Number++;
}while( Number <= 12 ); //end of do-while

return 0;
}
Example 2
1. Sum of Arithmetic Progression
The following program produces the sum 1+2+3+ ...+n, where a value for n is entered by the
user:
// Example program
// When user enter n (>0) the sum of the first n natural numbers is output.
#include <stdio.h>
void main()
{
int i,n;// i: conter, n number entered by the user
int sum;
printf( "Enter a value for n: ");
scanf(“%d”,& n);
sum = 0;//initializing the sum
i = 1;//initializing the counter
do
{
sum += i;
i++;// stepping
}

38
while (i <= n);//end of do-while
printf("The sum of the first %d natural numbers is %d\n",n,sum);
}

3.2.3. FOR

The format of a for loop is:

for(initializing expressions)
{
statements; // what the loop will do
}

three initializing conditions of the for loop:


· Telling the compiler at which value to begin
· Telling the compiler at which value to stop
· Incrementing or decrementing the loop (makes the loop
move to the next value for code processing)
Example1.
// Counting From 0 To 10
#include <stdio.h>
void main()
{
// declare a variable
int i;
for ( i= 0; i < 11; i++)
printf(“%d\n”, i );
}
Note: i= 0 told the compiler you are starting at 0; i < 11 told the compiler where to stop the loop
and i++ means i = i + 1

39
3.3. Jump statements.

3.3.1. The break statement


Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to
end an infinite loop, or to force it to end before its natural end. For example, we are going to stop
the count down before its natural end (maybe because of an engine check failure?):

// break loop example

#include <stdio.h>
int main ()
{
int n;
for (n=10; n>0; n--)
{
printf(“%d”, n); 10, 9, 8, 7, 6, 5, 4, 3, countdown
if (n==3) aborted!
{
printf( "countdown
aborted!");
break;
}
}
return 0;
}

3.3.2. The continue statement


The continue statement causes the program to skip the rest of the loop in the current iteration as
if the end of the statement block had been reached, causing it to jump to the start of the following
iteration. For example, we are going to skip the number 5 in our countdown:

// continue loop example


#include <stdio.h>
10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!

int main ()

40
{
for (int n=10; n>0; n--) {
if (n==5) continue;
printf(“%d,”, n);
}
Printf( "FIRE!\n");
return 0;}

3.3.3. The go to statement


goto allows to make an absolute jump to another point in the program. You should use this
feature with caution since its execution causes an unconditional jump ignoring any type of
nesting limitations.
The destination point is identified by a label, which is then used as an argument for the goto
statement. A label is made of a valid identifier followed by a colon (:).

Example:

#include <stdio.h>

int main()
{
for(int Count = 0; Count <= 12; ++Count)
{
Printf( "Count %d\n ", Count);

if( Count == 5 )
goto Copine;
}

Copine:
Printf( “This is a student of BacI\n");

return 0;}

41
EXERCISES

1. Write a cpp program to display the following

2. Write a c program that displays


1 3 5 7 9 ……n where n is entered from the keyboard.

3. Write a c program that displays


1
3
5
7
9
……
N
where N is entered from the keyboard.
4. Write a c program that displays the sum of all positive even numbers less or equal to n.
5. Write a c program that displays the divisors of n (n must be positive)
6. Using while, write a c program that adds the divisors of an entered number

42
CHAPTER FOUR: FUNCTIONS

4.1. Definition

A function in C is a small “sub-program” that performs a particular task, and supports the
concept of modular programming design techniques. In modular programming the various
tasks that your overall program must accomplish are assigned to individual functions and the
main program basically calls these functions in a certain order.
The functions are used for the following reasons:
– Don‟t have to repeat the same block of code many times in your code. Make that code block a
function and call it when needed.
– Function portability: useful functions can be used in a number of programs.
– Supports the top-down technique for devising a program algorithm. Make an outline and
hierarchy of the steps needed to solve your problem and create a function for each step.
– Easy to debug. Get one function working well then move on to the others.
– Easy to modify and expand. Just add more functions to extend program capability
– For a large programming project, you will code only a small fraction of the program.
– Make program self-documenting and readable.

4.2. Predefined functions

You need to have the #include <math.h> directive at the top of your program to use these. All
parameters and return values are of type double. math.h also defines some constants which may
be used. For example M_PI can be used for and M_E can be used for .

Function Description

sqrt(x) x : square root of x, x>=0

acos(x) inverse cosine, -1 <= x <= +1, returns value in radians in range 0 to PI

asin(x) inverse sine, -1 <= x <= +1, returns value in radians in range –PI/2 to PI/2

atan(x) inverse tangent, returns value in radians in range -PI/2 to PI/2

sin(x) trigonometric sine of x (x in radians)

43
cos(x) trigonometric cosine of x ( x in radians)

tan(x) trigonometric tangent of x ( x in radians)

exp(x) ex : exponential function

log(x) ln(x): natural logarithm of x (base e = 2.71823)

log10(x) logarithm of x to base 10

pow(x,y) xy:x raised to power y, x powered to y

ceil(x) smallest integer not less than x

floor(x) largest integer not greater than x

fabs(x) |x|: absolute value (unsigned)

rint(x) round x to nearest integer

4.3. USER DEFINED FUNCTIONS


In order to use functions, the programmer must do three things
– Define the function
– Declare the function
– Use the function in the main code.
The following is its format:
// Introducto ry comments
compiler directives
1.Function prototype
2. int main () // main program containing the function call
{
local declaratio ns
input statements
function call
output statements
retun 0;
} // end of main function
3.Funtion definition s // containing also function return

44
4.3.1. Function prototype
The general format for a prototype is simple:
Return-type function_name(arg_type arg1,………..arg_type argN);
arg_type just means the type for each argument -- for instance, an int, a float, or a char. It's
exactly the same thing as what you would put if you were declaring a variable.
There can be more than one argument passed to a function or none at all (where the parentheses
are empty), and it does not have to return a value. Functions that do not return values have a
return type of void. Lets look at a function prototype:
int mult ( int x, int y );

This prototype specifies that the function mult will accept two arguments, both integers, and that
it will return an integer. Do not forget the trailing semi-colon. Without it, the compiler will
probably think that you are trying to write the actual definition of the function.

4.3.2. Function main

The general form of a function definition in C is as follows:

Type main()
{
Declarations;
Function call;
}

4.3.3. Function definition

The general form of a function definition in C is as follows:

Function _type function_name(arguments)


{
Local definition
Function implementation
Function return
}

45
If the function returns a value then the type of that value must be specified in function-type. For
the moment this could be int, float or char. If the function does not return a value then the
function-type must be void.

 The function-name follows the same rules of composition as identifiers.


 The parameter-list lists the formal parameters of the function together with their types.
 The local-definitions are definitions of variables that are used in the function-
implementation. These variables have no meaning outside the function.
 The function-implementation consists of C executable statements that implement the effect
of the function.

e.g. Definition of a factorial function, and a function to calculate nCr

// Factorial function declaration (prototype)


int factorial(int n);
// Combinations function definition
int combinations(int n, int r)
{
return factorial(n) / (factorial(n - r)*factorial(r));
}
// Factorial function definition
int factorial(int n)
{
int i;
int factorial = 1;
// Calculate the factorial with a FOR loop
for (i = 1; i <= n; ++i)
{
factorial = factorial * i;
}
return factorial;}

46
4.3.4. return statement

Unless the function type is void , a function must return a single result of the indicated type. This
is accomplished through the use of C return statement.
General form:
return (expression);
e.g. return (k*k); return (x+y);

Note: When a return statement executes, the expression following return is evaluated and its
value is communicates back to the calling function as the function result.

4.3.5. Examples

1. A function to calculate the square of an integer

#include<stdio.h>
//Function prototype
int square_int(int); // type of function and type of the integer to be squared
//Main program: use of the function square_int to compute area of a square
int main()
{
//local data
int side;//input: side length of a square
int area;// output: area of square
area=square_int(side);//function call to compute area of square
return 0;
}// end of main function
//Function definition
int square_int( int k)
{
return (k*k);//function return
}// end of function definition

47
3.Functions with no parameters

Functions with no parameters are of limited use. Usually they will not return a value but carry out
some operation. For example consider the following function which skips three lines on output.

void skipthree(void)// skips three lines on output


{
Printf(“\n\n”);
}

4.3.6. Recursion

Recursion is a programming technique that allows the programmer to express operations in terms
of themselves. In C, this takes the form of a function that calls itself. A useful way to think of
recursive functions is to imagine them as a process being performed where one of the instructions
is to "repeat the process". This makes it sound very similar to a loop because it repeats the same
code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to
express ideas in which the result of the recursive call is necessary to complete the task.

Every recursion should have the following characteristics.

1. A simple base case which we have a solution for and a return value. Sometimes there are
more than one base cases.
2. A way of getting our problem closer to the base case. I.e. a way to chop out part of the
problem to get a somewhat simpler problem.
3. A recursive call which passes the simpler problem back into the function.

Let's write the factorial function recursively.

int myFactorial( int integer)


{
if(( integer == 1)||(integer==0))
return 1;
else

48
{
return (integer * (myFactorial(integer-1)));
}
}

EXERCISES
1. Consider the following code
#include <stdio.h>
float average(int list[], int length)
{
float total = 0;
int count;
for (count = 0 ; count < length ; count++)
total += float(list[count]);
return (total / length);
}
int main (){
int numbers[] ={2,4,6,8,10};
int size = 5;
printf(”The percentage is :%f\n “,average(numbers,size)*10);
return 0;}
The output is:
i. The percentage is 6
ii. The percentage is 66
iii. The percentage is 60
iv. None
2. write a c program to compute log(x) where x is entered from the keyboard

3. Using for/while/do ..while, write a c function that prompts the user to type two integers
and displays the following
Enter a:4
Enter b:3
Result:64
4. Using recursion, write a c function to sum all positive integers less than n

49
CHAPTER FIVE: ARRAYS FUNDAMENTALS

5.1. DEFINITION
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.
Arrays come in two flavors: one dimensional and multi-dimensional arrays.

5.2. DECLARING ARRAYS


The array is first identified by its kind, which could be a char, an int, a float, etc; followed by its
name that follows the C naming rules. The name is then followed by square brackets [ ] that
specify the dimension ( order or index) of the array or its size (how much your array is going to
occupy in computer memory).
Like any other variable, the syntax of declaring an array is:
DataType ArrayName[dimension\order] For one dimensional array
DataType ArrayName[dimension1] [dimension2] 2-dimensional array: dimension1
// Datatype: int,double,float, char indicates number of rows; dimension2
shows number of columns.

Note: The index must be an integer and indicates the position of the element in the array. Thus
the elements of an array are ordered by the index.
Here are examples of declaring arrays:
i. int Age[12]; //declares a group or array of 12 values, each one being an integer.
ii. float Grade[100]; // declares an array of 100 floating-point values.
iii. double Angle[360]; /*declares an array of double-precision numbers. There are 360 of these
items in the group.*/
iv. int A[4][6];/* declares an array of integer numbers. 4 rows and 6 columns. Each row has 6
elements. Therefore, the array is comprised of 24 elements. */

5.3. INITIALIZING ARRAYS

Just like any variable can be initialized, an array also can be initialized. you can start with the
data type to specify the kind of array you are declaring. This is followed by the array name, and
the square brackets. After specifying the dimension or not, and after the closing square bracket,
type the assignment operator (=). The elements, also called items, that compose the array are
50
included between an opening curly bracket '{' and a closing curly bracket '}'. Each item is
separate from the next by a comma operator. As a normal C/C++ initialization, you end it with
a semi-colon.

5.3.1. General form

DataType ArrayName[dimension] = { element1, element2, …, elementn};


DataType ArrayName[n][m] = { element1, element2, …, element n*m};
// number of elements = n*m

Examples:
double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};
int number[12]= {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12};
int primes[10] = {1, 2, 3, 5, 7}; /*would reserve space for a ten element array but would only
initialise the first five elements.*/
int primes[] = {1, 2, 3, 5, 7, 11, 13};/* initialising an array to hold the first few prime numbers*/
double distance[2][4] = { 44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12 }; /*
A 2-dimensional array having 2*4=8 elements */
C/C++ also allows you to include each row in its own pair of curly brackets. You must separate
each row from the next with a comma. Once again, this makes code easier to read. For example,
double distance[2][4] = { { 44.14, 720.52, 96.08, 468.78 },{ 6.28, 68.04, 364.55, 6234.12 }};

Note: After initializing an array, its elements are counted from left to right. Each element of the
array, also called a member of the array, has a specific and constant position. The position
of an item is also called its index. The first member of the array, the most left, has an index
of 0. The second member of the array has an index of 1. Since each array has a number of
items which can be specified as n, the last member of the array has an index of n-1.

Based on this system of indexing, to locate a member of an array, use its index in the group.
Imagine you declare and initialize an array as follows:

double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};

To locate the value of the 3rd member of the array, you would type distance[2]. In the
same way, the 1st member of the array can be located with distance[0].

51
Once you can locate a member of the array, you can display its value using cout. Here is
an example:

#include <stdio.h>

int main()
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};

printf( "2nd member =%f\n ", distance[1] );


printf( "5th member =%f\n " , distance[4]);

return 0;
}

This would produce:

2nd member = 720.52


5th member = 6.28

Example2 : A program to display a matrix of order 4x4


//this program is to display a matrix A[4][4]
#include<stdio.h> //input and output
#include<iomanip.h> // for setting width
int main()
{
int A[4][4];// declaration of matrix A[4][4]
printf("enter elements of matrix A\n");
for(int i=0;i<4;i++)// looping for row
{
for(int j=0;j<4;j++)//looping for columns
{
Printf("A[%d][%d]=”,i,j);
Scanf(“%d”,&A[i][j]);
}// end loop for columns
}// end loop for columns

52
// displaying results
Printf("\nThe matrix is :\n\n ");
i=0;
while(i<4)// loop for rows
{
for(int j=0;j<4;j++) // loop for columns
{
Printf(“%d”,A[i][j]); // sets width of 8 characters before and after each column
}// end loop for columns
i++ ;
printf("\n\n"); // skip 2 lines to begin the next row
}//end loop for rows
return 0;//succesful of program
}//end main program

THE OUT PUT


enter elements of matrix A
A[0][0]= 12
A[0][1]= 13
A[0][2]= 14
A[0][3]= 14
A[1][0]= 15
A[1][1]= 12
A[1][2]= 16
A[1][3]= 17
A[2][0]= 18
A[2][1]= 19
A[2][2]= 10
A[2][3]= 20
A[3][0]= 30
A[3][1]= 34
A[3][2]= 35
53
A[3][3]= 26
The matrix is :

12 13 14 14
15 12 16 17
18 19 10 20
30 34 35 26

5.4. ARRAYS of CHARACTERS

5.4.1. Declaring an Array of character


The general form of declaring an array of character is as follows:

char VariableName[NumberOfCharacters]; One-dimensional Array of characters


(string)
char VariableName[dimension1][dimension2]; 2-dimensional Array of characters (string)
dimension1: NumberOfstrings;
dimension2: Number of characterfor each string

Examples:
i. char name[12]; //The variable name should have at most 12 characters
ii. char studentname[20][30]; // 20 student names, each name having at most 30 characters.

5.4.2. Initializing an Array of Characters

To initialize a character variable, type it between single-quotes.

Here is an example:

char Answer = „y‟; char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

To display these characters as a group, you can use the following:

Printf("The name is %c%c%c%c%c", L1, L2, L3, L4, L5);

54
i). To initialize an array of characters, you use the curly brackets. Each character must be
enclosed in single-quotes. If you know the characters you will be using to initialize the array, you
should omit specifying the dimension. Here is an example:

char Color[] = { 'B', 'l', 'a', 'c', 'k' };


Example1: Consider a name such as James. This is made of 5 letters, namely J, a, m, e, and s.
Such letters, called characters, can be created and initialized as follows:

Here is such a program:

#include <stdio.h>
int main()
{
char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

printf( "The name is %c%c%c%c%c ", L1, L2, L3, L4, L5);

return 0;

This would produce:

The name is James

As done with other arrays, each member of this array of characters can be accessed using its
index. Here is an example:

#include <stdio.h>
int main()
{
char Name[6] = { 'J', 'a', 'm', 'e', 's' };// initializing characters
printf("The name is %c%c%c%c%c ", Name[0] , Name[1], Name[2], Name[3], Name[4]);
return 0;
}

55
ii). Another technique used to initialize an array of characters is to type the group of
characters between double-quotes. Since you know the array, let the compiler figure out
its dimension. Here is an example:

char arrayname[]=”string”;

example: char Country[] = "Swaziland";

Any of these two techniques would allow you to display the string using the cout operator.

5.4.3. Requesting an Array of Characters

Instead of initializing an array, sometimes you will have to wait until the program is running,
to assign a value to the array. First, you must declare the array, specifying an approximate
dimension. To request the value of an array of characters, use the cin operator, specifying
only the name of the array. Here is an example:

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[])

char FirstName[20];

char LastName[20];

printf( "The following pieces of information are needed to complete your application\n");

printf( "First Name: ");

scanf("%s",&FirstName);

printf("Last Name: ");

56
scanf("%s",&LastName);

// printf( "\nMember Information");

printf("\nFull Name:%s %s ", FirstName,LastName);

system("PAUSE");

return 0;

}Here is an example of running the program:

The following pieces of information are need to complete your application

First Name: Michael


Last Name: Callhoun

Member Information
Full Name: Michael Callhoun

5.5. SIZE OF AN ARRAY


We knew the dimensions of the arrays we have used so far, because we could count the number
of members of the array. Imagine you declare a large array, possibly made of 100 or 300
members, you wouldn't start counting the number of members. C/C++ provides the sizeof
operator that can be used to get the dimension of an array. The syntax you would use is:
sizeof(ArrayName) / sizeof(DataType)

Imagine you declare an array as follows:


int number[] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12, 127, 4762, 823, 236, 84, 5};
Instead of counting the number of members of this array (it makes me dizzy when I try), you can
use the sizeof operator as follows:
int NumberOfItemsOfTheArray = sizeof(Number)/sizeof(int);
One of the advantages of the sizeof operator used to get the number of members of the array is
that it can be used on a for loop to scan an array, either to locate the members or to look for a
value in the array. Here is an example of using this concept:
#include <stdio.h>
int main()
57
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};
// Using the sizeof operator to get the dimension of the array
int index = sizeof(distance) / sizeof(double);

printf( "Array members and their values : \n");


// Using a for loop to scan an array
for(int i = 0; i < index; ++i)
printf( "Distance %d:%f\n", i + 1, distance[i]);
return 0;
}

This would produce:

Array members and their values :


Distance 1 : 44.14
Distance 2 : 720.52
Distance 3 : 96.08
Distance 4 : 468.78
Distance 5 : 6.28

5.6. OPERATION ON ARRAYS

Each member of an array is a pseudo-variable and can be processed as such. This means that you
can add the values of two members of the array(Number[2]+Number[0]), you can subtract the
value of one of the members from another member(member[1]-Number[4]). In the same way,
you can perform multiplication, division, or remainder operations on members of an array.
Example1: One of the regular operations performed on an array consists of adding the values of
the members to produce a sum. Here is an example:

#include <stdio.h>
int main()
{
// We know that we need a constant number of elements
const int max = 10;
58
int number[max];

// We will calculate their sum


int sum = 0;

printf("Please type 10 integers.\n");

for( int i = 0; i < max; i++ )


{
Printf( "Number %d: ", i + 1);
Scanf(“%d”,&number[i]);
sum += number[i];
}

Printf( "\n\nThe sum of these numbers is %d\n\n " , Sum );

return 0;
}

This would produce:

Example2: Another type of operation regularly performed on an array consists of looking for
a value held by one of its members. For example, you can try to know if one of the members
holds a particular value you are looking for. Here is an example:

#include <stdio.h>
59
int main()
{
// Declare the members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int find; // find is the number to search
int i, m = 8;
//executable statements
Printf( "Enter a number to search: ");
Scanf(“d”,& find);
for (i = 0; (i < m) && (Numbers[i] != Find); ++i)
continue;

// Find whether the number typed is a member of the array


if (i == m)
printf(“%d is not in the list\n", find);
else
printf(“%d is the %d th element in the list\n ", find, i + 1);
return 0;
}

This would produce:

Enter a number to search: 44


44 is the 4th element in the list

Example3: One of the most regular operations performed consists of comparing the values
of different members to get the lowest value of the members. Here is an example:

// Example of finding the minimum member of an array


#include <stdio.h>
int main()
{
// The members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int minimum = numbers[0];
int a = 8;

// Compare the members


for (int i = 1; i < a; ++i) {
if (numbers[i] < minimum)

60
minimum = numbers[i];
}

// Announce the result


Printf("The lowest member value of the array is %d.\n", minimum );

return 0;
}

This would produce:

The lowest member value of the array is 8.

5.7. STRINGS

5.7.1. Defining Strings


A string is a character , an array of characters or an empty space whose last character is \0.
A typical string, such as Pacifique, is graphically represented as follows:

P a c i f i q u e \0

The last character \0 is called the null-terminating character. For this reason, a string is
said to be null-terminated. The string library ships with a lot of functions used to perform
almost any type of operation on almost any kind of string. Used under different
circumstances, the string functions also have different syntaxes.

The strings that you can use in your program may be defined in various libraries depending
on your compiler but most of the time, they are available once you include the string library
that is defined in the std namespace.

5.7.2. Declaring Strings

To use a string in your program, use the following library:

#include<string.h>

When requesting its value from the user, by default, the string identifier is used to get only a
one-word variable. Here is an example program that requests a first and last names:

61
#include <stdio.h>
#include <string.h> //to open the string library
int main()
{
string FirstName, LastName; // declaration of strings
printf( "Enter first name: ");
scanf(“%s”,&FirstName);
printf("Enter last name: ");
scanf(“%s”,& LastName);
// Printing the results
Printf("\n\nFull Name: %s %s\n\n ", FirstName, LastName);
return 0;
}

5.7.3. Initializing Strings


• Initializing a string can be done in three ways: 1) at declaration, 2) by reading in a value for the
string, and 3) by using the strcpy function. Direct
initialization using the = operator is invalid. The following code would
produce an error:
char name[34];
name = "Erickson"; /* ILLEGAL */
• To read in a value for a string use the %s format identifier:
scanf("%s",name);
• Note that the address operator & is not needed for inputting a string variable . The end-of-string
character will automatically be appended during the input process.

5.7.4. Copying Strings


• The strcpy function is one of a set of built-in string handling functions available for the C
programmer to use. To use these functions be sure to include the string.h header file at the
beginning of your program. The syntax of strcpy is strcpy(string1,string2);
• When this function executes, string2 is copied into string1 at the beginning of string1. The
previous contents of string1 are overwritten.
• In the following code, strcpy is used for string initialization:
62
#include <string.h>
main () {
char job[50];
strcpy(job,"Professor");
printf("You are a %s \n",job);
}
Output
You are professor

5.7.5. String I/O Functions


• There are special functions designed specifically for string I/O. They are
gets(string_name);
puts(string_name);
• The gets function reads in a string from the keyboard. When the user hits a carriage return the
string is inputted. The carriage return is not part of the string and the end-of-string character is
automatically appended.
• The function puts displays a string on the monitor. It does not print the endof- string character,
but does output a carriage return at the end of the string.
Here is a sample program demonstrating the use of these functions:
char phrase[100];
printf("Please enter a sentence\n");
gets(phrase);
puts(phrase);
• A sample session would look like this

Please enter a sentence


National university of Rwanda
National university of Rwanda

5.6.6. More String Functions

• Included in the string.h are several more string-related functions that are free for you to use.
Here is a brief table of some of the more popular ones
Function Operation

63
strcat Appends to a string
strchr Finds first occurrence of a given character
strcmp Compares two strings
strcmpi Compares two, strings, non-case sensitive
strcpy Copies one string to another
strlen Finds length of a string
strncat Appends n characters of string
strncmp Compares n characters of two strings
strncpy Copies n characters of one string to another
strnset Sets n characters of string to a given character
strrchr Finds last occurrence of given character in string
strspn Finds first substring from given character set in string

5.6.7. Examples of String Functions


• Here are some examples of string functions in action:
static char s1[]="big sky country";
static char s2[]="blue moon";
static char s3[]="then falls Caesar";
Function Result
strlen(s1) 15 /* e-o-s not counted */
strlen(s2) 9
strcmp(s1,s2) negative number
strcmp(s3,s2) positive number
strcat(s2,” tonight”) blue moon tonight

• As with strings, there is a library of functions designed to work with character


variables. The file ctype.h defines additional routines for manipulating characters. Here is a
partial list
Function Operation
isalnum Tests for alphanumeric character
isalpha Tests for alphabetic character
isascii Tests for ASCII character
iscntrl Tests for control character
isdigit Tests for 0 to 9
isgraph Tests for printable character
64
islower Tests for lowercase character
isprint Tests for printable character
ispunct Tests for punctuation character
isspace Tests for space character
isupper Tests for uppercase character
isxdigit Tests for hexadecimal
toascii Converts character to ASCII code
tolower Converts character to lowercase
toupper Converts character to upper

Example:
#include <stdio.h>
#include <ctype.h>
main() {
char name[80];
int loop;
printf ("Please type in your name\n");
gets(name);
for (loop=0; name[loop] !=0; loop++)
name[loop] = toupper(name[loop]);
printf ("You are %s\n",name);
}
Output

65
66
CHAPTER SIX: POINTERS AND STRUCTURES

6.1. What is a pointer?


A variable in a program is something with a name, the value of which can vary. The way
the compiler and linker handles this is that it assigns a specific block of memory within
the computer to hold the value of that variable. The size of that block depends on the
range over which the variable is allowed to vary. When we declare a variable we inform the
compiler of two things, the name of the variable and the type of the variable. For example, we
declare a variable of type integer
with the name k by writing:
int k;
On seeing the "int" part of this statement the compiler sets aside 2 bytes of memory (on a
PC) to hold the value of the integer. It also sets up a symbol table. In that table it adds the
symbol k and the relative address in memory where those 2 bytes were set aside.
Thus, later if we write:
k = 2;
we expect that, at run time when this statement is executed, the value 2 will be placed in
that memory location reserved for the storage of the value of k. In C we refer to a
variable such as the integer k as an "object".
In a generic sense, a “pointer” is anything that tells us where something can be found.
– Addresses in the phone book
– URLs for webpages
– Road signs
Each program variable is stored in the computer‟s memory at some location, or address. A
pointer is a variable that contains the address of another variable. Like all variables in C, a
pointer has a type. The type depends on the object addressed by the pointer. For example, a
pointer that points to an int has type “pointer to int”, written int*. Given a type T, the type T*
denotes a pointer to a variable of type T. For example, int* denotes a pointer to an integer.
Two essential operators are used to manipulate pointers. The first returns the address of an object
in memory, and the second returns the contents of a given address. In C the first task is performed
by the address-of operator, &. For example if x is an integer variable in your program &x is the
address of x in memory.
Accessing an object‟s value from its address is called dereferencing. This is done using the *
operator. For example, if we were to declare q to be a pointer to an integer (that is, int*) and then
set q = &x, we could access x‟s value with *q.
Assigning an integer value to *q effectively changes the value of x. Consider, for example, the
code fragment below. The variable p is declared to be a pointer to a char, and is initialized to
point to the variable ch. Thus, *p is another way of referring to ch. Observe that when the value
of ch is changed, the value of *p changes as well.
char ch = ‟Q‟;
char* p = &ch; // p holds the address of ch
printf(“%s”, *p); // outputs the character ‟Q‟
ch = ‟Z‟; // ch now holds ‟Z‟
printf(“%s”, *p); // outputs the character ‟Z‟

67
*p = ‟X‟; // ch now holds ‟X‟
printf(“%s”,ch); // outputs the character ‟X‟
It is useful to have a pointer value that points to nothing, that is, a null pointer.
By convention, such a pointer is assigned the value zero.
Example
int x = 1, y = 2, z[10];
int *ip; /* ip is a pointer to int */
ip = &x; /* ip now points to x */
y = *ip; /* y is now 1 */
*ip = 0; /* x is now 0 */
ip = &z[0]; /* ip now points to z[0] */

6.2. Why Pointers?


They allow you to refer to large data structures in a compact way
They facilitate sharing between different parts of programs
They make it possible to get new memory dynamically as your program is running
They make it easy to represent relationships among data items.

6.3. Pointer declaration


To declare a pointer variable, we must do two things
– Use the “*” (star) character to indicate that the variable being defined is a pointer
type.
– Indicate the type of variable to which the pointer will point (the pointee). This is
necessary because C provides operations on pointers (e.g., *, ++, etc) whose
meaning depends on the type of the pointee.
General declaration of a pointer
type *nameOfPointer;
int *intPtr;
defines the variable intPtr to be a pointer to a variable of type int. intPtr will contain the memory
address of some int variable or int array. Read this declaration as
– “intPtr is a pointer to an int”, or equivalently
– “*intPtr is an int”
Caution -- Be careful when defining multiple variables on the same line. In this definition
int *intPtr, intPtr2;
intPtr is a pointer to an int, but intPtr2 is not!

6.4. Pointer Operators


The two primary operators used with pointers are
* (star) and & (ampersand)
68
– The * operator is used to define pointer variables and to deference a pointer.
“Dereferencing” a pointer means to use the value of the pointee.
– The & operator gives the address of a variable.
Recall the use of & in scanf( )
Example
int x = 1, y = 2, z[10];
int *ip; /* ip is a pointer to an int */
ip = &x; /* ip points to (contains the memory address of) x */
y = *ip; /* y is now 1, indirectly copied from x using ip */
*ip = 0; /* x is now 0 */
ip = &z[5]; /* ip now points to z[5] */
If ip points to x, then *ip can be used anywhere x can be used so in this example *ip = *ip + 10;
and x = x + 10; are equivalent
The * and & operators bind more tightly than arithmetic operators so
y = *ip + 1; takes the value of the variable to which ip points, adds 1 and assigns it to y
Similarly, the statements *ip += 1; and ++*ip; and (*ip)++; all increment the variable to which ip
points. (Note that the parenthesis are necessary in the last statement; without them, the
expression would increment ip rather than what it points to since operators like * and ++
associate from right to left.)
Use ampersand ( & ) to obtain the address of the pointee
Use star ( * ) to get / change the value of the pointee
Use %p to print the value of a pointer with printf( )
What is the output from this code?
int a = 1, *ptr1;
/* show value and address of a
** and value of the pointer */
ptr1 = &a ;
printf("a = %d, &a = %p, ptr1 = %p, *ptr1 = %d\n",
a, &a, ptr1, *ptr1) ;
/* change the value of a by dereferencing ptr1
** then print again */
*ptr1 = 35 ;
printf(“a = %d, &a = %p, ptr1 = %p, *ptr1 = %d\n", a, &a, ptr1, *ptr1) ;
6.5. NULL POINTER
NULL is a special value which may be assigned to a pointer
NULL indicates that this pointer does not point to any variable (there is no pointee)
Often used when pointers are declared
int *pInt = NULL;
Often used as the return type of functions that return a pointer to indicate function failure
int *myPtr;
69
myPtr = myFunction( );
if (myPtr == NULL){
/* something bad happened */
}
• Dereferencing a pointer whose value is NULL will result in program termination.

6.6. CALLING FUNCTIONS BY REFERENCE


Call by reference with pointer arguments
Pass address of argument using & operator
Allows you to change actual location in memory
Arrays are not passed with & because the array name is already a pointer
* operator
Used as alias/nickname for variable inside of function
void double( int *number )
{
*number = 2 * ( *number );
}
*number used as nickname for the variable passed
CONST POINTERS
– Point to a constant memory location
– Must be initialized when declared
– int *const myPtr = &x;
• Type int *const – constant pointer to an int
– const int *myPtr = &x;
• Regular pointer to a const int
– const int *const Ptr = &x;
• const pointer to a const int
• x can be changed, but not *Ptr

6.7. POINTERS AND ARRAYS


Since a block of 10 integers located contiguously in memory is, by definition, an array of
integers, this brings up an interesting relationship between arrays and pointers.
Consider the following:
int my_array[] = {1,23,17,4,-5,100};
Here we have an array containing 6 integers. We refer to each of these integers by means
of a subscript to my_array, i.e. using my_array[0] through my_array[5]. But, we could
alternatively access them via a pointer as follows:
int *ptr;
ptr = &my_array[0]; /* point our pointer at the first
integer in our array */

70
And then we could print out our array either using the array notation or by dereferencing
our pointer. The following code illustrates this:

Compile and run the above program and carefully note lines A and B and that the
program prints out the same values in either case. Also observe how we dereferenced our
pointer in line B, i.e. we first added i to it and then dereferenced the new pointer. Change
line B to read:
printf("ptr + %d = %d\n",i, *ptr++);
and run it again... then change it to:
printf("ptr + %d = %d\n",i, *(++ptr));
and try once more. Each time try and predict the outcome and carefully look at the actual
outcome.
In C, the standard states that wherever we might use &var_name[0] we can replace that
with var_name, thus in our code where we wrote:
ptr = &my_array[0];
to achieve the same result.
This leads many texts to state that the name of an array is a pointer.
For example, while we can write
ptr = my_array;
we cannot write
my_array = ptr;
The reason is that while ptr is a variable, my_array is a constant. That is, the location at
which the first element of my_array will be stored cannot be changed once my_array[]
has been declared.
Example:
Declare an array b[ 5 ] and a pointer bPtr
To set them equal to one another use:
bPtr = b;
The array name (b) is actually the address of first element of the array b[ 5 ]
bPtr = &b[ 0 ]
71
Explicitly assigns bPtr to address of first element of b
– Element b[ 3 ]
• Can be accessed by *( bPtr + 3 )
– Where n is the offset. Called pointer/offset notation
• Can be accessed by bptr[ 3 ]
– Called pointer/subscript notation
– bPtr[ 3 ] same as b[ 3 ]
• Can be accessed by performing pointer arithmetic on the array itself
*( b + 3 )

6.8. Structures

A structure is a variable in which different types of data can be stored together in one variable
name. Consider the data a teacher might need for a high school student: Name, Class, GPA, test
scores, final score, ad final course grade. A structure data type called student can hold all this
information:
struct student {
char name[45];
char class;
float gpa;
int test[3];
int final;
char grade;
};
The above is a declaration of a data type called student. It is not a variable declaration, but a
type declaration.
To actually declare a structure variable, the standard syntax is used:
struct student Lisa, Bart, Homer;
You can declare a structure type and variables simultaneously. Consider the
following structure representing playing cards.
struct playing_card {
int pips;
char *suit;
} card1,card2,card3;
The different variable types stored in a structure are called its members. To
access a given member the dot notation is use. The “dot” is officially called
the member access operator. Say we wanted to initialize the structure card1
to the two of hearts. It would be done this way:
card1.pips=2;
card1.suit="Hearts";
• Once you know how to create the name of a member variable, it can be treated
72
the same as any other variable of that type. For example the following code:
card2.pips=card1.pips+5;
• would make card2 the seven of some suit.
• Structure variables can also be assigned to each other, just like with other
variable types:
card3 = card1;
• would fill in the card3 pips member with 2 and the suit member with
“Hearts”. In other words, each member of card3 gets assigned the value of
the corresponding member of card1.
// example about structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct movies_t {
string title;
int year;
} mine, yours;
void printmovie (movies_t movie);
int main ()
{
string mystr;
mine.title = "2001 A Space Odyssey";
mine.year = 1968;
cout << "Enter title: ";
getline (cin,yours.title);
cout << "Enter year: ";
getline (cin,mystr);
stringstream(mystr) >> yours.year;
cout << "My favorite movie is:\n ";
printmovie (mine);
cout << "And yours is:\n ";
printmovie (yours);
return 0;
}
void printmovie (movies_t movie)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}

73
6.9. Pointers and Structures
As you may know, we can declare the form of a block of data containing different data
types by means of a structure declaration. For example, a personnel file might contain
structures which look something like:
struct tag {
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
float rate; /* e.g. 12.75 per hour */
};

Example:
#include <stdio.h>
#include <string.h>
struct tag{ /* the structure type */
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
float rate; /* e.g. 12.75 per hour */
};
struct tag my_struct; /* define the structure */
void show_name(struct tag *p); /* function prototype */
int main(void)
{
struct tag *st_ptr; /* a pointer to a structure */
st_ptr = &my_struct; /* point the pointer to my_struct */
strcpy(my_struct.lname,"Jensen");
strcpy(my_struct.fname,"Ted");
printf("\n%s ",my_struct.fname);
printf("%s\n",my_struct.lname);
my_struct.age = 63;
show_name(st_ptr); /* pass the pointer */
return 0;
}
void show_name(struct tag *p)
{
printf("\n%s ", p->fname); /* p points to a structure */
printf("%s ", p->lname);
printf("%d\n", p->age);
}

74
CHAPTER VII. FILE INPUT AND OUTPUT
7.1.INTRODUCTION

So far, all the output (formatted or not) in this course has been written out to
what is called standard output (which is usually the monitor). Similarly all
input has come from standard input (usually associated with the keyboard).
The C programmer can also read data directly from files and write directly to
files. To work with files, the following steps must be taken:
1 Declare variables to be of type FILE.
2 Connect the internal FILE variable with an actual data file on your hard
disk. This association of a FILE variable with a file name is done with the
fopen() function.
3 Perform I/O with the actual files using fprint() and fscanf() functions.
4 Break the connection between the internal FILE variable and actual disk
file. This disassociation is done with the fclose() function.

• Declarations of the file functions highlighted on the previous page must be


included into your program. This is done in the standard manner by having
#include <stdio.h>
• as the first statement in your program.
• The first step is using files in C programs is to declare a file variable. This
variable must be of type FILE (which is a predefined type in C) and it is a
pointer variable. For example, the following statement
FILE *in_file;
• declares the variable in_file to be a “pointer to type FILE”.
• Before using a FILE variable, it must be associated with a specific file name.
The fopen() function performs this association and takes two arguments: 1)
the pathname of the disk file, and 2) the access mode which indicates how the
file is to be used. The following statement
in_file = fopen("myfile.dat","r");
• connects the variable in_file to the disk file myfile.dat for read
access. Thus, myfile.dat will only be read from. Two other access modes
can be used:
“w” indicating write-mode
“a” indicating append_mode
• The functions fprintf and fscanf are provided by C to perform the analogous operations for the
printf and scanf functions but on a file.
• These functions take an additional (first) argument which is the FILE pointer that identifies the
file to which data is to be written to or read from. Thus the statement,
fscanf(in_file,"%f %d",&x,&m);

75
• will input -- from the file myfile.dat -- real and integer values into the variables x and m
respectively.
• The fclose function in a sense does the opposite of what the fopen does: it
tells the system that we no longer need access to the file. This allows the
operating system to cleanup any resources or buffers associated with the file.
• The syntax for file closing is simply fclose(in_file);
• Many of the specialized I/O functions for characters and strings that we have
described in this course have analogs which can be used for file I/O. Here is a
list of these functions
• Another useful function for file I/O is feof() which tests for the end-of-file
condition. feof takes one argument -- the FILE pointer -- and returns a
nonzero integer value (TRUE) if an attempt has been made to read past the end
of a file. It returns zero (FALSE) otherwise. A sample use:
if (feof(in_file))
printf ("No more data \n");
Example
#include <stdio.h>
#include <ctype.h>
#include <string.h>
struct goods {
char name[20];
float price;
int quantity;
int reorder;
};
FILE *input_file;
void processfile(void);
void getrecord(struct goods *recptr);
void printrecord(struct goods record);
main() {
char filename[40];
printf("Example Goods Re-Order File Program\n");
printf("Enter database file \n");
scanf("%s",filename);
input_file = fopen(filename, "r");
processfile();
}

76
void processfile(void) {
struct goods record;
while (!feof(input_file)) {
getrecord(&record);
if (record.quantity <= record.reorder)
printrecord(record);
}
}
void getrecord(struct goods *recptr) {
int loop=0,number,toolow;
char buffer[40],ch;
float cost;
ch=fgetc(input_file);
while (ch!='\n') {
buffer[loop++]=ch;
ch=fgetc(input_file);
}
buffer[loop]=0;
strcpy(recptr->name,buffer);
fscanf(input_file,"%f",&cost);
recptr->price = cost;
fscanf(input_file,"%d",&number);
recptr->quantity = number;
fscanf(input_file,"%d",&toolow);
recptr->reorder = toolow;
}
void printrecord (struct goods record) {
printf("\nProduct name \t%s\n",record.name);
printf("Product price \t%f\n",record.price);
printf("Product quantity
\t%d\n",record.quantity);
printf("Product reorder level
\t%d\n",record.reorder);
}

77
REFERENCES
1. http://www.cplusplus.com/doc/tutorial
2. FRANK L.F et al. (2000). Problem solving, Abstraction, and Design Using C++, Addison
Wesley Longman, Inc, USA.
3. IAN A. and PETER K.(1997). Introduction to C++ Programming I, [online]
http://www.cee.hw.ac.uk/~pjbk/pathways/cpp1/cpp1.html, October, 2006

4. http://www.cprogramming.com/tutorial , January, 2007

5. http://en.wikipedia.org/wiki/Object-oriented_programming, January, 2007

6. http://www.functionx.com/cpp, march, 2007

7. http://www.fredosaurus.com/notes-cpp/

8. http://www.coronadoenterprises.com/tutorials/c/chap02.htm

78

You might also like