0% found this document useful (0 votes)
19 views

c_notes

The document outlines the syllabus for CMP 103.3 Programming in C, detailing course objectives, evaluation methods, and a comprehensive breakdown of topics covered, including programming logic, variables, control structures, functions, pointers, and file handling. It also includes a laboratory component for practical application of concepts learned in class, culminating in a final project. Recommended textbooks and references are provided for further study.

Uploaded by

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

c_notes

The document outlines the syllabus for CMP 103.3 Programming in C, detailing course objectives, evaluation methods, and a comprehensive breakdown of topics covered, including programming logic, variables, control structures, functions, pointers, and file handling. It also includes a laboratory component for practical application of concepts learned in class, culminating in a final project. Recommended textbooks and references are provided for further study.

Uploaded by

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

Programming Notes in

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

5 Arrays and Strings 6


Introduction to arrays, initialization of arrays, multidimensional arrays,
String, function related to the strings

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

8 Structure and Unions 5


Definition of Structure, Nested type Structure, Arrays of Structure, Structure and Pointers,
Unions, self-referential structure

9 Files and File Handling 4


Operating a file in different modes (Real, Write, Append), Creating a file in different modes
(Read, Write, Append)
Laborator
y:
Laboratory work at an initial stage will emphasize on the verification of programming
concepts learned in class and use of loops, functions, pointers, structures and unions. Final
project of 10 hours will be assigned to the students which will help students to put together
most of the programming concepts developed in earlier exercises.

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

Pokhara University/Faculty of Science & Technology/Revised Syllabus-2012/Programming in C 2


Contents
1 Introduction 7
1.1 Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2 Types of Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3 Basic Structure of a Digital Computer . . . . . . . . . . . . . . . . . . . 7
1.3.1 Operating System . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3.2 Utility Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 Programming Language . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4.1 Low level Language . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4.2 High level Language . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5 Compiler, Interpreter and Assembler . . . . . . . . . . . . . . . . . . . . 9
1.6 Traditional and Structured Programming . . . . . . . . . . . . . . . . . 9

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

3 Variables and Data Types 13


3.1 Constant and Variables......................................................................................13
3.2 Variable declaration in C..............................................................................13
3.3 Rules for writing variable name in C...........................................................14
3.4 Input Output Function..................................................................................14
3.5 Operators in C..............................................................................................14
3.5.1 Arithmetic Operator...............................................................................15
3.5.2 Relational Operator................................................................................15
3.5.3 Logical Operator.....................................................................................15
3.5.4 Assignment Operator.............................................................................16
3.5.5 Conditional Operator..............................................................................16
3.5.6 Bitwise Operator..................................................................................... 16
3.6 Operator Precedence in C..................................................................................17
3.7 Simple Input Output Function.....................................................................17
3.7.1 getchar() function...................................................................................17
3.7.2 putchar() function................................................................................... 18
3.7.3 scanf() function....................................................................................... 18
3.7.4 printf() function......................................................................................18
3.7.5 gets() and puts() function......................................................................19

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

5 Arrays and Strings 32


5.1 One Dimensional Array......................................................................................32
5.1.1 Declaring and Initialising...................................................................32
5.2 MultiDimensional Array...................................................................................... 33
5.2.1 Initialisation of Multidimensional Arrays...............................................33
5.3 String.............................................................................................................34
5.3.1 Accessing Strings....................................................................................35
5.3.2 String related fuctions............................................................................35

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

8 Structure and Unions 49


8.1 Accessing Members of Structure . . . . . . . . . . . . . . . . . . . . . . 49
8.2 Initialising Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
8.3 Array of Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
8.4 Nested Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
8.5 Pointer to a structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
8.6 Self Referential Structure . . . . . . . . . . . . . . . . . . . . . . . . . . 52
8.7 Union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
8.8 Difference between Structure and Union . . . . . . . . . . . . . . . . . . 52

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.

1.2 Types of Computer


Based on nature, computers are classified into Analog computers and Digital computers. The
former one deals with measuring physical quantities ( concerned with continuous variables )
which are of late rarely used. The digital computer operates by counting and it deals with the
discrete variables.There is a combined form called Hybrid computer, which has both features.

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.

1.3 Basic Structure of a Digital Computer


The von Neumann architecture, which is also known as the von Neumann model and Princeton
architecture, is a computer architecture based on that described in 1945 by the mathematician
and physicist John von Neumann.This describes a design architecture for an electronic
digital computer with parts consisting of a processing unit containing an arithmetic logic unit
and processor registers; a control unit containing an instruction register and program counter;
a memory to store both data and instructions; external mass storage; and input and output
mechanisms.The key idea of the Von Neumann ar- chitecture is the stored program concept.A
stored-program digital computer is one that keeps its program instructions, as well as its data,
in read-write, random-access memory (RAM). Stored-program computers were an
advancement over the program-controlled computers of the 1940s.

Figure 1: Block Diagram of Computer

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.

1.3.1 Operating System


The set of instructions which resides in the computer and governs the system are called
operating systems, without which the machine will never function. They are the medium of
communication between a computer and the user. DOS, Windows, Linux, Unix etc are
Operating Systems.

1.3.2 Utility Programs


These programs are developed by the manufacturer for the users to do various tasks. Word,
Excel, Photoshop, Paint etc are some of them.

