Professional Documents
Culture Documents
Module 1
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 circle)
FLOWING SYMBOL Indicates the direction of the
flow of the program
(arrows)
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.
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
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.
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.
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.
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
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.
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.
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
i. Integer constants: Integer constants are whole numbers without any fractional parts.
9
Prepared by: Koirala Niraj
Programming in C
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
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;
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.
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".
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
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.
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
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.
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.
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).
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.
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
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 (?:)
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.
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
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.
29
Prepared by: Koirala Niraj
Programming in C
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--)
30
Prepared by: Koirala Niraj
Programming in C
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.
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
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.
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.
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.
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();
}
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:
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();
}
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();
}
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( );
}
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.
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.
#include<stdio.h> #include<conio.h>
void main()
{
int n,i,count=0; float
x, average, sum=0;
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.
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.
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.
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
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.
54
Prepared by: Koirala Niraj
Programming in C
6.2 One dimensional and Multidimensional Array
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();
}
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 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
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},
};
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();
}
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:
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);
}
#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
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
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.
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
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>
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.
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
73
Prepared by: Koirala Niraj
Programming in C
float add(float c, float d) {
float result; result=c+d;
return result;
}
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.
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.
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);
}
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 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]);
}
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>
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]);
}
}
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.
#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();
}
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;
};
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
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);
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;
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
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.
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
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,
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
The above declaration variable emp_date_of_birth has now become the type of structure add.
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.
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;
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();
}
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.
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) 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
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
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 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.
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
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*/
}
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
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 */
}
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();
}
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.
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();
}
#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();
}
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.
#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();
}
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:
. . . . …………………………………………….
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
118
Prepared by: Koirala Niraj
Programming in C
}
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
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];
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();
}
}
#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();
}
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);
}
124
Prepared by: Koirala Niraj
Programming in C
int output(char *ptr)
{int l;
while(*ptr!=NULL)
{
printf("%c",*ptr);
ptr++;
l++;
}
return l;
}
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();
}
main()
{
struct book b1={"Let us C","YK",101};
display(&b1);
getch();
}
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();
}
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
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.
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.
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);
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.
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.
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:
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