You are on page 1of 142

Programming in C

Module 1

Problem Solving With Computer

1.1 Problem Analysis

It is the most important stage of program or software development process. There are different
techniques for analyzing problem depending upon the problem and situation. Each technique has
its own merits and demerits. Methods used to develop a solution or a program are called
programming techniques. The programmers use different techniques to develop the logical
sequence for the solution of the problem. Some of the most commonly used techniques in procedure
oriented programming are: algorithm and flowchart.

1.1.1 Algorithm

The term algorithm may be formally defined as a sequence of instructions designed in such a way
that if the instructions are executed in the specified sequence, the desired result will be obtained.
The instructions however, should be precise and unambiguous and the result should be obtained
after a finite number of executional steps. The later condition actually states that an algorithm must
terminate and should not repeat one or more instructions infinitely.
Basic guidelines for writing algorithms
• Use plain language
• Do not use any language specific syntax. Same algorithm should hold true for any programming
language.
• Do not make any assumptions. Describe everything clearly and explicitly.
• Ensure that the algorithm has single entry and exit point. Important features of an Algorithm:
1. Finiteness / Termination: Every algorithm should lead to a session of task that terminates after
a finite number of steps. (Each instruction should be such that it can be performed in a finite
time)
2. Definiteness: Each step must be precisely defined. Actions should be unambiguously specified
for each case.
The definiteness and effectiveness of an instruction implies the successful termination of that
instruction.
3. Inputs: Any algorithm can have zero or more inputs. Inputs may be given initially or as the
algorithm runs.
4. Outputs: Any algorithm may result in one or more outputs (quantities that have specified relation
to inputs). After algorithm terminates the desired result should be obtained.
5. Effectiveness: All operations must be sufficiently basis so as to be implemented with even paper
and pencil. This ensures that the algorithm will ultimately terminate.

1
Prepared by: Koirala Niraj
Programming in C
Therefore, an algorithm can be defined as a sequence of definite and effective instructions, which terminates
with the production of correct output from the given input.
Example1: A man brushing his own teeth
Step 1: Take the brush
Step 2: Apply the paste
Step 3: Start brushing
Step 4: Rinse
Step 5: Wash
Step 6: Stop
If one goes through these six steps without being aware of the statements of the problem, he could
possibly feel that this is the algorithm for cleaning a toilet. This is because of several ambiguities
while comprehending every step. The step 1 may imply toothbrush, paintbrush, toilet brush etc.
Thus every step should be made unambiguous. An unambiguous step is called definite instruction.
Even if step 2 is rewritten as apply the toothpaste, to eliminate ambiguities yet the conflicts such
as, where to apply the toothpaste and where the source of toothpaste is, need to be resolved. Hence
the act of applying the toothpaste is not mentioned. Although unambiguous, such unreliable steps
can’t be included as algorithmic instruction as they are not effective.
Example2: Algorithm for preparing tea:
1. Start
2. Fetch water and tea leaves along with sugar and milk
3. Boil the water
4. Put tea leaves and sugar in boiled water
5. Mix with milk
6. Serve the tea
7. Stop
Example3: Algorithm to calculate the sum of two numbers:
1. Input two numbers A and B
2. Sum=A+B
3. Print sum
Example4: Algorithms to determine the student’s final grade and indicate whether he is pass or fail
1. Input M1, M2, M3, M4
2. Grade=(M1+M2+M3+M4)/4
3. If (Grade<50) then
Print “Fail”
Else
Print “Pass”

2
Prepared by: Koirala Niraj
Programming in C
4. Stop

1.1.2 Flowchart

A flowchart can be defined as a pictorial representation of a sequence of steps required solving a


problem. A flowchart is simply a graphical method of indicating a proposed or an actual solution
of a problem. It is very helpful for debugging or tracing the flow of the diagram. Flowchart is
drawn by using basic block each having special meaning. Blocks used for drawing flowchart are
given below:

SYMBOL NAMES USE


TERMINAL SYMBOL To indicate the start and end
of a program
(flat oval)
PROCESSING SYMBOL Indicates certain processing
(a rectangle) operation other than input
and output
INPUT/OUTPUT Indicates input output
SYMBOL operation
(a parallelogram)
DECISION SYMBOL Used whenever a decision, a
logical choice or conditional
(a diamond) branch is to be made

FOR SYMBOL Indicates FOR statement

CONNECTOR SYMBOL Used to connect the flow of a


flowchart, a connector pair

(a circle)
FLOWING SYMBOL Indicates the direction of the
flow of the program
(arrows)

Figure: Basic blocks used in flowchart


For easy visual recognition a standard convention is used in drawing flow charts. This convention
has been standardized by the international standards organization, which is shown in figure.
1. Flat oval symbols are used to indicate the beginning and ending of the operations.
2. Rectangles are used to indicate any processing operation such as storage and arithmetic.
3. Parallelograms are used to represent input and output operations.

3
Prepared by: Koirala Niraj
Programming in C
4. Diamond shaped boxes are used to indicate questions asked or conditions tested based on whose
answers appropriate exists are taken by a procedure.
5. A circle is used to join different parts of a flow chart. This is called a connector. The use of connector
gives a neat appearance to a flow chart. Further, they are necessary if a flow chart extends over more
than one page and the different parts are to be joined together. The fact that two points are to be joined
is indicated by placing connectors at these points and by writing the same identifying letter or digit
inside both connectors.
6. Arrows indicate the direction to be followed in a flow chart.

1.2 Coding, Compilation, and Execution


Coding o It is the process of writing executable program statements using language specific syntax.
o It is the process of converting algorithm into executable program.
o It is the process of converting programming logic into executable program.
Compilation and Execution
Compilation refers to the process of converting source program into object program. After coding
the program using syntax of programming language the next step is to convert the source program
into object program. During this process compiler checks for syntax error i.e. if the program
contains syntax error compiler will display the list of errors in a separate window. Each error
message indicates the line number where the error was detected as well as the type of error. If the
program does compile successfully, it will immediately begin to execute, prompting for input,
displaying output.

1.3 Debugging, Testing, and Documentation


Debugging
It is the process of identifying and removing bugs from a program or system. Bugs may be syntax error,
logical error or runtime errors.

Testing
Testing is a process used to identify the correctness, completeness and quality of developed computer
program or software by providing various sets of input values.

Documentation
Documentation means recording all events, activities that are carried out during program or system
development. There are various tools that will aid documentation like system specifications
algorithm, flowchart, coding sheets, pseudocodes, test data, reports etc. Program documentation
varies according to its intended use. Three main uses are:
- For programmer's own present or future use, as an aid to all stages in programming
- For the presnt or future use of other programmers
- For the user of the program, who may themselves vary in expertise Program documentation is vital for the
successful implementation of a system.

4
Prepared by: Koirala Niraj
Programming in C
1.4 Characteristics of Procedural Programming Language

• Emphasis is on doing things


• Large programs are divided into smaller functions
• Most functions share global data
• Data move openly around the system from function to function
• Functions transform data from one form to another
• Employs top down approach

1.5 What is C language?

C is a general-purpose computer programming language.


This language is machine independent language.
The C language is often described as a middle level programming language. It permits
programs to be written in much the same style as that of most modern high level languages and
interact with the inner workings of the computer.
This language is attracting considerable attention worldwide because the software industry
is adopting it to great advantage. The reason for this popularity are:

 Versatility
 Portability
 Powerful
 The programs written in C are fast and efficient
Because of above all, it is now the preferred language among computer professionals for writing
efficient programs.

1.6 The History of C Language

A systems programmer, named, Dennis Ritchie, developed the C language at Bell laboratories in the
early 1972.
It was written originally for programming under an operating system called UNIX.
This language is not tied to anyone operating system or machine.
This language has been called a system programming language due to its capability for writing
compilers and operating systems.
Many of the important ideas of C stem from the language BCPL (Basic Combined Programming
Language), developed by Martin Richards.
The influence of BCPL on C proceeded indirectly through the language B, which was written
by Ken Thompson, another Bell Lab systems engineer in 1970 for the first UNIX system on
the DEC PDP-7 computer system Ken dubbed his language to B, the first initials of BCPL.
5
Prepared by: Koirala Niraj
Programming in C
The letter C (Second initials of BCPL) was chosen to represent the new version of BCPL by its
developer.

1.7 Characteristics of C Language

C is a middle level language capable of writing high level code and accessing machine internal parts
C is a structured programming language. 
Grouping of statements
 Decision making (if-else)
 Looping with termination conditions (while, for, do, break)
 Selecting possible cases (switch)
It is function oriented
It can access the computer memory where the variable has been stored.

1.8 Structure of C Program

Every C program consists one or more modules called functions. One of the functions is called a
main.
Program execution always starts from main function
Each function must contain:
 Function heading - consisting function name and list of arguments in a parenthesis.
 Declaration of the arguments.
 Compound statements enclosed within a pair of braces.
Each statement must terminate with a semicolon.
Comments may appear anywhere as long as they are within the delimiters /* and */

1. Preprocessor commands
#include<stdio.h>
#include<conio.h>
#define pi 3.14
2. Function Prototypes
int add(int a, int b);
3. Global variables
int a,b,c;
4. Main function main() {

6
Prepared by: Koirala Niraj
Programming in C
int a,b,sum; printf("Enter value
of a and b:");
scanf("%d%d",&a,&b);
sum=add(a,b);
printf("Sum=%d",sum);
getch();
}
5. Function definition int add(int c,int
d)
{
int e;
e=c+d;
return e; Module 2
}

Module 2

Basic Elements of C

2.1 C Basics

The C character set


C uses the uppercase letter A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special
characters as building blocks to form basic program elements.(e.g. constants, variables, operators,
expressions etc.). The special characters are listed below:
+ - * / = % & # ! ? ^
7
Prepared by: Koirala Niraj
Programming in C
" ' ~ \ | < > ( ) [ ]
{ } : ; . , _ (blank space)
Certain other characters such as @ and $ can be included within string and comments.
C uses certain combination of these characters such as \b, \n, \t to represent special conditions such
as backspace, new line, and horizontal tab respectively. These character combinations are known
as escape sequences.

C Tokens o In a C source program, the basic element recognized by the compiler is the
token. o Token is the smallest individual unit in a program.
o In any programming language, any program is made up of individual syntactic elements,
called tokens. These includes: identifiers, variables, constants, punctuators, keywords,
operators etc.
o A token is a source program text that the compiler does not break down into component
elements.

2.2 Escape Sequences


We saw earlier how the new line character,\n, when inserted in printf( )'s format string, takes the
cursor to the beginning of the next line. The new line character is an "escape sequence", so called
because the backslash symbol (\) is considered an "escape character": it causes an escape from
the normal interpretation of string, so that the character is recognized as one having a special
meaning.
Some escape sequences used in C are:
Escape Sequence Purpose
\n New Line (Line feed)
\b Backspace(Moves the cursor one position to the left of its
current position)
\t Horizontal Tab
\r Carriage return( Takes the cursor to the beginning of the
line in which it is currently placed)
\f Form feed
\' Single quote
\" Double quote
\\ Backslash
\a Alert (Alerts the user by sounding the speaker inside the
computer)
\? Question mark

e.g. printf("He said,\"Let's do it!\""); will print


He said,"Let's do it!"

8
Prepared by: Koirala Niraj
Programming in C
2.3 Identifiers (Variables and Constants)
Identifier is the word used for name given to variables, functions, constants etc. It can also be
defined as a set of combinations of one or more letters or digits used to identify constants, variables,
functions etc.
Rules for Valid Identifiers
1.ANSI standard - 31 characters are allowed. (Some implementation of C only recognizes 8 characters). It
would be better to follow the rule of 8 characters.
2.Both uppercase and lowercase letters may be used and are recognized as distinct.
3.First character should always be letter.
4.Only underscore (_) is allowed among special symbols and is treated as letter.
5.Space and other symbols are not valid.
6.Proper naming conventions should be followed.

Valid Identifiers Invalid Identifiers


th
Count 4
test23 order-no
high_balance error flag
_test hi!there

Keywords
Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a new
meaning to the keyword, which is not allowed by the compiler. The keywords are also called
reserve words. Note that keywords are always lowercase. There are only 32 keywords available in
C

auto double int struct break else


long switch case enum register typedef
char extern return union const float
for goto if short unsigned continue
signed void default sizeof do static
while volatile

Variables and Constants:


Constants
The term constant means that it does not change during the execution of a program. It can be classified as:
a)Primary constants (integer, real, character, string)
b)Secondary constants (array, pointer, structure, union) Here,
we will discuss only primary constants.

i. Integer constants: Integer constants are whole numbers without any fractional parts.
9
Prepared by: Koirala Niraj
Programming in C

Rules for constructing Integer constants:


1.An integer constant must have at least one digit.
2.It must not have a decimal point.
3.It could be either positive or negative
4.If no sign precedes an integer constant is assumed to be positive.
5.No commas or blank spaces are allowed within an integer constant.
6.The allowable range is -2147483648 to +2147483647.

Valid integer constants: 1345 3468 -9746


Invalid integer constants: 11. 45,35 $12 025 x248

There are three types of integers that are allowed in C


a)Decimal constants (base 10)
b)Octal constants (base 8)
c)Hexadecimal constants (base 16)

Decimal integer constants:


The allowable digits in a decimal integer constant are 0,1,2,3,4,5,6,7,8,9.
The first digit should not be 0.
Should at least one digit.
e.g. Valid -> 1334 -9746
Invalid -> 11. 256 $78 025 x248

Octal integer constants:


The allowable digits in a octal constant are 0,1,2,3,4,5,6,7 Must
have at least one digit and start with digit 0.
e.g. Valid-> 0245 -0476 +04013
Invalid-> 25 (does not start with 0) 0387( 8 is not an octal digit)
04.32(Decimal point is not allowed)

Hexadecimal integer constant:


The allowable digits in a hexadecimal constant are 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
Must have at least one digit and start with 0x or 0X.
e.g. Valid-> 0x14AF 0X34680 -0x2673E
Invalid-> 0345 (Must start with 0x) 0x45H3 ( H is not a hexadecimal digit)

ii. Floating point / Real Constants: A floating point constant may be written in one or two forms called
fractional form or the exponent form.
10
Prepared by: Koirala Niraj
Programming in C

Rules for constructing floating point / real constants:


1.A floating-point constant must have at least one digit to the left and right of the decimal point.
2.It must have a decimal point.
3.It could be either positive or negative
4.If no sign precedes an floating point constant is assumed to be positive.
5.No commas or blank spaces are allowed.
6.When value is too large or small, can be expressed in exponential form comprising mantissa
and exponent. E or e should separate mantissa and exponent. The mantissa may have upto 7
digits and the exponent may be between -38 and +38. e.g. Valid-> +325.34 , 426.0, 32E-89,
35e+56
Invalid-> 1 (decimal point missing) 1. (No digit following decimal digit)
-1/2 (Symbol / is illegal) .5 (No digit to the left of the decimal)
56,8.94 (Comma not allowed) -125.9e5.5 (exponent can not be fraction)
0.158e+954 (exponent too large)
iii. character constants: A character constant is a single alphabet, single digit, or a single
special symbol enclosed within single quotes. Remember golden rule: single character single quote.
e.g. 'A' '5' '+' '?'
iv. string constants: A string constant is a sequence of alphanumeric characters enclosed in
double quotation marks whose maximum length is 255 characters. For e.g. const char txt [ ]
=”This is C and C++ Programming language.”;
e.g. "green", "My name &&&!!! ???", "$2525"

Declaration of Constants
Value of an identifier defined as constant, cannot be altered during program execution.
Generally, the constant is associated with an identifier and that name is used instead of actual number.
General Syntax
const typename identifier = const;
e.g. const float pi=3.14159;
Another way to define constants is with the #define preprocessor which has the advantage that it does
not use ant storage (but who count bytes these days?).
#define Identifier Value
#define PI 3.1415

Variables

A variable is a named location in memory that is used to hold a value that may be modified by the
program.
A variable is an identifier that is used to represent some specified type of information within the
designated portion of a program. The information (data items) must be assigned to the variable at
11
Prepared by: Koirala Niraj
Programming in C
some point in the program. The data item can then be accessed later in the program simply by
referencing to the variable name.
Thus, the information represented by the variable can change during the execution of the program. So,
quantity that may vary during program execution is called variable. Each variable has a specific storage
location in memory where its numerical value is stored. These locations can contain integer, real, or character
constants.
User defined variables must be declared before using them in the program. General
syntax typename var1, var2;
e.g. int a, b;
float c,d;
char e;

Rules for constructing variable names


1.A variable name is any combination of 1 to 8 alphabets, digits, or underscore. Some compilers
allow variable names whose length could be up to 40 characters, still, it would be better to use
the rule of 8 characters.
2.Both uppercase and lowercase letters may be used and are recognized as distinct.
3.First character should always be letter.
4.Only underscore ( _ ) is allowed among special symbols and is treated as letter.
5.Space and other symbols are not valid.

2.4 Scope of Variables (Where Variables are declared?)


Variables will be declared in three basic places: inside functions, in the definition of function
parameters, and outside of all functions. These are local variables, global variables, and formal
parameters.

Local Variables
Variables that are declared inside a function are called local variables. Local variables may be
referenced only by statements that are inside the block in which the variables are declared.
Remember, a block of code begins with an opening curly brace and terminates with a closing curly
brace. For example consider the following two functions: void func1( )
{
int x;
x=10;
}

void func2( )
{
int x;
x=-199;
}

12
Prepared by: Koirala Niraj
Programming in C
The integer variable x is declared twice, once in func1( ) and once in func2( ). The x in func1( )
has no relationship to the x in func2( ). This is because each x is only known to the code within the
same block as the variable declaration.

Global Variables
Unlike local variables, global variables are known throughout the program and may be used by
any piece of code. Also, they will hold their value throughout the program's execution. You create
global variables by declaring them outside of any function.

#include<stdio.h>
#include<conio.h> int count; /*
count is global */
void func1( );
void func2( );
void main( )
{
count=100;
func1( );
getch( );
}
void func1( )
{
int temp;
temp=count; func2(
);
printf("count is %d",count);
}
void func2( )
{
int count=50;
printf("Value of count:%d",count);
}
Look closely at this program. Notice that although neither main() or func1() has declared the
variable count, both may use it. func2(), however, has declared a local variable called count. When
func2() refers to count, it refers to only its local variable, not the global one. If a global variable
and a local variable have the same name, all references to that variable name inside the code block
in which the local variable is declared will refer to that local variable and have no effect on the
global variable. This can be convenient, but forgetting it can cause your program to act strangely,
even though it looks correct.

Formal Parameters