1.4 Programming Language


1.4.1 Low level Language
Low level languages are machine level and assembly level language. In machine level language
computer only understand digital numbers i.e. in the form of 0 and 1. So, instruction given to
the computer is in the form binary digit, which is difficult to implement instruction in binary
code. This type of program is not portable, difficult to maintain and also error prone. The
assembly language is on other hand modified version of machine level language. Where
instructions are given in English like word as ADD, SUM, MOV etc. It is easy to write and
understand but it is hard for the computer to understand. So the translator used here is
assembler to translate into machine level. Although language is bit easier, programmer has
to know low level details related to low level language. In the assembly level language, the
data are stored in the computer register, which varies for different computer. Hence it is not
portable.

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.

1.5 Compiler, Interpreter and Assembler


Compiler and interpreter are used to convert the high level language into machine level
language. The program written in high level language is known as source program and the
corresponding machine level language program is called as object program. Both compiler and
interpreter perform the same task but there working is different. Compiler read the program
at-a-time and searches the error and lists them. If the program is error free then it is converted
into object program. When program size is large then compiler is preferred. Whereas
interpreter read only one line of the source code and convert it to object code. If it check
error, statement by statement and hence of take more time.

An assembler program creates object code by translating combinations of mnemonics and


syntax for operations and addressing modes into their numerical equivalents. This
representation typically includes an operation code (”opcode”) as well as other control bits and
data. The assembler also calculates constant expressions and resolves symbolic names for
memory locations and other entities.

1.6 Traditional and Structured Programming


Structured programming is a programming paradigm aimed at improving the clarity, quality,
and development time of a computer program by making extensive use of sub- routines, block
structures, for and while loops—in contrast to using simple tests and jumps such as the go to
statement which could lead to ”spaghetti code” causing diffi- culty to both follow and
maintain.

It is possible to do structured programming in any programming language, though it is


preferable to use something like a procedural programming language. Some of the languages
initially used for structured programming include: ALGOL, Pascal, PL/I and Ada – but most
new procedural programming languages since that time have included features to encourage
structured programming, and sometimes deliberately left out fea- tures – notably GOTO – in an
10
effort to make unstructured programming more difficult. Structured programming (sometimes
known as modular programming) is a subset of imperative programming that enforces a logical
structure on the program being written to make it more efficient and easier to understand
and modify.

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.

2.1 Understanding of problems, Feasibility and Requirement Analysis


In order to start to develop a solution to a problem using computer, we need to first
understand the problem about its nature, complexities and others. Problems can be of various
nature and we need to understand about the problems first to be able to solve it using
computer. Once the problem has been understood and we can solve it using computer the
feasibility of the problem solution needs to be determined. We can solve a problem using various
logic but what needs to be worked out is the most feasible solution that can be derived with the
least amount of complexities. Another major portion to solving problems using computer is the
analysis of the requirements. The solution to the problem can be solved however the
requirements required is beyond the possible technologies of today. Then the solution may not
be feasible to the problem.

2.2 Design FlowChart and Algorithm


An algorithm is a solution to a computer programming problem. In other words a step by step
procedure for developing a problem is called an algorithm.Algorithms can be written in two
different ways.

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:

(a) Step1: Input numbers as a and b


(b) Step2: Sum = x + y
(c) Step3: Print the sum

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

Set sum = num1 + num2

Output "The sum is " + sum

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

Set averageGrade = totalGrade / numStudents

Output "The average grade is " + averageGrade

End

2.4 Program Coding


Once algorithm and flowchart has been developed the task now remains is to write programs
using some high level programming language.C, C++, Java, Python are the most popular
programming language to develop programs. PHP and ASP remain a popular choice for
developing web based applications.

2.5 Testing and Debugging


Once the program code has been written in a selected programming language of choice the
next task to complete is the testing and debugging. Testing and debugging helps to find the
problems associated with the program behavior under normal and abnormal circumstances.
Extensive testing like white box testing and black box testing, integration testing needs to done
before the program is deployed into the real world scenario.

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

Table 1: Data types in C

3.2 Variable declaration in C


