c_notes
c_notes
1
CMP 103.3 Programming in C (3-0-3)
Evaluation:
Theory Practical Total
Session 30 20 50
al
Final 50 - 50
Total 80 20 100
Course Objectives:
The object of this course is to acquaint the students with the basic principles of programming and
development of software systems. It encompasses the use of programming systems to achieve specified
goals, identification of useful programming abstractions or paradigms, the development of formal
models of programs, the formalization of programming language semantics, the specification of
program, the verification of programs, etc. the thrust is to identify and clarify concepts that apply in
many programming contexts:
Chapter Content Hr
s.
1 Introduction 3
History of computing and computers, programming, block diagram of computer,
generation of computer, types of computer, software, Programming
Languages, Traditional and structured programming concept
2 Programming logic 5
Problems solving(understanding of problems, feasibility and requirement
analysis) Design (flow Chart & Algorithm), program coding (execution,
translator), testing and debugging, Implementation, evaluation and
Maintenance of programs, documentation
3 Variables and data types 3
Constants and variables, Variable declaration, Variable Types, Simple
input/output function, Operators
4 Control Structures 6
Introduction, types of control statements- sequential, branching- if, else, else-if
and switch statements, case, break and continue statements; looping- for
loop, while loop, do—while loop, nested loop, goto statement
6 Functions 6
Introduction, returning a value from a function, sending a value to a function,
Arguments,
parsing arrays and structure, External variables, storage classes, pre-processor
directives, C libraries, macros, header files and prototyping
Pokhara University/Faculty of Science & Technology/Revised Syllabus-2012/Programming in C 1
7 Pointers 7
Definition pointers for arrays, returning multiple values form functions using pointers.
Pointer arithmetic, pointer for strings, double indirection, pointer to arrays, Memory
allocation-malloc and calloc
Textbooks:
1. Programming with C, Byran Gottfried
2. C Programming, Balagurusami
References
1. A book on C by A L Kely and Ira Pohl
2. The C Programming Language by Kerighan, Brain and Dennis Ritchie
3. Depth in C, Shreevastav
2 Programming Logic 10
2.1 Understanding of problems, Feasibility and Requirement Analysis.................10
2.2 Design FlowChart and Algorithm.................................................................10
2.3 Program Coding.................................................................................................. 11
2.4 Testing and Debugging.......................................................................................11
2.5 Implementation.........................................................................................................11
2.6 Evaluation and Maintenance.............................................................................12
2.7 Documentation..........................................................................................................12
4 Control Statements in C 20
4.1 Branching Structure............................................................................................ 20
4.1.1 if Statement............................................................................................ 20
4.1.2 if..else Statement..........................................................................................21
4.1.3 if..else if..else Statement..............................................................................22
4.1.4 Nested if Statement...............................................................................22
4.1.5 Switch Statement...................................................................................22
4.1.6 The ? : Operator....................................................................................23
4.2 Looping Structure............................................................................................... 24
4
4.2.1 while loop.....................................................................................................24
4.2.2 for loop.........................................................................................................25
4.2.3 do while loop................................................................................................25
4.2.4 nested loop...................................................................................................26
4.3 Break Continue and Goto Statement................................................................27
4.3.1 Break Statement.....................................................................................27
4.3.2 Continue Statement...............................................................................28
4.3.3 Goto Statement......................................................................................30
6 Function 36
6.1 Function Definition............................................................................................. 36
6.2 Types of C function......................................................................................36
6.2.1 Library Function................................................................................36
6.3 User Defined Function........................................................................................ 36
6.4 Defining a Function............................................................................................ 36
6.5 Calling a function................................................................................................ 37
6.6 Call by Value.................................................................................................37
6.7 Call by Reference..........................................................................................37
6.8 Passing array as an argument to a function.....................................................38
6.9 Storage Class in C.........................................................................................38
6.9.1 auto...............................................................................................................38
6.9.2 register..........................................................................................................38
6.9.3 static........................................................................................................ 39
6.9.4 extern............................................................................................................39
6.10 Recursion............................................................................................................ 39
6.10.1 Factorial Using Recursion.......................................................................39
6.10.2 Fibonacci Series Using Recursion...........................................................40
6.11 Preprocessor Directives...................................................................................... 40
6.12 Macro Substitution............................................................................................. 41
7 Pointer 42
7.1 Using Pointers..................................................................................................... 42
7.2 Null Pointer......................................................................................................... 43
7.3 Pointer Arithmetic.............................................................................................. 43
7.3.1 Incrementing Pointer..............................................................................43
7.3.2 Decrementing a Pointer.........................................................................44
7.4 Definition Pointer to Arrays...............................................................................44
7.5 Returning Multiple Values from a function.......................................................45
7.6 Pointer to String................................................................................................. 45
7.7 Double pointer..........................................................................................................46
7.8 Dynamic Memory Allocation..............................................................................46
7.8.1 Malloc............................................................................................................46
7.8.2 Calloc.................................................................................................47
5
6
7.8.3 free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
9 File Handling in C 53
9.1 Opening a File in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
9.2 Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
9.3 Writing Character by Character in File . . . . . . . . . . . . . . . . . . 54
9.4 Reading and Writing From a file using fprintf() and fscanf() . . . . 54
9.5 fread() and fwrite() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
List of Figures
1 Block Diagram of Computer . . . . . . . . . . . . . . . . . . . . . . . . 7
2 Flow chart Basic Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3 FlowChart Control Statement . . . . . . . . . . . . . . . . . . . . . . . 20
4 if statement flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5 If else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
6 switch statement flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . 23
7 while loop flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
8 for loop flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
9 do..while loop flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
10 Flowchart Break Statement . . . . . . . . . . . . . . . . . . . . . . . . . 27
11 Working of Break Statement . . . . . . . . . . . . . . . . . . . . . . . . 28
12 Flowchart Continue Statement . . . . . . . . . . . . . . . . . . . . . . . 29
13 Working of Continue Statement . . . . . . . . . . . . . . . . . . . . . . . 30
14 Arrays Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
15 Arrays Initialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
16 Arrays Initialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
17 String Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
18 C program Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
List of Tables
1 Data types in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Preprocessor Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3 Function Dynamic Memory Allocation . . . . . . . . . . . . . . . . . . . 47
4 Difference between structure and union . . . . . . . . . . . . . . . . . . 53
5 File opening modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
7
1 Introduction
1.1 Computer
Basically it is a fast calculating machine which is now a days used for variety of uses ranging
from house hold works to space technology. The credit of invention of this machine goes to
the English Mathematician Charles Babbage.
Based on application computers are classified as special purpose computers and gen- eral
computers. As the name tells special computers are designed to perform certain specific tasks
where as the other category is designed to cater the needs of variety of users.
The main components of a computer are Input unit (IU), Central Processing unit (CPU) and
Output unit (OU). The information like data, programs etc are passed to the com- puter
through input devices. The keyboard, mouse, floppy disk, CD, DVD, joystick etc
8
are certain input devices. The output device is to get information from a computer after
processing . VDU (Visual Display Unit), Printer, Floppy disk, CD etc are output devices.
The brain of a computer is CPU. It has three components- Memory unit, Control unit and
Arithmetic and Logical unit (ALU)- Memory unit also called storage device is to store
information. Two types memory are there in a computer. They are RAM (ran- dom access
memory) and ROM (read only memory). When a program is called, it is loaded and processed
in RAM. When the computer is switched off, what ever stored in RAM will be deleted.So it is
a temporary memory. Where as ROM is a permanent memory, where data, program etc are
stored for future use. Inside a computer there is storage device called Hard disk, where data
are stored and can be accessed at any time.
The control unit is for controlling the execution and interpreting of instructions stored in the
memory. ALU is the unit where the arithmetic and logical operations are per- formed.The
information to a computer is transformed to groups of binary digits, called bit. The length of
bit varies from computer to computer, from 8 to 64. A group of 8 bits is called a Byte and a
byte generally represents one alphanumeric ( Alphabets and Numerals) character. The physical
components of a computer are called hardwares. But for the machine to work it requires
certain programs ( A set of instructions is called a program ). They are called softwares. There
are two types of softwares – System soft- ware and Application software – System software
includes Operating systems, Utility programs and Language processors.
9
1.4.2 High level Language
These languages are machine independent, means it is portable. The language in this category is
Pascal, Cobol, Fortran etc. High level languages are not understood by the machine. So it needs to
translate by the translator into machine level. A translator is software which is used to translate
high level language as well as low level language in to machine level language.
11
2 Programming Logic
Problems solving
First and foremost step of solving a problem is knowing about the nature of problem in order
to solve it. Almost all types of problems can be solved with computer. However, correct
formulation of the problem in computer understandable terms is essential to formulate the
problem and solve it using computer.
1. Pseudocode English like steps that describe the solution.Pseudocode is an ar- tificial and
informal language that helps programmers develop algorithms. Pseu- docode is a ”text-
based” detail (algorithmic) design tool.The rules of Pseudocode are reasonably
straightforward. All statements showing ”dependency” are to be indented. These include
while, do, for, if, switch.
Set t o t a l to zero
Set grade counter to one
While grade counter i s l e s s than or equal to ten Input the next
grade
Add the grade in to the t o t a l
Set the c l a s s average to the t o t a l d i v i d e d by ten Print the c l
a s s average .
2. FlowChart Pictures Detailing with specific blocks detailing out the logical flow of the
solution. For a better understanding of an algorithm, it is represented pictorially.The
pictorial representation of an algorithm is called a Flow Chart. The algorithm and
flowchart to add two numbers can be stated as:
Various symbols can be used to represent different actions like taking input, making decisions
and connecting flowcharts.
12
Figure 2: Flow chart Basic Symbols
The flow chart for the addition of two numbers whose algorithm has been stated above can be
drawn as.
13
2.3 Pseudocode
Pseudo code is a high-level description of a computer program that uses human-readable
instructions to describe the logic of the program without using a specific programming language.
Pseudo code is often used to help programmers plan out the structure and flow of their code
before actually writing it in a particular language. Here is an example of a simple pseudo code
program that adds two numbers together:
Example:
Start
Declare variables num1, num2, sum
Input num1
Input num2
End
here is an example of pseudocode for a complex program that calculates the average grade of a class
of students:
Start
Declare variables numStudents, totalGrade, averageGrade, studentGrade
Input numStudents
Set totalGrade = 0
14
For i = 1 to numStudents do:
Input studentGrade
Set totalGrade = totalGrade + studentGrade
End For
End
2.6 Implementation
After a program has been written and tested it needs to be implemented to the target
environment to solve the problem. Various needs of physical hardware and accessories
required by the program to solve the intended problem needs to be present upon imple-
mentation. Once the program is implemented it starts to work.
15
2.7 Evaluation and Maintenance
The evaluation of the performance of the program needs to be done at frequent interval once the
program or software is implemented. The advent of new technology, upscaling and downscaling
of the business, request for the change from customers, finding of a new bug are the major
reasons for the maintenance and change of the softwares. Once changes have been continuous
monitoring of the software performance needs to done to discover the flaws in the software.
2.8 Documentation
The same workforce that developed the program may have left the project and gone in search
of opportunities. So a program must be well documented in order for the new people to
understand how the software was developed and how can it be modified. The documentation
start from the very beginning of the problem formulation to the very end of the Evaluation
and Maintenance.
Lab Works
• Designing algorithm and draw flow chart for sequence, decision making and repetition
concept of general programming.
16
3 Variables and Data Types
3.1 Constant and Variables
The smallest meaningful units in C programming is called C Token. Keywords, vari- ables,
various special characters fall under c tokens.
Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals. Constants can be of any of the basic data types like an integer
constant, a floating constant, a character constant, or a string literal. There are enumeration
constants as well.Constants are treated just like regular variables except that their values
cannot be modified after their definition.
A variable is nothing but a name given to a storage area that our programs can ma- nipulate.
Each variable in C has a specific type, which determines the size and layout of the variable’s
memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable.The name of a variable can be composed of letters, digits,
and the underscore character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C is case-sensitive.
Type Size(Byte) Range
char 1 -127 to 127
int 2 -32,767 to 32,767
float 4 1*10−37 to 1*1037
six
digit precision
double 8 1*10−37 to 1*1037 ten
digit precision
long int 4 -2,147,483,647
to
2,147,483,647
a = 10;
b = 20;
17
c= a + b;
p r i n t f (” value o f c : %d \n” , c ) ; f = 7 0 . 0 / 3 . 0 ;
p r i n t f (” value o f f : %f \n” , f ) ; return 0 ;
}
3.5 Operators in C
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of
operators.
• Arithmetic Operator
• Relational Operator
• Logical Operator
• Bitwise Operator
• Assignment Operator
• Misc Operator
18
3.5.1 Arithmetic Operator
The basic operators for performing arithmetic are the same in many computer languages:
1. + Addition
2. - Subtraction
3. * Multiplication
4. / Division
5. % Modulus (Remainder)
For exponentiations we use the library function pow. The order of precedence of these
operators is % / * + - . it can be overruled by parenthesis.
Division of an integer quantity by another is referred to integer division. This operation results
in truncation. i.e.When applied to integers, the division operator / discards any remainder, so 1
/ 2 is 0 and 7 / 4 is 1. But when either operand is a floating-point quantity (type float or double
), the division operator yields a floating-point result, with a potentially nonzero fractional
part. So 1 / 2.0 is 0.5, and 7.0 / 4.0 is 1.75.
A operator acts up on a single operand to produce a new value is called a unary operator.
The decrement and increment operators - ++ and – are unary operators. They increase
and decrease the value by 1.
sizeof() is another unary operator. The output given by the sizeof() operator de- pends on
the computer architecture. The values stated by sizeof() operator down below are based on a
16 bit compiler.
1 int x , y ;
2 y=sizeof ( x ) ;
The value of y is 2. The sizeof() of an integer type data is 2 that of float is 4, that of double is 8,
that of char is 1.
1. && AND
19
2. || OR
3. ! NOT
The && (‘‘and’’) operator takes two true/false values and produces a true (1)
result if both operands are true (that is, if the left- hand side is true and the
right-hand side is true). The || (‘‘or’’) operator takes two true/false values and
produces a true (1) result if either operand is true. The ! (‘‘not’’) operator
takes a single true/false value and negates it, turning false to true and true to
false (0 to 1 and nonzero to 0).
&& (and ) and || (or) are logical operators which are used to connect logical expressions. Where
as ! ( not) is unary operator, acts on a single logical expression.
1 ( a <5) && ( a >2)
2 ( a<=3) | | ( a >2)
In the example if a= 3 or a=6 the logical expression returns true.
20
3.6 Operator Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has a higher precedence than the addition operator.
5 char pla ce [ 8 0 ] ;
6 int i;
7 for ( i = 0 ; ( pla ce [ i ] = ge t c h ar ( ) ) ! =‘\n ‘ , ++i ) ;
8 }
21
3.7.2 putchar() function
It is used to display single character. The syntax is
putchar(char c);
4{
5 char alphabet ;
6 p r i n t f ( ” Enter an alphabet ” ) ;
7 putchar ’ \ n ’ ) ;
8 alphabet=getchar ( ) ;
9 putchar ( alphabet ) ;
10 }
12 }
4{
5 int x ;
6 s c a n f ( ”%d”,&x ) ;
7 x=x ∗ x ;
8 p r i n t f ( ”The square o f the number i s %d” , x ) ;
9 }
22
Note that in this list of arguments the variable names are without & symbol unlike in the
case of scanf( ) function. In the conversion string one can include the message to be
displayed. In the above example ”The square of the number is” is displayed and is followed by
the value of x.
5 char s t r [ 5 0 ] ;
6 p r i n t f ( ” Enter a s t r i n g : ”);
7 g e ts ( s t r ) ;
8 p r i n t f ( ”You entered : %s ” , str );
9 return ( 0 ) ;
10 }
The C library function int puts() writes a string to stdout up to but not including the null
character. A newline character is appended to the output.
1 #include < s t d i o . h>
2 #include < s t r i n g . h>
3 int main ()
4{
5 char s t r 1 [ 1 5 ] ;
6 char s t r 2 [ 1 5 ] ;
7 s trcpy ( str 1 , ” Nepal” ) ;
8 s trcpy ( str 2 , ” Online ” ) ;
9 puts ( s t r 1 ) ;
10 puts ( s t r 2 ) ;
11 return ( 0 ) ;
12 }
23
4 Control Statements in C
C provides two types of Control Statements
• Branching Structure
• Looping Structure
4.1.1 if Statement
An if statement consists of a Boolean expression followed by one or more statements.If the
Boolean expression evaluates to true, then the block of code inside the ’if’ statement will be
executed. If the Boolean expression evaluates to false, then the first set of code after the end
of the ’if’ statement (after the closing curly brace) will be executed. C programming language
assumes any non-zero and non-null values as true and if it is either zero or null, then it is
assumed as false value.
1 #include < s t d i o . h>
2 int main () {
3 int a = 1 0 ;
4 i f ( a < 20 ) {
5 p r i n t f ( ”a i s l e s s than 20\ n” ) ;
6 }
7 p r i n t f ( ” value o f a i s : %d \ n” , a ) ;
8 return 0 ;
9 }
24
Figure 4: if statement flowchart
25
14 p r i n t f ( ”None o f the value s i s matching \n” ) ;
15
}
16 p r i n t f ( ” Exact value o f a i s : %d
\ n” , a ) ;
17 return 0 ;
18 }
26
Figure 6: switch statement flowchart
6 case ’A’ :
7 p r i n t f ( ” Exc e l l e n\ t ! n” ) ;
8 break ;
9 case ’B ’ :
10 case ’C ’ :
11 p r i n t f ( ” Well done \ n” ) ;
12 break ;
13 case ’D’ :
14 p r i n t f ( ”You passed\ n” ) ;
15 break ;
16 case ’F ’ :
17 p r i n t f ( ” Better try again \ n” ) ;
18 break ;
19 default :
20 p r i n t f ( ” In va l id grade \n” ) ;
21 }
22 p r i n t f ( ”Your grade is %c\ n” , grade );
23 return 0 ;
24 }
• Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of
the entire ? expression.
• If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the
expression.
27
4.2 Looping Structure
Programming languages provide various control structures that allow for more compli- cated
execution paths. A loop statement allows us to execute a statement or group of statements
multiple times.C programming language provides the following types of loops to handle looping
requirements.
• while loop
• do while loop
• for loop
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately
following the loop.Here, the key point to note is that a while loop might not execute at all.
When the condition is tested and the result is false, the loop body will be skipped and the first
statement after the while loop will be executed. flow chart and program remaining
28
4.2.2 for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
1 for ( i n i t ; c o n d i t io n ; increment ){
2 statement ( s ) ;
3 }
1. The init step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and the flow of control jumps to the next
statement just after the ’for’ loop.
3. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and the flow of control jumps to the next
statement just after the ’for’ loop.
4. The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes false, the ’for’ loop terminates.
29
do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at
least one time.
1 do {
2 statement ( s ) ;
3 } while ( c o n d i t io n ) ;
Notice that the conditional expression appears at the end of the loop, so the statement(s) in
the loop executes once before the condition is tested.If the condition is true, the flow of
control jumps back up to do, and the statement(s) in the loop executes again. This process
repeats until the given condition becomes false.
3 while ( c o n d i t io n {
)
4 statement ( s ) ;
5 }
6
7 statement ( s ) ;
8 }
30
1 do {
2
3 statement ( s ) ;
4
5 do {
6 statement ( s ) ;
7 } while ( c o n d i t io n ) ;
8
9 } while ( c o n d i t io n ) ;
int main () {
2
3 /∗ l o c a l v a r i a b l e d e f i n i t i o n /
4 int i , j ;
5 for ( i = 2 ; i <100; i++) {
6 for ( j = 2 ; j <= ( i / j ) ; j++)
7 i f ( ! ( i%j )) break ; // i f f a c t o r found , not prime
8 i f ( j > ( i / j )) p r i n t f ( ”%d i s prime \n” , i ) ;
9 }
10 return 0 ;
11 }
31
1 // Program to c a l c u l a t e the sum o f maximum o f 10 numbers
2 // C a l c u l a t e s sum u n t i l user e n t e r s p o s i t i v e number
3 # include < s t d i o . h>
4 int main ()
5{
6 int i;
7 double number , sum = 0 . 0 ;
9{
10 p r i n t f ( ” Enter a n%d : ” , i ) ;
11 s c a n f ( ”%l f ”,&number ) ;
12 // I f user e n t e r s n e g a t i v e number , loop i s terminated
13 i f ( number < 0 . 0 )
14 {
15 break ;
16 }
18 }
32
Example of Continue Statement
4 int main ()
5{
6 int i;
7 double number , sum = 0 . 0 ;
9{
10 p r i n t f ( ” Enter a n%d : ” , i ) ;
11 s c a n f ( ”%l f ”,&number ) ;
12 // I f user e n t e r s n e g a t i v e number , loop i s terminated
13 i f ( number < 0 . 0 )
14 {
15 continue ;
16 }
18 }
33
Figure 13: Working of Continue Statement
6 int i;
7 double number , average , sum= 0 . 0 ;
8 for ( i =1; i<=maxInput ; ++i )
9{
14 goto jump ;
16 }
17 jump :
18 average=sum/( i − 1 );
34
20 p r i n t f ( ” Average = %.2 f ” , average ) ;
21 return 0 ;
22 }
1. The use of goto statement may lead to code that is buggy and hard to follow.
35
5 Arrays and Strings
Arrays a kind of data structure that can store a fixed-size sequential collection of ele- ments of
the same type. An array is used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same type.Instead of declar- ing individual
variables, such as number0, number1, ..., and number99, you declare one array variable such
as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables. A specific element in an array is accessed by an index.All arrays consist of contiguous
memory locations. The lowest address corresponds to the first element and the highest
address to the last element.
36
5.2 MultiDimensional Array
C programming language allows programmer to create arrays of arrays known as mul-
tidimensional arrays.
1 f loat a [ 2 ] [ 6 ] ;
18 i f ( n != p)
19 p r i n t f ( ” can ’ t be m u l t ip l i e d with each other
\ . n” ) ;
20 else
21 {
22 p r i n t f ( ” Enter the e lements o f second matrix\n” ) ;
23
24 for ( c = 0 ; c < p ; c++)
25 for ( d = 0 ; d < q ; d++)
26 s c a n f ( ”%d” , &second [ c ] [ d ] ) ;
27
34 m u l t i p l y [ c ] [ d ] = sum ;
35 sum = 0 ;
36 }
37 }
38
45 p r i n t f ( ”\n” ) ;
46 }
47 }
48
49 return 0 ;
50 }
5.3 String
Strings are actually one-dimensional array of characters terminated by a null character. Thus a
null-terminated string contains the characters that comprise the string followed by a null.The
following declaration and initialization create a string consisting of the word ”Hello”. To hold
the null character at the end of the array, the size of the character array containing the string is
one more than the number of characters in the word ”Hello.”
38
1 char g r e e t in g [ 6 ] = ” He l lo ” ;
2 char g r e e t in g [ 6 ] ={ ’H’ , ’ e ’ , ’ l ’ , ’ l ’ , ’ o ’ , ’ \0 ’ };
5 p r i n t f ( ”%s ” , g r e e t in g ) ;
6 puts ( g r e e t in g ) ;
5.3.2 String related fuctions
• strcpy(s1,s2) copies string s2 into the string s1.
• strcat(s1,s2) concatenates string s2 onto the end of string s1
• strlen(s1) returns the length of string s1
• strcmp(s1,s2) returns 0 if s1 and s2 are the same, less than 0 if s1<s2 and greater than 0
if s1>s2
• strrev(s1) reverses the string s1 and places it in s1
39
6 Function
6.1 Function Definition
A function is a group of statements that together perform a task. Every C program has at
least one function, which is main(), and all the most trivial programs can define additional
functions.A function declaration tells the compiler about a function’s name, return type, and
parameters. A function definition provides the actual body of the function.
40
• Parameters A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument.
The parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
• Function Body The function body contains a collection of statements that define what the
function does.
7 int main () {
8 int a=10;
9
10 p r i n t f ( ”a = %d b e f o re f u n c t io\ n . n” , a ) ;
11 call by value(a);
12 p r i n t f ( ”a = %d a f t e r f u n c t io\n . n” , a ) ;
13 return 0 ;
14 }
In the main() we create a integer that has the value of 10. We print some information at every
stage, beginning by printing our variable a. Then function call by value is called and we input
the variable a. This variable (a) is then copied to the function variable x. In the function we
add 10 to x (and also call some print statements). Then when the next statement is called in
main() the value of variable a is printed. We can see that the value of variable a isn’t
changed by the call of the function call by value().
41
7 int main () {
8 int b=10;
9 p r i n t f ( ”b = %d b e f o re f u n c t io\ n . n” , b ) ;
10 c a l l b y r e f e r e n c e (&b ) ;
11 p r i n t f ( ”b = %d a f t e r f u n c t io \n . n” , b ) ;
12 return 0 ;
13 }
We start with an integer b that has the value 10. The function call by reference() is called and
the address of the variable b is passed to this function. Inside the function there is some before
and after print statement done and there is 10 added to the value at the memory pointed by y.
Therefore at the end of the function the value is 20. Then in main() we again print the variable b
and as you can see the value is changed (as expected) to 20.
6.9.2 register
The register storage class is used to define local variables that should be stored in a register
instead of RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and can’t have the unary ’&’ operator applied to it (as it does not have a
memory location).
1 {
2 register int mile s ;
3 }
42
The register should only be used for variables that require quick access such as counters. It
should also be noted that defining ’register’ does not mean that the variable will be
stored in a register. It means that it MIGHT be stored in a register depending on hardware and
implementation restrictions.
6.9.3 static
The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope. Therefore, making local variables static allows them to maintain their values
between function calls.The static modifier may also be applied to global variables. When this is
done, it causes that variable’s scope to be restricted to the file in which it is declared.In C
programming, when static is used on a class data member, it causes only one copy of that
member to be shared by all the objects of its class.
1 #include < s t d i o . h>
2 void func ( void ) ;
3 s t a t ic int count = 5 ; /∗ g l o b a l v a r i a b l e /
4 main () {
5 while ( count−−)
6 func ( ) ; {
7 }
8 return 0 ;
9 }
10 /∗ f u n c t i o n d e f i n i t i o n /
11 void func ( void ) {
12 s t a t ic int i = 5 ; /∗ l o c a l s t a t i c v a r i a b l e /
13 i ++;
14 p r i n t f ( ” i i s %d and count i s %d\n” , i , count ) ;
15 }
6.9.4 extern
The extern storage class is used to give a reference of a global variable that is visible to ALL
the program files. When you use ’extern’, the variable cannot be initialized however, it points
the variable name at a storage location that has been previously defined.When you have
multiple files and you define a global variable or function, which will also be used in other files,
then extern will be used in another file to provide the reference of defined variable or function.
Just for understanding, extern is used to declare a global variable or function in another file.
6.10 Recursion
A function that calls itself is known as recursive function and this technique is known as
recursion in C programming.Recursion is more elegant and requires few variables which make
program clean. Recursion can be used to replace complex nesting code by dividing the problem
into same problem of its sub-type.In other hand, it is hard to think the logic of a recursive
function. It is also difficult to debug the code containing recursion.
1#include<s t d i o . h>
2 int f a c t o r i a l ( int n ) ;
3 int main ()
4 {
43
5 int n ;
6 printf(” an p o s i t i v i n t e g e r ”);
Enter e :
7 s c a n f ( ”%d”,&n ) ;
8 p r i n t f ( ” Fa c t o r i a l o f %d = %ld ” , factorial (n))
n, ;
9
11 int
return
f a c t o r0i a
; l ( int n)
10 }
12 {
13 i f ( n! =1 )
14 return n∗ f a c t o r i a l ( n− 1 );
15 }
1 #include<s t d i o . h>
2 int Fi bonac c i ( int ) ;
3 main ()
4{
5 int n , i = 0 , c ;
6 s c a n f ( ”%d”,&n ) ;
7 p r i n t f ( ” Fibonacci s e r i e\s n” ) ;
8 for ( c = 1 ; c <= n ; c++ )
9 {
10 p r i n t f ( ”%d
\ n” , F ib on ac c i ( i ) ) ;
11 i ++;
12 }
13 return 0 ;
14 }
15 int Fi bonac c i ( int n)
16 {
17 i f ( n == 0 )
18 return 0 ;
19 else i f ( n == 1 )
20 return 1 ;
22
21 elsereturn ( F ib on ac c i ( n−1) + F ib on ac c i ( n−2) ) ;
23 }
8{
16 }
44
Preprocessor Syntax Description
Macro #define macro defines con-
stant value and can
be any of the basic
data types
Header #include<file source code of the
name> file
Inclusion file name is included
Files in the program at
the specified place
Conditional Compi- #ifedf, set of commands
lation are
#en- included or
dif,#if,#else excluded in source
program before
compilation with
respect to the
condition
Other directives #undef,#pragma #undef is used
to undefine a de-
fined macro vari-
able.#pragma is
used to call a func-
tion before and
after function in C
program.
45
Figure 18: C program Compilation
7 Pointer
A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before using it to
store any variable address. The general form of a pointer variable declaration is
1 type ∗ var−name ;
Here, type is the pointer’s base type; it must be a valid C data type and var-name is the
name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk
used for multiplication. However, in this statement the asterisk is being used to designate a
variable as a pointer. Take a look at some of the valid pointer declarations
1 int ∗ ip ; /∗ pointer to an i n t e g e r ∗/
2 double ∗dp ; /∗ pointer to a d o u b l e ∗/
3 f loat ∗ fp ; /∗ pointer to a f l o a t ∗/
4 char ∗ ch /∗ pointer to a c h a r a c t e r ∗/
4 int var = 2 0 ; /∗ a c t u a l v a r i a b l e d e c l a r a t i o n ∗/
5 int ∗ i p ; /∗ p o i n t e r v a r i a b l e d e c l a r a t i o n ∗/
6 i p = &var ; /∗ s t o r e a d d r e s s o f v a r i n p o i n t e r v a r i a b l e ∗/
46
7
4 int ptr
∗ = NULL;
5 p r i n t f ( ”The value o f ptr i s : %x \ n” , ptr );
6 return 0 ;
7 }
47
15 }
16 return 0 ;
17 }
10 /∗ o u t p u t each a r r a y e l e m e n t ’ s v a l u e ∗/
11 p r i n t f ( ” Array value s using p o in te r \n” ) ;
12 for ( i = 0 ; i < 5 ; i++ ) {
13 p r i n t f ( ” ∗ ( p + %d ) : %f \n” , i , ∗ ( p + i ) ) ;
14 }
48
15 p r i n t f ( ” Array value s using balance as address \n” ) ;
16
1 main () {
2 int ∗ p , sum , i ;
3 int x [ 5 ] ={5 , 9 , 6 , 7 , 3 ;
4 i =0; }
5 p=x ; // p=&x [ 0 ] ;
6
7 while ( i <5){
8 p r i n t f ( ”x[%d ] %d %u” , i∗, p , p ) ;
9 sum=sum+∗ p ;
10 i ++; p++;
11 }
12 p r i n t f ( ”\n sum=%d\n” , sum ) ;
13 }
Here the base address of array x is assigned to the pointer p. sum adds the value of the int
pointed by the pointer p using (*p) indirection operator and the increment i++ increases the
value of the variable i by i and the increment p++ increase the value of the address pointed
by p which is an integer and infact increased by 2 bytes.Ultimately the sum is calculated and
printed.
The variables *sum and *diff are known as pointers and sum and diff as pointer vari-
ables.Since they are declared as the int, they can point to locations of int type data.
49
This creates a string literal and then stores its address in the pointer variables str. The pointer
now pointer to the first character of the string good.we can print the content of the str using
printf or puts function
1 p r i n t f ( ”%s ” , s t r ) ;
2 puts ( s t r ) ;
Remember although str is a pointer to the string, it is also the name of the string. Therefore we
do not need an indirection operator *.
1 main () {
2 char ∗ name ;
3 int le ngth ;
4 char ∗ cptr=name ;
5 name=”DELHI”
6 p r i n t f ( ”%s\ n” , name ) ;
7 while (∗ cptr != ’\ 0 ’ )
8 printf{ ( ”%c i s s to re d at address at %u
\ n” , cptr , cptr ) ;
9 cptr++;
10 }
11 le ngth=cptr−name ;
12 p r i n t f ( ”\n Length o f Strin g i s =%d\n” , name ) ;
13 }
1#include<s t d i o . h>
2 int main ()
3 {
4
10 }
7.8.1 Malloc
The name malloc stands for ”memory allocation”. The function malloc() reserves a block of
memory of specified size and return a pointer of type void which can be casted into pointer of
any form
1 p t r =( c a s t −type ∗ ) m a l l o c ( byte−s i z e )
50
Function Use of Function
malloc Allocates requested size of bytes and returns a
pointer first byte of allocated space
calloc Allocates space for an array elements,
initializes
to zero and then returns a pointer to memory
free dellocate the previously allocated space
realloc Change the size of previously allocated space
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
1 p t r =( int ∗ ) m a l l o c ( 10 0 ∗ s i z e o f ( int ) ) ;
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively
and the pointer points to the address of first byte of memory.
7.8.2 Calloc
The name calloc stands for ”contiguous allocation”. The only difference between mal- loc() and
calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple
blocks of memory each of same size and sets all bytes to zero.
1 p t r =( c a s t −type ∗ ) c a l l o c ( n , element−s i z e ) ;
This statement will allocate contiguous space in memory for an array of n elements.
1 p t r =( f l o a t ∗ ) c a l l o c ( 2 5 , s i z e o f ( f l o a t ) ) ;
This statement allocates contiguous space in memory for an array of 25 elements each of size
of float, i.e, 4 bytes.
7.8.3 free
Dynamically allocated memory with either calloc() or malloc() does not get return on its
own. The programmer must use free() explicitly to release space.
1 f r e e ( ptr ) ;
This statement cause the space in memory pointer by ptr to be deallocated. Find sum of n
elements entered using malloc
1 #include < s t d i o . h>
2 #include < s t d l i b . h>
3 int main () {
4 int n , i ,∗ ptr , sum=0;
5 p r i n t f ( ” Enter number o f e lements : ” ) ;
6 s c a n f ( ”%d”,&n ) ;
7 ptr=( int ∗ ) malloc ( n s i ze o f ( int ) ) ; // malloc a l l o c a t i o n
8 i f ( ptr==NULL)
9 {
10 p r i n t f ( ” Error ! memory not a l l o c a t e d . ” ) ;
11 exit(0);
12 }
13 p r i n t f ( ” Enter e lements o f array : ” ) ;
14 for ( i =0; i <n;++ i )
51
15 {
16 s c a n f ( ”%d” , ptr+i ) ;
17 sum+=∗( p t r+i ) ;
18 }
19 p r i n t f ( ”Sum=%d” , sum ) ;
20 f r e e ( ptr ) ;
21 return 0 ;
22 }
Find sum of n elements entered using malloc
1 #include < s t d i o . h>
2 #include < s t d l i b . h>
3 int main () {
4 int n , i ,∗ ptr , sum=0;
5 p r i n t f ( ” Enter number o f e lements : ” ) ;
6 s c a n f ( ”%d”,&n ) ;
7 ptr=( int ∗ ) c a l l o c ( n , s i ze o f ( int ) ) ;
8 i f ( ptr==NULL)
9 {
10 p r i n t f ( ” Error ! memory not a l l o c a t e d . ” ) ;
11 exit(0);
12 }
13 p r i n t f ( ” Enter e lements o f array : ” ) ;
14 for ( i =0; i <n;++ i )
15 {
16 s c a n f ( ”%d” , ptr+i ) ;
17 sum+=∗( p t r+i ) ;
18 }
19 p r i n t f ( ”Sum=%d” , sum ) ;
20 f r e e ( ptr ) ;
21 return 0 ;
22 }
52
8 Structure and Unions
A structure is a collection of logically related data items grouped together under a single
name, called structure tag.The data items enclosed within a structure are known as members.
The members can be of same or different data types.
1 struct st ru c t u re name
2 {
3 data type member1 ;
4 data type member2 ;
5 data type member3 ;
6 }
7 } e1 , e2 ;
The members of a structure do not occupy memory until they are associated with a structure
variable. Above examples shows the structure variable e1 and e2 of structure employee.
4 int emp id ;
5 char name [ 2 5 ] ;
6 int age ;
7 f loat s a l a r y ;
8
9 };
10 struct employee e1 ={555 ,” Sudip ” , 2 5 , 8 0 0 0 0 . 0 };
The members of the variable e1 emp id,name,age,salary are initialised to 555,
”Sudip”,25,80000.0
53
8.3 Array of Structure
Likewise the array of data types arrays of structure can be initialised.
1 #include<s t d i o . h>
2 #include<c o n i o . h>
3 struct employee {
4 int emp id ;
5 char name [ 2 5 ] ;
6 int age ;
7 f loat s a l a r y ;
8}
9 int main ()
10 {
11 struct employee e [ 5 0 ] ;
12 int i , n ;
13 for ( i =0; i <50; i++)
14 {
15 p r i n t f ( ” Enter id , name , age and s a l a r y ” ) ;
16 s c a n f ( ”%d%s%d%f ”,& e [ i ] . emp id , e [ i ] . name,& e [ i ] . age ,& e [ i ] . s a l a r y ) ;
17 }
18 for ( i =0; i <50; i ++){
19 p r i n t f ( ”Data on Employee %d” , i +1 );
20 p r i n t f ( ”ID:%d” , e [ i ] . emp id ) ;
21 p r i n t f ( ”Name:% s ” , e [ i ] . name ) ;
22 p r i n t f ( ”Age:%d” , e [ i ] . age ) ;
23 p r i n t f ( ” Salary :% f ” , e [ i ] . s a l a r y ) ;
24 }
25 getch ( ) ;
26 }
1 struct employee {
2 int emp id ;
3 char name [ 2 5 ] ;
4 struct date{
5 int day ;
6 int month ;
7 int year ;
8 }dob ;
9 }
Accessing the members of the nested structure
54
1 #include<s t d i o . h>
2 #include<c o n i o . h>
3 struct employee {
4 int emp id ;
5 char name [ 2 5 ] ;
6 int age ;
7 f loat s a l a r y ;
8 struct date
9 {
10 int day ;
11 int month ;
12 int year ;
13 }dob ;
14 }
15 int main ()
16 {
17 struct employee e [ 5 0 ] ;
18 int i , n ;
19 for ( i =0; i <50; i++)
20 {
21 p r i n t f ( ” Enter id , name , age and s a l a r y ” ) ;
22 s c a n f ( ”%d%s%d%f ”,& e [ i ] . emp id , e [ i ] . name,& e [ i ] . age ,& e [ i ] . s a l a r y ) ;
23 p r i n t f ( ” Enter the date o f b i r th ” ) ;
24 s c a n f ( ”%d%d%d”,& e [ i ] . dob . day,& e [ i ] . dob . month,& e [ i ] . dob . year ) ;
25 }
26 for ( i =0; i <50; i ++){
27 p r i n t f ( ”Data on Employee %d” , i +1 );
28 p r i n t f ( ”ID:%d” , e [ i ] . emp id ) ;
29 p r i n t f ( ”Name:% s ” , e [ i ] . name ) ;
30 p r i n t f ( ”Age:%d” , e [ i ] . age ) ;
31 p r i n t f ( ” Salary :% f ” , e [ i ] . s a l a r y ) ;
32 p r i n t f ( ” Date o f Birth i s %d — %d %d” , e [ i ] . dob . year ,
33 e [ i ] . dob . month , e [ i ] . dob . day ) ;
34 }
35 getch ( ) ;
36 }
1 #include<s t d i o . h>
2 struct employee
3{
4 int emp id ;
55
5 char name [ 2 5 ] ;
6 int age ;
7 f loat s a l a r y ;
8 }
9 int main () {
10 struct employee e1 ={1 ,”Roshan” , 2 5 , 8 0 0 0 0 . 0 ;
11 struct employee ∗ p s} tru c tva r ;
12 p s tru c tva r=&e1 ;
13 p r i n t f ( ”Data on Employee” ) ;
14 p r i n t f ( ”Emp ID=%d” , p s t r u c t v a r− >emp id ) ;
15 p r i n t f ( ”Name=%s ” , pstructvar − >char ) ;
16 p r i n t f ( ”Age=%d” , p s t r u c t v a−
r >age ) ;
17 p r i n t f ( ” Salary=%f ” , p s t r u c t v a −
r >s a l a r y ) ;
18 getch ( ) ;
19 return 1 ;
20 }
The next refers to the name of a pointer variable to point structure of its own type. The
structure of type struct name will contain a member that points to another structure of type
struct name.
8.7 Union
Union are almost like structures with subtle differences.Declaration of the union is the same
as structure. Instead of the keyword struct the keyword union is used.
1 union union name {
2 data type member1 ;
3 data type member2 ;
4 ......... .......
5 ......... .......
6 data type member3 ;
7 }
56
Structure Union
Keyword struct defines structure keyword union defines Union
Within a structure all member gets For a union compiler allocates the
allocated and members have address memory for the largest of all mem-
that increase as the declarators are ber.
read left to right.The total size of
the structure is the sum of all the
members.
Within a structure all members gets While retrieving data from a union
memory allocated; therefore any the type that is being retrieved
member can be retrieved at any must be the type most recently
time. stored.
One or more members of structure A union may only be initialised with
can be initialised at once. a value of the type of its first mem-
ber.
9 File Handling in C
A file represents a sequence of bytes on the disk where a group of related data is stored. File is
created for permanent storage of data. It is a ready made structure.In C language, we use a
structure pointer of file type to declare a file.
1 FILE ∗ fp ;
58
mode description
r opens a text file in reading mode
w opens or create a text file in writing mode
a open a file in append mode
r+ opens a file in both reading and writing mode
w+ opens a file in both reading and writing mode
a+ opens a file in both reading and writing mode
4{
5 FILE ∗ fp ;
6 char ch ;
7 fp = fopen ( ” one . txt ” , ”w” ) ;
8 p r i n t f ( ” Enter data ” ) ;
9 while ( ( ch = g e t c har ( ) ) != EOF) {
10 putc ( ch , fp ) ;
11 }
12 f c l o s e ( fp ) ;
13 fp = fopen ( ” one . txt ” , ” r ” ) ;
14 while ( ( ch = getc ( ) ) != EOF)
15 p r i n t f ( ”%c” , ch ) ;
16 f c l o s e ( fp ) ;
17 }
9.4 Reading and Writing From a file using fprintf() and fscanf()
1 #include<s t d i o . h>
2 #include<c o n i o . h>
3 struct emp
4{
5 char name [ 1 0 ] ;
6 int age ;
7 };
8
9 void main ()
10 {
11 struct emp e ;
12 FILE ∗ p , q ;
13 p = fopen ( ” one . txt ” , ”a” ) ;
14 q = fopen ( ” one . txt ” , ” r ” ) ;
15 p r i n t f ( ” Enter Name and Age” ) ;
16 s c a n f ( ”%s %d” , e . name , &e . age ) ;
17 f p r i n t f ( p , ”%s %d” , e . name , e . age ) ;
18 fclose (p);
19 do
59
20 {
21 f s c a n f ( q , ”%s %d” , e . name , e . age ) ;
22 p r i n t f ( ”%s %d” , e . name , e . age ) ;
23 }
24 while ( ! f e o f ( q ) ) ;
25 getch ( ) ;
26 }
In this program, we have create two FILE pointers and both are refering to the same file
but in different modes. fprintf() function directly writes into the file, while fscanf() reads from
the file, which can then be printed on console usinf standard printf() function.
1 #include<s t d i o . h>
2 struct Student
3{
4 int r o l l ;
5 char name [ 2 5 ] ;
6 f loat marks ;
7 };
8 void main ()
9{
10 FILE ∗ fp ;
11 char ch ;
12 struct Student Stu ;
13 fp = fopen ( ” Student . dat” , ”w” ) ;
14 do
15 { p r i n t f (\” nEnter Roll : ” ) ;
16 s c a n f ( ”%d”,& Stu . r o l l ) ;
17 p r i n t f ( ” Enter Name : ” ) ;
18 s c a n f ( ”%s ” , Stu . name ) ;
19 p r i n t f ( ” Enter Marks : ” ) ;
20 s c a n f ( ”%f ”,& Stu . marks ) ;
21 f w r i t e (&Stu , s iz e o f ( Stu ) , 1 , fp ) ;
22 p r i n t f ( \” nDo you want to add another data ( y/n) : ”);
23 ch = getche ( ) ;
24 } while ( ch==’ y ’ | | ch==’Y ’ ) ;
25 p r i n t f ( \” nData w r i tte n s u c c e s s f u l l y . . . ” ) ;
26 f c l o s e ( fp ) ;
27 }
60
FILE* : FILE* is a file where the records will be read.
1 #include<s t d i o . h>
2 struct Student
3{
4 int r o l l ;
5 char name [ 2 5 ] ;
6 f loat marks ;
7 };
8 void main () {
9 FILE ∗ fp ;
10 char ch ;
11 struct Student Stu ;
12 fp = fopen ( ” Student . dat” , ” r ” ) ;
13 i f ( fp == NULL)
14 {
15 p r i n t f ( \” nCan ’ t open f i l e or f i l e doesn ’ t e x i s t . ” ) ;
16 exit(0);
17 }
18 p r i n t f (\” \ n t Ro \l l tName
\ tMarks \ n” ) ;
19 while ( f re a d (&Stu , s iz e o f ( Stu ) , 1 , fp ) >0)
20 p r i n t f (\” \ n t%d\ t%s \ t%f ” , Stu . r o l l , Stu . name , Stu . marks ) ;
21 f c l o s e ( fp ) ;
22 }
Write a program to write details of student to a file and read the same file and display the
records.
1 #include<s t d i o . h>
2 struct student {
3 char name [ 2 0 ] ;
4 int age ;
5 char dept [ 2 0 ] ;
6 };
7 int main () {
8 FILE ∗ fp ;
9 fp=fopen ( ” student . txt ” , ”w+” ) ;
10 int i ;
11 struct student s [ 2 ] ;
12 for ( i =0; i <2; i ++){
13 p r i n t f ( ” Enter name” ) ;
14 s c a n f ( ”%s ” , s [ i ] . name ) ;
15 p r i n t f ( ” Enter age ” ) ;
16 s c a n f ( ”%d”,& s [ i ] . age ) ;
17 p r i n t f ( ” Enter dept” ) ;
18 s c a n f ( ”%s ” , s [ i ] . dept ) ;
19 f w r i t e (& s [ i ] , sizeof ( s ) , 1 , fp ) ;
20 }
21 rewind ( fp ) ;
22 for ( i =0; i <2; i ++){
23 f re a d (& s [ i ] , sizeof ( s ) , 1 , fp ) ;
24 p r i n t f ( \” n Name : %s \ t Age : %d \ t Department : %s ” ,
25 s [ i ] . name , s [ i ] . age , s [ i ] . dept ) ;
26 }
27 f c l o s e ( fp ) ;
28 return 0 ;
29 }
61
Write a program to input data of 100 employee to a file and display records of those
employees living in ”Kathmandu”
1 #include<s t d i o . h>
2 #include<s t r i n g . h>
3 struct employee {
4 char name [ 2 0 ] ;
5 char address [ 2 0 ] ;
6 long t e l e p h o n e ;
7 f loat s a l a r y ;
8 struct dob{
9 int mm, dd , yy ;
10 }db ;
11
12 };
13 int main () {
14 struct employee e [ 1 0 0 ] ;
15 int i;
16 FILE ∗ fp ;
17 fp=fopen ( ” employee . txt ” , ”w” ) ;
20 p r i n t f ( \” nEnter name” ) ;
21 s c a n f ( ”%s ” , e [ i ] . name ) ;
22 p r i n t f ( \” nEnter address ” ) ;
23 s c a n f ( ”%s ” , e [ i ] . address ) ;
24 p r i n t f ( \” nEnter t e l e p h o n e ” ) ;
25 s c a n f ( ”%ld ”,& e [ i ] . t e l e p h o n e ) ;
26 p r i n t f (\” nEnter s a l a r y ” ) ;
27 s c a n f ( ”%f ”,& e [ i ] . s a l a r y ) ;
28 p r i n t f ( \” nEnter date o f b i r th in − dd mm− yyyy” ) ;
29 s c a n f ( ”%d — %d %d” ,& e [ i ] . db . dd,& e [ i ] . db .mm,& e [ i ] . db . yy ) ;
30 f w r i t e (&e [ i ] , sizeof ( e ) , 1 , fp ) ;
31 }
32 for ( int i = 0 ; i < 10 0 ; ++i )
33 {
34 i f ( strcmp ( ”Kathmandu” , e [ i ] . ad d re ss )==0)
35 {
36 p r i n t f ( ”\n%s ” , e [ i ] . name ) ;
37 p r i n t f ( ”\n%s ” , e [ i ] . address ) ;
38 p r i n t f ( ”\n%ld ” , e [ i ] . t e l e p h o n e ) ;
39 p r i n t f ( ”\n%f ” , e [ i ] . s a l a r y ) ;
40 p r i n t f ( ”\n%d−%d−%d” , e [ i ] . db . dd , e [ i ] . db .mm, e [ i ] . db . yy ) ;
41 }
42 }
43 return 0;
44 }
Write a program to read the name, author and price of 500 books in a library from the file
library.dat. Now print the book name and price of those books whose price is above 300.
1 #include < s t d i o . h>
2 #include < s t r i n g . h>
3 struct book {
4 char name [ 1 0 0 ] ;
5 char author [ 1 0 0 ] ;
6 f loat p r i c e ;
7 };
62
8 int main ()
9 {
10 FILE ∗ fp ;
11 struct book b ;
12 fp=fopen ( ” l i b r a r y . dat” , ” r ” ) ;
13
14 while ( f re a d (&b , s iz e o f ( b ) , 1 , fp ) >0){
15 i f ( b . price > 300 . 0 )
16 {
17 p r i n t f ( ”%s \n” , b . name ) ;
18 p r i n t f ( ”%f \n” , b . p r i c e ) ;
19 }
20 }
21
22 return 0 ;
23 }
Write a program to create a ”student.txt” file to store the above records for 100 students. Also
display the records of students who are not from Pokhara.
1 #include < s t d i o . h>
2 #include < s t r i n g . h>
3 struct student
4{
5 int r o l l ;
6 char name [ 2 0 ] ;
7 char address [ 2 0 ] ;
8 char f a c u l t y [ 2 0 ] ;
9 struct dob
10 {
11 int mm, dd , yy ;
12 }db ;
13 };
14 int main ()
15 {
16 FILE ∗ fp ;
17 int i ;
18 struct student s [ 1 0 0 ] ;
19 fp=fopen ( ” student . txt ” , ”w” ) ;
20 for ( int i = 0 ; i < 10 0 ; ++i )
21 {
22 p r i n t f ( ” Enter Roll No. \ n” ) ;
23 s c a n f ( ”%d”,& s [ i ] . r o l l ) ;
24 p r i n t f ( \” nEnter name” ) ;
25 s c a n f ( ”%s ” , s [ i ] . name ) ;
26 p r i n t f ( \” nEnter address ” ) ;
27 s c a n f ( ”%s ” , s [ i ] . address ) ;
28 p r i n t f (\” nEnter Faculty ” ) ;
29 s c a n f ( ”%s ” , s [ i ] . f a c u l t y ) ;
30 p r i n t f ( \” n Enter date o f b i r th in format − dd mm
− yyyy” ) ;
31 s c a n f ( ”%d — %d %d” ,& s [ i ] . db . dd,& s [ i ] . db .mm,& s [ i ] . db . yy ) ;
32 f w r i t e (& s [ i ] , sizeof ( s ) , 1 , fp ) ;
33 }
34 for ( int i = 0 ; i < 10 0 ; ++i )
35 {
36 i f ( strcmp ( ” Pokhara” , s [ i ] . address )! = 0 )
37 {
38 p r i n t f ( ”%d\n” , s [ i ] . r o l l ) ;
39 p r i n t f ( ”%s \n” , s [ i ] . name ) ;
63
40 p r i n t f ( ”%s \n” , s [ i ] . address ) ;
41 p r i n t f ( ”%s \n” , s [ i ] . f a c u l t y ) ;
42 p r i n t f ( ”%d−%d−%d\n” , s [ i ] . db . dd , s [ i ] . db .mm, s [ i ] . db
. yy ) ;
43 }
44 }
45 f c l o s e ( fp ) ;
46 return 0 ;
47 }
64