13
Prepared by: Koirala Niraj
Programming in C
If a function is to use arguments, it must declare variables that will accept the values of the
arguments. These variables are called the formal parameters of the function. They behave like any
other local variables inside the function.
#include<stdio.h>
#include<conio.h>
int square(int x);
main()
{
int t;
t=square(t); printf("Value of
t:%d",t);
getch();
}
int square(int x)
{
x=x*x;
return x;
}
2.5 Simple Data Types in C
C has a concept of 'data types’ that are used to define a variable before its use. The definition of a
variable will assign storage for the variable and define the type of data that will be held in the
memory location.
Broadly, Primary data types in C can be categorized as
int
char
float
double

int: Integers are whole numbers, both positive and negative. The keyword used to define integer is
int. Example of declaring integer variable is
{
int sum;
sum=10;
}
float: float is used to define floating point numbers. Example of declaring float variable is
{
float miles;
miles=5.6;
} double: double is used to define BIG floating point numbers. It reserves twice the
storage for the numbers. Example of declaring double variable is

14
Prepared by: Koirala Niraj
Programming in C
{
double big;
big = 312E7;
}
char: char is used to define single character. Example of declaring character variable is
{
char letter;
letter = 'x';
}
*Note: Single character use single quote.
Sample program illustrating each data type
#include<stdio.h>
#include<conio.h>
main() { int sum;
float money; char
letter; double pi;
sum = 10; money
= 2.21; letter =
'A'; pi = 2.01E6;
printf("Value of
sum=%d\n",sum);
printf("Value of
money=%f\n",mon
ey); printf("Value
of
letter=%c\n",letter)
; printf("Value of
sum=%e\n",pi);
getch( ); }
Memory requirement of data type may vary from one compiler to another.

Modifying the Basic Data Types:

The basic types may have various modifiers preceding them. The modifiers define the amount of
storage allocated to the variable. You use a modifier to alter the meaning of the base type to fit
various situations more precisely. The lists of modifiers are:
signed
unsigned
short
long

15
Prepared by: Koirala Niraj
Programming in C
signed, unsigned, short, long can be used with int.
signed, unsigned can be used with char. long can
be used with double.

Use of signed on integers is allowed, but redundant, because the default integer declaration assumes
a signed number.
Char is unsigned by default, so signed is used to modify character.

The amount of storage allocated is not fixed. ANSI has the following rules
short int <= int <= long int float <= double <= long double
What this means is that a "short int" should assign less than or same amount of storage as an "int" and
the "int" should be less or the same bytes than a "long int".

Data Type No of Bytes Numeric range Format


Int 4 -2147483648 to +2147483647 %d
Char 1 0 to 255 %c
Float 4 -3.4e38 to +3.4e38 %f
Double 8 -1.7e308 to +1.7e308 %lf or %e
Using modifiers
Short int / signed short 2 -32768 to +32767 %d
int
Unsigned short int 2 0 to 65535 %d
Unsigned int 4 0 to 4294967295 %lu
Signed int / int 4 -2147483648 to +2147483647 %d
Long int / signed long int 4 -2147483648 to +2147483647 %ld
Unsigned long int 4 0 to 4294967295 %lu
Signed char 1 -128 to +127 %c
Unsigned char / char 1 0 to 255 %c
Long double 10 -1.7e4932 to +1.7e4932 %Lf

These figures only apply to today’s generation of PCs. Mainframes and midrange machines could use
different figures.
You can find out how much storage is allocated to a data type by using the size of operator.
e.g main( ) { int a;
printf("Size of Integer is %d", sizeof a); getch(
);
}

16
Prepared by: Koirala Niraj
Programming in C
2.6 Expressions
An expression is any valid combination of different entities for example a constant, a variable, an array
element or a reference to a function.
It may also consists of some combination of such entities, interconnected by one or more operators.
Types of Expressions:
Simple Expression
The simplest C expression consists of a single item: a simple variable, a literal constant, or symbolic constant.
Expression Description
PI A symbolic constant defined in the program
20 A literal constant
sum A variable
Complex Expression
Complex expressions consists of simple expressions connected by operators. For example a+b is a
complex expression in which two simple expressions are connected with + operator.
Logical Expressions
The expressions which represents logic conditions that are either true or false are logical expressions. The
conditions true and false are represented by integer value 1 and 0 respectively.
e.g x<=y ,x!=y etc

2.7 Statements and Comments


Statements
A statement is a part of your program that can be executed. A statement causes the computer to carry
out some action. In C, there are three different classes of statements. They are:
i. Expression Statement ii.
Block Statement
iii. Control Statement

i. Expression Statement
An expression statement consists of an expression followed by a semicolon. The execution of an expression
statement causes the expression to be evaluated.

Example:
A = 3;
C = A + B;
++i;
printf ( “ Area = %f ”, area);
;

The first two expression statements are assignment-type statements. Each causes the value of the expression
on the right of the equal sign to be assigned to the variable on the left.

17
Prepared by: Koirala Niraj
Programming in C
The third expression statement is an incrementing-type statement, which causes the value of i to increase
by 1.
The fourth expression statement causes the printf( ) function to be evaluated. This is a standard C library
function that writes information out of the computer.
The last expression statement does nothing, since it consists of only a semicolon. It is simply a
mechanism for providing an empty expression statement in places where this type of statement is
required. Consequently, it is called a null statement.

ii. Block Statement


Block statements are simply groups of related statements that are treated as a unit. The statements
that make up a block are logically bound together. Block statements are also called compound
statement. A block begins with a {and terminated by its matching}. The individual statements may
themselves be expression statements, compound statements, or control statements. Thus, the
compound statement provides a capability for embedding statements within other statements.
Unlike an expression statement, a compound statement does not end with a semicolon.
Example:
{
pi = 3.141593;
Circumference = 2 * pi * radius;
Area = pi * radius * radius;
}
iii. Control Statements
In most of the C programs we have encountered so far, the instructions that were executed in the
same order in which they appeared within the program. Each instruction was executed one and only
once. Program of this type are unrealistically simple, since they do not include any logical control
structures. But in realistic C programs, the program needs logical condition to determine if certain
conditions are true or false, they do require the repeated execution of groups of statements and,
they involve the execution of individual groups of statements on a selective basis. And all these
operations can be carried out using the various control statements included in C.
The different types of control statements are:
a. Branching or Selection Statement
b. Iteration or Looping Statement
c. Jump Statement

Comments
Comments are the text in the program, which won't be compiled or executed. It is good to put comments
because it will be helpful to debug the program in the future, which is made before.
There are two types of comments:
Single line comment: It means we can give comment for a single line. It uses double forward slash (//).
e.g. //This is a test program.
Multi line comment: Multi line comment means programmer can give comment for multiple line.
This type of comment is enclosed with in a /* comment */ e.g. /* this is
18
Prepared by: Koirala Niraj
Programming in C
a simple
program */
Comments can appear anywhere in the program provided that either they are enclosed within a /* */
or folloed by //

Module 3

Console Input/Output Operation

Input and Output Statements


There are numerous library functions available for input-output functions. Depending upon the
input and output devices used, these statements can be categorized into three groups as followings.

a)Console Input / Output Functions: These are functions used to receive input from keyboard and write
output to VDU.
b)Disk Input / Output Functions: When the input-output operations are to be performed on a floppy or
hard disk.
c)Port Input / Output Functions: For performing input-output functions on various ports.

Console Input/Output Functions


These library functions can be categorized as formatted and unformatted I/O functions. The basic
difference between them is that the formatted functions allow the input read from the keyboard or
output displayed on the VDU to be formatted as per our requirements. For example, if values of
average marks and percentage are to be displayed on the screen, then the details like where this
output should appear on the screen, how many spaces would be present between the two values,
the number of places after the decimal point etc. can be controlled using formatted functions.

Console I/O functions can be classified into two categories:


i. Formatted I/O Functions ii.
Unformatted I/O Functions

3.1 Formatted I/O Functions


The functions printf( ) and scanf( ) fall under this category.
3.1.1 Formatted Data Output Function-printf( )

19
Prepared by: Koirala Niraj
Programming in C
The general form of printf( ) looks like this:
printf("Format String", list of variables); The
format string can contains:
Characters that are simply printed as they are
Conversation specification that begins with a % sign
Escape sequences that begin with a \ sign For
example:
main( )
{
int avg=346; float per=69.3;
printf("Average=%d\nPercentage=%f",avg,per);
getch();
}
How does printf() function interpret the contents of the format string? For this it examines the
format string from left to right. So as long as it doesn't come across either a % or a \ it continues to
dump the characters that it encounters, on the screen. In this example, Average= is dumped on the
screen. The moment it comes across a conversion specification in the format string it picks up the
first variable in the list of variables and prints its value in the specified format. In this example, the
moment %d is met the variable avg is picked up and its value is printed. Similarly, the moment an
escape sequence is met it takes the appropriate action. In this example, the moment \n is met it
places the cursor at the beginning of the next line. This process continues till the end of the format
string is reached.

Some conversion specifier used with printf() statements


Conversion specifier Meaning
%d Convert to decimal integer
%f Convert to floating point number
%c Convert to Charcacter
%e or %E Convert to scientific notation/double
%s Convert to string of characters
%u Convert to unsigned decimal integer
%o Convert to octal number
%x or %X Convert to hexadecimal number

3.1.2 Formatted Data Input Function-scanf( )


The general form of scanf() function is as follows:
scanf("Format String", List of addresses of variables); For
example:
scanf("%3d%0.2f%3c",&c,&a,&ch);

20
Prepared by: Koirala Niraj
Programming in C
Note that we are sending addresses of variables(addresses are obtained by using '&' the address of operator)
to scanf() function. This is necessary because the values received from the keyboard must be dropped into
variables corresponding to these addresses. The values that are supplied through the keyboard must be
separated by either blank(s), tab(s), or new line(s).

Some conversion specifier used with scanf() statements


Conversion specifier Meaning
%d Data item is a decimal integer
%f Data item is a floating point value wiyhout exponent
%e Data item is a floating point value with exponent
%c Data item is a single character
%s Data item is a string variable
%[^\n] Data item is a string variable with space support

3.2 Unformatted Input-Output Functions


So far for input we have consistently used the scanf( ) function. However, for some situation, the
scanf( ) function has weakness…you need to hit the enter key before the function can digest what
you have typed. However, we often want a function that will read a single character the instant it
is typed without waiting for the enter key to be hit. getch( ) and getche( ) are two functions which
serve this purpose. These functions return the character that has been most recently typed. The 'e'
in the getche( ) function means it echoes(displays) the character you typed to the screen. As against
this getch( ) just returns the character you typed without echoing it on the screen. getchar( ) works
similarly and echoes the character you typed on the screen, but unfortunately requires enter key to
be typed following the character that you typed. e.g.
main( )
{
char ch;
printf("\n Press any key to continue");
getch( ); /* Will not echo the character */
printf("\n Type any Character:"); ch=getche( );
printf("\n Type any Character:"); getchar( ); /*Will echo
character must be followed by enter key */ printf("\n Continue Y/N:");
getchar( );
}
Output: Press any key to continue
Type any Character:K
Type any Character:W
Continue Y/N:Y

putch( ) and putchar( ) print a single character on the screen. For these functions argument should
be supplied. The following program illustrate this: main( )
{
21
Prepared by: Koirala Niraj
Programming in C
char ch='A';
putch(ch); putchar(ch);
putch('Z');
putchar('Z');
}
Output: AAZZ
The limitation of putch( ) and putchar( ) is that they can output only one character at a time.

gets( ) and puts( ) functions gets( ) receives a string from the keyboard. Why is it needed?
Because scanf( ) function has some limitations while receiving string of characters, as the
following program illustrates: main( )
{
char name[50];
printf("Enter name: ");
scanf("%s",name);
printf("%s",name);
getch( );
}
Output: Enter name:Ram Chandra
Ram
Surprised? Where did "Chandra" go? It never stored in the array name[ ], because the moment the
blank was typed after "Ram" scanf( ) assumed that the name being entered has ended. So, to enter
multi-word string from scanf( ) function extra trouble is required. The solution to this problem is
to use gets( ) function. It gets a string from the keyboard and terminates when an Enter key is hit.
Thus, spaces and tabs are perfectly acceptable as a part of the input string. More exactly, gets( )
gets a newline(\n) terminated string of characters from the keyboard and replaced the \n with a \o.
The puts( ) function works exactly opposite to gets( ) function. It outputs a string to the screen.
e.g. main( ) {
char name[40];
puts("Enter name:");
gets(name);
puts("Have a nice Day");
}
Output: Enter name:
Ram Chandra
Have a nice Day

Why did we use two puts( ) functions to print "Have a nice Day" and "Ram Chandra"? Because,
unlike printf( ), puts( ) can output only one string at a times. If we attempt to print two strings using
puts( ), only the first one gets printed. Similarly gets( ) can be used to read only one string at a time.

Reading string with blank spaces using scanf( ) function Example:


22
Prepared by: Koirala Niraj
Programming in C
main( )
{
char line[80];
……………
scanf("%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]",line);
…………….
getch( );
}
Here, in control string whit space and sequence of uppercase characters are enclosed in a square brackets.
So, it can read the string containing blank spaces and uppercase letters.
If the string like NEW YORK CITY is entered from the keyboard when the program is executed,
the entire string will be assigned in the array 'line' since the string is comprised entirely of uppercase
letters and blank spaces. If the string were written as New York City , then only the single character
N would be assigned to 'line' because the second character 'e' is not included in the square brackets.

A variation of this feature which is often more useful is to precede the characters within the square
brackets by a circumflex(i.e., ^). This causes the subsequent characters within the brackets to be
interpreted in the opposite manner. Thus, when the program is executed, successive characters will
continue to be read from the keyboard as long as each input character does not match one of the
character enclosed within the brackets. e.g. main( ) {
char line[80];
printf("Enter String:");
scanf("%[^\n]",line);
printf("%s",line);
getch( );
}
It will allow the user to enter the string of up to 80 characters until the user press the enter key. Here
enter key will be interpreted as a new line character.

23
Prepared by: Koirala Niraj
Programming in C

Module 4

Operators and Expressions

Operators
Operators are those symbols that perform some specific task. Like, when we add two numbers we
generally use '+' sign. In programming also, to perform some specific task, compiler has assigned
some specific symbols. These symbols are called operators. The data items that operators act upon
are called operands. Some operators require one operand to act upon, whereas some require more
than one. Thus, depending upon the number of operands required by the operators, we can broadly
divide operators into three distinct categories.
1.Unary operators (++, -- ,-,sizeof)
2.Binary operators (Arithmetic, Assignment, Relational, Logical)
3.Tertiary operators (?:)

4.1 Unary operators

24
Prepared by: Koirala Niraj
Programming in C
C includes a class of operators that act upon a single operand to produce a new value. Such operators
are known as unary operators. Unary operators usually precede their single operand, though some
unary operators are written after their operand.
The most common unary operator is unary minus, where a numerical constant, variable, or
expression is preceded by a minus sign. e.g. -743, -a,-root
Hence, this operator requires single operand.
The other commonly used unary operators are: ++ ( increment operator) and -- (decrement
operator). The increment operator causes its operand to be incremented by 1, whereas the
decrement operator causes its operand to be increased by 1. e.g a++, a--, ++a, --a
main()
{
int a=5; printf("Value of
a=%d",a);
a++;
printf("Value of a=%d",a);
a--;
printf("Value of a=%d",a);
getch();
} output
a=5
a=6 (incremented by 1) a=5
(decremented by 1)

The increment and decrement operators can each be utilized in two different ways, depending upon
whether the operator is written before or after the operand. If the operator precedes the operand
(e.g. ++i), then the operand will be altered in value before it is utilized for its intended purpose
within the program. If, however, the operator follows the operand (e.g. i++), then the value of the
operand will be altered after it is utilized. Hence, increment and decrement can be pre or post.

i++ (post increment), ++i(pre increment), i--(post decrement), --i(pre decrement) e.g.
printf("i=%d\n",i);
printf("i=%d\n",++i);
printf("i=%d\n",i);
output
i=1 i=2
i=2
The first statement causes the original value of i to be displayed. The second statement increments i and then
displays its value. The last statement displays the final value of i.
printf("i=%d\n",i);
printf("i=%d\n",i++);
printf("i=%d\n",i);
output
25
Prepared by: Koirala Niraj
Programming in C
i=1 i=1
i=2
The first statement causes the original value of i to be displayed. The second statement causes the
current value of i to be displayed and then incremented to 2. The last statement displays the final
value of i.
Another unary operator is sizeof. It returns the size of operand in Bytes. e.g.
main()
{
int i; float x;
double d;
char c;
printf("integer: %d\n", sizeof i);
printf("float: %d\n", sizeof x);
printf("double: %d\n", sizeof d);
printf("Character: %d\n", sizeof c);
getch();
}
output integer:
4 float: 4
double: 8
character: 1
Typecast operator is also unary operator. It is used to change the data type of a variable.
Syntax: (type) expression e.g. (float) x/2; main()
{ int var1;
float var2;
var2= (float) var1; }

Unary operators have higher precedence. Also, the associativity of the unary operator is right to left.

4.2 Binary operators


Binary operators act upon a two operands to produce a new value. Such, operators can be classified
into different categories. a)Arithmetic operators
Arithmetic operators are the operators used to perform the arithmetic operations like addition, subtraction,
multiplication, division, and modulo operation. Hence five arithmetic operators are:
+ for addition
- for subtraction
* for multiplication
/ for division
% for remainder operation, modulo operator
General structure:
Result = operand1 (Arithmetic operator) operand2

26
Prepared by: Koirala Niraj
Programming in C
Where, arithmetic operator could be any one of the five operators mentioned above. Once the operator
performs a particular operation, result is then assigned to 'result'.
Operands acted upon by arithmetic operators must represent numeric values. Thus, operands may be integer,
float, or character quantities. Character quantities are also allowed as each character is associated with
equivalent integer number ( ASCII value).
Modulus operator requires that both operands be integer and second operator be non zero.
Similarly, division operator requires the second operator be non zero.
Arithmetic operators (except %) can be used in 3 modes:
 Integer mode: where both the operands are integer
 Real mode: where both the operands are real
 Mixed mode: where one operand is integer and second operator is real Result
is always a floating point number for real mode and mixed mode. For integer mode, result is always an integer
number.
All the operators should be explicitly written. No assumption should be made as in normal math
like z=ab is not valid. We must write z=a*b e.g.
main()
{
int a=10,b=3;
int c,d,e,f;
c=a+b; d=a-
b; e=a*b;
f=a%b;
printf("Value of c=%d\n",c);
printf("Value of d=%d\n",d);
printf("Value of e=%d\n",e); printf("Value of
f=%d\n",f);
getch();
}
b)Assignment operators
Assignment operators are used when the value is to be assigned to an identifier, a variable. With
execution of assignment operators, value at the right is assigned to the left. The destination variable
looses the old value, i.e. old value is over ridden with the new value. If previous value is also
required; it should be saved in some other variables.
General structure
Destination (assignment operator) Source The
assignment operators available in C are:
= for assignment
+= add with destination and assign
-= deduct from destination and assign
*= multiply with destination and assign
/= divide the destination and assign
27
Prepared by: Koirala Niraj
Programming in C
%= assign the remainder after dividing the destination

exp1+=exp2 is equivalent to exp1=exp1+exp2


exp1-=exp2 is equivalent to exp1=exp1-exp2
exp1*=exp2 is equivalent to exp1=exp1*exp2
exp1/=exp2 is equivalent to exp1=exp1/exp2
exp1%=exp2 is equivalent to exp1=exp1%exp2

If the two operands in an assignment expression are of different data types, then the value of the
expression on the right will automatically be converted to the type of identifier on the left. e.g.
main()
{
int i=5;
float j=3.14;
i=j; j=i;
printf("value of i=%d\n",i);
printf("value of j=%f\n",j);
getch();
}
output value
of i=3 value
of j=3.0
Under some circumstances, this automatic type conversion can result in an alteration of the data being
assigned. For example:
 A floating point value may be truncated if assigned to an integer identifier
 A double precision value may be rounded if assigned to an floating point
identifier Now suppose that j and k are both integer type variables, and that k has been
assigned a value of 5. Several assignment expressions that make use of these two variables
are shown below.
Expression Value
j=k 5 j=k/2 2 j=2*k/2 5
j=2*(k/2) 4 (truncated division followed by division)
For multiple assignment, identifier1=identifier2=identifier3, assignment operation is carried out form
right to left. So, given expression is equivalent to
Identifier1=(identifier2=identifier3)

Hierarchy of operation
Precedence and associativity comes into role when evaluating complex mathematical expression in
programming. Suppose, we have an expression like:
Z=a+2*b/c*d+23+a*a;

28
Prepared by: Koirala Niraj
Programming in C
Precedence defines which of the operator is to be executed first, like in simple rule of mathematics,
BODMAS, bracket is operated first. However, evaluating expression in programming is not that
simple. Though BODMAS rule is valid, we have to tale in account some other rules also.
Priority Operators
st
I */%
nd rd
2 +- 3 =
In case, there is a tie between operators of same priority preference is given to the one that occurs
first. This is called associativity. Associativity is the preference of the operators (of same
precedence level), when there is tie between them. e.g. suppose we have
z=a+b*c
Then, operation occurs as z=a+(b*c) as * higher precedence than +
But when the case is like
Z=a*b+c/d, operation occurs as
Z=(a*b)+(c/d) i.e. multiplication is done first. Then (c/d) is evaluated. Then only the two values
are added. It happens so because * and / have higher precedence than +. However, as * and / have
same precedence level, * is evaluated first, as the associativity of the arithmetic operators is from
left to right, hence whichever operator occurs first, that is evaluated. c)Relational and Logical
Operators
These operators are very helpful for making decisions. Depending upon the condition, it returns
either 0 or 1. When the condition with these operators is true, 1 is returned. If the condition is false,
it returns 0.
There are four relational operators in C
< less than
> greater than
<= less than or equals to
>= greater than or equals to
The precedence of these operators is below the arithmetic and unary operators. The
associativity of these operators is from left to right.
Equality operators are closely associated with this group
= = equal to
!= not equal to
Precedence level of equality operator is below the relational operators. These operators also have a
left to right associativity.

There are two logical operators


&& logical and
|| logical or
Logical operators act upon operands that are themselves logical expressions.
Individual logical expressions are combined into more complex conditions that are either true or false.
For the logical operators, any non-zero positive value is considered as true.

29
Prepared by: Koirala Niraj
Programming in C

Consider a case where int j=7; float k=5.4; char c='w';

Expression Interpretation Value


(j>=6)&&(c= ='w') true 1
(k<11)&&(j>100) false 0
(j>=6)||(c= = 19) true 1
(c!=p)||(j+k)<10 true 1

d)Comma operator o C uses comma operator(,) as the separator in declaration of the same
types. e.g. int a,b,c o It can also be used while initializing the content of an array. e.g. int
a[3]={1,5,7} o It is also used for separating expressions. e.g. for(i=0,j=1;i<j;i++,j--)

4.3 Ternary operators


Binary operators work on two operands. Unary operators operate on single operand whereas tertiary operator
requires three operands to operate. Conditional operator is a tertiary operator.
Conditional operator
Simple conditional operations can be carried out with the conditional operator ( ? : ). An expression
that makes use of the conditional operator is called a conditional expression. Such an expression
can be written in place of the more traditional if-else statement.
A conditional expression is written in the form
(Test expression) ? true_value: false-value;
Example: In the conditional expression shown below, assume that j is an integer variable
(j<0)?0:100
The expression (j<0) is evaluated first. If it is true (i.e. if the value of j is less than 0), the entire
conditional expression takes on the value 0. Otherwise, the entire conditional expression takes on
the value 100.

4.4 Operator precedence group

Operator category Operators Associativity


Unary operators - ++ -- sizeof (type) R--->L
Arithmetic multiply, divide, and remainder * / % L-->R
Arithmetic Add and Subtract + - L-->R
Relational operators < > <= >= L-->R
Equality operators = = != L-->R
Logical and && L-->R
Logical or || L-->R
Conditional operator ?: R--->L
Assignment operator = += -= *= /= %= R--->L