A variable declaration provides assurance to the compiler that there exists a variable with the
given type and name so that the compiler can proceed for further compilation without
requiring the complete detail about the variable. A variable definition has its meaning at the
time of compilation only, the compiler needs actual variable definition at the time of linking
the program.
#in c lu d e < s t d i o . h> extern in t a , b ;
extern in t c ;
extern f l o a t f ; in t main () {
in t a , b ;
in t c ;
float f ;

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.3 Rules for writing variable name in C


1. A variable name can have letters (both uppercase and lowercase letters), digits and
underscore only.
2. The first letter of a variable should be either a letter or an underscore. However, it is
discouraged to start variable name with an underscore. It is because variable name that
starts with an underscore can conflict with a system name and may cause error.
3. There is no rule on how long a variable can be. However, the first 31 characters of a
variable are discriminated by the compiler. So, the first 31 letters of two variables in a
program should be different.

3.4 Input Output Function


C programming language provides many of the built-in functions to read given input and
write data on screen, printer or in any file.

scanf() and printf() functions #include <s t d i o . h>


#include <conio . h>
void main ()
{
in t i ;
p r i n t f (” Enter a value ” ) ; s c a n f (”%d”,& i ) ;
p r i n t f ( ”\nYou entered : %d ” , i ) ; getch ( ) ;
}

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.

3.5.2 Relational Operator


< ( less than ), <= (less than or equal to ), > (greater than ), >= ( greater than or
equal to ), == ( equal to ) and ! = (not equal to ) are relational operators. A logical
expression is expression connected with a relational operator. For example ‘b*b
– 4*a*c<0 is a logical expression. Its value is either true or false.
1 int i , j , k ;
2 i =1;
3 j =2;
4 K=i+j ;
The expression k>5 evaluates to false and the expression k<5 evaluates to true.

3.5.3 Logical Operator


The relational operators work with arbitrary numbers and generate true/false values.You can
also combine true/false values by using the Boolean operators, which take true/false values as
operands and compute new true/false values. The three Boolean operators are:

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.

3.5.4 Assignment Operator


These operators are used for assigning a value of expression to another identifier.

=, + =, - = , * =, /= and % = are assignment operators. a = b+c results in storing the


value of b+c in ‘a’.
a += 5 results in increasing the value of a by 5.
a /= 3 results in storing the value a/3 in a and it is equivalent a=a/3

3.5.5 Conditional Operator


The operator ?: is the conditional operator. It is used as variable 1 = expression 1 ? expression
2 : expression 3. Here expression 1 is a logical expression and expression 2 and expression 3 are
expressions having numerical values. If expression 1 is true, value of expression 2 is assigned
to variable 1 and otherwise expression3 is assigned.
1 int a , b , c , d , e ;
2 a=3; b=5; c =8;
3 d=(a<b) ? a : b ;
4 e=(b>c ) ? b : c ;
The evaluation of the expression results the value of d = 3 and e = 8.

3.5.6 Bitwise Operator


C has a distinction of supporting special operator known as bitwise operator for manip- ulation
of data at bit level. These operators are used for testing bits or shifting them right or left.
Bitwise operator may not be applied to float or double. Following are the bitwise operators.
• & bitwise AND
• | bitwise OR
• ˆ bitwise exclusive OR
• << shift left
• >> shift right

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.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a


higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.An
arithmetic expression without parenthesis will be evaluated from left to right using the rules of
precedence. There are two distinct priority levels of arithmetic operators in C.
• Higher Priority * /
• Lower Priority + -
The expression x=a-b/3+c*2-1 where a=9, b=12 and c=3 will be evaluated as step1: x=9-
12/3+3*2-1 Higher priority operators left to right division first step2: x=9-4+3*2-1 Higher
priority operators left to right multiply
step3: x=9-4+6-1 Lower priority operators left to right subtraction step4: x=5+6-1 Lower
priority operators left to right addition step5: x=11-1 Lower priority operators left to right
subtraction step6: x=10 Final Result

Rules for Evaluation of Expression


• First, parenthesized sub expression from left to right are evaluated.
• If parentheses are nested, the evaluation begins with innermost sub expression.
• The precedence rule is applied in determining the order of operands in evaluating sub
expressions.
• Arithmetic expressions are evaluated from left to right using the rules of prece- dence.
• When parentheses are used, the expressions within the parentheses assume highest
priority.

3.7 Simple Input Output Function


For inputting and outputting data we use library function .the important of these func- tions
are getch( ), putchar( ), scanf( ), printf( ), gets( ), puts( ).

3.7.1 getchar() function


It is used to read a single character (char type) from keyboard. The syntax is
char variable name = getchar( );
For reading an array of characters or a string we can use getchar( ) function.
1#include<s t d i o . h>
2#include<c o n i o . h>
3 void main ( )
4{

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);

1 #include < s t d i o . h>


2 #include <conio . h>
3 void main ()

4{

5 char alphabet ;

6 p r i n t f ( ” Enter an alphabet ” ) ;
7 putchar ’ \ n ’ ) ;
8 alphabet=getchar ( ) ;
9 putchar ( alphabet ) ;

10 }

3.7.3 scanf() function


This function is generally used to read any data type- int, char, double, float,string.The syntax is
scanf (control string, list of arguments)
The control string consists of group of characters, each group beginning % sign and a
conversion character indicating the data type of the data item. The conversion characters are
c,d,e,f,o,s,u,x indicating the type resp. char decimal integer, floating point value in exponent
form, floating point value with decimal point, octal integer, string, unsigned integer,
hexadecimal integer. ie, “%s”, “%d” etc are such group of characters.
1 #include<s t d i o . h>
2 #include<c o n i o . h>
3 void main ( )
4{

5 char name [ 3 0 ] , line ;


6 int x ;
7 f loat y ;
8 . . . . . . . .
9 . . . . . . . .
10 s c a n f ( ”%s%d%f ” , name , &x , &y ) ;
11 s c a n f ( ”%c” , l i n e ) ;

12 }

3.7.4 printf() function


This is the most commonly used function for outputting a data of any type. The syntax is
printf(control string, list of arguments)
Here also control string consists of group of characters, each group having % symbol and
conversion characters like c, d, o, f, x etc.
1#include<s t d i o . h>
2#include<c o n i o . h>
3 void main ()

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.

3.7.5 gets() and puts() function


The C library function gets() reads a line from stdin and stores it into the string pointed to by
str. It stops when either the newline character is read or when the end-of-file is reached,
whichever comes first.
1 #include<s t d i o . h>
2 #include<c o n i o . h>
3 int main ()
4{

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 Branching Structure


Branching is deciding what actions to take and looping is deciding how many times to take a
certain action.Decision making structures require that the programmer specifies one or more
conditions to be evaluated or tested by the program, along with a statement or statements to
be executed if the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false. Show below is the general form of a typical
decision making structure found in most of the programming languages.

Figure 3: FlowChart Control Statement

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

4.1.2 if..else Statement


An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.If the Boolean expression evaluates to true, then the if block will be
executed,otherwise, the else block 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.

Figure 5: If else Statement

1 #include < s t d i o . h>


2 int main () {
3 int a = 10 0 ;
4 i f ( a == 10 ) {
5 p r i n t f ( ” Value o fa i s 10\ n” ) ;
6 }
7 else i f ( a == 20 ) {
8 p r i n t f ( ” Value o f ai s 20\ n” ) ;
9 }
10 else i f ( a == 30 ) {
11 p r i n t f ( ” Value o f ai s 30\ n” ) ;
12 }
13 else {

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 }

4.1.3 if..else if..else Statement


An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.When using if...else if...else
statements, there are few points to keep in mind:
• An if can have zero or one else’s and it must come after any else if’s.
• An if can have zero to many else if’s and they must come before the else.
• Once an else if succeeds, none of the remaining else if’s or else’s will be tested.

4.1.4 Nested if Statement


It is always legal in C programming to nest if-else statements, which means you can use one if
or else if statement inside another if or else if statement(s).

4.1.5 Switch Statement


A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each switch case.The
following rules apply to a switch statement:
• The expression used in a switch statement must have an integral or enumerated type,
or be of a class type in which the class has a single conversion function to an integral
or enumerated type.
• You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases is
true. No break is needed in the default case.

1 #include < s t d i o . h>


2 int main () {
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 char grade = ’B ’ ;
5 switch ( grade ) {

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 }

4.1.6 The ? : Operator


Exp1? Exp2 : Exp3 is the general structure of the ? : operator. The value of a ? expression

is determined like this:

• 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

4.2.1 while loop


A while loop in C programming repeatedly executes a target statement as long as a given
condition is true.
1 while ( c o n d i t io n )
2 {
3 statement ( s ) ;
4 }

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

Figure 7: while loop flowchart

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.

Figure 8: for loop flowchart

4.2.3 do while loop


Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming checks its condition at the bottom of the loop.A

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.

Figure 9: do..while loop flowchart

4.2.4 nested loop


C programming allows to use one loop inside another loop.
• Nested for loop
1 for ( i n i t ; c o n d i t io n ; increment ){
2 for ( i n i t ; c o n d i t io n ; increment {
)
3 statement ( s ) ;
4 }
5 statement ( s ) ;
6 }

• Nested while loop


1 while ( c o n d i t io n ) {
2

3 while ( c o n d i t io n {
)
4 statement ( s ) ;
5 }
6
7 statement ( s ) ;
8 }

• Nested do while loop

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 ) ;

• Find Prime numbers between 2 to 100 using prime number


#include < s t d i o . h>
1

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 }

4.3 Break Continue and Goto Statement


4.3.1 Break Statement
The break statement terminates the loop (for, while and do...while loop) immediately when it
is encountered. The break statement is used with decision making statement such as if...else.
The syntax of the statement is
break;
Example of Goto Statement

Figure 10: Flowchart Break Statement

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 ;

8 for ( i =1; i <= 1 0 ; ++i )

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 }

17 sum += number ; // sum = sum + number ;

18 }

19 p r i n t f ( ”Sum = %.2 l f ” , sum ) ;


20 return 0;
21 }

Working of Break Statement

Figure 11: Working of Break Statement

4.3.2 Continue Statement


The continue statement skips some statements inside the loop. The continue statement is used
with decision making statement such as if...else. The syntax is
continue;

32
Example of Continue Statement

Figure 12: Flowchart Continue Statement

1 // Program to c a l c u l a t e sum o f maximum o f 10 numbers


2 // Negative numbers are s k i p p e d from c a l cu l a t i o n
3 # include < s t d i o . h>

4 int main ()
5{

6 int i;
7 double number , sum = 0 . 0 ;

8 for ( i =1; i <= 1 0 ; ++i )

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 }

17 sum += number ; // sum = sum + number ;

18 }

19 p r i n t f ( ”Sum = %.2 l f ” , sum ) ;


20 return 0;
21 }

Working of Continue Statement

33
Figure 13: Working of Continue Statement

4.3.3 Goto Statement


The goto statement is used to alter the normal sequence of a C program. The syntax of
goto statement is
1 goto l a b e l ;
2 .......
3 .......
4 .......
5 label :
6 statements ;
Example of Goto Statement

1 // Program to c a l c u l a t e the sum and average o f maximum o f 5 numbers