30
Prepared by: Koirala Niraj
Programming in C

4.5 Type Conversion


Data type of one type can be converted to another type explicitly by using type cast operator. In C
typecasting can be done as:
(new type) variable;
Consider a case as: int
a;
float b;
Then, b=(int) a;
Besides type casting operator, there occurs default promotion or demotion of the value to be
assigned during operations. e.g. #include<stdio.h>
main( )
{
int a;
float b;
a=3.5;
b=30;
}
Here, for a=3.5, 3.5 is demoted to an integer and hence, a is assigned an integer value of 3.
Similarly, 30 is promoted to floating point value of 30.000000 and assigned to b. In tis case type
casting occurs automatically.
Generally, source data is converted to match the data type of destination.

4.6 Library functions and Header Files


The C language is accompanied by a number of library functions that carry out various commonly
used operations or calculations. For example, there are library functions that carry out standard
input output operations (e.g. read and write characters, open and close files, test for end of file etc.),
functions that perform operations on characters (e.g. convert from lowercase to uppercase, test to
see if a character is a uppercase etc.), functions that perform operations on string (e.g copy a string,
compare strings, concatenation of strings etc.), and functions that carry out various mathematical
calculations (e.g. compute absolute values, square root etc.).
A library function is accessed simply by writing the function name, followed by a list of arguments
that represent information being passed to a function. The arguments must be enclosed in
parenthesis and separated by commas. The arguments can be constants, variable names, or more
complex expressions. The parenthesis must be present even if there are no arguments. Example:
31
Prepared by: Koirala Niraj
Programming in C
abs(j) Returns the absolute value of j
cos(d) Returns the cosine of d
rand( ) Returns random positive number
tolower(c) Convert letter to lowercase
toupper(c) Convert letter to uppercase
getchar( ) Enter a character from the standard input device
putchar(c) Send a character to the standard output device
printf(…) Send data items to the standard output device
scanf(…) Enter data item from the standard input device

C place the required library function declarations in special source files, called header files so,
for every library function used, associated header file should be included with preprocessor
directive.
For example, stdio.h is a header file containing declaration for input/output routines; math.h
contains declarations for certain mathematical functions; and so on. The required header file must
be merged with the source program during the compilation process. This is accomplished by
placing one or more # include statements at the beginning of the source program.
#include<stdio.h>
This is called a preprocessor directive. It commands that the contents of the file stdio.h should be included
in the compiled machine code at the place where # include appears.
Note: The # include line must not terminate with a semicolon
- Only one preprocessor directive can appear in one line
Example: Read a lowercase character and display its uppercase equivalent
#include<stdio.h>
#include<conio.h>
#include<stype.h>
void main( )
{
int lower,upper;
lower=getchar( );
upper=toupper(lower);
putchar(upper);
getch( );
}
This program contains three library functions getchar, toupper, and putchar.
Also, notice the preprocessor statement #include<stdio.h> and #include<ctype.h>, which appear at
the start of a program. The statement causes the contents of the files stdio.h and ctype.h to be
inserted into the program when the compilation process begins. The information contained in these
files is essential for the proper functioning of the library functions getchar, putchar, and toupper.

4.7 Storage Classes in C

32
Prepared by: Koirala Niraj
Programming in C
There are mainly two locations, where the data will be stored. These locations are main memory
and registers. Storage class of any variable determines where the value of that variable would be
stored. Beside that, the storage class of any variable provides programmer, other vital information
like:
What will be the initial value of the variable?
Which functions will the value of the variable be available? That is, scope of the variable.
How long will the value of variable be available, i.e. life span of the variable.
So, any variable declaration essentially comprises following pattern:
Storage-class data-type identifier
There are four storage classes in C
a)Automatic storage class
b)Register storage class
c)Static storage class
d)External storage class

a)Automatic storage class


Method of declaring the variable x of type integer with automatic storage class is:
auto int x; OR int x; auto is the default storage class for local variables.
Characteristics of the variables of this storage class:
Storage: Memory
Default initial value: Garbage
Scope: Local to the block in which the variable is declared or defined
Life: Till the control remains within the block where the variable is defined

b)Static Storage class


Method of declaring the variable x of type integer with static storage class is:
static int x;
static is the default storage class for global variables. The two variables below (count and road) both
have a static storage class.
static int count; int road;
main( )
{
printf("%d\n",count);
printf("%d\n",road);
}
Characteristics of the variables of this storage class:
Storage: Memory
Default initial value: Zero

33
Prepared by: Koirala Niraj
Programming in C
Scope: Local to the block in which the variable is declared or defined Life:
Value is maintained between different function calls.

As the value is maintained between different function calls, usually used as a counter variable that has
to be accessed by different function call.
Given below are two identical programs. All the syntaxes are same, except the storage class of the
variable j.
Program A Program B
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void increment( ) void increment( )
{ {
auto int j=1; static int j=1;
printf("%d",j); printf("%d",j);
j++; j++;
} }
main( ) main( )
{ {
increment(); increment(); increment();
increment();
increment(); increment();
} }
For Program A: Output: 1 1 1(Since life of automatic variable is destroyed when the control exit from
the block)
For Program B :Output: 1 2 3 (Since value is maintained between each function calls)
C) External Storage Class
extern defines a global variable that is visible to all object modules. Method of declaring the variable x of
type integer with external storage class is:
extern int x;
Characteristics of the variables of this storage class:
Storage: Memory
Default initial value: Garbage
Scope: Global
Life: As long as the program execution remains
These variables are declared outside all functions.

D) Register Storage Class


Method of declaring the variable x of type integer with register storage class is: register
int x;
Characteristics of the variables of this storage class:
Storage: CPU Register
34
Prepared by: Koirala Niraj
Programming in C
Default initial value: Garbage
Scope: Local to the block in which the variable is declared or defined
Life: Till the control remains within that block

The values of variables are stored in CPU registers. They are accessed much faster. Generally,
frequently used variables are declared with register storage class. However, if many variables are
declared as of type register, they may not be register type due to limited number of CPU registers

Module 5

Control Statements

Control Statements
In most of the C programs we have encountered so far, the instructions that were executed in the
same order in which they appeared within the program. Each instruction was executed one and only
once. Program of this type are unrealistically simple, since they do not include any logical control
structures. But in realistic C programs, the program needs logical condition to determine if certain
conditions are true or false, they do require the repeated execution of groups of statements and,
35
Prepared by: Koirala Niraj
Programming in C
they involve the execution of individual groups of statements on a selective basis. And all these
operations can be carried out using the various control statements included in C.

The different types of control statements are:


1. Branching or Selection Statement
2. Iteration or Looping Statement
3. Jump Statement

5.1 Branching or Selection Statement


In realistic C program, it may require a logical test to be carried out at some particular point within
the program. Then depending on the outcome of the logical test, several possible actions will then
be carried out, this is known as branching.

There is a special kind of branching, called selection in which one group of statements is selected from
several available groups. C supports two types of selection statements:
i. If Statement
ii. Switch Statement

i. The if Statement
"if statement" is very useful and easy to use for decision making. It allows a particular statement or
more than one statements (Block statement) to be executed only when certain condition is fulfilled.
The general form of if statement is

If (expression)
Statement;
else Statement;

Where, a statement may consist of a single statement, a block of statements, or nothing (in case of
empty statements). The else clause is optional.

In the above general form if the expression is TRUE then the statement below if is executed and
control jumps to the next statements following the if statement. Thus, the statement following the
else is ignored.

If the expression is FALSE then the statement below if is ignored and the statement following the else
is executed.

Ex1: Simple if statement


if (logical expression)
{
S1;
36
Prepared by: Koirala Niraj
Programming in C
S2;
.
.
Sn;
}

Ex2: if else statement


If (logical expression)
{
S1;
S2;
.
.
Sn;
}
else
{
S1;
S2;
.
.
Sm;
}

Ex3: Nested if else statement


If (logical expression)
{
if (logical expression)
statement;
else
statement;
}
else
statement;

Example 4: Picking largest of three numbers


#include<stdio.h>
main()
{
int a, b, c;

37
Prepared by: Koirala Niraj
Programming in C
printf(“ Enter the value of a, b, and c “);
scanf(“ %d %d %d ”, &a, &b, &c);
printf(“ a = %4d, b = %4d, c = %4d “, a, b, c);
if (a>b)
{
if (a>c)
printf(“ a = %4d \n”, a);
else
printf(“ c = %4d \n”, c);
}
else
{
if (b>c)
printf(“ b = %4d \n“, b);
else
printf(“ c = %4d \n”, c);
}
getch();
}
/* Alternative method to pick the largest of three numbers */
#include<stdio.h>
main()
{
int a, b, c, big; printf(“ enter the value of a, b,
and c”);
scanf(“ %d %d %d “, &a, &b, &c);
big = a; if (b>big)
big = b; if (c>big) big = c;
printf(“ \n the largest number is %4d “, big);
getch();
}
//Largest of four numbers using nested if-else

#include<stdio.h> #include<conio.h>
main()
{
int a,b,c,d; printf("Enter four
numbers:");
scanf("%d%d%d%d",&a,&b,&c,&d);
if(a>b)
{
38
Prepared by: Koirala Niraj
Programming in C
if(a>c)
{
if(a>d)
printf("Maximum is %d", a);
else
printf("MAximum is %d",d);
}
else
{
if(c>d)
printf("Maximum is %d",c);
else
printf(“Maximum is %d”,d);
}
}
else
{
if(b>c)
{
if(b>d)
printf("Maximum is %d",b);
else printf("Maximum is
%d",d);
}
else
if(c>d)
printf("Maximum is %d",c);
else printf("Maximum is
%d",d);
}
getch();
}
//Largest of four numbers using if-else and && operator
#include<stdio.h>
#include<conio.h> main()
{ int
a,b,c,d;
scanf("%d%d%d%d",&a,&b,&c,&d);
if(a>b && a>c && a>d)
printf("maximum is%d",a);

39
Prepared by: Koirala Niraj
Programming in C
else if(b>a && b>c && b>d)
printf("maximum is %d",b); else
if(c>a && c>b && c>d)
printf("Maximum is %d",c);
else
printf("Maximum is %d",d);
getch();
}

Example 5: Program to calculate the number of days in the months.

“ 30 days has September, April, June, and November”


“ All the rest have 31 days except February alone”
“ February have 29 days in Leap year and 28 in other years”

The program will ask the user to enter month and year and the rest of the calculations are performed using
if-else condition.

#include<stdio.h>

main()
{
int month, years, days;
clrscr();
printf(“ Enter the month: “);
scanf(“ %d “, &month); printf(“
\n Enter the years: “);
scanf(“ %d “, &years);
clrscr(); if (month == 2)
{ if ( years%4 == 0)
days = 29;
else
days = 28;
}
if ( month != 2)
{
if ((month == 4) || (month == 6) || (month == 9) || (month == 11))
days = 30;
else
days = 31;
}
printf(“ number of days in the year %d and month %d is : %d”, year, month, days); getch();
40
Prepared by: Koirala Niraj
Programming in C
}
The ? Alternative
You can use the ? operator to replace if-else statements of the general form:

If (condition)
Statement;
else
Statement;

However, the target of both if ans else must be a single statement not group of statement.

The ? operator is also called ternary operator because it requires three operands. It takes the general form:

Exp1 ? Exp2 : Exp3


Where, Exp1, Exp2, Exp3 are expressions.
Here, the Exp1 is evaluated. If it is TRUE, Exp2 is evaluated and become the value of the entire ?
expression. If Exp1 is FALSE, then Exp3 is evaluated and its value becomes the value of the
expression. For example,
Consider,
X = 10;
Y = X>9 ? 100 : 200;
o/p: Y = 100
Same code written with the if-else statement would be
X = 10; if
(X>9)
Y = 100;
else
Y = 200;
Example 6: Find the square of the given number
#include<stdio.h>
main( )
{
int sqrd, n; printf(“
enter a number: “); scanf(“ %d
“, &n); sqrd = n>0 ? n*n : - (n*n);
printf(“ %d squared is %d “, n, sqrd);
}
ii. The switch Statement
C has a built - in multiple - bench selection statement called switch . It is useful when on out of set
alternative action is to be taken based on the value of an expression . It is particularly useful when
variable values are classified with codes . The switch statement cause to be chosen from several
41
Prepared by: Koirala Niraj
Programming in C
available groups . The selection is based upon the current value of an expression that is included
within the switch statement . The switch statement evaluates an expression & then transfer control
to the following statement whose expression equals the evaluated expression . The general form of
switch statement is given bellow :
switch(expression)
{ case
constant_1:
statement1;
statement2;

break; case constant_2:


statement1;

break; case constant_3:


statement1;
break;
default:
statement;
}

Example:Program displaying day using the switch statement depending upon the number
entered. #include <stdio.h>
#include <conio.h> main()
{
int choice;
printf(“Enter the number of day:”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:
printf("The day you've chosen is Sunday");
case break;
2:
printf("The day you've chosen is Monday");
case break;
3:
printf("The day you've chosen is Tuesday");
break;
case 4:
printf("The day you've chosen is Wednesday");
break;

42
Prepared by: Koirala Niraj
Programming in C
case 5:
printf("The day you've chosen is Thursday");
break;

case 6:
printf("The day you've chosen is Friday");
break;

case 7:
printf("The day you've chosen is Saturday");
break;
default:
printf("Invalid option given");
break;
}
getch();
}

5.2 Iteration or Looping Statement


In C, the program may require that a group of statements be executed repeatedly, until some logical
condition has been satisfied this is known as looping or iteration. Some times the required number
of repetition is known in advance; and sometimes the computation indefinitely until the logical
condition becomes true.
There are three methods for generating repetition of a certain part of the program a)
for loop
b) while loop
c) do…while loop

a) for loop
The for loop is the most commonly used statement in C++. This loop consists of three expression.
The first expression issued to initialize the index value, the second to check whether the loop is to
be continued again and third to change the index value for further repetition. for( count = 0 ; count
< 5 ; count++ )
Example
A program to display the numbers from 0 to 10 using for loop
#include <stdio.h>
#include<conio.h>
main()
{
int i=0;
for(i=0;i<=10;i++)

43
Prepared by: Koirala Niraj
Programming in C
printf(“%d”,i);
getch();
}
Example
A program to find the sum and the average of given numbers.
#include<stdio.h>
#include<conio.h>
main()
{
int n,i;
float sum=0.0,a,average;
printf("How many numbers you want?");
scanf(“%d”,&n);
for(i=0;i<=n-1;i++)
{
printf("Enter a number:");
scanf(“%d”,&a);
sum+=a;
}
average=sum/n;
printf("Sum=%d",sum);
printf("\nAverage= %d",average);
getch();
}
Example
A program to create the multiplication table
#include <stdio.h>
#include <conio.h>
main()
{
int a,b,c,count=0;
for(a=1;a<=5;a++)
{
printf("\nMultiplication table no. of %d\n",a);
for(b=1;b<=10;b++)
{
c=a*b;
printf("%d*%d=%d\n",a,b,c);
count++;
if(count==20)
{

44
Prepared by: Koirala Niraj
Programming in C
getch();
printf("Press any key to continue:");
count=0;
}

}
}
}