2 # include < s t d i o . h>
3 int main ()
4{

5 const int maxInput = 5 ;

6 int i;
7 double number , average , sum= 0 . 0 ;
8 for ( i =1; i<=maxInput ; ++i )
9{

10 p r i n t f ( ”%d . Enter a number : ” , 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 , f l ow o f program moves to l a b e l jump
13 i f ( number < 0 . 0 )

14 goto jump ;

15 sum += number ; // sum = sum+number ;

16 }
17 jump :

18 average=sum/( i − 1 );

19 p r i n t f ( ”Sum = %.2 f \n” , sum ) ;

34
20 p r i n t f ( ” Average = %.2 f ” , average ) ;
21 return 0 ;
22 }

Reasons to avoid using goto statement

1. The use of goto statement may lead to code that is buggy and hard to follow.

2. Goto make jumps that are out of scope so it is difficult 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.

Figure 14: Arrays Representation

5.1 One Dimensional Array


5.1.1 Declaring and Initialising

1 data type array name [ a r r a y s i z e ] ;


2 double balance [ 1 0 ] ;
balance is a variable array which is sufficient to hold up to 10 double numbers.size of array
defines the number of elements in an array. Each element of an array can be accessed and
used as per the need of the program.
1 int age [ 5 ] ={ 2 , 4 , 3 4 , 3 , 4 };
2 int age [ ] ={ 4 , 6 , 8 , 9 , 1 0 };
In the second case the compiler determines the size of an array by calculating the number of
elements in an array.

Figure 15: Arrays Initialisation

Program to find sum of marks of n students


1 #include < s t d i o . h>
2 int main () {
3 int marks [ 1 0 ] , i , n , sum=0;
4 p r i n t f ( ” Enter number o f s t u d e n t s : ” ) ;
5 s c a n f ( ”%d”,&n ) ;
6 for ( i =0; i <n;++ i{ )
7 p r i n t f ( ” Enter marks o f student%d : ” , i +1 );
8 s c a n f ( ”%d”,&marks [ i ] ) ;
9 sum+=marks [ i ] ;
10 }
11 p r i n t f ( ”Sum= %d” , sum ) ;
12 return 0;
13 }

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 ] ;

Figure 16: Arrays Initialisation

5.2.1 Initialisation of Multidimensional Arrays

1 int c [ 2 ] [ 3 ] ={{ 1 , 3 , 0 } ,{ − 1 , 5 , 9 }};


2 int c [ 2 ] [ 3 ] ={ 1 , 3 , 0 , − 1 , 5 , 9 };
In the second case the compiler creates two rows from the given array.
Program to add two matrices
1 #include < s t d i o . h>
2 int main () {
3 f loat a [ 2 ] [ 2 ] , b [ 2 ] [ 2 ] , c [ 2 ] [ 2 ] ;
4 int i , j ;
5 p r i n t f ( ” Enter the e lements o f 1 s t matrix\n” ) ;
6
7 for ( i =0; i <2;++i )
8 for ( j =0; j <2;++j { )
9 p r i n t f ( ” Enter a%d%d : ” , i +1 , j +1 );
10 s c a n f ( ”%f ”,&a [ i ] [ j ] ) ;
11 }
12

13 p r i n t f ( ” Enter the e lements o f 2nd matrix \ n” ) ;


14 for ( i =0; i <2;++i )
15 for ( j =0; j <2;++j { )
16 p r i n t f ( ” Enter b%d%d : ” , i +1 , j +1 );
17 s c a n f ( ”%f ”,&b [ i ] [ j ] ) ;
18 }
19
20 for ( i =0; i <2;++i )
21 for ( j =0; j <2;++j { )
22 c [ i ] [ j ]=a [ i ] [ j ]+b [ i ] [ j ] ;
23 }
24 p r i n t f (\” nSum Of Matrix : ” ) ;
25 for ( i =0; i <2;++i )
26 for ( j =0; j <2;++j { )
27 p r i n t f ( ”%.1 \f t ” , c [ i ] [ j ] ) ;
28 i f ( j==1)
29 p r i n t f ( ”\n” ) ;
30 }
31 return 0;
32 }

Program to Multiply Two matrices


1 #include < s t d i o . h>
37
2 int main ()
3 {
4 int m, n , p , q , c , d , k , sum = 0 ;
5 int f i r s t [ 1 0 ] [ 1 0 ] , second [ 1 0 ] [ 1 0 ] , m u l t i p l y [ 1 0 ] [ 1 0 ] ;
6

7 p r i n t f ( ” Enter rows and columns o f f i r s t matrix\ n” ) ;


8 s c a n f ( ”%d%d” , &m, &n ) ;
9 p r i n t f ( ” Enter the e lements o f f i r s t matrix\n” ) ;
10
11 for ( c = 0 ; c < m; c++)
12 for ( d = 0 ; d < n ; d++)
13 s c a n f ( ”%d” , & f i r s t [ c ] [ d ] ) ;
14

15 p r i n t f ( ” Enter rows and columns o f second matrix


\ n” ) ;
16 s c a n f ( ”%d%d” , &p , &q ) ;
17

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

28 for ( c = 0 ; c < m; c++) {


29 for ( d = 0 ; d < q ; d++) {
30 for ( k = 0 ; k < p ; k++) {
31 sum = sum + f i r s t [ c ] [ k ] ∗ second [ k ] [ d ] ;
32 }
33

34 m u l t i p l y [ c ] [ d ] = sum ;
35 sum = 0 ;
36 }
37 }
38

39 p r i n t f ( ” Product o f entered m a t r i c e s : −\n” ) ;


40
41 for ( c = 0 ; c < m; c++) {
42 for ( d = 0 ; d < q ; d++)
43 p r i n t f ( ”%d\ t ” , m u l t i p l y [ c ] [ d ] ) ;
44

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 ’ };

Figure 17: String Representation

5.3.1 Accessing Strings

1 //no need to use address & in scanf f or s t r i n g s


2 s c a n f ( ”%s ” , g r e e t in g ) ;
3 g e ts ( g r e e t in g ) ;
4

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.

6.2 Types of C function


There are two types of C functions
• Library Function
• User Defined Function

6.2.1 Library Function


Library functions are the in-built function in C programming system.
1 main ()
2 p r i n t f ()
3 s c a n f ()
4 s t rc p y ()
5 s t r c a t ()
6 strcmp ()
are the examples of Library functions available in C.

6.3 User Defined Function


C allows programmer to define their own function according to their requirement. These types
of functions are known as user-defined functions.
Function Prototype(Declaration)
Every function in C programming should be declared before they are used. These type of
declaration are also called function prototype. Function prototype gives compiler information
about function name, type of arguments to be passed and return type.
1 int add ( int a , int b ) ;

6.4 Defining a Function


The general form of a function definition in C programming language is as follows
1 re tu rn typ e function name ( parameter list ){
2 body o f the f u n c t io n
3 }
A function definition in C Programming consists of a function header and a function body.Here
are all parts of a function.
• Return Type A function may return a value. The return type is the data type of the
value the function returns. Some functions perform the desired operations without returning
a value. In this case, the return type is the keyword void.
• Function Name This is the actual name of the function. The function name and the
parameter list together constitute the function signature.

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.

6.5 Calling a function


Function with return and without return can be called to using the different syntax.
1 add ( a , b ) ; // c a l l i n g f u n c t i o n w i t h o u t return
2 c=add ( a , b ) ; // c a l l i n g f u n c t i o n with return

6.6 Call by Value


If data is passed by value, the data is copied from the variable used in for example main() to a
variable used by the function. So if the data passed (that is stored in the function variable) is
modified inside the function, the value is only changed in the variable used inside the function.
1 #include < s t d i o . h>
2 void c a l l b y v a l u e ( int x) {
3 p r i n t f ( ” In s id e f u n c t io n x = %d b e f o re adding \ 10 . n” , x ) ;
4 x += 1 0 ;
5 p r i n t f ( ” In s id e f u n c t io n x = %d a f t e r adding 10 .\ n” , x ) ;
6}

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

6.7 Call by Reference


If data is passed by reference, a pointer to the data is copied instead of the actual variable as is
done in a call by value. Because a pointer is copied, if the value at that pointers address is
changed in the function, the value is also changed in main().
1 #include < s t d i o . h>
2 void c a l l b y r e f e r e n c e ( int ∗y ) {
3 p r i n t f ( ” In s id e f u n c t io n y = %d b e f o re adding 10 .\ n” , ∗y ) ;
4 ( ∗ y) += 1 0 ;
5 p r i n t f ( ” In s id e f u n c t io n y = %d a f t e r adding 10 .\ n” , ∗y ) ;
6 }

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.8 Passing array as an argument to a function


Likewise int and floats an array can be passed as an argument to the function .
1 f loat l a r g e s t ( f loat a [ ] , int s i z e ) ;
2 main (){
3 f loat value [ 4 ] ={ 2 . 5 , − 1 . 6 , 3 . 4 , 6 . 8 };
4 p r i n t f ( ”%f \n” , l a r g e s t ( value , 4 ) ) ;
5}

6 f loat l a r g e s t ( f loat a [ ] , int s i z e{)


7 int i ;
8 f loat max;
9 max=a [ 0 ] ;
10 for ( i =1; i <s i z e ; i ++){
11 i f (max<a [ i ] )
12 max=a [ i ] ;
13 return (max ) ;
14 }
15 }

6.9 Storage Class in C


6.9.1 auto
The auto storage class is the default storage class for all local variables.
1 {
2 int mount ;
3 auto int month ;
4 }
The example above defines two variables with in the same storage class. ’auto’ can only be
used within functions, i.e., local variables.

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.

6.10.1 Factorial Using 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 }

6.10.2 Fibonacci Series Using Recursion

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 }

6.11 Preprocessor Directives


Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.Commands used in preprocessor are called
preprocessor directives and they begin with “#” symbol.
1 #include<s t d i o . h>
2 #define he ight 100
3 #define number 3 . 1 4
4 #define l e t t e r ’A’
5 #define l e t t e r s e q u e n c e ”ABC”
6 #define b a c ks la s h c h a r \’ ? ’
7 void main ()