Example
A program to generate number in pyramid format
#include<stdio.h>
#include<conio.h> main()
{
int p,q,a,k,l; printf("\nEnter the value
for pyramid:"); scanf(“%d”,&a);
for(p=1;p<=a;p++) /*for a row implement*/
{
for(q=a;q>p;q--) /*for the space(s)*/
printf(” “);
for(k=1;k<=p;k++) /*for previously printed number*/
printf(“%d”,k);
for(l=p-1;l>=1;l--) /*for printing new nos.*/
printf(“%d”,l); printf("\n");
} getch();
}

b. while loop statement


The second type of loop statement is while loop. While loop first checks whether the initial condition is true
r false and finding it to be true, it will enter the loop and execute the statement
For single statement
while(condition)
statement;

For compound statement


while(condition)
{
statement1;
statement2;
}

45
Prepared by: Koirala Niraj
Programming in C
The while loop doesn’t have initialization and increment part like for loop has

Example
Program to print numbers from 1 to 10
#include<stdio.h>
#include<conio.h> main()
{
int number=1;
while(number<=10)
{
printf(“%d”,number);
number++;
}
getch();
}
Example
A Program to check prime number
#include <stdio.h>
#include <conio.h> main()
{
int num,i;
printf("Enter the number:");
scanf(“%d”,&num);
i=2;
while(i<=num-1)
{
if (num%i==0)
{
printf("Not a prime number");
break;
}
i++;
}
if(i==num)
printf("Prime number");
getch();
}

Example
A Program to find factorial of a given number

46
Prepared by: Koirala Niraj
Programming in C

#include<stdio.h>
#include<conio.h> main()
{
int a=1,n;
long float fact=1; printf(“Enter
the value for n:");
scanf(“%d”,&n);
while(a<n)
{ a++;
fact*=a;
}
printf(“Factorial of given no. is: %ld",fact); getch();
}

c. do..while loop
do...while loop is another repetitive loop used in C and C++ programs. In case of do..while loop,
as it enters loop at least once and then checks whether the give condition is true or false. As long
as the test condition is true, statements will be repeated again and again, otherwise loop will
terminate.
The general syntax of do..while loop is

do
{
statement1;
statement2;
}while(condition);

Example
A program to find the sum of odd numbers using do..while loop
#include <stdio.h>
#include<conio.h> main()
{
int n,sum=0,i=1;
printf("Enter the value of n:");
scanf(“%d”,&n);
do {
sum+=i;
i+=2;
}while(i<=n);
printf("The sum of odd number is %d”,sum);
getch();
47
Prepared by: Koirala Niraj
Programming in C
}

Example
A program to accepts a character and returns its ascii value
#include <stdio.h>
#include <conio.h> main()
{
char somechar,answer;
int asc_value;
do
{
printf("Enter any character:"); scanf(“%c”, &somechar;);
asc_value=somechar; /*assigning a character to an integer stores its ASCII value*/
printf(“\nThe ASCII value of alphabet:",asc_value); printf("\nDo you want to input
another character?"); scanf(“%c”,&answer);
}while(answer=='y' || answer=='Y');
getch( );
}

5.3 Jump Statement


C has four statements that perform an unconditional branch. They are:
i. Break Statement ii.
Continue Statement iii.
Goto Statement
iv. Return Statement

i. The break Statement


In C programming, we often come across situations where we want to jump out of a loop instantly,
without going back to the conditional test. In such situation keyword break allows us to do this.
When the keyword break is encountered inside any C loop, control automatically passes to the first
statement after the loop. In other words, the break statement is used to terminate loops or to exit
from a switch. It can be used within a for, while, do-while, or switch statement. The break statement
is written simply as:
break;
Without any embedded expressions or statements.

Example: Program to determine whether a number is prime or not. A


prime number is one which is divisible only by 1 and itself.

48
Prepared by: Koirala Niraj
Programming in C
To find prime number we have to divide a given number by all numbers from 2 to one less that itself. If
remainder of any of these divisions is zero, the number is not prime.

#include<stdio.h> #include<conio.h>
void main()
{
int num, i; printf(“ Enter
a number: “); scanf(“%d”,
&num);

for(i=2;i<=num-1;i++)
{
if(num% i == 0)
{
printf(“ \n Not a prime number”);
break;
}
}
if (num == i) printf(“\n
prime number”); getch();
}

In this program the moment num%i turns out to be zero, (i.e num is exactly divisible by i) the
message “Not a prime number” is printed and the control breaks out of for loop. Why does the
program require if statement after the while loop at all? In this case, there are two ways the control
could have reached outside for loop:
It jumped out because the number proved to be not a prime.
The loop came to an end because the value of I become equal to num.
In second case it means that there was no number between 2 and num-1 that could exactly divide
num. that is, num is indeed a prime. If this is true the program should printout message “prime
number”.

The keyword break breaks the control only from the loop in which it is places. Consider the
following program: #include<stdio.h>
void main()
{
int i=1, j=1;

while(i++<=100)
{
while(j++<=200)

49
Prepared by: Koirala Niraj
Programming in C
{
if (j == 150)
break;
else
printf(“%d %d \n”, i, j);
}
}
getch();
}

In this program when j equals to 150, break takes the control outside the inner while only, since it is
places inside the inner while.

ii. The continue Statement


In C programming, sometimes we want to take the control to the beginning of the loop, by passing
the statement inside the loop which has not yet been executed. The keyword continue allows us to
do this. When the keyword continue is encountered inside any C loop, control automatically passes
to the beginning of the loop.

The continue statement can be included within a while, do-while or a for statement. It is written simply
as:
continue;
Without any embedded statements or expression.

Example: Calculate the average of the nonnegative numbers in a list of numbers

#include<stdio.h> #include<conio.h>
void main()
{
int n,i,count=0; float
x, average, sum=0;

/* Initialize and read in a value for n */


printf(“ How many numbers?”);
scanf(“%d”, &n);

/* Read in the values of x */


for(i=1;i<=n;i++)
{
printf(“X = “);
scanf(“ %f “, &x);
50
Prepared by: Koirala Niraj
Programming in C
if(x<0)
continue; sum
+= x;
++count;
}
/* calculate the average and write out the answer */
average = sum/count; printf(“\n the average is %f
\n”, average); getch();
}

output:
how many numbers? 6
X=1
X = -1
X=2
X = -2
X=3
X = -3
Note that the average would have been zero if all of the numbers had been averaged.
But in this case only the positive numbers are summed and count is incremented so, the output is 2.000000.

iii. The goto Statement


In a difficult programming situation it seems so easy to use a goto to take the control where you
want to. However, almost always, there is a more elegant way of writing the same program using
if, for, while, and switch. These constructs are far more logical and easy to understand. So avoid
using goto statements! They make a C programs life miserable.

A goto statement can cause program control to end up almost anywhere in the program, for reasons
that are often hard to unravel. With good programming skills, goto can always be avoided.

The general form of goto statement is


goto label;
.
.
label:

where label is any valid label either before or after goto.

Example: Check whether a person can vote or not


#include<stdio.h>
#include<conio.h>
51
Prepared by: Koirala Niraj
Programming in C
Void main()
{ int age;
printf(“Enter age: “);
scanf(“ %d ”, &age);
if (age<18) goto
input; else {
printf(“\n you can vote “);
exit(0);
}
input: printf(“ \n You cannot vote “);
getch();
}

iv. The return Statement


The return statement is used to return from a function. It is categorized as a jump statement became
it cause execution to return (jump back) to the point at which the call to the function was made. A
return may or may not have a value associated with it. If return has a value associated with it, that
value becomes the return value of the function.

In C, a non-void function does not technically have to return a value. If no return value is specified,
a garbage value is returned. In C, if a function is declared as returning a value, it is good practice
to actually return one. The general form of the return statement is

return expression;

The expression is present only if the function is declared as retuning a value. In this case, the value of
expression will become the return value of the function.

A function expression declared as void may not contain a return statement that specifies a value.
Since a void function statement has no return value, it makes sense that no return statement within
a void function can return a value.

Some Looping Examples

// Program to Compute the Sine Series Sin(X)=x-x3/3!+x5/5!-x7/7!+.....xn/n!


#include<stdio.h>
#include<conio.h> #include<math.h>
main()
{ int n; float t,x,sum; printf("enter
the value of x and n:");

52
Prepared by: Koirala Niraj
Programming in C
scanf("%f%d",&x,&n); x=x*3.1412/180;
//Convert degree to radian t=x; sum=x; fflush(stdin);
for(int i=1;i<=n;i++)
{
t=-t*x*x/(2*i*(2*i+1));
sum=sum+t;
}
printf("%f",sum); getch();
}
// Program to check whether the String is Palindrome or not #include<stdio.h>
#include<conio.h> #include<string.h>
main()
{
char name[50];
int i,l,flag=1; puts("Enter
String:"); gets(name);
l=strlen(name);
for(i=0;i<(l/2);i++)
{
if(name[i]!=name[l-1-i])
{
flag=0;
break;
}
}
if(flag==1) printf("The String
is Palindrome");
else
printf("The String is not a palindrome"); getch();
}

53
Prepared by: Koirala Niraj
Programming in C

Module 6

ARRAYS

6.1 Introduction and Declaration of Array

What is array?
An array is a collection of identical data objects, which are stored in the consecutive memory
locations under a common heading or a variable name. In other word, array is a group or a table of
value referred to by the same variable name. The individual values in an array are called elements.

Arrays are set of values of the same type, which have single name followed by an index. In C &
C++, square brackets around the right after the name, with the first element referred to by the
number. Whenever a variable name with an index appears in an expression, C & C++ compiler
assumes that element to be an array type.

Array declaration
Declaring the name and type of an array and setting the number of element in an array is known as
dimensioning the array. It must be declared before one uses it in a C program like other variables.
In the array declaration, one must define the type of array, Name of the array and the total number
of memory locations to be allowed.

In general, one-dimensional array may be expressed as For


example:
int marks [300];

54
Prepared by: Koirala Niraj
Programming in C
6.2 One dimensional and Multidimensional Array

One Dimensional Array


The automatic arrays cannot be initialized, unlike automatic variables. However, external and static
arrays can be initialized if it is desired. The initial values must appear in the same order in which
they will be assigned to the individual array elements, enclosed in braces and separated by commas.
The general format of the array initialization is,
datatype array_name [expression] = {element1, element2… element n}
For example int values[3]={10,11,12} char sex [2] = {‘m’,’f ‘}
float co_ordinates [4] = {0, 0.45,-0.50,-4.0} The
results of each of the value of array element are;
values [0] =10 values [1] =11 values [2] =12 sex [0]
= ‘m’
sex [1] = ‘f ‘

co_ordinates [0] = 0
co_ordinates [1] =0.45
co_ordinates [2] = -0.50
co_ordinates [3] = -4.0

Note that in C & C++, the first element is always placed in 0th place; it means that array
Starts from 0 to n-1. Where n is the maximum size of the array declared by the
programmer.

Example
A program to initialize a set of numbers the array and to display it in standard output.

11 12 13 14 15 16
main()
int a [7] = {11,12,13,14,15,16,17};
int i; printf(“contents
of the array \n”);
for(i =0; i<=6; ++i)
printf(“%d\t”,a[i]); getch( );
}
Example
A program to read n number from the keyboard (where n is defined by the user to store it in onedimensional
array and to display the contents of the array.

#include<stdio.h> #include<conio.h>
main ( )

55
Prepared by: Koirala Niraj
Programming in C
{
int a [100];
int i,n;
printf(“How many numbers are in the array?”);
scanf(%d”,&n);
for (i = 0; i<=n-1; ++ i)
{
printf(”array[%d]=”,i);
scanf(“%d”,&a[i]);
}
printf(“\n content of array”); for (i=0;
i<=n-1; ++i)
{
printf(“%d\t”,a[i]);
}
getch();
}

Finding Maximum and Minimum of an Array

Example
A program to read numbers from the keyboard and find out largest and smallest numbers in the given
array.

#include<stdio.h> #include<conio.h>
main( )
{
int a[10];
int i,n,largest, smallest; printf("Number of element to be
added in array?)";
scanf(“%d”,&n);
for (i=0 ; i<=n-1; i++)
{
printf("Enter the elements of array [%d]",i);
scanf(“%d”,&a[i]);
}

56
Prepared by: Koirala Niraj
Programming in C
printf("\n Contents of the array\n");
for (i=0 ; i<=n-1 ; i++)
{
printf(”%d\t",a[i]);
}
printf("\n");
largest=a[0]; smallest =
a[0];
for (i=0; i<=n-1 ; ++i)
{
if(largest<a[i] )
largest=a[i];
if(smallest>a[i] )
smallest =a[i];
}
if(largest!=smallest)
{
printf("\n largest value in the array is %d",largest);
printf("\n smallest value in the array is %d”,smallest);
}
else
printf("\n sorry, values can’t be displayed");
}

Sorting
Arranging data either in increasing or decreasing order is called sorting. Here we will discuss about two
types of sorting techniques:
i. Bubble sort ii.
Selection sort

Bubble Sort
The basic idea of bubble sort is to compare two neighboring objects, and to swap them if they are in
the wrong order.
Bubble sort focuses on successive adjacent pairs of elements in the array, compares them, and either
swaps them or not. In either case, after such a step, the larger of the two elements will be in the
higher index position. The focus then moves to the next higher position, and the process is repeated.
When the focus reaches the end of the effective array, the largest element will have ``bubbled'' from
whatever its original position to the highest index position in the effective array. For example,
consider the array:

57
Prepared by: Koirala Niraj
Programming in C
In the first step, the focus is on the first two elements which are compared and swapped, if
necessary. In this case, since the element at index 1 is larger than the one at index 0, no swap takes
place.

Then the focus move to the elements at index 1 and 2 which are compared and swapped, if
necessary. In our example, 67 is larger than 12 so the two elements are swapped. The result is that
the largest of the first three elements is now at index 2.

The process is repeated until the focus moves to the end of the array, at which point the largest of all
the elements ends up at the highest possible index. The remaining steps and result are:

Thus, in first pass the largest element has bubbled to the top index of the array.The process is repeated again
and again to sort an entire array.
Given an array a of numbers, with length n, here's a snippet of C code for bubble sort (Descending Sort):
for (i=0; i<n-1; i++)
{ for (j=0; j<n-1-i; j++) if (a[j+1] < a[j]) /*
compare the two neighbors */ {tmp = a[j]; /*
swap a[j] and a[j+1] */ a[j] = a[j+1];
a[j+1] = tmp;
}
}
As we can see, the algorithm consists of two nested loops. The index j in the inner loop travels up
the array, comparing adjacent entries in the array (at j and j+1), while the outer loop causes the
inner loop to make repeated passes through the array. After the first pass, the largest element is
guaranteed to be at the end of the array, after the second pass, the second largest element is in
position, and so on. That is why the upper bound in the inner loop (n-1-i) decreases with each
pass: we don't have to re-visit the end of the array.
In bubble sort if there are n elements to be sorted it will take n-1 pass to sort entire elements.

Selection Sort
The idea of selection sort is rather simple: we repeatedly find the next largest (or smallest) element
in the array and move it to its final position in the sorted array. Assume that we wish to sort the
array in increasing order, i.e. the smallest element at the beginning of the array and the largest
element at the end. We begin by selecting the largest element and moving it to the highest index
position. We can do this by swapping the element at the highest index and the largest element. We
then reduce the effective size of the array by one element and repeat the process on the smaller

58
Prepared by: Koirala Niraj
Programming in C
(sub)array. The process stops when the effective size of the array becomes 1 (an array of 1 element
is already sorted).
For example, consider the following array, shown with array elements in sequence separated by commas:

The leftmost element is at index zero, and the rightmost element is at the highest array index, in
our case, 4 (the effective size of our array is 5). The largest element in this effective array (index
0-4) is at index 2. We have shown the largest element and the one at the highest index in bold. We
then swap the element at index 2 with that at index 4. The result is:

We reduce the effective size of the array to 4, making the highest index in the effective array now
3. The largest element in this effective array (index 0-3) is at index 1, so we swap elements at index
1 and 3 (in bold):

The next two steps give us:

The last effective array has only one element and needs no sorting. The entire array is now sorted.
Given an array a of numbers, with length n, here's a snippet of C code for selection sort: for
(i=0; i<n-1; i++)
{ for (j=i+1; j<n; j++)
if (a[i] < a[j])
{tmp = a[i];
a[i] = a[j]; a[j] =
tmp;
}
}

Multidimensional Array
Multidimensional arrays are similar to single dimensional array expect two separate pair of square
brackets is required. Similarly three dimensional arrays require three pair of square brackets and so
on.
In general two dimensional arrays may be expressed as:
data type array name [expression 1] [expression 2];
For example
int x[2][2]={1,2,3,4}

59
Prepared by: Koirala Niraj
Programming in C
Where x is the two dimensional array of integer numbers whose maximum size is 4 and the assignments
would be
x [0] [0] =1 x
[0] [1] =2 x
[1] [0] =3 x
[1] [1] =4
float sum[3] [2] = {0.1,0.2,0.3,0.4,0.5,0.6}
Where value is a two dimensional array of integer numbers whose maximum size is 6 and the
assignment would be sum [0] [0] = 0.1 sum [1] [0] =0.3 sum [2] [0] =0.5 sum [0] [1] =0.2 sum
[1] [1] =0.4 sum [2] [1] = 0.6

eg. int values[3][2]={{10,21},{3,45},{52,-6}}

10 21
3 45
52 -6
Example
A program to initialized a set of numbers in two dimensional array a and to display the content of
the array on screen. #include<stdio.h> #include <conio.h> main ( )
{
int i,j;
float a [3] [4] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
};

printf(“values in the array\n”);


for (i=0;i<3:i++)
{
for (j=0;j<4;j++)
printf("%d\t”,a[i][j]);
}
}

//Program for Matrix Addition


#include<stdio.h> #include<conio.h>
main()
{

60
Prepared by: Koirala Niraj
Programming in C
int a[5][5],b[5][5],c[5][5],row,col,i,j;
printf("Enter the no of rows and columns:");
scanf("%d%d",&row,&col); //Read A Matrix
printf("Enter the elements of Matrix A:\n");
for(i=0;i<row;i++)
{for(j=0;j<col;j++)
{ printf("a[%d][%d]",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\nMatrix A :\n");
//Print A Matrix
for(i=0;i<row;i++)
{for(j=0;j<col;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
//Read B Matrix printf("Enter the elements
of matrix B:\n");
for(i=0;i<row;i++)
for(j=0;j<col;j++)
{printf("b[%d][%d]",i,j);
scanf("%d",&b[i][j]);
}
printf("\n");
//Print B Matrix
for(i=0;i<row;i++)
{for(j=0;j<col;j++)
printf("%d\t",b[i][j]);
printf("\n");
}
//Addition
for(i=0;i<row;i++)
for(j=0;j<col;j++)
c[i][j]=a[i][j]+b[i][j];
//Display the Result of Addition
printf("The Result of Addition is:\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{printf("%d\t",c[i][j]);}
61
Prepared by: Koirala Niraj
Programming in C
printf("\n");
}
getch();
}

6.3 Character Array and String Manipulation (String Declaration)


The string that will hold an array of character which is declared in the format
Storage class character data type array _name [size]; e.g. char name[10];
So here, the declaration char name [10] declares the name as the character array (string) variable that
can hold a maximum of character. Suppose user want to store constant string “program” into char
array name.
Here each element is treated as an element of the array name and stored in the memory as follows

0 1 2 3 4 5 6 7 8 9
P R O G R A M \0
null character

When the compiler encounters a constant string, it terminates with an additional null character. So
while declaring character arrays, we must always reserve one extra element space for the
terminator.

Initializing a string
A string cannot be initialized like other variables. The following way of declaring a string is not possible.
char name [16]; name [16]=
“programming”;
The general rule is that each element of an array_each character of a string is a separate variable.
There we should initialize each character in a string should be initialized individually, as we always
do while initializing an array.
Same string can be initialized as follows
name[0]= “p”
name[1]= “r”
name[2]= 'o’
name[3]= 'g'
name[4] = 'r'
name[5]= 'a'
name[6]= 'm'
name[7]= 'm'
name[8]= 'e'
Similarly same string can be initialized in other array char
name []={‘p’ ,‘r’,’o’,’g’,’r’,’a’,’m’,’m’,’e’};

String functions
62
Prepared by: Koirala Niraj
Programming in C

String Concatenation:
The function strcat(string1, string2); concatenates the character string 1 and string2 to the end of the
string1, placing a null character at the end of the final string. Finally function returns string1.

Example
Program to concatenate two strings.
#include<stdio.h> #include<string.h>
main ( )
{
char string1[ ]=”spot”; char
string2 [ ]= “light”; strcat
(string1, string2);
printf("%s",string1);
getch( );
}

String Compare:
strcmp(string1,string2) compares two strings and return 1 if they are different and 0 if they are similar.

Example
Program to compare two strings.
#include<stdio.h> #include<string.h>
main( )
{
char string1[10],string2[10];
int a;
printf(“enter a word:”);
scanf("%s",string1);
printf(“Enter another word for comparision”);
scanf("%s",string2);
a=strcmp (string1,string2);
if (a= =0) printf(“They are similar words \n”);
else
printf(“They are not similar words \n”); getch( );
}

String Copy
The function strcpy(string1, string2); copy the character string2 to string1 and finally function returns
string1.
63
Prepared by: Koirala Niraj
Programming in C

Example:
Program to copy a string to another string.
#include<stdio.h> #include<conio.h>
main ( )
{
char string1[15], string2[10];
printf("Enter the first word \n”);
scanf("%s",string1); printf("Enter the
word to be copied”);
scanf("%s",string2);
strcpy(string1,string2);
printf("%s",string1);
}

String Length:
Strlen(string) returns the number of character in string, excluding the null characters.

Example:

Program to compare the length of two string.


#include<stdio.h> #include
<conio.h>
main( )
{
int n1,n2; char str[15], str[15];
printf(“Enter two words”);
scanf("%s %s",str,str1);
n1=strlen(str); n2=strlen(str1); if (n1= =n2)
printf("they are of equal size \n”); else
printf(”they are not equal \n”);
}

String Lower and Upper


Strlwr(string) converts entire string to lowercase and strupr(string) converts wntire string to uppercase.

Example:

Program to convert a string from lowercase to uppercase and from uppercase to lowercase.
#include<stdio.h> #include<conio.h>

64
Prepared by: Koirala Niraj
Programming in C
main ( )
{
char string1[15], string2[10];
printf("Enter the string inuppercase \n”);
scanf("%s",string1); printf("Enter the string in
lowercase”); scanf("%s",string2); strlwr(string1);
printf("%s",string1); strupr(string2);
printf("%s",string2);
}

Example: Sorting string in descending order using selection sort

#include<stdio.h>
#include<conio.h>
#include<string.h> main()
{
int i,j;
char name[20][10],temp[10];
for(i=0;i<10;i++)
{
printf("enter name:\n");
scanf("%s",name[i]);
}
for(i=0;i<10;i++)
{
//printf("enter name:\n");
printf("%s\t",name[i]);
}

for(i=0;i<9;i++)
{
for(j=i+1;j<10;j++)
{
if(strcmp(name[i],name[j])<0) //strcmp returns >0 if s1 is greater than s2
{ // returns <0 if s1 is less than s2
strcpy(temp,name[i]); // returns 0 if they are equal
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}

65
Prepared by: Koirala Niraj
Programming in C
}
printf("\n Sorted names:\n");
for(i=0;i<10;i++)
printf("%s\t",name[i]); getch();
}

Some EXAMPLES

bubble sort ascending


#include<stdio.h>
#include<conio.h> main()
{ int
a[10]; int
i,j;
int n,temp; printf("how
many nos:");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n\n Content\n"); for(i=0;i<n;i++)
printf("%d\t",a[i]);

for (i=0; i<n-1; i++)


{
for (j=0;j<n-1-i;j++) if (a[j] > a[j+1]) /* compare
the two neighbors */ {temp = a[j]; /* swap
a[j] and a[j+1] */ a[j] = a[j+1];
a[j+1] = temp;
}
}
printf("\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}
66
Prepared by: Koirala Niraj
Programming in C

selection sort ascending


#include<stdio.h>
#include<conio.h> main()
{ int
a[10]; int
i,j;
int n,temp; printf("how
many nos:");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n\n Content\n"); for(i=0;i<n;i++)
printf("%d\t",a[i]);

for (i=0; i<n-1; i++)


{
for (j=i+1; j<n; j++)
if (a[i] > a[j])
{temp = a[i]; a[i]
= a[j];
a[j] = temp;
}
}
printf("\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

NOTE: To sort in descending order use < sign instead of > sign in if expression

67
Prepared by: Koirala Niraj
Programming in C

Module 7

Functions

7.1 Introduction and Advantages

What is a function?
A function is a single comprehensive unit containing blocks of statements that performs a specific
task. The specific task is repeated each time function is called. So this avoid the need of rewriting
the same code again and again. Every program must contain one function named main() where the
program always begin execution. When a function is called, the program execution is shifted to the
first statement in the called function. After the function returns to the calling function, values can
be returned and that value can be used as an operand in an expression.

Why to use function?


To avoid rewriting of the same code again and again
Separating the code into modular functions also make the program easier to design, understand and
debug
It helps us create to manageable program development environment.
68
Prepared by: Koirala Niraj
Programming in C
So it is not good to write a entire program into one function. Instead, break a program into small units
and write functions for each of these isolated subdivisions.

7.2 Defining and Declaring a function


Defining a function
A function definition has name, a parenthesis pair containing one or more parameters and a body.
For each parameter, there should be a corresponding declaration that occurs before the body.
The general format of the function definition is given as follows

return_type function_name(datatype argument1,datatype argument2,….)


{
statement1;
;
;
return ;
}

Declaring the type of the function


The function may return varying type of value to the calling portion of the program. Any of the
datatype such as int, float, char etc. can be in the function declaration. If a function is not supposed
to return value, it can be declared as type void. Example of i)
void myfunction ( float a,char b, int c)
{
;
;
}

Example of ii)
void myfunction ( void)
{
;
;
}

Example of iii)
float myfunction ( float a,char b, int c) {
;
;
}

69
Prepared by: Koirala Niraj
Programming in C
Example of iv) int
myfunction ( void )
{
;
;
}

Function Definition
A function definition is a unit of a function itself with the type of value it returns and its parameters declared
and the statements specified in it, that are executed when the function is called.
Actual arguments and Formal arguments
Any variable declared in the body of a function is said to be local to that function. If the variables
are not declared either or arguments or inside function body are considered “global” to the function
and must be defined externally. Arguments defined inside the function are called formal
arguments where as the argument from which the arguments have been passed to a function is
known as actual arguments.

#include <stdio.h>
void line(void); //function prototype or function declaration

void line(void) //function definition


{ int
j;
for(j=1;j<=42;j++)
printf("*”);
}
void main(void)
{ clrscr(); printf("Welcome to the world of C
programming \n)"; line(); //function call
}
return statement
The return() statement has two purposes. First, executing it immediately transfers control from the
function back to the calling program. And second, whatever is inside the parentheses following
return is returned as a value to the calling program. The return statement may or may not include
an expression. If return contains no parameters then this return is used to transfer the control used
only with void else if return has got argument having bracket or without bracket then this return is
returning value to the calling portion of the program. There is no restriction on the number of return
statements that may be present in a function. Also the return statement need not be always be
present at the end of the called function.
Note: Using a return statement, only one value can be returned by a function

70
Prepared by: Koirala Niraj
Programming in C
Syntax: return ;
return (expression);
Example:
A program to return value from a function.
#include<stdio.h>
#include<conio.h>

float max_value(float,float); //function prototype or function declaration void


main(void)
{
float x,y,max;
printf("Enter the two numbers");
printf(“%d %d”,&x,&y);
max=max_value(x,y); printf("The
maximum value is %d",max); getch();
}

float max_value(float a,float b)


{
if(a>b)
return a;
else return b;
}

7.3 Library functions and User Defined Functions

There are basically two types of c functions - library functions and userdefined functions. Library
functions are predefined in the header files and are not required to be written by the user at the time
of writing a program. Example of some library functions are getch(), getche(); (For more page no:
28)

User defined functions may be classified in the following three ways based on formal arguments passed
and the usage of the return statement.

a) A function is invoked without passing any formal arguments from the calling portion of a
program and doesn’t return any value back to the calling function.

#include<stdio.h> #include<conio.h>
void main()
{

71
Prepared by: Koirala Niraj
Programming in C
void display(void); //function declaration or function prototype
display();
getch();
}
void display(void) //Function definition
{ int x,y,sum; printf("Enter the
value of x and y:");
scanf("%d%d",&x,%y);
sum=x+y; printf("Sum=%d",sum);
}

b) A function is invoked with formal arguments from the calling portion of a program but the
function doesn’t return any value back to the program.

#include<stdio.h>
#include<conio.h> void
square(int);
void main()
{
int max;
printf("Enter the value for n:");
scanf(“%d”,&max);
for(int i=1;i<=max;++i)
square(i);
getch();
}
void square(int n)
{
int value;
value=n*n;
printf("Square of i is %d\n”,value);
}

c)Function is invoked with formal arguments from the calling portion of a program which returns
a value back to the calling environment.

//Program to calculate factorial using function


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

int fact(int);
72
Prepared by: Koirala Niraj
Programming in C
void main(void)
{
int x,n;
printf(“enter the number");
scanf(“%d”,&n);
x=fact(n);
printf("The factorial is %d",&x);
getch();
}

int fact(int n)
{
int i,value=1;
if(n==1)
{
return value;
}
else
{
for(i=1;i<=n;i++)
{
value=value*i;
}
return value;
} //else ends here
} //function fact ends here

//Program to add two digits using function


#include<stdio.h>
#include<conio.h> float
add(float,float); void
main()
{
float x,y,sum; printf("Please enter value
for x and y:\n")l
scanf("%f%f",&x,&y); sum=add(x,y);
printf("The Sum of %fand %f=%f",x,y,sum);
getch()
}

73
Prepared by: Koirala Niraj
Programming in C
float add(float c, float d) {
float result; result=c+d;
return result;
}

Rules that must be remembered while defining function

A function prototype declaration must appear at the beginning of the program following the
#include statement. In a function prototype the type of the function and the type of each formal
argument must be specified. The variable names used for formal arguments in a function
prototypes are arbitrary; they may even be blanks. Each function prototype must be terminated
by a semicolon.
A function name may be any valid identifier. The type of the function specifies the type of the
quantity which will be returned to the calling program.
The formal arguments used in defining a function may be scalars or arrays. Each formal
arguments type must be specified. For example int add(float a,b,c) is invalid and should be in
the form int add(float a,float b,float c)
Within a function definition other variables may be declared and used. Such variables are local to
the function and are not known outside the body of the function.
Within a function definition one cannot define another function.

Rules that must be remembered while calling a function

The actual arguments in the calling function must agree in number, order and type with the formal
arguments in the function declaration.
Copies of the values of actual arguments are sent to the formal arguments and the function is
computed. Thus the actual arguments remain unchanged.
If the formal arguments is an array name the corresponding actual arguments in the calling function
must also be an array name of the same type.
A return statement in the body of the function returns a value to the calling function. The type
of expression used in return statement must match with the type of the function declared. There
may be functions without return statement. In such a case the function must be declared as void.
A function can return only one value.

7.4 Recursion or Recursive function

A function which calls itself directly or indirectly again and again is known as recursive function.
Recursive functions are useful while constructing the data structures like linked list etc. There is
distinct difference between normal and recursive functions. A normal function will be invoked by

74
Prepared by: Koirala Niraj
Programming in C
the main function whenever a function call is made, whereas the recursive function will be invoked
itself directly or indirectly as long as the given condition is satisfied.

Recursion is the process of defining something in terms of itself, and is sometimes called circular definition.
Recursion has many negatives:
It repeatedly invokes the mechanism, and consequently increases the overhead of function calls.
This repetition can be expensive in terms of both processor time and memory space. Each recursive
call causes another copy of the function, these set of copies can consume considerable memory
space.

#include<stdio.h>
#include<conio.h> long
fact(int);
void main()
{
int n;
long y;
clrscr();
printf("Enter the factorial number");
scanf(“%d”,&n);
y=fact(n);
printf("The factorial number is %d and the factorial of the given number is
%ld",n,y);
getch();
}
long fact(int z)
{
long value;
if(z==1) return 1;
else value= z*fact(z-1); //function recursion occurs here.
return value;
}
555 sequence
of recursive calls
//Recursive function to calculate Power
#include<stdio.h> #include<conio.h>
double power(float val, unsigned pow);

main()
{ int n; float x;
printf("\nX=");

75
Prepared by: Koirala Niraj
Programming in C
scanf("%f",&x);
printf("\nN=");
scanf("%d",&n);
printf("\nPower=%f",power(x,n));
}
double power(float val,unsigned pow)
{
if(pow==0) return 1.0; else
return(power(val,pow-1)*val);
}
// Recursive function to calculate the nth term of the fibonnacci series

#include<stdio.h>
#include<conio.h> int
fibo(int);
main()
{
int x,y; scanf("%d",&x);
y=fibo(x);
printf("%d”,y);
getch();
}
int fibo(int n)
{
if(n==0 || n==1)
return 1;
else
return fibo(n-1)+fibo(n-2);
}

Recursion Vs. Iteration


1Both Iteration and recursion are based on control statements: Iteration uses a repetition
statement (such as for, while, do-while); Recursion uses a selection statement such as (if, ifelse,
or switch).
2Both Iteration and Recusrsion involves repetition: Iteration explicitly uses a repetition statement;
Recursion achieves repetition through repeated function calls.
3Both Iteration and Recursion each involve a termination test: Iteration terminates when the
loop continuation condition fails; Recursion terminates when a base case is recognized. 4Both
Iteration and Recursion can occur infinitely: An infinite loop occurs in the iteration if the loop
continuation test never becomes false(e.g. for(i=1;i>0;i++)); Infinite recursion occurs if the
recursion step does not reduce the problem each time in a manner that converges on the base
case.
76
Prepared by: Koirala Niraj
Programming in C

7.5 Use of Array in Function (Array and Functions)

The entire array can be passed on to a function in C. No subscript or brackets are required to invoke a
function using arrays.

Example
Program using array to do sorting in ascending and descending order

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

/*function prototypes*/ void


getdata(int array[10],int); void showdata
(int array[10],int); void descending_sort
(int array[10],int);
void ascending_sort (int array[10],int n);

/*function definition*/
void descending_sort (int array[10],int n)
{
int temp,i,j;
for ( i=0;i<n-1;++i)
{
for (j=i+1;j<n;++j)
if (array [j]>array[i])
{
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
showdata(array,n);
}
void ascending_sort (int array[10],int n)
{
int temp,i,j; for (
i=0;i<n-1;++i)
{
77
Prepared by: Koirala Niraj
Programming in C
for (j=i+1;j<n;++j)
if (array [i]>array[j])
{
temp=array[i];
array[i]=array[j];
array[j]=temp;

}
}
showdata(array,n);
}
void getdata(int array[10],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("enter the elements in an array[%d]=",i);
scanf("%d",&array[i]);
}

void showdata(int array[10],int n)


{
int i;
printf("the data in the array are \n"); for
(i=0;i<n;i++)
printf("%d\t",array[i]);
}
main()
{
int x[100]; int n,choice; printf("Enter how many
elements in the array:\n"); scanf("%d",&n);
getdata(x,n);
do
{
printf("*Bubble sort Operation*");
printf("\n1. Ascending Order");
printf("\n2.Decsending Sort");
printf("\n3. Exit"); printf("\n

78
Prepared by: Koirala Niraj
Programming in C
Enter your choice:");
scanf("%d",&choice);
switch (choice)
{ case 1:
ascending_sort(x,n);
break; case
2:
descending_sort(x,n);
break; case 3:
exit(0);
}
} while(choice>=1 || choice<=3);
}

Example
A program to add two matrix using array and function.

#include<stdio.h>
#include<conio.h> void add(int
x[5][5],int y[5][5]); void
display(int t[5][5]); void
read(int d[5][5]); int row,col,i,j;
main()
{
int a[5][5],b[5][5]; printf("Enter the no of
rows and columns:");
scanf("%d%d",&row,&col); printf("Enter the
elements of Matrix A:\n");
read(a); printf("\n"); display(a);
printf("\n"); printf("Enter the elements of
Matix B:\n");
read(b); printf("\n"); display(b);
printf("\n"); printf("The result of Matrix
Addition is:\n"); add(a,b);
getch();
}
void add(int x[5][5],int y[5][5])
{ int c[5][5];
for(i=0;i<row;i++)
for(j=0;j<col;j++)
c[i][j]=x[i][j]+y[i][j];
display(c);
79
Prepared by: Koirala Niraj
Programming in C
}
void display(int t[5][5])
{ for(i=0;i<row;i++)
{for(j=0;j<col;j++)
printf("%d\t",t[i][j]);
printf("\n");
}
}
void read(int d[5][5])
{
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("[%d][%d]",i,j);
scanf("%d",&d[i][j]);
}
}}
Example:
A program to multiply two matrix using array.
#include<stdio.h>
#include<conio.h>

void output (int a[3][3]); void


mul(int a[3][3],int b[3][3]);
void mul(int a[3][3],int b[3][3])
{
int c[3][3]; int i,j,k;
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++) {
c[i][j]=0.0; for(k=0;k<=2;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf(”\n”);
}
printf(”matrix after multiplication\n");
output(c);

80
Prepared by: Koirala Niraj
Programming in C
}
void main()
{
int a[3][3],b[3][3];
int i,j,n;
printf("\t\tNow we are doing multiplication of matrix\n");
printf("Enter the elements of Matrix A:\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("array[%d][%d]=",i, j);
scanf(%d",&a[i][j]);
}
}

cout<<"\nEnter the elements of Matrix B:\n";


for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("array[%d][%d]=",i,j);

scanf("%d",&a[i][j]);

}
}
mul(a,b);
getch();
}
void output(int x[][3])
{
int i,j;
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf(”%d\t", x[i][j]);
}
printf("\n");

81
Prepared by: Koirala Niraj
Programming in C
}
}

7.6 Passing By value and Passing By address (Call By Value and Call By Reference)
Arguments can be passed in function in one of the following two ways
Passing by value( Sending the values of the arguments)
Passing by reference(Sending the address of the arguments)

When arguments are passed by values the "value" of each actual argument in the calling function
is copied into corresponding formal argument of the called function. With this method, changes
made to the formal arguments in the called function have no effect on the values of the actual
arguments in the calling function. As we noted the function doesn’t have to access the original
variable in the function definition. In fact, this provides security such that the function cannot harm
the original variable.

Program illustrating Call by value

#include<stdio.h>
#include<conio.h> void
swap(int ,int);
void main()
{
int m=5; int n=10;
clrscr(); swap(m,n);
printf("m=%d\tn= %d”,m,n);
getch();
}

void swap(int a,int b)


{
int t;
t=a; a=b;
b=t;
printf("a=%d\tb=%d",a,b);
}
Output: a=10 b=5 m=5 n=10
In the above case when the function is called, it gets a copy of the arguments ("Call By Value"). The
function can not affect the value that was passed to it, only its own copy.
If it is necessary to change the original values, the addresses of the arguments can be passed as shown
below, which is called Call By Reference.

82
Prepared by: Koirala Niraj
Programming in C
Passing arguments by reference uses a different mechanism. Instead of a value being passed to a
function, a reference of the original variable, in the function definition is passed. In this case the
address of actual arguments in the calling function are copied into formal arguments of the called
function
The primary advantage of passing by reference is that the function can access the actual variables
in the calling program. The other benefit is that it provides a mechanism for returning more than
one value from the function back to the calling program.

Program illustrating Call By Reference. (The concept will be clear after reading pointer concept)
#include<stdio.h> #include<conio.h> void swap(int *,int *); void main()
{
int m=5;
int n=10;
clrscr();
swap(&m,&n);
printf("The value of m and n after swapping is %d and %d”,m,n);
getch();
}
void swap(int *a,int *b)
{
int t;
t=*a; *a=*b;
*b=t;
}

7.7 Macros
We have already seen that the #define statement can be used to define symbolic constants within a
program. At the beginning of a compilation process, all symbolic constants are replaced by their
equivalent text. Thus, symbolic constants provide a form of shorthand notation that can simplify
the organization of a program.
The #define statement can be used to define macros; i.e., single identifiers that are equivalent to expressions,
complete statements or group of statements.
Example
#include<stdio.h>
#include<conio.h>
#define area length*breadth
main()
{
int length,breadth;
printf("Enter Length and Breadth:\n");
scanf("%d%d",&length,&breadth); printf("Area=%d",area);
getch();
83
Prepared by: Koirala Niraj
Programming in C
}
Example: Macro with argument
#include<stdio.h>
#include<conio.h>
#define area(x) (3.14*x*x)
main()
{
float r1=6.25,r2=2.5,a;
a=area(r1); printf("\n Area of
Circle=%f",a); a=area(r2);
printf("\nArea of Circle=%f",a);
getch();
}
Though macro calls are like function calls, they are not really the same thing. In a macro call the
preprocessor replaces the macro template with its macro expansion. Whereas, in a function call the
control is passed to a function along with certain arguments, some calculations are performed in
the function and a useful value is returned back from the function. Usually macros make the
program run faster but increases the program size, whereas the function make the program smaller
and compact.
If we use macro hundred times in a program, the macro expansion goes into our source code at
hundred different places, thus increasing the program size. On the other hand, if a function is used,
then even if it is called from hundred different places in the program, it would take the same amount
of space in the program.
So, if the macro is simple and sweet like in our examples, it makes a nice shorthand and avoids the
overheads associated with function calls. On the other hand, if we have a fairly large macro and it
is used fairly often, replace macro with a function.

84
Prepared by: Koirala Niraj
Programming in C
Module 8

Structures

8.1 Introduction

A structure is a collection of one or more than one variable, possibly of different data type, grouped
together under a single name for convenient handling. Thus, a structure might contain integer
elements, floating-point elements and character elements. Structure helps to organize data
especially in large programs, because they provide group of variables of different data type to be
treated as a single unit.

For making, usefulness of structure more clear let us consider an example. In an organization an
employee’s details (i.e. name, address, designation, salary etc.) have to be maintained. Once
possible method would be to create a multi dimensional array to contain all employee details. But
this is not possible because the variables are of different data type i.e. name is of type char, salary
is of type float and so on. Hence, the simple solution is the structure. We should be clear about
array and structures.

Structure declarations are some what more complicated than array declarations, since a structure
must be defined in terms of its individual members. In general terms, the composition of a structure
may be defined

struct tag
{
member 1;
member 2; ………...
member n;
};

Where, struct is a required keyword;


tag is a name that identifies structure of this type; and member 1, member 2, …….,
member n are individual member declarations.

Note: There is no formal distinction between a structure definition and a structure declaration; the
terms are used interchangeably.

The individual members can be ordinary variables, pointers, arrays, or other structures. The
member names within a particular structure must be distinct from one another, though a member
name can be the same as the name of variable that is defined outside of the structure. A storage
class, however can not be assigned to an individual member, and individual members cannot be
initialized within a structure type declaration.
85
Prepared by: Koirala Niraj
Programming in C

Declaration of a Structure variable


A structure variable is a variable of a structurte type. Once the structure has been defined, individual structure-
type variable can be declared as follows:
storage-class struct tag variable 1,variable 2,……………,variable n; Where,
storage-class is an optional storage class specifier,
struct is a required keyword tag is the name of the structure and variable
1, variable 2,……, variable n are the structure variables of type tag. e.g.
struct account
{
int acc_no;
char acc_type;
char name[80];
float balance;
};
struct account oldcustomer,newcustomer;

The structure is named account (i.e. the tag is account). It contains four members: an integer
quantity(acc_no), a single character(acc_type), an 80 element character array(name[80]), and a
floating point quantity(balance).
We can now declare the structure variables oldcustomers and newcustomers as follows:
struct account oldcustomer,newcustomer;
It is possible to combine the declaration of structure with that of structure variables as shown below:
Storage-class struct tag
{
member 1;
member 2;
…………
memebr n;
}variable1, variable2, …, variable n;
The tag is optional in this situation. e.g.
struct account
{
int acc_no; char
acc_type; char
name[80]; float
balance;
}oldcustomer,newcustomer;

OR
struct
86
Prepared by: Koirala Niraj
Programming in C
{
int acc_no;
char acc_type;
char name[80];
float balance;
}oldcuctomer,newcustomer ;
When a structure variable such as newcustomer is declared, the compiler automatically allocates sufficient
memory to accommodate all of its members.
Example
#include<stdio.h> #include<conio.h>
struct book
{
char name[20];
float price;
int pages;
};
struct book b1,b2,b3;
main( )
{
printf("\nEnter names,Price,and No of Pages of 3 books\n");
scanf("%s%f%d",&b1.name,&b1.price,&b1.pages); scanf("%s%f%d",&b2.name,&b2.price,&b2.pages);
scanf("%s%f%d",&b3.name,&b3.price,&b3.pages);

printf("\nThis is what you entered");


printf("\n%s\t%f\t%d",b1.name,b1.price,b1.pages);
printf("\n%s\t%f\t%d",b1.name,b1.price,b1.pages);
printf("\n%s\t%f\t%d",b1.name,b1.price,b1.pages); getch();
}
This program demonstrates two fundamental aspects of structures:
Declaration of a structure
Accessing of a structure elements
Note the following points while declaring a structure type:
a)The closing brace in the structure type declaration must be followed by a semicolon.
b)It is important to understand that a structure type declaration does not tell the compiler to reserve
any space in memory. All a structure declaration does is, it defines the form of the structure.
c)Usually structure type declaration appears at the top of the source code file, before any variables
or functions are defined. In very large programs they are usually put in a separate header file, and
the file is included (using the preprocessor directive #include) in whichever program we want to
use this structure type.

Accessing of Structure elements

87
Prepared by: Koirala Niraj
Programming in C
Structure use a dot(.) operator to access individual elements. The structure variable name followed
by a period and the member name references that individual member. The general form for
accessing a member of a structure is
structure-name. member-name
So to refer to pages of the structure defined in our sample program we have to use.
b1.pages
Similarly, to refer to price we should use,
b1.price
So,to print the name of book we can write
printf("The book's name is %s",b1.name);

Initializing Structures
Like primary variables and arrays, structure variables can also be initialized where they are declared. The
format used is quite similar to that used to initialize arrays.

struct book
{
char name[20];
float price;
int pages;
};
struct book b1={"Basic",130.00,550};
struct book b2={"Math",150.50,800};

Structure Assignment
The information contained in one structure may be assigned to another structure of the same type using
a single assignment statement. That is, you do not need to assign the value of each member separately.
The following program illustrates structure assignments:

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

struct
{ int a;
int b;
}x,y;

main()
{
x.a=10;

88
Prepared by: Koirala Niraj
Programming in C
x.b=20; y=x; //Assign one structure
to another
printf("%d",y.a);
printf("%d",y.b); getch();
}
8.2 Nested structures
Nested structures are structures within structure. Let us construct two different structures and consolidates it
into single nested structures.

Example 1
struct employee
{
char name[20]; int
emp_code; char
designation[20];
float salary; } emp1,
emp2;
struct emp_address
{ int no; char
street[15]; char
area[20];
} address1;

These two structures can be consolidated as struct


employee
{
char name[20];
struct emp_address
{ int no;
char street[15];
char area[20];
} address1;

int emp_code; char


designation[20];
float salary;
} emp1, emp2;

Example 2:We can also tag names to define inner structures struct
date
{

89
Prepared by: Koirala Niraj
Programming in C
int month;
int day;
int year;
};
struct account
{
int acc_no;
char acc_type;
char name[80];
float balance;
struct date lastpayment;
}customers;

If a structure member is itself a structure, then a member of the embedded structure can be accessed by
writing
variable.member.submember
e.g. customers.lastpayment.month

Example 3:A sample to demonstrate nesting of structure


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

struct address
{
char phone[15];
char city[25];
int citycode;
};

struct emp
{
char name[25];
struct address a;
};
void main()
{
int i;
struct emp e={"Jack","54515","KTM",101};
printf("\nname=%s\tPhone=%s",e.name,e.a.phone);
printf("\nCity=%s\tCitycode=%d",e.a.city,e.a.citycode); getch();

90
Prepared by: Koirala Niraj
Programming in C
}

Example 4:
#include <stdio.h> #include<conio.h>
struct add
{
int door_no;
char street[10];
char place[10];
int pin;
};

struct student
{
char name[10];
int roll_no;
struct add address;
};

main()
{
struct student stud; printf("Enter the
name of the student:");
scanf("%s",stud.name); printf("Enter the
roll no. of the student:");
scanf("%d",&stud.roll_no); printf("Enter
the door no.:");
scanf("%d",&stud.address.door_no);
printf("Enter the street name:");
scanf("%s",stud.address.street);
printf("Enter the area name:");
scanf("%s",stud.address.place);
printf("\nThe student's details are....\n");
printf("\nThe name is %s",stud.name);
printf("\nThe roll no is %s",stud.roll_no);
printf("\nThe door no is
%d",stud.address.door_no); printf("\nThe
area name is %s",stud.address.place);
printf("\nThe street name is
%s",stud.address.street); getch(); }
It is also permissible to nest more than one type of structures. struct
personal_record
{

91
Prepared by: Koirala Niraj
Programming in C
struct name_part name;
struct address_part address;
struct date_aprt dateofbirth;
…………….
};
struct personal_record personal;
The first member of this structure is name which is of the type name_part. Similarly other members have
their own structure types.

8.3 Array of structures


Since we can create an array of any valid type, it is possible to define an array of structure also; i.e.
an array in which each element is a structure. To create the array of structures, you must first define
a structure and then declare an array variable of that type. For example, to declare a 100element
array of structures of type books, you can write struct book b1[100];
This creates 100 sets of variables that are organized as defined in the structure book.
To access a specific structure, index the structure name. For example, to print the price of structure 3, write
printf("%f",b1[2].price);
Like all array variables, arrays of structures begin indexing at 0.

Example: To demonstrate arrays of structures


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

struct marks
{ int english;
int math; int
computer; int
total;
};

void main()
{ int
i;
static struct marks student[3]={ {50,70,91,0},{75,55,72,0},{54,41,72,0}};
printf("English\tMath\tComputer\tTotal"); for(i=0;i<3;i++)
{
student[i].total=student[i].english+student[i].math+student[i].computer;
printf("\n%d\t\t%d\t\t%d",student[i].english,student[i].math,student[i].computer, student[i].total);
}
getch();
}
92
Prepared by: Koirala Niraj
Programming in C

Example: Storing book information using structure


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

struct book
{
char name[20];
float price; int
pages; }b[100];
void main()
{
int i;
for(i=0;i<=99;i++)
{
printf("\n Enter Name, Price, and Pages:");
scanf("%s%f%d",&b[i].name,&b[i].price,&b[i].pages);
}
for(i=0;i<=99;i++)
{
printf("\n%s%f%d",b[i].name,b[i].price,b[i].pages);
}
getch();
}
This provides space in memory for 100 structures of the type structure book. In an array of
structures all elements of the array are stored in adjacent memory locations. Since each element of
this array is a structure, and since all structure elements are always stored in adjacent locations you
can visualize the arrangement of array of structures in memory.
e.g. b[0]'s name, price, and pages in memory would be immediately followed by b[1]'s name, price, and
pages, and so on.

Note that the array is declared just as it would have been, with any other array. Since student is an
array, we use the usual array-accessing methods to access individual elements and then the member
operator to access members. Example
struct employee
{
char name[20];
char roll_no[5]; int
salary;
} emp [5];

93
Prepared by: Koirala Niraj
Programming in C
The above declaration defines five instances of the variable emp of the type struct employee. They could
be initialized in this manner.

struct employee
{
char name[20];
char roll_no[5]; int
salary;
} emp [5] = { {"james","e01", 2000},
{"Jerry","e02", 4100},
{"Sheryl","e03", 2500},
{"Vicky","e04", 5000}
};
Actually size need not to be specified, because the initialization by itself will determine the size. In
above initialization part, every particular employee’s details have been enclosed in braces. This is
not necessary, but it improves the clarity of code. In case a member is not be initialized, the value
for it can be omitted. Assume the name and salary of the employee is not known; the declaration
will be as follows. { ,”e06”, }
In case any member of structure can be accessed using the index number along with the structure name.
For e.g., if he/she wants to print the name of the first employee,

printf (“The name of the first employee is %s”, emp [0].name);

User-Defined datatype
C language provides the opportunity to define new datatype equivalent to the existing system using the
typedef statement. Let us take an example. The declaration would be

typedef struct add


{
int dd; int mm;
int yyyy;
}dob;
dob emp_date_of_birth;

The above declaration variable emp_date_of_birth has now become the type of structure add.

8.4 Structures and functions


C supports the passing of structure values as arguments of functions. There are three methods by which
the values of a structure can be transferred from one function to another.
94
Prepared by: Koirala Niraj
Programming in C
The first method is to pass each member of the structure as an actual argument of the function call.
The actual arguments are then treated independently like ordinary variables. This is the most
elementary method and becomes unmanageable and inefficient when the structure size is large. The
second method involves passing of a copy of the entire structure to the called function. Since the
function is working on a copy of the structure, any changes to structure members within the function
are not reflected in the original structure(in the calling function). It is, therefore, necessary for the
function to return the entire structure back to the calling function. All compilers may not support
this method of passing the entire structure as a parameter.
The third method employs a concept called pointer to pass the structure as an argument. In this
case, the address location of the structure is passed to the called function. The function can access
indirectly the entire structure and work on it. This is similar to the way arrays are passed to the
functions. This method is more efficient as compared to the second one.

1. Passing Structure Members to Functions


When you pass a member of a structure to a function, you are actually passing the value of that
member to the function. E.g.
struct fred
{
char x; int y;
float z;
char s[10];
}mike;
Here are examples of each member being passed to function e.g.
function(mike.x); //Passes character value of x
function1(mike.y); //Passes integer value of y
function2(mike.z); //Passes float value of z function3(mike.s)
//Passes address of string s function4(mike.s[2]); //Passes
character value of s[2]

If you wish to pass the address of an individual structure member, put the & operator before the
structure name e.g.
function(&mike.x); //Passes address of character x
function1(&mike.y); //Passes address of integer y function2(&mike.z);
//Passes address of float z
function3(mike.s) //Passes address of string s
function4(&mike.s[2]); //Passes address of character s[2]
Remember that the & operator preceds the structure name, but not the individual member name.

2. Passing Entire Structures to Functions


When a structure is used as an argument to a function, the entire structure is passed using the standard call-
by-value method. This means that any changes made to the contents of the structure inside the function to
which it is passed do not affect the structure used as an argument.

95
Prepared by: Koirala Niraj
Programming in C
When using a structure as a parameter, remember that the type of the argument must match the
type of the parameter. For example, in the following program both the argument arg and the
parameter parm are declared as the same type of structure.

Example 1:
#include<stdio.h> #include<conio.h>
struct test
{ int
a,b;
char ch;
};
void function(struct test parm);
main( )
{
struct test arg;
arg.a=1000; function(arg);
getch();
}
void function(struct test parm)
{
printf("%d",parm.a);
}

Example 2:

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

typedef struct
{
char name[20];
int price; int
quantity;
}stores;

stores update(stores product,int p,int q)


{
product.price+=p;
product.quantity+=q;
return(product);
}
96
Prepared by: Koirala Niraj
Programming in C
float mul(stores stock)
{
return(stock.price*stock.quantity);
}
void main( )
{ float
value;
int p_increment,q_increment; static stores
item={"XYZ",25,12}; printf("\nInput increment
values:"); printf("price increment and quantity
increment\n");
scanf("%d%d",&p_increment,&q_increment);
item=update(item,p_increment,q_increment);
printf("Update values of item\n\n");
printf("Name %s\n",item.name);
printf("Price %d\n",item.price);
printf("Quantity %d\n",item.quantity);
value=mul(item); printf("\n Value of the
item=%f\n",value); getch();
}

8.5 Structure and Pointer


( Refer page no: 115 )

8.6 Unions
Unions have the same relationship to structures. Both structures and unions are used to group a
number of variables of different data type together. But the difference is that the structure enables
us to reserve a separate place in memory for every individual member of the structure. Whereas
with union, it enables to reserve the definite place in memory and use it for all members of the
unions. This implies that, although a union may contain many members of different types, it can
handle only one member at a time.
In unions while deciding the size of the memory to reserved, it will reserve the memory space
equals to size occupied by the union member with data type that has highest precision. i.e. if there
is union with two data members of type int, float. Here, since float has higher precision, union will
occupy the memory space of byte.
Like structures, a union can be declared using the keyword union as follows:
union item
{
int m; char c;
float x;
}code;

97
Prepared by: Koirala Niraj
Programming in C
Example:
#include<stdio.h> #include<conio.h>
union course
{ int major;
char minor[10]; };

struct student
{
char name[20];
int rollno; union
course course_no;
}student1;

main()
{
char c_name;
clrscr(); printf("Enter the name of the
student:"); scanf("%s",student1.name);
fflush(stdin);
printf("Enter the roll no of the student:");
scanf("%d",student1.rollno);
fflush(stdin); printf("Enter the course('M' for major or
'm' for minor)"); scanf("%c",&c_name); fflush(stdin);
if(c_name=='M')
{
printf("The course('1'or '2')?");
scanf("%d",&student1.course_no.major);
fflush(stdin);
}

if(c_name=='m')
{
printf("Enter the name of the course:");
scanf("%d",&student1.course_no.minor); fflush(stdin);
}
printf("\nPress any key to exit...");
getch();
}

How is the structure different from an array?

98
Prepared by: Koirala Niraj
Programming in C
 An array can hold multiple elements of same data type whereas a structure can hold
multiple elements of different data types
 The component element of an array is referenced by the array name and the index value
e.g. name[3], a[5] etc where as component element of a structure is referenced by the structure
name and the element name e.g. book.id, stu.name etc.

Differentiate between Structure and Union

structure union
1. Members of a structure doesn't share 1. Members of a union share space
space
2. Don’t' Conserves storage 2. Conserves storage
3. Each and every data member defined 3. Only the last data member defined can be
can be accessed whenever it has been accessed
defined.
4. Each data member will occupy its own 4. The size required by a union variable is
size finally the size of the strcture in the the size required by the member
sum of the total memory occupied by requiring the largest size
each member.
5. Specially designed to create own data 5. Specially designed to handle or control
type or typically used to create simple the hardware operation.
database.
6 Example: Example:
struct book{int id; union selection{
char name[10]; char major[10];
}b; char minor[15];
}u;

99
Prepared by: Koirala Niraj
Programming in C

module 9

Pointer

9.1 Introduction
Pointer data type is one of the strengths of C and C++ language. The pointer is a powerful technique
to access the data by indirect reference as it holds the address of that variable where it has been
stored in memory. A pointer is a variable, which holds the memory address of another variable.
Sometimes, only with the pointer a complex data type can be declared and accessed easily. The
pointer has the following advantages.
It allows passing variables arrays, strings and structures as function arguments.
A pointer allows returning structures variables from functions.
It provides functions, which can modify their calling arguments. It
supports dynamic allocations and de-allocations of memory segments
Pointer can return more than one value.
A pointer improves the efficiency of certain routines.
A pointer contains the memory address. Most commonly this address is the locations of another
variable, where it has been stored in memory. If one variable contains the address of another
variable then the first variable is said to point to the second. In C and C++ pointer are distinct such
as integer pointer, character pointer, floating point number pointer etc. A pointer consists of two
parts, namely

a) The pointer operator


b) The address operator
100
Prepared by: Koirala Niraj
Programming in C

a) Pointer operator
A pointer operator can be represented by combinations of * (asterisk) with a variable. For e.g. if a
variable of integer data type and also declared * (asterisk) with another variable, it means the
variable is of type “pointer to integer”. In other words, it will be used in the program indirectly to
access the value of one or more integer variables.

For e.g.
int *myptr;
where myptr is a pointer, which holds the address of an integer data type All pointer variables must
be declared before it is used in C and C++ programs like other variables. When a pointer variables
is declared, and asterisk must precede the variable name this identifies the variable as a pointer

The general form of pointer declaration


data_type *pointer_variable_name;

b) Address operator
An address operator can be represented by a combination of & (ampersand) with a pointer variable.
For e.g. if a pointer variable is an integer type and also declared & with the pointer variable then it
means that the variable is of type “address of”. In other words, it will be used in the programs to
indirectly access the value of one or more integer variables. The “&” is unary operator that returns
the memory address of its operand. A unary operator requires only on operand.

m=&ptr;
Note, that the pointer operator & is an operator that returns the address of the variable following it.
Therefore, the preceding assignment statement could be verbalized as “in receives the address of
ptr”.
The other operator * is the complement of &. It is unary operator that returns the value of the variable
located at the address that follows
The operation of * implies to the phrase “at address”. Unfortunately, the symbol * represents both
the multiplication sign and the “at address”, and the symbol & represents both bitwise AND and
the “address of” sign. When these are used as pointer operators, they have no relationship to the
arithmetic operators. That happened to look like the same. Both, the pointer operators, & and *,
have higher precedence over all other arithmetic operators except the unary minus, with which they
have equal precedence.

Pointer assignment:
A pointer is a variable data type and hence the general rule to assign its value to the pointer is same as
that of any other variable data type.
For e.g.

int x=5,y;
101
Prepared by: Koirala Niraj
Programming in C
int *ptr1,*ptr2;

1) ptr1=&x;
Here, the memory address of variables x is assigned to the pointer variable ptr1.

2) y=*ptr1;
The contents of the pointer variables is assigned to the variable y, not the memory address

3) ptr2=ptr1; /*address if ptr1 is assigned to the ptr2*/


The address of the ptr2 is assigned to the pointer variable ptr2. The contents of both ptr1 and ptr2 will
be same as these tow pointer variables hold the same address

Graphical figure of the above demo


1)
X
5
100H
Ptr1
100H
5000H
2)
Y
5
300H
ptr1
100H
5002H

Here, the value or content of ptr1 i.e 100H (address) si assigned to another pointer. So, this both
pointers show to the same variables. 3)
ptr2
100H
5002H
ptr1
100H
5000H

102
Prepared by: Koirala Niraj
Programming in C
Legend of above diagram

ptr2
100H
5002H
Variable name

A program to display the contents of the pointer


#include<stdio.h>
#include <conio.h> main()
{ int x;
int *ptr;
x=10;
ptr=&x;
printf("x=%d and ptr=%d",x,ptr);
printf("\nx=%d and contents of ptr=%d”,*ptr);
getch();
}

A program to assign a character variable to the pointer and to display the contents of the
pointer #include<stdio.h> #include <conio.h> main()
{ char x,y;
char *ptr;
x='c';
/*assignment
of
character*/
ptr=&x;
y=*ptr;
printf("Value of x=%c", x);
printf("\nPointer value ptr=%c",y);
getch();
}
A program to assign the pointer variable to another pointer and display the contents of the both
the pointer variables
main()
{ int x; int
*ptr1,*ptr2;
x=10; ptr1=&x;
ptr2=ptr1;

103
Prepared by: Koirala Niraj
Programming in C
printf("Value of x=%d",x);
printf("\nContents of ptr1=%d”,*ptr1);
printf("\nContents of ptr2=%d",*ptr2);
getch();
}
A program for assignment and usage of & operator main()
{ int i=3; printf("The address of i is
%d",&i); printf("\nValue of i=%d",i);
printf("\nValue of i using *(&i) %d=”,*(&i));
getch();
}

main()
{
int *j,k=5;
j=&k;
printf("Address of k=%d",&k);
printf("\nAddress of j=%d”,&j);
printf("\nValue of j=%d",j); printf("\nValue
of k=%d”,<<k); printf("\nValue of
k=%d",(&k)); printf("\nValue of k=%d",*j);
getch();
}

main()
{
int p=10,*q,**r;
q=&p;
r=&q;
printf("Address of p=%d",&p);
printf("\nAddress of p=%d",q);
printf("\nAddress of p=%d",*r);
printf("\nAddress of q=%d",&q);
printf("\nAddress of q=%d",r);
printf("\nAddress of r=%d",&r);
printf("\nValue of q=%d",q);
printf("\nValue of r=%",q); printf("\nValue
of p=%d",p); printf("\nValue of
p=%d",*(&p)); printf("\nValue of
p=%d",*q); printf("\nValue of p=%d",**r);
getch();
}

104
Prepared by: Koirala Niraj
Programming in C

Pointer Arithmetic
As a pointer holds the memory address of variable, some arithmetic operations can be performed
with pointers. C and C++ supports four arithmetic operators that can be used with pointers, such as

Addition +
Subtraction - Incrementation
++
Decrementation --

Pointers are variables. They are not integers, but they can be displays as unsigned integers. The conversion
specifier for a pointer is added and subtracted. For e.g.

pr++ causes the pointer to be incremented, but not by 1 ptr--


causes the pointer to be decremented, but not by 1

According to datatype declared to that pointer variable if arithmetic operation is done then values(contents)
will be incremented or decremented as per the data type is chosen

The following program segment illustrates the pointer arithemetic.


The integer would occupy adderss 2000 to 2001 (two bytes of memory allocation)

A program to increment the pointer’s address main()


{
int value,*ptr;
value=120; clrscr();
ptr=&value;
printf("ptr=%d",ptr);
ptr++;
printf("\nptr=%d”,ptr);
getch();
}
Here, lets say address of ptr which it is pointing is 4050 then after ptr++ is now increment not by one
but by 2 as it is defined as integer and compiler knows that it should occupy 2 bytes show as first ti
will show 4050 and after ptr++ it wil 4052.

A program to show the arithmentic operation on pointers main()


{

105
Prepared by: Koirala Niraj
Programming in C
float value,*ptr; int x,*ptr1,*ptr2; value=120.0;
ptr=&value; printf("\nMemory address=%d",ptr);
ptr++; printf("\nMemory address after
increment=%d",ptr); ptr--;
printf("\nMemory address after decrement=\n\n\n%d",ptr);
x=101; ptr1=&x;
printf("ptr1=%d",ptr1);
ptr2=ptr1+6;
printf("\nValue of x=%d",x); printf("\nCotents of
ptr1=%d”<<*ptr1; printf("\nAddress of ptr1=%d",&ptr1);
printf("\nAddress of (ptr2=ptr1+6)=%d",&ptr2); printf("\nAddress
of ptr2=%d”,*ptr2); /*gives the garbage value*/
}

Other examples using pointer operation main()


{
int x,y,*ptr; x=10; ptr=&x; printf(”Value
of x=%d and pointer=%d",x,*ptr); y=++ *ptr;
/*y=11*/
printf("\nValue of y=%d”and pointer=%d",y,*ptr);
getch();
}

main()
{
int x,y,*x_pointer,temp;
temp=3;
x=5*(temp+5);
x_pointer=&temp;
y=6*(*x_pointer+5);
printf("x=%d",x);
printf("\ny=%d",y);
getch();
}

main()
{
int x,y,*ptr,*ptr2; x=25; ptr=&x;
printf("Contents of pointer=%d",*ptr);
*ptr=*ptr+1; /* ++*ptr */
106
Prepared by: Koirala Niraj
Programming in C
y=*ptr; printf("\nValue of y=%d”and pointer
(*ptr=*ptr+1)=%d",y,*ptr);
(*ptr)++; y=*ptr; printf("\nValue of y=%d”and
pointer (*ptr)++=”,y,*ptr);
++ *ptr; y=*ptr; printf("\nValue of y=%d”and pointer
++ *ptr=%d”,y,*ptr);
++ *ptr; ptr2=ptr;
printf("\nPointer *ptr=%d”,*ptr);
printf("\nPointer *ptr2=%d",*ptr2);
getch();
}
Valid pointer operations:
Assignment to a pointer of the same type
Assigning a pointer to pointer of type (void *) and back
Adding or subtracting a pointer and an integer (including increment and decrement)
Subtracting or comparing two pointers which point to members of the same array Assigning
or comparing to zero

#define NULL 0 main(


)
{ int x,y;
int *px=&x;
int *py;
void *pv;
py=px; /* Assignment to a pointer of the same type*/ px=(int *)
pv; /* recast a (void *) pointer */ pv=(void *)px; /* recast to type
(void *) */ py=px+2; /* Adding or subtracting a pointer and an integer
is legal */ px++; /* Increment and decrement is legal*/
if(px==NULL) /* Compare to null pointer*/ py=NULL; /* Assign to
null pointer*/
}

Invalid pointer operations:


Adding two pointers
Multiply, divide, shift, mask pointers
Add float or double numbers to a pointer
Assign a pointer of different types without cast
main()
{ int x,y; int
*px,*py,*p;

107
Prepared by: Koirala Niraj
Programming in C
float *pf;
px=&x; py=&y;
p=px+py; /*Addition of two pointer is illegal */ p=px*py; /*
Multiplication of two pointer is illegal */ p=px/py; /* Division
of two pointer is illegal */ p=px+10.5; /* Addition of float to
pointer is illegal */ pf=px; /* Assignment of different types
of pointer is illegal */
}

9.2 Pointers and Functions


Pointers are very much used in function declaration. Sometimes only with a pointer a complex function can
be easily represented and accessed. The use of the pointers in a function definition
may be classified into two groups they are call by value and call by reference Call
by value
Whenever a portion of the program invokes a function with formal arguments, control will be
transferred from the main to the calling function and the value of the actual argument is copied to
the function. Within the function, the actual value is copied from the calling portion of the program
may be altered or changed. When the control is transferred back from the function to the calling
portion of the program, the altered values are not transferred back from the function to the calling
portion of the program, the altered values are not transferred back. This type of passing formal
arguments to a function is technically known as call by value.
main()
{
int x=100,y=20;
clrscr();
printf("Values after swap\n");
printf(”x=%d”and y=%d”,x,y); swap(x,y);
printf("\nValues after swap\n");
printf(”x=%d and y=%d”,x,y); getch();
}
swap(int a,int b)
{ int
temp;
temp=a;
a=b;
b=temp;
}
Since, the above function is declared call by value, the value is not swapped. As a single variable
is transferred to the function, it protects the value of this variable from alteration within the
function. On the other hand, it prevents the altered value being transferred back from the function
to the calling portion of the program.

108
Prepared by: Koirala Niraj
Programming in C
Call by Reference
When a portion of a program calls the function, the addresses of the actual arguments are copied
on to the formal arguments, though they may be referred by different variable names. The content
of the variables that are altered within the function block are returned to the calling portion of the
program in the altered form itself, as the formal and actual arguments are referencing the same
memory location or address. The technique is known as call by reference or call by adder or call
by location.

When an argument is passed by value, the data item is copied to the function. Thus, any alteration
made to the data item within the function is not carried over into the calling routine. When
arguments passed by reference(i.e. when a pointer is passed to the function), the address of the data
item is passed to the function. The contents of that address can be accessed freely, either within a
function or within a calling routine. Moreover, any changes that is made to the data item(i.e. the
contents of the address(will be recognized in both the function and the calling portion of the
program. Thus, the use of the pointer as function arguments permits the corresponding data item to
be altered globally from within the function.

A program to exchange the content of two variables using call by reference main()
{
int x=100,y=20;
clrscr();
printf("Values before swap\n");
printf(”x=%d”and y=%d”,x,y);
swap(&x,&y); printf("\nValues
after swap\n"); printf(”x=%d
and y=%d”,x,y);
getch();
}

swap(int *a,int *b)


{ int
temp;
temp=*a;
*a=*b;
*b=temp;}

9.3 Pointers and One-dimensional Array


In C and C++, there is a close correspondence between array datatype and pointers. Any array name
is C and C++ is very muck like a pointer but there is difference between them. The pointer is
variable that can appear on the left side of an assignment operation. The array name is constant and
can’t appear on the left side of an assignment operator. In all the other aspects, both the pointer and
the array are the same.

109
Prepared by: Koirala Niraj
Programming in C
Recall that an array name is really a pointer to the first element in the array. Therefore, if x is a one-
dimensional array, then the address of the first array element can be expressed as either &x[0] or
simply as x. Moreover the address of the second array element can be written as either &x[1] or as
(x+1), and so on. In general the address of array element (i+1) can be expressed as either &x[i] or
as (x+i). Thus we have two different ways to write the address of an array element: we can write
the actual array element, preceded by an ampersand; or we can write an expression in which the
subscript is added to the array name.
Since &x[i] and (x+i) both represent the address of the ith element of x, it would seem reasonable
that x[i] and *(x+i) both represent the contents of that address, i.e., the value of the ith element of x.
Hence, either term can be used in any particular application.

A program to access the array element using pointer main()


{
int myArray[5]={1,2,3,4,5};
int i; for(i=0;i<5;i++)
printf("%d\t",*(myArray+i));
getch();
}
OR
main()
{
int myArray[5]={1,2,3,4,5};
int i;
for(i=0;i<5;i++)
printf("%d\t",myArray[i]);
getch();
}
In above program, instead of adding i to myArray to step through the array address, we wanted to
use the increment operator. Could we write *(myArray++) ? The answer is no, and the reason is
that we want increment a constant(or indeed change it in anyway). The expression myArray is the
address where the system has chosen to place our array, and it will stay at this address until the
program terminates. myArray is constant. We can’t say myArray++ any more though we can the
array element of pointer to which it is pointer can be incremented. While we can’t increment an
address, we can increment a pointer that holds an address.
main()
{
int myArray[]={1,2,3,4,5};
int *ptr2myArray,i;
clrscr();
ptr2myArray=myArray;
for(i=0;i<5;i++)
printf("%d",*(ptr2myArray++));
getch(); }

110
Prepared by: Koirala Niraj
Programming in C
When assigning a value to an array element such as x[i], the left side of the assignment statement
be written as either x[i] or as *(x+i). Thus, a value may be assigned directly to an array element, or
it may be assigned to the memory area whose address is that of the array element.
On the other hand, it is sometimes necessary to assign an address to an identifier. In such situations,
a pointer variable must appear on the left side of the assignment statement. It is not possible to
assign an arbitrary address to an array name or to an array element. Thus, expressions such as x,
(x+i) and &x[i] cannot appear on the left side of an assignment statement. Moreover, the address
of an array cannot arbitrarily be altered, so that expressions such as ++x are not permitted.
Note that the address of one array element cannot be assigned to some other array element.
Thus, we cannot write a statement such as
&line[2]=&line[1];
On the other hand, we can assign the value of one array element to another through a pointer if we
wish,e.g.,
p1=&line[1];
line[2]=*p1;
OR
P1=(line+1);
*(line+2)=*p1;
If a numerical array is defined as a pointer variable, the array elements cannot be assigned initial
values. Therefore, a conventional array definition is required if initial values will be assigned to
the elements of a numerical array. However, a character-type pointer variable can be assigned an
entire string as a part of the variable declaration. Thus, a string can conveniently be represented by
either a one-dimensional character array or a character pointer.

#include<conio.h>
#include<stdio.h> char
x[]="this is first\n\n";
main()
{
char y[]="this is second\n";
printf("%s",x);
printf("%s",y);
getch();
}

#include<conio.h>
#include<stdio.h> char
*x="this is first\n\n";
main()
{
char *y="this is second\n";
printf("%s",x);
printf("%s",y);
111
Prepared by: Koirala Niraj
Programming in C
getch();
}

Example: Finding smallest element of Array using pointer

#include<stdio.h>
#include<conio.h> main()
{
int i,n,small,*ptr,a[10];
printf("How many elements?\n");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
printf("%d\t",a[i]);
//Assign address of a[0] to pointer variable
//It can be done in two ways ptr=&a[0] or ptr=a
ptr=a; small=*ptr;
ptr++; //Pointer points to next location in an array for(i=1;i<n;i++)
//loop n-1 times to search smallest element
{
if(small>*ptr)
small=*ptr;
ptr++; //pointer is incremented to pointed a[i+1]
}
printf("\nSmallest element of array:%d",small); getch();
}

Dynamic Memory Allocation


Since an array name is actually a pointer to the first element within the array, it should be possible
to define the array as a pointer variable rather than as a conventional array. Syntactically, the two
definitions are equivalent. However, a conventional array definition results in a fixed block of
memory being reserved at the beginning of program execution, whereas this does not occur if the
array is represented in terms of a pointer variable.

Using malloc( ) and calloc( ) functions we can allocate memory only at the time of execution. Since
these functions allocate memory on the fly(during execution) they are often known as "Dynamic
Memory Allocation" functions.

Therefore, the use of a pointer variable to represent an array requires some type of initial memory
assignment before the array elements are processed. This is known as dynamic memory allocation.
Generally the malloc library function is used for this purpose, as illustrated in the next example.
112
Prepared by: Koirala Niraj
Programming in C
Example:
Suppose x is a one-dimensional, 10 element array of intergers. It is possible to define x as a pointer variable
rather than an array. Thus, we can write
int *x;
rather than
int x[10];
However, x is not automatically assigned a memory block when it is defined as a pointer variable,
though a block of memory large enough to store integer quantities will be reserved in advance when
x is defined as an array.
To assign sufficient memory for x, we can make use of the library function malloc, as follows. x=(int
*)malloc(10*sizeof(int));
Since malloc() returns a void pointer, we have to typecast it into apprpriate pointer (as int in above
example)
This function reserves a block of memory whose size(in bytes) is equivalent to 10 integer quantities.
As written, the function returns a pointer to an integer. This pointer indicates the beginning of the
memory block. In general, the type cast preceding malloc must be consistent with the data type of
the pointer variable. Thus, if y were defined as a pointer to a doubleprecesion quantity and we
wanted enough memory to store 10 double-precesion quantities, we would write
y=(double*)malloc(10*sizeof(double));

The calloc( ) function work exactly similar to malloc( ) except for the fact that it needs two
arguments. For example:
int *x;
x=(int *)calloc(n,sizeof(int));
Here, sizeof(int) indicates that we wish to allocate memory for storing integers and n indicates that
we want to reserve space for storing n integers. Another minor difference between malloc( ) and
calloc( ) is that, by default, the memory allocated by malloc( ) contains garbage values, whereas
that allocated by calloc( ) contains all zeros.
While using these functions it is necessary to include the file "alloc.h" at the beginning of the program.

Example: Finding smallest element of array using dynamic memory allocation


#include<stdio.h>
#include<conio.h>
#include<alloc.h> main()
{
int i,n,small,*a;
printf("How many elements?\n"); scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
scanf("%d",a+i);
for(i=0;i<n;i++)
printf("%d\t",*(a+i));
113
Prepared by: Koirala Niraj
Programming in C
small=*a; //first element is considered as small for(i=1;i<n;i++)
//loop n-1 times to search smallest element
{
if(small>*(a+i))
small=*(a+i);
}
printf("\nSmallest element of array:%d",small); getch();
}

Sorting elements of array in ascending order using pointer

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

main()
{ int
i,n,*x;
printf("How many nos?");
scanf("%d",&n); x=(int
*)calloc(n,sizeof(int));
for(i=0;i<n;i++)
scanf("%d",x+i);
for(i=0;i<n;i++)
printf("%d\t",*(x+i));

for(i=0;i<n-1;i++)
{
int temp;
for(j=i+1;j<n;j++)
{
if(*(x+i)>*(x+j)) // This is for ASCENDING ORDER, for DESCENDING use < sign
{
temp=*(x+i);
*(x+i)=*(x+j);
*(x+j)=temp;
}
}
}

for(i=0;i<n;i++)
printf("%d\t",*(x+i));
getch();
}

Example: Program to reorder a one-dimensional, integer array from largest to smallest using
pointer and function

114
Prepared by: Koirala Niraj
Programming in C

#include<conio.h>
#include<stdio.h>
#include<stdlib.h> void
reorder(int n, int *y);
main()
{ int i,n,*x; printf("How many nos will be
entered?"); scanf("%d",&n);
printf("\n");
//Allocate Memory x=(int
*)malloc(n*sizeof(int)); //Read
in the list of numbers
for(i=0;i<n;i++)
{
printf("i=%d x=",i+1);
scanf("%d",x+i);
}
//Reorder all array elements
reorder(n,x);
//Display the reordered list of numbers
printf("\n\nReordered List of numbers:\n\n");
for(i=0;i<n;i++) printf("i=%d x=%d\n",i+1,*(x+i));
getch();
}

void reorder(int n, int *y) //Rearrange the list of numbers


{ int
i,j,temp;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(*(y+i)<*(y+j))
{
temp=*(y+i);
*(y+i)=*(y+j);
*(y+j)=temp;
}
}

9.4 Pointers and Multidimensional Arrays

115
Prepared by: Koirala Niraj
Programming in C
A two-dimensional array is actually a collection of one-dimensional arrays. Therefore, we can
define a two-dimensional array as a pointer to a group of contiguous one-dimensional arrays. Thus
a two-dimensional array declaration can be written as
data_type (*ptrvar)[expression 2]; rather than
data_type array[expression 1][expression 2];
This concept can be generalized to higher dimensional arrays; that is,
data_type (*ptrvar)[expression 2][expression 3] . . .[expression n];
replaces
data_type array[expression 1][expression 2]. . . . [expression n];

In these declarations data_type refers to the data type of the array, ptvar is the name of the pointer
variable, array is the corresponding array name, and expression 1, expression 2, . . .
.,expression n are positive-valued integer expressions that indicate the maximum number of array
elements associated with each subscript.

Example:
Suppose x is a two-dimensional integer array having 10 rows and 20 columns. We can declare x as
int (*x)[20];
rather than
int x[10][20];
In the first declaration, x is defined to be a pointer to a group of contiguous, one-dimensional, 20-
element integer arrays. Thus, x points to the first 20-element array, which is actually the first row
(i.e., row 0,x[0]) of the original two-dimensional array. Similarly, (x+1) points to the second 20-
element array, which is the second row(row 1) of the original two-dimensional array, and so on, as
illustrated in figure:

x Ist one-dimensional array

(x+1) 2nd one-dimensional array

. . . . …………………………………………….

(x+9) 10th one-dimensional array

The item in row 2, column 5 can be accessed by writing either


x[2][5] or *(*(x+2)+5) or *(x[2]+5)
(x+2) is a pointer to row 2. Therefore the object of this pointer, *(x+2), refers to the entire row.
Since row 2 is a one dimensional array, *(x+2) is actually a pointer to the first element in row 2.
116
Prepared by: Koirala Niraj
Programming in C
We now add 5 to this pointer. Hence, (*(x+2)+5) is a pointer to element 5 (i.e., the sixth element)
in row 2. The object of this pointer, *(*(x+2)+5), therefore refers to the item in coulmn 5 of row 2,
which is x[2][5]. These relatinships are illustrated in figure:

x Ist one-dimensional array

(x+1) 2nd one-dimensional array

(x+2) 3rd one-dimensional array

*(x+2) *(*(x+2)+5) *(x+2)+5

Similarly, x[2] refers to the row 2 and x[2]+5 refers to the address of fifth element of row 2. So *(x[2]+5)
will give the fifth element of row 2.

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j; int
stud[5][2];
for(i=0;i<=4;i++)
{
for(j=0;j<=1;j++)
scanf("%d",*(stud+i)+j);
}

for(i=0;i<=4;i++)
{
printf("\n");
for(j=0;j<=1;j++)
printf("%d ",*(*(stud+i)+j));
}
getch();
}
Array of Pointers
117
Prepared by: Koirala Niraj
Programming in C
Like array of ints, floatts;we can have array of pointers. Since a pointer variable always contains
an address, an array of pointers would be nothing but a collection of addresses. The addresses
present in the array of pointers can be addresses of isolated variables or addresses of array elements
or any other addresses. All rules that apply to an ordinary array apply in to the array of pointers as
well.
Example:
#include<stdio.h>
#include<conio.h> main()
{ int *arr[4]; int
i=21,j=5,k=19,l=71,m;
arr[0]=&i; arr[1]=&j;
arr[2]=&k; arr[3]=&l;
for(m=0;m<3;m++)
printf("\n%d",*(arr[m]))
;
getch();
}
Demonstartion of Array of Pointers

Example: Matrix addition using pointer


#include<stdio.h>
#include<conio.h> #include<alloc.h>
main()
{
int *a[3],*b[3],*c[3]; int
i,j;
//Memory Allocation for first matrix
for(i=0;i<3;i++) a[i]=(int
*)malloc(3*sizeof(int)); //Read First
Matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",*(a+i)+j);
}
//Display First Matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d\t",*(*(a+i)+j));
printf("\n");

118
Prepared by: Koirala Niraj
Programming in C
}

//Memory Allocation for second matrix


for(i=0;i<3;i++) b[i]=(int
*)malloc(3*sizeof(int)); //Read Second
matrix for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",*(b+i)+j);
}
//Display Second Matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d\t",*(*(b+i)+j));
printf("\n");
}
//Memory Allocation for Resultant matrix for(i=0;i<3;i++) c[i]=(int *)malloc(3*sizeof(int)); //Matrix addition
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
*(*(c+i)+j)=*(*(a+i)+j)+*(*(b+i)+j);
}
printf("\n"); //Display
Resultant matrix
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
printf("%d\t",*(*(c+i)+j));
printf("\n");
}
getch();
}
Matrix addition using pointer and functions

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

void read(int *b[3]); void


display(int *c[3]);

119
Prepared by: Koirala Niraj
Programming in C
void add(int *d[3],int *e[3]); int
i,j;

main()
{
int *x[3],*y[3];

//Memory Allocation for first matrix


for(i=0;i<3;i++)
{
x[i]=(int *)malloc(3*sizeof(int));
y[i]=(int *)malloc(3*sizeof(int));
}
printf("Enter the elements of Matrix A:\n");
read(x); printf("\nContent of A:\n"); display(x);
printf("\nEnter the contents of Matrix B:\n");
read(y); printf("\nContent of
Matrix B:\n"); display(y);
printf("\nResult of addition is:\n");
add(x,y);
getch();
}

void read(int *b[3])


{ for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",*(b+i)+j);
}
}

void display(int *c[3])


{ for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d\t",*(*(c+i)+j)); printf("\n");
}
}

void add(int *d[3],int *e[3])

120
Prepared by: Koirala Niraj
Programming in C
{ int *c[3]; for(i=0;i<3;i++)
c[i]=(int *)malloc(3*sizeof(int));
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
*(*(c+i)+j)=*(*(d+i)+j)+*(*(e+i)+j);
}
printf("\n");
display(c);
}
Example: Matrix Multiplication
#include<stdio.h>
#include<conio.h> #include<stdlib.h>
main()
{
int *a[10],*b[10],*c[10]; int
i,j,n,r1,r2,c1,c2; void get(int
*x[10],int r,int c); void display(int
*x[10],int r,int c);
void mul(int *a[10],int *b[10],int *c[10],int row,int m,int col); printf("Siza of matrix A:\n");
scanf("%d%d",&r1,&c1); printf("Siza of matrix B:\n");
scanf("%d%d",&r2,&c2);
if(c1!=r2)
{
printf("\nMultiplication Not possible.\n\n"); printf("Columns of
Matrix A are not equal to rows of Matrix B\n");
}
else
{
printf("\nMUltiplication Possible\n\n");
for(i=0,j=0;i<r1,j<r2;i++,j++)
{
a[i]=(int *)malloc(c1*sizeof(int));
b[j]=(int *)malloc(c2*sizeof(int));
c[i]=(int *)malloc(c2*sizeof(int));
}
printf("Matrix A(%d*%d)elements?\n",r1,c1);
get(a,r1,c1);
display(a,r1,c1);

121
Prepared by: Koirala Niraj
Programming in C
printf("\n"); printf("Matrix
B(%d*%d)elements?\n",r2,c2);
get(b,r2,c2); display(b,r2,c2); printf("\n");
mul(a,b,c,r1,c1,c2); printf("Product Matrix
C(%d*%d):\n",r1,c2);
display(c,r1,c2);
getch();
}
}

void get(int *x[10],int r,int c)


{
int i,j;
for(i=0;i<r;i++) {
for(j=0;j<c;j++)
scanf("%d",x[i]+j);
}
}

void display(int *x[10],int r,int c)


{
int i,j;
for(i=0;i<r;i++)
{ for(j=0;j<r;j++)
printf("%5d",*(x[i]+j));
printf("\n");
}
}

void mul(int *a[10],int *b[10],int *c[10],int row,int m,int col)


{ int
i,j,k;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
*(c[i]+j)=0;
for(k=0;k<m;k++)
*(c[i]+j)=*(c[i]+j)+(*(a[i]+k)*(*b[k]+j));
}
}
122
Prepared by: Koirala Niraj
Programming in C
}

Passing arrays using pointers


As we passed the variables onto the function based using pointer in the same way arrays are passed
as arguments to functions, and their elements being access by the function. However, it’s more
common to use pointer notation instead of array notation when arrays are passed to the function.

#define MAX 5
void multiply_array(int *ptr); main()
{
int myArray[MAX]={10,12,14,16,18},j;
clrscr();
multiply_array(myArray);
for(j=0;j<MAX;j++)
printf(”myArray[%d]=”,myArray[j]); getch();
}

void multiply_array(int *ptr)


{ int
j;
for(j=0;j<MAX;j++)
*ptr++ *=2; /*here ptr points to elements of myArray*/
}
9.5 Pointers and strings
Strings are one-dimensional arrays of type char. In C and C++, a string is terminated by NULL or
‘\0’. String constants are written in double quotes. Suppose we want to store "Hello". We may either
store it in a string or we may ask the C compiler to store it at some location in memory and assign
the address of the string in a char pointer. This is shown below: char str[]="Hello"; char *p="Hello";
There is a subtle difference in usage of these two forms. For example, we cannot assign a string to
another, whereas, we can assign a char pointer to another char pointer. This is shown in the
following program.
main( )
{
char str1[]="Hello";
char str2[10]; char
*p="Hello"; char *q;
str2=str1; //Error
q=s; //Works
getch();
}

123
Prepared by: Koirala Niraj
Programming in C
Also, once a string has been defined it can be initialised to another set of characters. Unlike strings, such
an operation is perfectly valid with char pointers.
main( )
{
char str1[]="hello";
char *p="hello";
str1="bye"; //Error
p="bye"; //Works
getch();
}
A program to read word from the stdin and to display it in video screen using a pointer technique.
#include <stdio.h>
#include<conio.h> void
output(char *ptr);
main()
{
char s[20];
printf("Enter a word:");
scanf("%s",s);
printf("\nOutput\n");
output(s);
}

void output(char *ptr)


{
while(*ptr!=NULL)
{
printf("%c",*ptr);
ptr++;
}
}
A program to find the number of characters in a given string using a pointer method
#include <stdio.h> #include<conio.h> int output(char *ptr); main()
{
char s[20];
int k; printf("Enter a
word:"); scanf("%s",s);
printf("\nOutput\n");
k=output(s);
printf("Length=%d",k);
}

124
Prepared by: Koirala Niraj
Programming in C
int output(char *ptr)
{int l;
while(*ptr!=NULL)
{
printf("%c",*ptr);
ptr++;
l++;
}
return l;
}

Pointer to string constant


Here, the pointer pointers to string constant. Pointer is increased by whom the value is holding.
Example: main()
{
char str1[]="This is a string stored in an array";
char *str2="This is string stored using pointer";
printf("%s",str1); printf("%s",str2); str2+=5;
printf("%s",str2);
getch();
}
Example:
#include <stdio.h>
#include<conio.h> void
output(char *ptr);
main()
{
char s[]="I\'m string stored in an array";
output(s);
getch();
}
void output(char *ptr)
{
while(*ptr)
{
printf("%c",*ptr++);
}
}
A program to copy string form one array to another array
void CopyString(char *dest,char *src); main()

125
Prepared by: Koirala Niraj
Programming in C
{
char source[20],destination[20];
printf("Enter the string:");
scanf("%s",source);
CopyString(destination,source);
printf("%s",destination);
getch();
}
void CopyString(char *dest, char *src)
{
while (*src!='\0')
*dest++=*src++;
*dest='\0';
}

Example: main()
{
char *ptr2array[7]={
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
}; int j;
clrscr(); for(j=0;j<7;j++)
printf(”\n%s",ptr2array[j]);
getch();
}
Example: Breaking String using pointer notation
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h> main()
{
char *c="this is a c programming";
*c=toupper(*c);
for(int i=0;i<strlen(c);i++)
{ if(*(c+i)==32)
{
126
Prepared by: Koirala Niraj
Programming in C
*(c+i)='\n';
*(c+i+1)=toupper(*(c+i+1));
printf("\n");
}
}
printf("%s",c);
getch();
}
Pointers and structure
C language allows declaring pointer to structure just like pointer to other ordinary variables. The declaration
can be done in the following manner.
struct employee
{
char *name;
char *roll_no;
int salary;
}*emp1;

Above declaration make pointer variable *emp1 of type struct employee. Now, here *emp1 is the
pointer to the structure. So while accessing structure members we can use either (*emp1).name or
emp1->name. Here, -> is termed as the member access operator for pointers.

Same arithmetic operation can be performed with pointer for structure as for any other datatype.
Pointer to structure can perform all the operation that an ordinary pointer can do variables of
different datatype.
Example:
#include<stdio.h>
#include<conio.h> main()
{
struct book
{
char name[25];
char author[25];
int callno;
};
struct book b1={"Let us C","YK",101}; struct book *ptr;
ptr=&b1;
printf("%s\t%s\t%d\n",b1.name,b1.author,b1.callno);
printf("%s\t%s\t%d\n",b->name,b->author,b->callno);
}

127
Prepared by: Koirala Niraj
Programming in C
Example:
#include<stdio.h> #include<conio.h>
main( )
{
struct student_record
{
char name[25];
char reg_no[10];
float average; char
grade;
}student[50],*ptr;
/* ptr is a pointer of type structure student_record */ int
i,n;
printf("Number of students grades to be computed?");
scanf("%d",&n); printf("%d",n);
for(i=0;i<n;i++)
{
printf("\nStudent[%d]information:\n",i+1);
printf("Name?");
scanf("%s",student[i].name);
printf("%s\n",student[i].name);
printf("Register number?");
scanf("%s",student[i].reg_no);
printf("%s\n",student[i].reg_no);
printf("Average Score?");
scanf("%f",&student[i].average);
printf("%8.2f\n",student[i].average);
}
/* pointer 'ptr' points to student[0] */ ptr=student;
/* Assigning grades to 'n' students*/
for(ptr=student;ptr<student+n;ptr++)
{
if(ptr->average<30.0) ptr-
>grade='D';
else if(ptr->average<50.0) ptr-
>grade='C';
else if(ptr->average<70.0)
ptr->grade='B';
else
ptr->grade='A';
}
/*Displaying Student Records*/
128
Prepared by: Koirala Niraj
Programming in C
printf("\n");
printf("NAME REGISTER_NUMBER AVERAGE GRADE\n");
printf("…………………………………………………………….\n"); for(ptr=student;ptr<student+n;ptr++)
{
printf("%-20s%-10s",ptr->name,ptr->reg_no);
printf("%10.2f %c\n",ptr->average ,ptr->grade);
}
getch();
}

Passing structure to function using reference


Structures may be passed to function either by value or by reference. However, they are usually
passed by reference, i.e., the address of the structure is passed to the function. Let us consider the
employee for instance.
Example:
#include<stdio.h> #include<conio.h>
struct book
{
char name[25];
char author[25];
int callno;
};

void display(struct book *);

main()
{
struct book b1={"Let us C","YK",101};
display(&b1);
getch();
}

void display(struct book *b)


{
printf("\n%s%s%d",ptr->name,ptr->autuor,ptr->callno);
}

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

129
Prepared by: Koirala Niraj
Programming in C
float grosscalc(struct employee *);

struct employee
{
char name[20];
float basic;
float HRA;
}emp;

main()
{
float gross;
clrscr(); printf("Enter the
employee's name:");
scanf("%s",emp.name);
fflush(stdin);
printf("Enter the employee's basic salary:");
scanf("%f",&emp.basic);
fflush(stdin); printf("Enter the employee's HRA:");
scanf("%f",&emp.HRA); fflush(stdin); gross=grosscalc(&emp);
printf("The employee %s's gross salary is Rs%0.0f",emp.name,gross);
getch();
}

float grosscalc(struct employee *emp) /*emp is a pointer of type struct employee*/


{
return(emp->basic+emp->HRA); /*adds up the employee’s basic and HRA, and returns the result as
gross salary*/
}

Pointer is different from ordinary variable because we can use : In


situations when passing actual values is difficult or undesirable To
return more than one value from a function.
• To pass arrays and string conveniently from one function to another.
• To manipulate arrays more easily by moving pointers to them, instead of moving the arrays
themselves
• To create complex data structures like linked lists and binary tree etc.
• To allocate the memory as per we need (dynamic memory allocation)

130
Prepared by: Koirala Niraj
Programming in C

Module 10

Files in C

10.1 Introduction
Many applications require the information to be written or read from an auxiliary memory device.
Such information is stored on the memory device in the form of a data file. Thus, data files allow
us to store information permanently, and to access and alter that information whenever necessary.
131
Prepared by: Koirala Niraj
Programming in C
In C, an extensive set of library functions are available for creating and processing these files.
There are two different types of data files:
1. Stream-oriented (or standard) data files
2. System-oriented (or low-level) data files
Stream-oriented data files are divided into two categories:
Text Files:
-consists of consecutive characters
-these characters can be interpreted as individual data items, or as components of strings or numbers
Unformatted data files:
-organizes data into blocks containing contiguous bytes of information
-these blocks represents more complex data structures, such as array and structures.
System-oriented data files:
-are more closely related to the computer's operating system
-more complicated to work with
-A seperate set of procedures, library functions are require to process these files Here,
we will discuss only about Stream-oriented data files.
The C file system is composed of several interrelated functions. The most common of these are shown
below. They require the header file stdio.h to be included.
Name Function
fopen() Opens a file
fclose() Closes a file
putc() Writes a character to a file
fputc() Same as putc() getc() Reads a character from a file
fgetc() Same as getc()
fgets() Seads a string from a file fputs()
Writes a string from a file fseek() Seeks to a
specified byte in a file ftell() Returns the current file position
fprintf() Is to a file what printf() is to the console fscanf()
Is to a file what scanf() is to the console feof()
Return true if end-of-file is reached ferror()
Return true if an error has occured rewind() Resets the
file position indicator to the beginning
remove() Erases a file
fflush() Flushes a file

Table: Commonly used C file system functions


The FILE Pointer
The FILE pointer is the common thread that unites the C I/O system. A file pointer is a pointer to
a structure of type FILE. It points the information that defines various things about the file,
including its name, status, and the current position of the file.
Inorder to read or write files, your program needs to use file pointers.
132
Prepared by: Koirala Niraj
Programming in C
FILE *fp;

Opening a file
Before we can write a file to disk, or read it, we must open it. Opening a file establishes an
understanding between our program and the operating system about which file we are going to
access and how we are going to do it. We provide the operating system with the name of a file and
other information like whether we plan to read or write to it.
Opening a file start with the declaration of variable of type pointer to a file in the statement as:
FILE *fptr;
Then we open the file with the statement
fptr=fopen("name.txt","w");
Thus, fopen() function takes two arguments. The first argument is the name of file to be opened and
the second argument is the mode in which file has to be opened.

The table below shows the legal values for mode.

Mode Meaning
r Opens a text file for reading. The file must exist.
w Create a text file for writing. If the file exists, its contents will be written
over. If does not exist it will be created.
a Append to a text file. Data will be added to the enf of an existing file, or a new file will be
created
r+ Opens a text file for both reading and writing. The file must already exist.
w+ Opens a text file for both reading and writing. If the file exists its contents are written over.
a+ Opens a text file for both reading and appending. If file does not
exist it will be created.
rb Opens a binary file for reading. wb
Create a binary file for writing ab Append
to a binary file r+b Opens a binary file for
read/write w+b Create a binary file for
read/write a+b Append or create a binary file
for read/write.

Table: The legal values for mode


Note: Strings like "r+b" may also be represented as "rb+"

Closing a file
The fclose() function closes a stream that was opened by a call to fopen(). The fclose() function has
this prototype:
int fclose(FILE *fp);
133
Prepared by: Koirala Niraj
Programming in C
Where, fp is the file pointer returned by the call to fopen(). A return value of zero signifies a
successful close operation. The function returns EOF if an error occurs. You can use the standard
function ferror() to determine and report any problems. Generally, fclose() will fail only when a
disk has been permanently removed from the drive or there is no more space in the disk. The opened
file is closed with the following statement: fclose(fp);

10.2 Character input/Output functions in file

getc(), putc(), fgetc(), and fputc() are charcter input output functions. As a practical use of these
character input output functions we can read line of text in lowercase and convert it to uppercase, as
demonstrated in the following example.

use of getc( ) and putc( ) functions to read a line of text in lowercase and store in data file after converting it
to uppercase.
Example 1
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> #include<ctype.h>
main()
{
char ch; FILE
*fp;
fp=fopen("file1.txt","a+");
if(fp==NULL)
{
printf("cannot open file"); fclose(fp);
exit(1);
}
do
{
ch=toupper(getchar());
putc(ch,fp);
}while(ch!='\n'); clrscr();
rewind(fp);
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
getch();
}

Coping contents of one file into another. This program takes the contents of a text file and copies them
into another text file character by character
134
Prepared by: Koirala Niraj
Programming in C

Example 2
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> main()
{
char ch; FILE *fs,*ft;
fs=fopen("file1.txt","r");
if(fs==NULL)
{
printf("can not open source file\n"); exit(1);
}
ft=fopen("file2.txt","w");
if(ft==NULL)
{
printf("Cannot open target file"); fclose(ft);
exit(1);
}
while((ch=fgetc(fs))!=EOF)
fputc(ch,ft);
fclose(fs); fclose(ft);
getch();
}
In this program file1.txt is a source file which is opened in read mode and file2.txt is a destination file which
is opened in write mode.

Using feof() function


The function feof() determines when the end of the file has been encountered. The feof() function
has this prototype: int feof(FILE *fp); feof() returns true(1) if the end of the file has been reached;
otherwise, it returns 0. e.g.
while(!feof(fp)) ch=getc(fp);
The operation of feof() is illustrated in the Example 3.

10.3 String input/output function in file


Reading or writing strings of characters from and to files is easy as reading and writing individual characters.
fputs() and fgets() are string(line) input/output function in C.

The fputs() function writes the string pointed to by string variable to the specified stream. It returns
EOF if an error occurs.Since fputs() does not automatically add a new line character to the end if
the string; we must do this explicitly to read the string back from the file.
135
Prepared by: Koirala Niraj
Programming in C

The fgets() function reads a string from the specified stream until either a new line character is read
or length-1 character have been read. The function fgets() takes three arguments: the first is the
address where the string is stored, the second is the maximum length of the string, and the third is
the pointer to the structure FILE. When all the lines from the file have been read, if we attempt to
read one more time it will return NULL.

Here is a sample program that writes strings to a file using the function fputs() and reads string from the
file using fgets() function.

Example 3
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h> main()
{
char string[25]; FILE
*fp;
fp=fopen("file3.txt","a+");
if(fp==NULL)
{
puts("can not open file");
exit(1);
}
do
{
printf("Enter a string to store in data file:"); gets(string); strcat(string,"\n"); //add new line, since
fgets() does not automatically add new line character to the end of the string fputs(string,fp);
}while(*string!='\n'); rewind(fp);
while(!feof(fp))
{
fgets(string,2,fp);
puts(string);
}
fclose(fp);
getch();
}

In this example, while writing to a data file do while loop is used, which allows you to enter any
number of strings. To stop entering you have to press enter key at the beginning (i.e. new line

136
Prepared by: Koirala Niraj
Programming in C
character should appear at the beginning). Similarly strings can be read from the data file until the
end-of-file is reached.

Using rewind() function


The rewind() function resets the file position indicator to the beginning of the file specified as its
arguments. That is, it "rewinds" the file. Its protype is void rewind(FILE *fp); where fp is a
valid file pointer.
In Example 1 and Example 3 the rewind() function is used after input is complete to move file position
indicator at the beginning so that data can be read from the beginning.

10.4 Formatted Disk I/O Functions in file


For formatted reading and writing of characters, strings, integers, float, there exist two functions:
fscanf() and fprintf(). Here is a sample program which illustrates the use of these functions.
Program to write information to a file and read from using formatted Input/Output. Example
4
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> main()
{
char choice;
char name[40];
int age; float
height; FILE
*fp;
fp=fopen("myname.txt","w+"); do
{
printf("\nEnter name:");
scanf("%s",name); fflush(stdin);
printf("\nEnter age:");
scanf("%d",&age); fflush(stdin);
printf("\nEnter height:");
scanf("%f",&height); fflush(stdin);
printf("\nDo you wish to continue:");
scanf("%c",&choice);
fprintf(fp,"%s\t%d\t%f",name,age,height);
}while(choice=='Y'||choice=='y'); rewind(fp);
while(!feof(fp))
{
fscanf(fp,"%s%d%f",name,&age,&height);
printf("\n%s\t%d\t%0.2f",name,age,height);
}
137
Prepared by: Koirala Niraj
Programming in C
fclose(fp);
getch();
}
In this program the function fprintf() writes the values of three variables to the file. This function
is similar to printf(), except that a FILE pointer is included as the first argument.The function
fflush() is designed to remove or flush out any data remaining in the buffer. The argument to
fflush() must be the buffer which we want to flush out. Here we use 'stdin', which means buffer
related with standard input device, the keyboard. The fscanf() function is used to read the data from
the disk. This function is similar to scanf(), except that, as with fprintf(), a pointer to FILE is
included as the first argument.

10.5 Record Input/Output functions in file


In above cases we found that storing number in the format provided by formatted Input/Output
functions take up a lot of disk space, because each digit is stored as a character. Similarly, formatted
Input/Output has another problem: there is not direct way to read and write complex data types
such as arrays and structures. Arrays can be handled but inefficiently by writing each array element
one at a time.
A possible solution for this problem is record input/output, which is sometimes called "block
input/output". Record input/output writes number to disk file in binary(or "untranslated") format,
so that integers are stored in 4 bytes, floating point number in 4 bytes, and so on for the other
numerical types. Record I/O also permits writing any amount of data at once. Array, structures, and
other data constructions can be written with a single statement. The functions used for this purpose
are fread() and fwrite().

fread() and fwrite()


To read and write data types that are longer than one byte, the C file system provides two functions:
fread() and fwrite(). These functions allow the reading and writing of blocks of any type of data
(they are used for reading/writing records with binary file). The following program writes and reads
data to and from binary file.
Program to write and read the data of structure to and from data file Example
5
#include<stdio.h>
#include<conio.h> #include<stdlib.h>
struct employee
{
char name[40]; int
age;
float basicsal;
};
main()
{
struct employee e; FILE *fp;
char choice;
138
Prepared by: Koirala Niraj
Programming in C
fp=fopen("employee.txt","a+b");
if(fp==NULL)
{
printf("Can not open file!"); exit(0);
}
do
{
printf("Enter name,age, and basic salary:\n"); scanf("%s%d%f",e.name,&e.age,&e.basicsal);
fwrite(&e,sizeof(e),1,fp); fflush(stdin);
printf("Add another record(Y/N)");
scanf("%c",&choice);
}while(choice=='Y'||choice=='y');

rewind(fp); //Moves file pointer to the beginning to read from the beginning

while(!feof(fp))
{
fread(&e,sizeof(e),1,fp); printf("\n%s\t%d\t%f",e.name,e.age,e.basicsal);
}
fclose(fp);
getch();
}
The information obtained about the employee from the keyboard is placed in the structure variable e. Then,
the following statement writes the structure to the file.
fwrite(&e,sizeof(e),1,fp);
Here, the first argument is the address of the structure to be written to the disk. The second argument
is the size of the structure in bytes. Instead of counting the bytes occupied by the structure ourselves,
we let the program do it for us by using sizeof() operator, which gives the size of the variable in
bytes. The third argument is the number of such structures that we want to write at one time. In this
case, we want to write only one structure at a time. The last argument is the pointer to the file we
want to write to.
The fread() function causes the data read from the disk to be placed in the structure variable e. The
format of fread() is same as fwrite(). The function fread() returns the number of records read. If
we have reached the end of file, since fread() can not read anything, it returns 0.

Program on reading and wrting arrays with record I/O functions Example
6
#include<stdio.h>
#include<conio.h> #include<stdlib.h>
int table[10]={1,2,3,4,5,6,7,8,9,10}; main()
{

139
Prepared by: Koirala Niraj
Programming in C
FILE *ftp;
ftp=fopen("table.txt","wb+");
if(ftp==NULL)
{
printf("Can not open file"); exit(0);
}
else
fwrite(table,sizeof(table),1,ftp); printf("Data has been
written on file successfully....\n"); rewind(ftp);
while(!feof(ftp))
fread(table,sizeof(table),1,ftp);
for(int i=0;i<10;i++)
{
printf("%d\t",table[i]);
}
fclose(ftp);
getch();
}

ftell() function
ftell() returns the current file pointer for stream. The offset is measured in bytes from the beginning
of the file (if the file is binary). Its prototype is
long int ftell(FILE *stream);
The value returned by ftell can be used in a subsequent call to fseek.
ftell returns the current file pointer position on success. It returns -1L on error and sets the global variable
errno to a positive value.
In the event of an error return the global variable errno is set to one of the following values:
EBADF Bad file pointer
ESPIPE Illegal seek on device

/* ftell example */
#include <stdio.h> main()
{
FILE *stream; stream = fopen("MYFILE.TXT", "w+");
fprintf(stream, "This is a test"); printf("The file pointer
is at byte %ld\n", ftell(stream)); fclose(stream);
getch();
}

fseek() function
Repositions a file pointer on a stream.
140
Prepared by: Koirala Niraj
Programming in C
fseek() sets the file pointer associated with stream to a new position that is offset bytes from the file
location given by origin.
Syntax:
int fseek(FILE *stream, long offset, int origin); offset is the number of bytes
from the origin that will become the new current position.
For text mode streams offset should be 0 or a value returned by ftell().
origin must be one of the values 0, 1, or 2 which represent three symbolic constants (defined in stdio.h) as
follows:

Constant Origin File location


SEEK_SET 0 File beginning
SEEK_CUR 1 Current file pointer position
SEEK_END 2 End-of-file
After fseek the next operation on an update file can be either input or output.
Return Value fseek returns 0 if the pointer is successfully moved and
nonzero on failure.

Random File Processing


Example 7
#include<stdio.h> #include<conio.h>
struct employee
{
char name[10]; char
address[15]; long int
phone; char
qualification[10];
}emp[5],emp1;
main()
{
int endposition,current_position,total_no,n,i; FILE
*fptr;
fptr=fopen("random.txt","a+"); char
choice;
for(i=0;i<5;i++)
{
printf("Enter the name:");
scanf("%s",emp[i].name); printf("Enter the
address:"); scanf("%s",emp[i].address);
printf("Enter Phone No:");
scanf("%ld",&emp[i].phone); printf("Enter
Qualification:");
scanf("%s",emp[i].qualification);

141
Prepared by: Koirala Niraj
Programming in C
fwrite(&emp[i],sizeof(struct employee),1,fptr);
clrscr();
}
rewind(fptr); fseek(fptr,0,SEEK_END);
endposition=ftell(fptr);
total_no=endposition/sizeof(struct employee);
do
{
printf("There are %d structures,which u want to view?",total_no);
scanf("%d",&n); current_position=(n-1)*sizeof(struct employee);
fseek(fptr,current_position,SEEK_SET);
fread(&emp1,sizeof(struct employee),1,fptr); printf("\n The name
is %s\n",emp1.name);
printf("The address is %s\n",emp1.address);
printf("The phone no is %ld\n",emp1.phone);
printf("The qualification is %s\n",emp1.qualification);
fflush(stdin); printf("Do u want to see some other
records(Y/N):"); scanf("%c",&choice); clrscr();
}while(choice=='Y'||choice=='y'); fclose(fptr);
getch();
}

142
Prepared by: Koirala Niraj

You might also like