8{

9 p r i n t f ( ” value o f he ight : %d \ n” , he ight ) ;


10 p r i n t f ( ” value o f number : %f \ n” , number ) ;
11 p r i n t f ( ” value o f l e t t e r : %c \ n” , l e t t e r ) ;
12 p r i n t f ( ” value o f l e t t e r s e q u e n c e : \%s n” , l e t t e r s e q u e n c e ) ;
13 p r i n t f ( ” value o f backs lah char : %c \ n” , b a c ks la s h c h a r ) ;
14 getch ( ) ;
15

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.

Table 2: Preprocessor Directives

6.12 Macro Substitution


One of the major use of the preprocessor directives is the creation of macros.Macro
Substitution is a process where an identifier in a program is replaced by a predefined string
composed of one or more tokens.The general form of macro definition is
1 #define i d e n t i f i e r s t r i n g
2 #define count 100
3 #define area 5 ∗ 12 . 46
4 #define cube ( x ) ( x∗x∗x )

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 ∗/

7.1 Using Pointers

1#include < s t d i o . h>


2 int main () {
3

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

8 p r i n t f ( ” Address o f var v a r i a b l e : %x\n” , &var ) ;


9 /∗ a d d r e s s s t o r e d i n p o i n t e r v a r i a b l e ∗/
10 p r i n t f ( ” Address s to re d in ip v a r i a b l e : %x\n” , ip );
11 /∗ a c c e s s t h e v a l u e u s i n g t h e p o i n t e r ∗/
12 p r i n t f ( ” Value o f ∗ ip v a r i a b l e : %d\n” , ∗ ip ) ;
13
14 return 0 ;
15 }
7.2 Null Pointer
It is always a good practice to assign a NULL value to a pointer variable in case you do not have
an exact address to be assigned. This is done at the time of variable declaration. A pointer that
is assigned NULL is called a null pointer.
1#include < s t d i o . h>
2 int main () {
3

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 }

7.3 Pointer Arithmetic


A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer just as you can on a numeric value. There are four arithmetic operators
that can be used on pointers: ++, –, +, and -.
1 ptr++
After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 2 bytes next to the current
location in 16 bit system. This operation will move the pointer to the next memory location
without impacting the actual value at the memory location. If ptr points to a character whose
address is 1000, then the above operation will point to the location 1001 because the next
character will be available at 1001.

7.3.1 Incrementing Pointer


We prefer using a pointer in our program instead of an array because the variable pointer can be
incremented, unlike the array name which cannot be incremented because it is a constant pointer.
1#include < s t d i o . h>
2 int main () {
3

4 int var [ 3 ] = { 10 , 100 , 200 };


5 int i , ∗ ptr ;
6

7 / ∗l e t us have array address in p o i n t e r /


8 ptr = var ;
9

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


11 p r i n t f ( ” Address o f var[%d ] = %x
\ n” , i , ptr ) ;
12 p r i n t f ( ” Value o f var[%d ] = %d
\ n” , i , ptr ) ;
13 /∗ move to the next l o ca t io n /
14 ptr++;

47
15 }
16 return 0 ;
17 }

7.3.2 Decrementing a Pointer


Likewise the increment of pointer the pointer variable can also be decremented which is shown as:
1 in c lu d e < s t d i o . h>
2 int main () {
3

4 int var [ 3 ] = {10 , 100 , 200 ;


5 int i , ∗ ptr ; }
6 /∗ l e t us have array address in p o i n t e r /
7 ptr = &var [ 2 ] ;
8 for ( i = 2 ; i >= 0 ; i −−) {
9 p r i n t f ( ” Address o f var[%d ] = %x\n” , i , ptr ) ;
10 p r i n t f ( ” Value o f var[%d ] = %d\n” , i , ∗ ptr ) ;
11 /∗ move t o t h e p r e v i o u s l o c a t i o n ∗/
12 ptr −−;
13 }
14 return 0 ;
15 }

7.4 Definition Pointer to Arrays


An array name is a constant pointer to the first element of the array. Therefore, in the
declaration
1 double balance [ 5 0 ] ;
balance is a pointer to &balance[0], which is the address of the first element of the array
balance. Thus, the following program fragment assigns p as the address of the first element of
balance.
1 double ∗ p ;
2 double balance [ 1 0 ] ;
3 p = balance ; // p=&b a lance [ 0 ] ;
It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance
+ 4) is a legitimate way of accessing the data at balance[4].Once you store the address of the
first element in ’p’, you can access the array elements using *p, *(p+1), *(p+2) and so on.
1#include < s t d i o . h>
2 int main () {
3

4 /∗ an array with 5 e lements /


5 double balance [ 5 ] = {10 00 . 0 , 2 . 0 , 3 . 4 , 1 7 . 0 , 5 0 . 0 ;
6 double ∗ p ; }
7 int i ;
8 p = balance ; // p=&b a lance [ 0 ]
9

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

17 for ( i = 0 ; i < 5 ; i++ ) {


18 p r i n t f ( ” ∗ ( b a l a n c e + %d ) : %f \n” , i , ∗ ( b a l a n c e + i ) ) ;
19 }
20 return 0 ;
21 }

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.

7.5 Returning Multiple Values from a function


Return statement can return a single value. however multiple values can be returned from
functions using arguments that we pass to a function.The arguments that are used to send
out information are called output parameters.The mechanism of sending back information
through arguments is achieved using what are known as the address operator(&) and
indirection operator (*).
1 void mathoperation ( int x , int y , int ∗ s , int d ) ;
2 main () {
3 int x=20 ,y=20 , s , d ;
4 mathoperation ( x , y,& s ,&d ) ;
5 p r i n t f ( ”sum=%d\n d i f f=%d” , s , d ) ;
6 }
7 void mathoperation ( int a , int b , int ∗sum , int ∗ d i f f ){
8 ∗sum=a+b ;
9 ∗ d i f f=a−b ;
10 }
11 }

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.

7.6 Pointer to String


As string can be considered as a character array. C supports an alternative way to create strings
using pointer variables of type char.
1 char ∗ s t r =” good” ;

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 }

7.7 Double pointer


Stores the address of a pointer variable. Generally declared as
1 ∗∗ ptr ;

1#include<s t d i o . h>
2 int main ()
3 {
4

5 int num = 45 , ∗ ptr , ptr 2 ptr ;


6 ptr = &num ;
7 ptr 2 ptr = &ptr ;
8 p r i n t f ( ”%d”∗∗
, ptr 2 ptr ) ;
9 return ( 0 ) ;

10 }

7.8 Dynamic Memory Allocation


The exact size of array is unknown untill the compile time,i.e., time when a compier compiles
code written in a programming language into a executable form. The size of array you have
declared initially can be sometimes insufficient and sometimes more than required. Dynamic
memory allocation allows a program to obtain more memory space, while running or to
release space when no space is required.

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

Table 3: Function Dynamic Memory Allocation

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 }

Examples of Structure can be as follows


1 struct employee {
2 int emp id ;
3 char name [ 2 5 ] ;
4 int age ;
5 f loat s a l a r y ;
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.

8.1 Accessing Members of Structure


The members of a structure can be accessed with the help of .(dot) operator. The syntax for
accessing the members of the structure variable is as follows
1 s t r u c t v a r i a b l e . member
2 struct employee e1 ;
3 e1 . emp id ;
4 e1 . name ;
5 e1 . s a l a r y ;

8.2 Initialising Structure


The values to the members of the structure must appear in the order as in the definition of the
structure within braces and separated by the commas. C does not allow the initialisation of
individual structure members as within the definition.The general from is
1 s tru c t n a m e va r ia b le=
{ value 1 , value 2 . . . . . . , value n ;
2 struct employee }
3{

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 }

8.4 Nested Structure


Sometimes the member of structure needs to have multiple values, For the case the members
should be another variable of another structure type.C allows the member structure to be the
structure. The mechanism is called nesting of the structure. Nesting enables to build powerful
data structures.Following is an illustration of nested structure
1 struct date {
2 int day , month , year ;
3 };
4 struct employee {
5 int emp id ;
6 char name [ 2 5 ] ;
7 struct date dob ;
8 }

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 }

8.5 Pointer to a structure


We can have a pointer that holds the address of the structure.We can declare a pointer
variable of a structure by writing
1 struct structname ∗ p s tru c tva r ;
where struct is the required keyword structname represents the name of the userdefined structure
and pstructvar represents the name of the pointer variable.The address of the structure variable to
the pointer variable can be assigned as
1 p s tru c tva r=&v a r ib a l e ;
Likewise the pointer to the structure variable can be accessed and processed as
1 ( ∗ struct name ) . f ie ld n a m e=v a r i a b l e ;
1 struct name −>f ie ld n a m e=v a r i a b l e ;

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 }

8.6 Self Referential Structure


A structure can have members which point to a structure variable of the same type. These
types of structure are called self referential structure. It is widely used in dy- namic data
structure like linklist, trees etc.Following is the syntax of the self referential structure
1 struct struct name
2 {
3 data type member1 ;
4 .......... .......
5 struct struct name ∗ next ;
6 }

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 }

8.8 Difference between Structure and Union

56
Structure Union
Keyword struct defines structure keyword union defines Union

1 struct mystructure { 1 struct myunion{


2
int id ; 2 int id ;
char name [ 2 0 ] ; 3 char name [ 2 0 ] ;
3
f loat age ; 4 f loat age ;
4
} s1; 5 }u1 ;
5

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.

Table 4: Difference between structure and union

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 ;

9.1 Opening a File in C


The fopen() function is used to create a new file or to open an existing file.
1 ∗ fp = FILE ∗ fopen ( const char ∗ f i lename , const char mode ) ;
2 fp=fopen ( ” te
∗ xt . txt ” , ”w” ) ;
3 // opens a f i l e t e x t . t x t in w r i t ing mode
Here filename is the name of the file to be opened and mode specifies the purpose of opening
the file. *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.

9.2 Closing a File


The fclose() function is used to close an already opened file.
1 int f c l o s e ( FILE ∗ fp ) ;
Here fclose() function closes the file and returns zero on success, or EOF if there is an error
57
in closing the file. This EOF is a constant defined in the header file stdio.h.

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

Table 5: File opening modes

9.3 Writing Character by Character in File


In the above table we have discussed about various file I/O functions to perform reading and
writing on file. getc() and putc() are simplest functions used to read and write individual
characters to a file
1 #include<s t d i o . h>
2 #include<c o n i o . h>
3 main ()

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.

9.5 fread() and fwrite()


1 f w r i t e ( ptr , int s i z e , int n , FILE ∗ fp ) ;
The fwrite() function takes four arguments.
ptr : ptr is the reference of an array or a structure stored in memory. size : size is the total
number of bytes to be written.
n : n is number of times a record will be written.
FILE* : FILE* is a file where the records will be written in binary mode.

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 }

1 f re a d ( ptr , int s i z e , int n , FILE ∗ fp ) ;


The fread() function takes four arguments.
ptr : ptr is the reference of an array or a structure where data will be stored after
reading.
size : size is the total number of bytes to be read from file. n : n is number of times a record
will be read.

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” ) ;

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


19 {

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

You might also like