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

IP_RG23

Uploaded by

priyaindhu699
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

IP_RG23

Uploaded by

priyaindhu699
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 86

1

INTRODUCTION TO PROGRAMMING

UNIT-I : Introduction to Programming and Problem Solving

Introduction to Computer :-

In the modern era, computers are an essential part of our everyday existence. That means computers are
present in almost every field, making our day-to-day tasks easier and faster. Now-a-days, computers can be
seen in banks, shops, schools, hospitals, railways, and many more places, including our home. As they are
such an essential part of our lives.

What is a Computer?

The straightforward meaning of a computer is a machine that can calculate. However, modern computers are
not just a calculating device anymore. They can perform a variety of tasks. In simple terms, a computer is a
programmable electronic machine used to store, retrieve, and process data.

According to the definition, "A computer is a programmable electronic device that takes data, perform
instructed arithmetic and logical operations, and gives the output."
2

Whatever is given to the computer as input is called 'data', while the output received after processing is called
'information'.

A Brief History of Computers :-

The term 'Computer' was first introduced in 1640 and referred to as 'one who calculates'. It was derived from
the Latin word 'computare', which meant 'to calculate'. In 1897, it was known as the 'calculating machine'.
Later in 1945, the term 'computer' was introduced as 'programmable digital electronic computer, which is now
called a 'computer'.

When the computers were introduced, they were large and could fill an entire room. Some computers were
operated using large-sized vacuum tubes. In 1833, Charles Babbage (known as the father of the computer)
invented an early calculator, which was named as the 'difference engine'. Later in 1837, he introduced the
first mechanical, general-purpose computer 'Analytical Engine'. Over time, computers became powerful in
performance and small in size.

Generations of Computer :-

There are five generations of the computer, which can be classified as below:

First Generation (1946 - 1959): During the first generation, computers were based on electronic valves
(Vacuum Tubes). Some popular computers of first-generation are ENIAC, EDVAC, UNIVAC, etc.

Second Generation (1959 - 1965): During the second generation, computers were based on Transistors.
Some popular computers of second-generation are IBM 1400, IBM 1620, IBM 7000 series, etc.

Third Generation (1965 - 1971): During the third generation, computers were based on Integrated Circuits
(ICs). Some popular computers of the third generation are IBM 360, IBM 370, PDP, etc.

Fourth Generation (1971 - 1980): During the fourth generation, computers were based on very large scale
integrated (VLSI) circuits. Some popular computers of fourth-generation are STAR 1000, CRAY-1, CRAY-
X-MP, DEC 10, etc.

Fifth Generation (1980 - Present): The fifth generation is still ongoing. The computers are based on multiple
technologies, such as ultra large scale integration (ULSI), artificial intelligence (AI), and parallel
processing hardware. The fifth generation of computers includes Desktop, Laptop, NoteBook, etc.

Basic organization of a Computer :-

The basic organization of a computer contains many components. The essential components of the computer
can be defined as follows:

Input Unit:- Input Units or devices are used to input the data or instructions into the computers. Some most
common input devices are mouse and keyword.

Output Unit:- Output Units or devices are used to provide output to the user in the desired format. The most
popular examples of output devices are the monitor and the printer.

Control Unit:- As its name states, this unit is primarily used to control all the computer functions and
functionalities. All the components or devices attached to a computer interact with each other through the
control unit. In short, the control unit is referred to as 'CU'.
3

Arithmetic & Logic Unit:- The arithmetic & logic unit helps perform all the computer system's arithmetic
and logical operations. In short, the arithmetic logic unit is referred to as 'ALU'.

Memory Unit:- Memory unit is used to store all the input data, instructions, and output data. Memory usually
has two types: Primary Memory and Secondary Memory. The memory found inside the CPU is called the
primary memory, whereas the memory that is not the integral part of the CPU is called secondary memory.

Control Unit, arithmetic & logic unit, and the memory simultaneously form the central processing unit
(called CPU in short).
The block diagram of any computer system is as shown below:
C.P.U

Arithmetic &
Input Unit Logic Unit Output Unit

Control Unit

Memory Unit

program counter :- A program counter (PC) is a CPU register in the computer processor which has the
address of the next instruction to be executed from memory. It is a digital counter needed for faster execution of
tasks as well as for tracking the current execution point.

Characteristics of a Computer :-

The basic characteristics of computers are given below :

 Speed:- Computers are high-speed electronic machines. They can carry around 3-4 million
instructions per second. Even advanced computers can handle trillions of instructions per second.
 Accuracy:- Computers are also known for their accurate performance. They can complete the given
jobs at almost 100% accuracy. Although errors may occur in computers, they are usually caused by
incorrect input, incorrect instructions, or bugs in chips. All of these are human errors.
 Storage Capacity:- Computers can easily store a massive size of data. Modern computers come
inbuilt with high storage features compared to older days. Additional data can be stored on secondary
devices like external hard disks, or flash memory, etc.
 Reliability:- Computers are reliable and consistent; they can process the same tasks any number of
times without throwing any error. Computers don't get tired like humans, so they are superior to
perform rule-based, repetitive tasks.
 Versatility:- The variety of tasks that a computer can perform are almost infinite. That means
computers can perform different tasks without making errors. For one moment, a computer can be
used to perform data entry tasks or ticket booking, and the very next moment, it can be used for
complex mathematical calculations or continuous astronomical observations, etc.

Types of Computers :-

According to physical size, computers are classified into the following types:
4

 Super Computer:- Super computers are the fastest and the most expensive type of computers. They
are large and require more space for installation. These types of computers are mainly designed to
perform massive data-based and complex tasks. Super computers are capable enough to handle
trillions of instructions at the same time.
 Mainframe Computer:- Mainframe computers are comparatively smaller in size as compared to
super computers. However, they are not much small. These types of computers are designed to
perform hundreds or thousands of jobs at a time simultaneously. These computers can handle heavy
tasks, including complex calculations and can store vast amounts of data. They are best suited for big
organizations such as banking, telecom, and educational sectors.
 Micro Computer:- Microcomputers are cheap in price and support multi-user platform. These are the
general-purpose computers designed to handle all the necessary tasks of individual needs. Since they
are comparatively slower than mainframe computers, thereby are suitable for small organizations.
They are best suited for internet café, schools, universities, offices, etc. A microcomputer is also
referred to as the 'Personal Computer (PC)' in general life. Laptop and desktop are examples of micro
computers.
 Mini Computer:- Mini computers are also referred to as Mini frame computers. These are the midsize
multiprocessing computer designed purposely for easy carry. These types of computers are light-
weight and can fit in a small space. They are suitable for billing, accounting, education, and business
purposes. Since these minicomputers are easy to carry, they are the best option for those who need a
computer while traveling. Tablet PC, Notebooks, and cell phones are examples of mini computers.
 Workstation: Workstation is a powerful, single-user computer. A workstation is a personal computer
with a faster microprocessor, a massive amount of RAM, higher-quality monitors, high graphic
memory, etc. This is best suited for performing any specific type of task professionally. According to
the type of tasks, a workstation can be referred to as a music workstation, graphic workstation, or
engineering design workstation. Most businesses and professionals use workstations for performing
tasks like animation, music creation, video editing, poster designs, data analysis and more.

Advantages of Using Computers :-

The following are the main advantages of using computers:

 Computers can perform given tasks at incredible speed.


 Computers can perform the same task multiple times with the same accuracy.
 Computers allow doing several tasks simultaneously as they are best suited for multitasking.
 Computers keep the stored data secure and inaccessible from unauthorized users.
 Computers can automatically perform routine tasks with automation, making humans available for
more intelligent tasks.

Disadvantages of Using Computers :-

The following are the main disadvantages of using the computer:

 Computers cannot work on their own. They need instructions from humans to complete tasks.
Moreover, computers follow the given instructions blindly without thinking about the outcomes.
 Computers need a power supply to work. Without a power supply, they are just useless.
 Working on a computer continuously for a long period can cause several health issues.
 Wastage of computers and their parts leave a negative impact on the environment.

 Computers are taking human jobs in many sectors. They are replacing human work and thus
increasing unemployment.

Applications of Computers :-
5

The following are some of the applications of computers:

• Government:- Computers are used in government Organizations to keep records on governmental


actions.
• Traffic Control:- In the United States(US), Computers are used for city planning and traffic
control.
• Legal System: - Computers are used by lawyers to conduct case research.
• Retail Business:- Computers are used in retail shops to enter orders, calculate costs and print receipts.
• Sports:- In sports, computers are used to identify weak players and strong players by analyzing
statistics.
• Music: - All computers have Musical Instrument Digital Interface (MIDI) facility to generate variety of
sounds.
• Movies:- Computers are used to create sets, special effects, animations, cartoons and videos etc.,
• Hospitals: - Hospitals use computers to record information about patients like admit time to exit time,
Blood pressure, lab reports etc.
• Weather Forecasting:- Weather forecasting is the process of predict the state of the weather for a
given location.
• Education: A Computer is a powerful teaching aid and acts as another teacher in the classroom.
• Online Banking:- Now a day’s bank transactions can be made anywhere and anytime using
computers.
• Robots: - Robots are computer-controlled machines. Robots are able to perform various tasks, which
could not be done by the humans.
• Expert Systems: An expert system is a computer program that simulates the knowledge of humans.

Introduction to Programming Languages :-


A programming language is a computer language that is used by programmers (developers) to
communicate with computers. It is a set of instructions written in any specific language ( C, C++, Java,
Python) to perform a specific task. A programming language is mainly used to develop desktop applications,
websites, and mobile applications.
The different types of types of programming languages are given below:
1. Low-level programming language:-

Low-level language is machine-dependent (0s and 1s) programming language. The processor runs low-
level programs directly without the need of a compiler or interpreter, so the programs written in low-level
language can be run very fast. Low-level language is further divided into two parts :

i. Machine Language -: Machine language is a type of low-level programming language. It is also called as
machine code or object code. Machine language is easier to read because it is normally displayed in binary
or hexadecimal form (base 16) form. It does not require a translator to convert the programs because
computers directly understand the machine language programs.

The advantage of machine language is that it helps the programmer to execute the programs faster than the
high-level programming language.

ii. Assembly Language -: Assembly language is also a type of low-level programming language that is
designed for specific processors. It represents the set of instructions in a symbolic and human-
understandable form. It uses an assembler to convert the assembly language to machine language.
6

The advantage of assembly language is that it requires less memory and less execution time to execute a
program.

2. High-level programming language :-

High-level programming language (HLL) is designed for developing user-friendly software programs and
websites. This programming language requires a compiler or interpreter to translate the program into machine
language (execute the program).

The main advantage of a high-level language is that it is easy to read, write, and maintain.

High-level programming language includes Python, Java, JavaScript, PHP, C#, C++, Objective C, Cobol,
Perl, Pascal, LISP, FORTRAN, and Swift programming language.

A high-level language is further divided into three parts :

i. Procedural Oriented programming language -: Procedural Oriented Programming (POP) language is


derived from structured programming and based upon the procedure call concept. It divides a program into
small procedures called routines or functions.

Procedural Oriented programming language is used by a software programmer to create a program that can be
accomplished by using a programming editor like IDE, Adobe Dreamweaver, or Microsoft Visual Studio.

The advantage of POP language is that it helps programmers to easily track the program flow and code can be
reused in different parts of the program.

The advantage of POP language is that it helps programmers to easily track the program flow and
code can be reused in different parts of the program.

Example: C, FORTRAN, Basic, Pascal, etc.

ii. Object-Oriented Programming language -: Object-Oriented Programming (OOP) language is based


upon the objects. In this programming language, programs are divided into small parts called objects. It
is used to implement real-world entities like inheritance, polymorphism, abstraction, etc in the program to
makes the program reusable, efficient, and easy-to-use.

The main advantage of object-oriented programming is that OOP is faster and easier to execute, maintain,
modify, as well as debug.

Note: Object-Oriented Programming language follows a bottom-up approach.

Example: C++, Java, Python, C#, etc.

iii. Natural language -: Natural language is a part of human languages such as English, Russian, German,
and Japanese. It is used by machines to understand, manipulate, and interpret human's language. It is used by
developers to perform tasks such as translation, automatic summarization, Named Entity Recognition
(NER), relationship extraction, and topic segmentation.

The main advantage of natural language is that it helps users to ask questions in any subject and directly
respond within seconds.
7

3. Middle-level programming language :-

Middle-level programming language lies between the low-level programming language and high-level
programming language. It is also known as the intermediate programming language and pseudo-language.

A middle-level programming language's advantages are that it supports the features of high-level
programming, it is a user-friendly language, and closely related to machine language and human language.

Example: C, C++ language

Algorithm & Characteristics of algorithms :-

An algorithm is a finite set of instructions which are being carried in a specific order to perform the specific
task. It is not the complete program or code; it is just a solution (logic) of a problem, which can be represented
either as an informal description using a Flowchart or Pseudo code.

Characteristics of an Algorithm:-

The following are the characteristics of an algorithm:

 Input: An algorithm has some input values. We can pass 0 or some input value to an algorithm.
 Output: We will get 1 or more output at the end of an algorithm.
 Unambiguity: An algorithm should be unambiguous which means that the instructions in an
algorithm should be clear and simple.
 Definiteness: Algorithms must specify every step and the order the steps must be taken in the process.
Definiteness means specifying the sequence of operations for turning input into output.
 Finiteness: An algorithm should have finiteness. Here, finiteness means that the algorithm should
contain a limited number of instructions, i.e., the instructions should be countable.
 Effectiveness: An algorithm should be effective as each instruction in an algorithm affects the overall
process.
 Language independent: An algorithm must be language-independent so that the instructions in an
algorithm can be implemented in any of the languages with the same output.

Algorithm Development Steps


The process of algorithm development generally involves many steps. The general steps involved in algorithm
development are as follows:

 Problem Definition
 Problem Analysis
 Algorithm Design
 Flowchart
 Implementation
 Testing
 Documentation
8

Problem Definition

We have to clearly define the problem that the algorithm needs to solve. We have to clearly understand the
problem statement so that a proper algorithm can be designed. This stage includes understanding the input data,
desired output, and constraints or requirements.

Problem Analysis

Analyze the problem to gain insights into its characteristics, complexity, and potential solutions. This may
involve studying the data, identifying patterns, understanding the relationships between different variables, and
considering different approaches.

Algorithm Design

Based on the problem analysis, design an algorithm that outlines the step-by-step process for solving the
problem. This may involve selecting appropriate data structures, choosing suitable problem-solving techniques,
and designing tools for defining the logic or flow of the algorithm.

Flowchart Development

A flowchart is a visual representation of the algorithm for non-technical people so that they can easily
understand the algorithm. Create a high-level representation of the algorithm using flowcharts. Flowcharts use
graphical symbols to represent the steps and flow of the algorithm.
Implementation
Translate the algorithm design into a specific computer programming language. Write the code to implement the
algorithm, taking into consideration the syntax, data types, and control structures of the programming language.
Testing
Test the algorithm by giving the test data and see if the desired output is generated. Testing with various inputs
to verify the correctness and effectiveness of the algorithm. Identify and fix any bugs or errors that may arise
during testing. Testing may involve different types of inputs to ensure the algorithm performs correctly in
different scenarios.
Documentation
Document the algorithm, including its design, implementation details, and any assumptions or limitations. This
documentation helps others understand and use the algorithm effectively.

Complex Algorithm Design

Complex algorithm design may involve multiple iterations to redefine the development process. These stages
are:
 Evaluation
 Iteration
 Optimization

Evaluation

Evaluate the algorithm’s performance against specific criteria, such as accuracy, speed, memory usage, and
scalability. Compare it with other existing algorithms or benchmarks to determine its effectiveness in solving
the problem.
9

Iteration

Based on the evaluation results, refine and iterate the algorithm to further improve its performance or address
any shortcomings. This may involve revisiting the problem analysis, design, or implementation stages to fine-
tune the algorithm.

Optimization

Optimize the algorithm to improve its performance, efficiency, or scalability. This may involve analyzing the
time and space complexity of the algorithm, identifying bottlenecks, and making necessary adjustments or
optimizations to enhance its performance.

Advantages and Disadvantages of Algorithms

Advantages of Algorithms:-

 Efficiency: Algorithms streamline processes, leading to faster and more optimized solutions.
 Reproducibility: They yield consistent results when provided with the same inputs.
 Problem-solving: Algorithms offer systematic approaches to handle complex problems effectively.
 Scalability: Many algorithms can handle larger datasets and scale with increasing input sizes.
 Automation: They enable automation of tasks, reducing the need for manual intervention.

Disadvantages of Algorithms:-

 Complexity: Developing sophisticated algorithms can be challenging and time-consuming.


 Limitations: Some problems may not have efficient algorithms, leading to suboptimal solutions.
 Resource Intensive: Certain algorithms may require significant computational resources.
 Inaccuracy: Inappropriate algorithm design or implementation can result in incorrect outputs.
 Maintenance: As technology evolves, algorithms may require updates to stay relevant and effective.

Problem solving strategies: Top-down approach, Bottom-up approach


Top-down approach :-
The top-down approach, also known as the "top-down design" or "stepwise refinement," is a method of
problem-solving that starts with an overview of the problem and divides it into smaller sub-problems.
It involves breaking down a complex system into smaller, more manageable components and solving
each component individually, ultimately leading to the solution of the overall problem.

The top-down approach is best used when:

 The problem is complex and needs to be broken down into smaller, manageable parts.
 There is a need to understand the big picture before diving into details.
 A clear understanding of the end goal is required before starting the project.
 The solution can be divided into smaller subproblems that can be solved independently.
 The problem has multiple potential solutions, and a top-down approach can help prioritize and evaluate
them.
10

Top-Down Approach Advantages and Disadvantages

Advantages:
 Easy to understand and implement.
 Provides clear objectives and expectations.
 Supports effective allocation of resources.
Disadvantages:
 Inflexible to change
 Limited to pre-determined solutions.
 Can lead to missed opportunities or inefficiencies.
 Can result in lower motivation and participation from lower-level employees.

Bottom-Up Approach

 A bottom-up approach, on the other hand, is an investment strategy that depends on the selection of
individual stocks.
 It observes the performance and management of companies and not general economic trends.
 The bottom-up approach analyzes individual risk in the process by using mathematical models and is
thus data-intensive.
 This method does not rely on historical data.
 It is a forward-looking approach unlike the top-down model, which is backward-looking.

The bottom-up approach can be useful in situations where:

 The problem or project is too complex to be fully understood at the outset


 There is a need to build a foundation of detailed knowledge before moving on to higher-level work
 It's unclear how the different components of a problem or project fit together
 There is a need to experiment and iterate on different components to find the best solution.

Bottom-Up Approach Advantages and Disadvantages

Advantages:
 Flexibility: Bottom-up approach allows for changes to be made at any stage of the process.
 Empowerment: It gives individuals and smaller groups the power to make decisions.
 Robustness: This approach can result in more robust solutions, as each component can be thoroughly
tested and debugged.

Disadvantages:
 Slow Progress: The bottom-up approach can be slow, as each component must be completed before
moving on to the next.
 Lack of coherence: The final solution may lack coherence, as it is assembled from individual parts.
 Difficulty in managing complex projects: This approach can be difficult to manage for complex
projects with many components.

Problem solving using algorithmic approach


Algorithm is a sequence of steps, which are used to solve a problem systematically. It a good
practice to solve any kind of problems. The following algorithm is used to print addition of new
numbers.
Step1 : Start
Step2 : A←5
Step3 : B←3
11

Step4 : c=A+B
Step5 : Print c
Step6 : Stop

In the above example “step-1” indicates the starting point of an algorithm “step-2” and “step-3” are used to
assign values to the variables A and B. “Step-4” calculates the addition operation. “Step-5” prints the result of
“C” and finally “step-6” stops the process and ends the execution.

We may write one more algorithm for the above task like the following. Here we read values for the
variables. This technique helps us to read different value to different variables.

Step1 : Start
Step2 : Read A
Step 3 : Read B
Step 4: C←A+B
Step 5: Print C
Step 6: Stop

Flow charts :-
A flow chart is a pictorial (or) graphical representation of an algorithm. It represents the logic flow in which
the different types of instructions are drawn in the form of different shapes of boxes and the logical flow is
indicated by interconnecting the arrows. The boxes represent operations, while the arrows represent the sequence
of the operations. The following table shows the flow charts symbols and their use (processing).

Symbols Symbol Names


Flow Lines
Terminal (Start / Stop)

Input / Output
Processing
Decision
Connector

 Flow line:- Flow line is represented by an arrow which is used to connect symbols.
 Terminals: - The terminal symbol is used to indicate the beginning (start), the termination (end) or
halt (pause) in the program logic.
 Input output:-The symbol represents an input taken from the user or output is displayed to the user
 Processing:- The process symbol is used to process the data like performing calculations, moving
data from memory to other devices.
 Decision:-The decision symbol is used to construct conditions and then execute a path of statements
based on the given condition. If the condition is TRUE, one path of process will be executed otherwise
(FALSE) another will execute.
 Connector:- This symbol is used to join different flow lines.

Pseudocode :-
12

Pseudo code is a term which is often used in programming and algorithm based fields. It is a methodology
that allows the programmer to represent the implementation of an algorithm. It is simply an implementation
of an algorithm in the form of annotations and informative text written in plain English. It has no syntax like
any of the programming language and thus can’t be compiled or interpreted by the computer.

Pseudo code can be written as follows:

1. Arrange the sequence of tasks and write the pseudo code accordingly.
2. Start with the statement of a pseudo code which establishes the main goal or the aim.

Example:

This program will allow the user to check


the number whether it is even or odd.

3. The way the if-else, for, while loops are indented in a program, indent the statements likewise, as it
helps to comprehend the decision control and execution mechanism. They also improve the readability
to a great extent.

Example:

if "1"
print response
"I am case 1"
if "2"
print response
"I am case 2"

4. Use appropriate naming conventions. The human tendency follows the approach to follow what we
see. If a programmer goes through a pseudo code, his/her approach will be the same as per it, so the
naming must be simple and distinct.
5. Use appropriate sentence casings, such as CamelCase for methods, upper case for constants and lower
case for variables.

6. Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code
abstract.
7. Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in
programming.
8. Check whether all the sections of a pseudo code is complete, finite and clear to understand.
9. Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to
understand even for a layman or client, hence don’t incorporate too many technical terms.
13

Space complexity & Time complexity :-

Performance analysis of an algorithm depends upon two factors i.e. amount of memory used and amount of
computing time consumed on any CPU. Formally they are notified as complexities in terms of:

 Space Complexity.
 Time Complexity.

Space Complexity of an algorithm is the amount of memory it needs to run to completion i.e. from start of
execution to its termination. Space needed by any algorithm is the sum of following components:

1. Fixed Component:- This is independent of the characteristics of the inputs and outputs. This part
includes: Instruction Space, Space of simple variables, fixed size component variables, and constants
variables.
2. Variable Component:- This consist of the space needed by component variables whose size is
dependent on the particular problems instances(Inputs/Outputs) being solved, the space needed by
referenced variables and the recursion stack space is one of the most prominent components. Also this
included the data structure components like Linked list, heap, trees, graphs etc.

Therefore the total space requirement of any algorithm 'A' can be provided as:

Space(A) = Fixed Components(A) + Variable Components(A)

Time Complexity of an algorithm is the amount of computer time it needs to run to completion. The time taken
by a program is the sum of the compile time and the run/execution time . The compile time is independent of the
instance (problem specific) characteristics. Following factors affect the time complexity:

1. Characteristics of compiler used to compile the program.


2. Computer Machine on which the program is executed and physically clocked.
14

3. Multiuser execution system.


4. Number of program steps.

Therefore the again the time complexity consist of two components fixed(factor 1 only) and
variable/instance(factor 2,3 & 4), so for any algorithm 'A' it is provided as:

Time(A) = Fixed Time(A) + Instance Time(A)

‘C’-LANGUAGE
Introduction & History:-
C language is one of the structured programming languages. It was developed by Dennis
Ritchie at Bell laboratories, U.S.A in 1972. It is derived from the language BCPL (Basic Combined
Programming Language).
‘C’ language is called middle level language because ‘C’ supports both features of low-level
language and high-level language. Through low-level features, C language is used for memory
management, bit manipulations and direct memory access using pointers. The high-level language
features are conditional statements, functions and files that are used for general purpose.

Features of C language:-
1. General Programming Language: ‘C’ was originally developed for system programming. But it
is also used for writing commercial as well as scientific applications.
2. Maintainability: It is reliable, simple and easy to use.
3. System Programming: C language is used to develop compilers, operating systems and other
utility programs for system software.
4. Portability: C language is highly portable language i.e. a C program written on one computer can
be compiled and executed on a different computer with less or no modifications in the program.
5. Structured Programming Language: It supports many control structures such as “if, switch,
while, do…while, for” etc. to develop well defined and easy to maintain programs.
6. Modularity: Through modularization, we can break down program code into small functional
units called functions and then integrate them to make a complete application.
7. Limited Keywords: It has only 32 keywords and hence several standard functions are available
with ‘C’ are used for developing error free programs.

Structure of ‘C’ Program


Every C program consists of one or more units called functions. Every C program must contain at
least one function called main( ), which access other functions.
A ‘C’ program can be divided into different sections. They are as shown below:
15

Documentation Section
Link Section
Definition Section
Global Variables Declaration Section
main( )
{
Local variables declaration part Executable
statements part
}
Sub-program Section
Function 1
Function 2
: (User-defined functions)
:
:

Documentation Section:-
It is an optional section that consists of a set of comment lines that are enclosed within /*
and */ and giving the details of the program. The comment lines are not executed in a program.

Example: /* This program finds factorial of a given number */

Link Section:-
It is also an optional section that provides instructions to the compiler to link functions from
the other files.
Example: #include <stdio.h>
#include “sample.c”

Definition Section:-
It is also an optional section that defines the symbolic constants (macros) that are used in the
program.
Examples: #define CITY “DELHI”
#define cube(n) n*n*n

Global Declaration Section:


It is also an optional section that is used to declare variables that are used commonly in all
functions of the program.
Example: extern int a=1,b=2;

main( ) function Section:-


This section is the main program section of a ‘c’ program. Every ‘c’ program must have only one
main( ) function. It contains two parts namely declaration part and executable part.
The declaration part contains all the local variables that are used in the executable part of main( )
function. But this part is optional.
16

The executable part may contain one or more statements to display, read and controlling
programming elements. But this part must contain at least one executable statement.
The declaration part and execution part must be enclosed within curly braces.

Sub-program Section:-
This section contains the definitions of all the user-defined functions. The user-defined
functions can be defined before or after the main( ) function section. This section is also optional
section.
Each and every user-defined function can also be divided into two parts namely declaration
part and executable part.

Example:
/* This program finds area of circle */
#include <stdio.h>
#define PI 3.141
extern int r = 0;
main( )
{
float areaofcircle( );
float area;
clrscr( );
printf(“Enter radius of circle “);
scanf(“%d”,&r);
area = areaofcircle( );
printf(“%f”, area);
}
float areaofcircle( )
{
float a;
a = PI * r * r;
return (a);
}

Compiling And Executing ‘C’ Program

To get a result form C program, we should compile and execute the C program.
Compiling a c program:- Compiler is a translator, which is used to convert a source program into machine
code which is run on computer. Here C compiler helps us to make sure that the program is free from syntax
errors. To compile the program - select  Compile menu command and execute Compile command like the
following.
17

After compiling, we will see as dialog box as shown below. If the compilation is success – we will see a
Success message. Otherwise, we will see the error message with number of errors. These are shown in the
following diagrams.
The screen shot of a Successful compilation:

The screen shot of an Error compilation:

We may run the program only after a successful compilation.

Executing a C program:- To execute the C program – we select  Run menu command and execute
Run command like the following:
18

Now we will see the output on the screen like the screen like the following:

C- Language elements
The C -Character Set :-

The C- character set consists of :

1. Alphabets – A to Z(upper case), a to z (lower case).


2. Digits- 0 to 9.
3. Special Symbols - (+,-,*,/,:, ;, [ ], { }, ( ), #, ?, ‘, “ ,$ ,%, _, etc),
white spaces (blank space, newline, horizontal tab, etc).

C- Language elements(C Tokens) :-

The following are the tokens in C language:


C tokens are the basic buildings blocks in C language which are constructed together to write a
‘C’
 program.
KeywordsEach and every smallest individual units in a C program are known as C tokens.
(or) The smallest individual unit in a C program is called token.
 Identifiers
 Constants
 Operators

Keywords (Reserved Words)


A keyword is a sequence of characters that has standard and pre-defined meaning in the
language. It is also known as reserved word. There are 32 keywords used in ‘C’ language. The
keywords must be used only for their specified purpose. The programmer cannot modify keywords.
The following are the list of keyword in C language.

auto Break case char const continu default do


e
19

double Else enum extern float for goto if


int Long register return short signed sizeof static
struct switch typedef union unsigned void volatile while

Identifiers

An identifier is a name given to a program such as variables, constants, function names,


array names and so on. An identifier is also called user-defined word.
Rules for naming an identifier:-
1. An identifier must contain combination of alphabets, digits and underscore only.
2. The first letter must be an alphabet.
3. The length of an identifier should not exceed 8 characters. But, some compilers allow upto 31
characters.
4. Commas are not allowed
5. Blank spaces are not allowed
6. Special symbols other than underscore are not allowed
7. Keywords must not be used as identifiers.
8. An identifier must not be repeated (declaration) in a program
Examples:
Valid Identifiers: a salary sum emp_name c123 etc.
Invalid Identifiers: a+b ( Special Character present)
2abc ( First letter is not an alphabet)
float ( it is a keyword)

Data Types

The data type specifies what type of data is stored and manipulated in the computer
system. It also specifies the memory usage by a memory variable.
In ‘C’ language, the data types are classified as shown below:
Data Types

Primary Derived User-Defined EmptyData set

Structures Unions Enum typedef void


IntegerFloat Char Arrays Pointers
Primary Data Types:-
The primary data types are also known as scalar (or) fundamental (or) built-in (or) Basic (or)
Pre-defined data types.
There are 3 primary data types used in ‘C’ language.
20

Primary
Datatypes

Integer Floa Character


t

short signed int float signed


short unsigned doubl char
int long signed e unsigned
int long long char
unsigned int double

Integer Family:-
The keyword ‘int’ is used to declare integer type variables. We can use sign qualifiers (signed
or unsigned) and size qualifiers (short or long) in the declaration of integer type variables. The
qualifiers ‘short’ and ‘signed’ are the default qualifiers and hence they are optional in the declaration.
The following table shows integer data types and their range of values:

Memory
Data type Range Format Character
Reserved
int (or) short int (or) -32768 to +32767
2 bytes %d or %i
short signed int (-215 to +215-1)
unsigned int (or) 0 to 65535
2 bytes %u or %ud
short unsigned int (0 to +216-1)
long int (or ) -2147483648 to +2147483647
4 bytes %𝑙d
long signed int (-231 to +231-1)
0 to 4294967295
long unsigned int 4 bytes %𝑙u
(0 to +232-1)
Float Family:-
The keywords ‘float’ and ‘double’ are used to declare float type variables. We can also use
qualifiers to declare float type variables. The following table shows float data types and their range of
values:

Memory
Data type Range Format Character
Reserved

float 4 bytes 3.4e-38 to 3.4e+38 %f or %e

double 8 bytes 1.7e-308 to 1.7e+308 %𝑙f or %𝑙e

3.4e-4932 to
long double 10 bytes %Lf or %Le
1.1e+4932
Character Family:-
The keyword ‘char’ is used to declare character data type variables. It contains any alphabet,
digit (or) special character. The following table shows character data types and their range of values:
21

Memory
Data type Range Format Character
Reserved
char (or) -128 to +127
1 byte %c
signed char (-27 to +27-1)
0 to 255
unsigned char 1 byte %c
(0 to +28-1)

Void data type:-


The data type void is used to specify an empty set of values and do not occupy any memory. Void
type is generally used with functions that do not return any value to the calling portion of the
program.

Variables

A variable is a name which is given to a memory location where the data is stored
temporarily. It is an identifier whose value is changed during the execution of a program.
The user is allowed to access the data from the memory location through the variable name.
A variable can hold only one value in its location.

Rules for naming a variable:-

1. A variable name must contain combination of alphabets, digits and underscore only.
2. The first letter must be an alphabet.
3. The length of a variable should not exceed 8 characters. But some compilers allow upto 31
characters.
4. Commas are not allowed
5. Blank spaces are not allowed
6. Special symbols other than underscore are not allowed
7. Keywords must not be used as variable names.
8. A variable name must not be repeated (declaration) in the declaration
Examples:
Valid Variables: a salary sum stud_name c123 etc.
Invalid Variables: a+b ( Special Character present)
2abc ( First letter is not an alphabet)
float ( it is a keyword)

Declaration of Variables:-
A variable must be declared before it is used in the program. The declaration of variables tells
the compiler to reserve memory space with specified variable names depending on the specified data
type.
The general format of variable declaration is as follows:
Syntax:-

datatype
In the above syntax, var1, var2, …. refers
the ‘datatype’ ; to any valid data type. Var1, var2, …. are the
variable names associated to the data type.
22

Ex:
int a, b, sum ;
float avg, f ;
char ch ;
double xyz ;
Initialization of Variables:-
Assigning a value to a variable while declaration is called initialization of variables. If a
variable is not initialized it contains garbage value.

Syntax:-

datatype var1= value, var2=value, …. ;


Examples:-
int a=40, b=50, c=90;
In this example, variables a, b and c are declared as integer data type and they are initialized
with values 40, 50 and 90 respectively.

Constants
A constant is a fixed value. It doesn’t change its value during the execution of the program.
The following are the different types of constants used in C language.

• Integer Constants
• Floating Point Constants Number Type

• Character Constants Character Type


• String Constants

• Symbolic Constants
23

Integer constants:-
Any number without fractional part is called an integer constant. The integer numbers can
be represented using decimal numbers (0…9) or Octal numbers (0…7) or Hexa-decimal numbers
(0…9 A B C D E F). Octal number must be preceded with ‘0’ and hexa-decimal number must be
preceded with ‘0x’ (or) 0X. An integer constant must not contain commas and spaces.

Ex: 3 -3 15 -15 2500 -9700  Decimal Constants


045 0675 0200  Octal Constants
0x45 0xAF 0x7D4  Hexa-decimal Constants

Floating Point (Real) Constants:-


Floating point constants are also called real numbers. The floating point number can contain
digits (0…9), a decimal point (or) exponent (or) combination of both decimal point and exponent.
The letter ‘E’ or ‘e’ represents the exponent.
Ex: 45.0 4520.2587 -6847.000 -74.56000 etc.
The exponent format (‘e’ notation) can be used to represent very small or large number.
Ex: 650000.00 can be represented as 65E4, 65E+4, 6.5E5, 6.5E+5.
0.000065 can be represented as 65E-6, 6.5E-5.

Character Constants:-
A character constant contains only one character enclosed within single quotes. A character
constant may contain any alphabet, digit or special symbol. It can be used for arithmetic operations.
However, its ASCII value is used in arithmetic operation.
Ex: ‘A’ ‘h’ ‘4’ ‘+’ ‘&’ etc.

String Constants:-
A string constant is a sequence of one or more characters enclosed within double quotes. It
can contain alphabets, digits or special symbols.
Ex: “A” “ABCDE” “%d” “Result = %d” etc.

Symbolic Constants:-
A symbolic constant is a name substituted for sequence of characters. It can be used to
represent a numeric constant or a character constant or a string constant.
Syntax: #define scname sctext
Where ‘scname’ is the name of symbolic constant and ‘sctext’ is the text of a symbolic
constant.
Ex:
#define PI 3.1419
#define name “abcde”
#define max_value 400.75
24

Input-Output Statements

In 'C' language , the input and output statements (or) functions are used to receive data from
the input device and to send data to the output device. These functions are standard built-in
functions which are available in “stdio.h” header file.
The input-output (I/O) functions are classified into 2 categories as shown below:

I / O Statements

Formatted Unformatted

scanf() getch() getche()


printf() getchar() putchar()
getc() putc()
gets() puts()

Formatted I/O Functions :-

The functions that accept numbers, characters and strings as arguments to read and display
using format characters (like %d, %f etc.) are called formatted input-output functions. Using these
functions the values can be formatted (arranged) according to the user requirements. The ‘scanf( )’
and ‘printf( )’ functions are used as formatted I/O functions.

Scanf( ) Function:-
It is a formatted input function which is used to accept data from the user (keyboard) at run
time. The given data is transferred to the memory and is stored in the specified variables.
Syntax:

Inscanf(format-string
the above syntax, the, &var1, &var2, ……
‘format-string’ ) ; to a string constant that contains format
refers
characters according to the type and number of variables. Other characters are not allowed.
var1, var2, …… are the variables to hold the given values. All the variables except string
variables must be preceded by the address (&) operator.
The values that are supplied through keyboard must be separated by either space(s), tab(s),
or newline(s).
Example:- Let a and b are integer type, c is float type, x and y are character type variables. Then
this can be used as follows:
1. scanf(“%d”, &a);
2. scanf(“%d %f”,&a, &c);
25

3. scanf(“%d %f %c”, &a, &c, &y);


Printf( ) Function:-
The printf( ) function is a formatted output function that is used to display the given
information on the standard output device. It is used to print numbers, characters and strings or
combination of the above along with appropriate message.
The syntax of this function can be any one of the following:

Syntax-1: printf(string) ;
In the above syntax, the ‘values-list’ can be variables, constants, or expressions separated by
commas. Syntax-2: printf(string, values-list) ;
The ‘string’ is a string constant that contains the following:
i. Any character in the ‘C’ character set.
ii. Format characters that begin with ‘%’ symbol
iii. Escape sequence characters that begin with ‘\’ symbol

Examples:-
1. printf(“Hello. What is your name?”);
2. printf(“%d”, 70*45);
3. printf(“Sum of 2 numbers = %d”, sum);
4. printf(“Total = %d \n Average = %f”, total, avg);

Unformatted I/O Functions (Character I/O Functions) :-


The unformatted I/O functions only work with character data type. They do not require
formatting characters. The following are some of unformatted functions used in ‘C’ language.

getch() putchar()
getche() putc()
getchar() puts()
getc()
gets()
getch():-
This function is used to accept a character from the console and stores it in a variable, if
specified. It will not echo the character on the screen. It continues program execution whenever we
press any key.
Syntax:- variable = getch();
26

getche():-
This function is used to accept a character from the console and stores it in a variable, if
specified. It will echo the character on the screen. It continues program execution whenever we
press any key.
syntax:- variable = getche();
getchar():-
This function is used to accept a character from the keyboard and stores it in a variable, if specified. It
continues program execution whenever we press ENTER key.
Syntax:- variable = getchar();

getc():-
This function is used to read a character from the file and stores it in a variable, if specified.
Syntax:- variable = getc(filepointer);

gets():-
This function is used to accept a string from the keyboard and stores it in a array variable. It
reads a sequence of characters until ENTER key is pressed. It stores a null character ‘\0’ at the end
of the string.
Syntax:- gets(variable);
putchar():-
This function is used to print a character on the standard output device i.e. monitor.
Syntax: putchar(arg);

Here, the ‘arg’ may be a character constant or character variable.

putc():-
This function is used to store a character in the file.
Syntax: putc(variable, filepointer);

Here, variable represents any character variable and the file pointer is the file variable which
represents the file in which character is stored.

puts():-
This function is used to print a string on the monitor.
Syntax:- puts(string);

Here, the string can be either string constant or string variable.


Operators
An operator is a symbol used to perform different types o f o p e r a t i o n s s u c h a s arithmetic and
logical operations, etc. It is used to manipulate data stored in the variables.
‘C’ language supports the following types of operators.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional or Ternary operator
7. Bitwise operators
8. Special operators

1. Arithmetic operators:-
Arithmetic operators are used to perform arithmetic calculations. The following are the
various arithmetic operators.

Operator Meaning
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulo division (Remainder)

Example: a+b, 5*4 , etc.


2. Relational Operators:-
The relational operators are used to compare two values and to give either true (1) or false
(0) result. The following are the relational operators.

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Examples: a>b, 5<90, n==m


3. Logical Operators:-
These are used to combine two or more conditions and give the result either true or false.
They are used to form compound conditions.
Operator Meaning
&& Logical AND
¦¦ Logical OR
! Logical NOT

Logical AND (&&) Operator-: This operator gives true if all the conditions are true otherwise it
gives false.
Ex:- A && B
Logical OR ( ¦¦ ) Operator-: This operator gives true if any or all the conditions are true otherwise
it gives false.
Ex:- X ¦¦ Y
Logical NOT (!) Operator-: This operator negates the result of a condition. It means if the
condition is true then it gives false. If the condition is false then it returns true.
Ex:- !N

4. Assignment Operators:-
The assignment operators are used to assign (store) a value to a variable. An assignment
operator always consists of a variable on left hand side and a valid expression / constant / variable
on right hand side.
Syntax:-
Expression/
Variable =
Constant/
Variable
Eg: 1) x = 35; y = a + b * c; z = y; a = b = 50;
2) x+=80; y-+30; z*=20; a/=5;

5. Increment and Decrement Operators:-


Increment and decrement operators are used to increment and decrement the value
of an operand by 1. It is incremented and decremented only 1 value at a time. These operators also
called as Unary operators.
Ex: a++; ++a;
n--; --m;
6. Conditional (or) Ternary Operator:-
This operator performs condition based execution. This operator operates on three
operands. Hence it is also known as Ternary Operator. This operator simplifies “if…else” control
statement. The general format of conditional operator is as follows:

Syntax:- (condition) ? Statement-block1 : Statement-block2


; Ex:- a>b ? 5 : 3;
Working:- The conditional operator first tests the given condition. If the condition is true then all
the statements in ‘Statement-block1’ is evaluated. If the condition is false then ‘Statement-
block2’ is evaluated. Statement blocks may contain one or more statements. When there is more
than one statement, they must be separated by commas.
7. Bitwise Operators:-
‘C’ language has the capability of manipulating the bits (0 or 1) directly stored in the
memory. These operators perform bitwise operations on a bit by bit level. However, they must be
used only with integer or character type of values. The operators are as follows:

Operator Meaning
& Bitwise AND
¦ Bitwise OR
^ Bitwise XOR (Exclusive OR)
~ 1’s complement
>> Right shift
<< Left shift
Ex: A<<2, B>>3, x ^ y

8.Special Operators:-

The ‘C’ language support the following special operators:

 sizeof Operator: Ex:- sizeof(a)


 Typecasting: Ex:- (int) a + b;
 Address Operator: Ex: - &a;
 Indirection Operator Ex:- *P;
 Comma Operator Ex:- a=b, c=d, x=y;

Type Conversion And Type Casting


Type conversion and type casting is the process of converting one type into another
type. This kind of operation is needed to evaluate an expression with different types of
operands.

Type Conversion:- ‘C’ language automatically converts lower type to higher type or
same type. For example, Converting int type to long type because int is lower type than
long or float type to long type because both allocates the same size of memory. The result
of the above is higher type.
Ex: int
a=90;
long b;
b=a;
Type Casting:- Sometimes, we may convert higher type to lower type. In such situation,
we must cast the value into one type to a specific type. So that, the process of converting
one type to another is called type-casting. The general form of type casting is as follows.
Syntax:- dataType variable1= (type) variable2;
In the above syntax, the type which is placed in between parenthesis is the
primary data-type which is converted variable2 to variable1.
Ex:- int a;
long
b=80;

a = (int)
b;
In the above example, the long variable ‘b’ is converted to int variable ‘a’.
Example:-
main()
{

int n;
long
a,b;

a=
10;
b = 20;
n = (int) a + b;
printf(“ %d \n“,n);

Expressions in C-Language :-
An expression is a collection of operands joined together by certain operators that represent a value. There
are two types of expressions. They are :
1. Arithmetic or Numeric Expression (it uses arithmetic operators).
2. Relational or Boolean Expression (it uses relational or logical operators).
In the C programming language, an expression is evaluated based on the operator precedence and
associativity. When there are multiple operators in an expression, they are evaluated according to their
precedence and associativity.

What is Operator Precedence?


Operator precedence is used to determine the order of operators evaluated in an expression. In c
programming language every operator has precedence (priority). When there is more than one operator in
an expression the operator with higher precedence is evaluated first and the operator with the least
precedence is evaluated last.

What is Operator Associativity?


Operators Associativity is used when two operators of same precedence appear in an expression.
Associativity can be either Left to Right or Right to Left.
Precedence and Associativity Table
Example Program:-

#include<stdio.h> main()
{
float a,b,c,x,y,z; a=9;
b=12; c=3;
x= a-b/3+c*2-1;
y= a-b/(3+c)*(2-1);
z=a-(b/(3+c)*2)-1;
printf("x = %f\n",x);
printf("y = %f\n",y);
printf("z = %f\n",z);
}

Output:-
x = 10.000000
y = 7.000000
z = 4.000000

Escape Sequence Characters or Backslash Characters:-

C supports some character constants having a backslash in front of it. The lists of backslash characters have
a specific meaning which is known to the compiler. They are also termed as "Escape Sequence Characters".
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
Unit-II : Control Structures (or) Control Statements

Control Structures are the statements used to specify the order in which the instruction is executed in
the program. These are used in the following situations:
 To execute statements based on a condition
 To execute a set of statements repeatedly until a condition is satisfied
 To branch the execution sequence from one statement to another statement.

In ‘C’ language, the control statements are classified into 3 types. They are as follows:
Control Statements

Conditional Control Statements Repetitive/Iterative Control Statements


Unconditional Control Statements

Conditional Control Statements / Decision Control statements/ Branching


Statements if while
do...while
goto
continue
These statements are used to execute a single statement
for
or group of statements sequentially
break
depending
if...else
on the given condition. There are mainly 4 types of conditional statements. They are
1. if statement
2. Nested if/ else-if
if…else statement
3. Nested if statement/else-if ladder
Ladder
4. switch statement
switch

1).if statement
The ‘if’ statement is a conditional execution statement that executes the specified set of
instructions based on the condition. The Syntax and flowchart are as follows:
if (condition) Flowchart
{

statement-block ;
T
} condition T

F Statement-block
F

In the above syntax, the condition is a relational/logical/Boolean expression that must be enclosed within
parenthesis. If the condition is true then the statements in the statement-block are executed, otherwise they
are not executed. To specify more than one statement in a statement-block, they must be enclosed within a
pair of flower braces ({}).
Example:-
1. if (avg >= 75)
printf(“grade is distinction”);
2. if (a < 0)
a++;
2) if…else statement
It is also conditional execution statement that executes the statements based on the
condition. If the condition is true then it executes one group of instructions otherwise it executes
another group of statements. The Syntax and flowchart are as follows:
if (condition)
{ Flowchart

statement-block1 ;
}
T
else FF ccsscondition T
{
statement-block2 ; Statement-block2 Statement-block1

Here, if the condition is true then statement-block1 is executed otherwise statement-block2 is


executed.
Example:-
if (a % 2 = = 0)
printf(“Even number”);
else
printf(“Odd Number”);

3).Nested ‘if’ Statement/else-if ladder


When the ‘if’ statement is used within another ‘if’ statement then it is called “nested if”
statement. The general format is as follows:
Syntax:-
If (condition1)
{
if (condition2)

statement-block1 ;

else
statement-block2 ;
}
else
{
if (condition3)

statement-block3 ;

else
statement-block4 ;
}

Cond-1

In the above syntax,


i. If ‘condition1’ and ‘condition2’ are true then stament-block1 is executed
ii. If ‘condition1’ is true and ‘condition2’ is false then stament-block2 is executed
iii. If ‘condition1’ is false and ‘condition3’ is true then stament-block3 is executed
iv. If ‘condition1’ and ‘condition3’ are false then stament-block4 is executed
Example:
If (x= =y)
{
if (a= =b)
printf(“x is equal to y and a is equal to b”);
else
printf(“x is equal to y, but a is not equal to b”);
}
else
{
if (a= =b)
printf(“x is not equal to y, but a is equal to b”);
else
printf(“x is not equal to y and a is not equal to b”);
}

4). Switch Statement


The ‘switch’ statement is a multiple branching statement. It can be used to make a decision from the
number of choices. It is an extension of ‘if…else’ statement. The general format of switch statement is as
follows: Syntax:- Flowchart:-
switch (op)

case V1 : statement-block1;

[break;]

case V2 : statement-block2;

[break;]

: :

: :

case Vn : statement-block-n;

[break;]

default : statement-block-d;

}
In the above syntax, ‘op’ is either a constant, variable (or) expression that results an integer value. The switch
statement uses the value of ‘op’ to execute the statement-blocks.
V1, V2, …, Vn are the values that represent the value of ‘op’. These are the constants either integer or
character type. These values must be unique.
When statement-block contains many statements then they must be enclosed within a pair of braces ({}).

Working: The switch statement searches for a match of switch variable (op) and case constants (V1, V2, …,
Vn). If a value matches to the ‘op’, the switch statement executes all the statements in that case-block. If there
is ‘break’ statement in that block then it terminates the execution of switch statement. If ‘break’ is not present
then all the statements of remaining blocks are executed.
If any value doesn’t match to the ‘op’ then the ‘default’ block is executed, if it is specified in the switch
statement.
Example: main( )
{
int a;
clrscr( );
printf(“Enter a single digit
number”); scanf(“%d”,&a);
switch (a)
{
case 1: printf(“Sunday”);
break;
case 2: printf(“Monday”);
break;
case 3: printf(“Tuesday”);
break;
case 4:
printf(“Wednesday”);
break;
case 5: printf(“Thursday”);
break;
case 6:
printf(“Friday”);
break;
case 7:printf(“Saturday”);
break;
default:printf(“Wrong digit”);
}
Iterative / Looping / Repetitive Control Statements
The iterative statements are used to execute a single statement or a group of statements
repeatedly or continuously as long as the given condition has been satisfied. The iterative
statements are also called Repetitive (or) Looping control statements.
In 'C' language, there are 3 types of repetitive control structures. They are
1. while
2. do…while
3. for

while Statement (while loop)


This statement is used to execute one or more statements repeatedly as long as the specified
condition is satisfied. It is an entry control loop statement. The syntax and flowchart of while
statement is as follows:

Syntax:-

while (condition)

statement-block;

}
In the above syntax,
1. The ‘condition’ is a relational expression that must be enclosed within parenthesis.
2. The statement-block specifies one or more statements. When there is more than one
statement, they must be enclosed with in braces ({}).

Working:- The ‘while’ statement executes all the statements in the statement-block as long as the
given condition true. When the condition false then the loop is terminated and the control is
transferred to the statement after the statement-block.

Example: A program to print first ‘n’ natural numbers.


#include<stdio.h>
void main( )
{
int a=1, n;
clrscr( );
printf(“Enter n
value”);
scanf(“%d”,&n);
while (a<=n)
{
printf(“%d \t”, a);
a++;
}
}

do…while Statement
This statement is used to execute one or more statements repeatedly as long as the specified
condition is satisfied. It is an exit control loop structure. The do…while structure executes at least
one time even initially the condition is false.

Syntax:-
do
{
statement-block;
} while (condition);
In the above syntax,
1. The ‘condition’ is a relational expression that must be enclosed within parenthesis.
2. The statement-block specifies one or more statements. When there is more than one
statement, they must be enclosed in braces ({}).

Working:-The ‘do…while’ statement executes all the statements in the statement-block first and
then tests the condition. When the condition true (non-zero) then the loop is repeated otherwise the
loop is terminated.
Example: A program to print first ‘n’ natural
numbers. #include<stdio.h>
main( )
{
int a=1, n;
clrscr( );
printf(“Enter n
value”);
scanf(“%d”,&n);
do
{
printf(“%d \t”, a);
a++;
} while (a<=n);
}

for Statement
This statement is used to execute a set of statements repeatedly as long as the specified
condition is satisfied.

Syntax:-
for(initialization ; condition ; increment/decrement)
{
statement-block;
}

Here,

 The initialisation specifies assignment statements for the loop variable.


 The condition is a relational expression used to execute statements repeatedly and to terminate
the loop
 Increment/decrement specifies assignment statements used to change the value of the loop
variable.
 The statement-block specifies one or more statements. When there is more than one statement,
they must be enclosed in braces ({}).
Working:- It evaluates the statement in initialisation part and then it checks the condition. If the
condition is true then it executes all the statements in the statement-block. After executing all the
statements, increment/decrement part is executed. This looping process is continued as long as
condition is true. When the condition is false, the loop is terminated.

Flowchart:-

initialization

F
condition
co

Increment /
T decrement

Statement-block

Example:-
A program to find and print the sum of first ‘n’ natural numbers.
#include<stdio.h>
void main( )
{
int a, n, sum=0;
clrscr( );
printf(“Enter n
value”);
scanf(“%d”,&n);
for (a=1; a<=n; a++)
{
printf(“%d \t”, a);
sum+=a;
}
printf(“Result = %d”,sum);
}

Unconditional Control Structures


The unconditional control statements are used to change the execution sequence of a
program by transferring the control from one place to another place within a program without using
any condition.
The following are the unconditional control structures used in 'C' language.
1. goto
2. break
3. continue

goto Statement
The ‘goto’ statement is an unconditional branching statement used to transfer the program
control from one place to another place within a program.
Syntax:-
goto label ;

Here, the label is an identifier used to name the target location to which the control is
transferred. The target statement must be named with label name followed by a colon as follows:

label : statement ;
The label names must be unique within a program.

Working:- While program execution, when ‘goto’ statement is reached then it branches the
execution control to the specified label in the program and it continues execution from that point.

Example: Forward Jump Example: Backward Jump


void main( ) void main( )
{ { int num;
int num; input: printf(“Enter a value”);
printf(“Enter a scanf(“%d”,&num);
value”); if (num < 0 )
scanf(“%d”,&num); goto input;
if (num < 0 printf(“Value = %d”,num);
) goto }
end;
printf(“Value = %d”,num);
end : printf(“End of
program);
}

break Statement
Normally the break statement is used in switch statement. But it is also used to terminate the
execution of a loop unconditionally.
Syntax:-
break ;

Example:
void main( )
{

int i, num, n, sum=0;


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

for(i=1;i<=n;i++)
{
scanf(“%d”,&num);
if (num<0)
break;
sum=sum+num;
}
printf(“Result=%d”,sum);
}

continue Statement
The continue statement must be used in loops only. When the continue statement is reached
within a loop, it continues the execution from the first statement of the loop.
Syntax:-
continue;

Example:-
void main( )
{
int i, n, sum, num;
printf(“How many values?”);
scanf(“%d”,&n);
i=0;
while (i<=n)
{
i++;
scanf(“%d”,&num);
if (num<0)
continue;
}
}
UNIT–III : Arrays & Strings

Arrays
Definition: An array is a collection of elements of same type that share a common name.
The elements of an array are stored in contiguous memory locations.
In ‘C language, arrays are classified into two types. They are
1. One Dimensional Arrays
2. Multi Dimensional Arrays

One dimensional array


When an array is declared with only one dimension (subscript) then it is called “One
dimensional array” or “single dimensional array”.
Declaration of one dimensional Array:-
The general format of declaring a one dimensional array is as follows:
Syntax:-
datatype arrayname[size] ;
In the above syntax,
 The datatype is any valid data type of ‘ C’ language. An array can hold all the values based
on the specified data type.
 The ‘arrayname’ is an identifier that specifies name of the array variable. All the elements
will share this variable name.
 The ‘size’ indicates maximum number of elements that an array can hold. It must be a
positive integer constant.

Example-1: int a[5];


The above declaration reserves 5 contiguous memory locations of integer data type for the
array ‘a’. The conceptual view for the above declaration is as shown below:

0 1 2 3 4

a[0] a[1] a[2] a[3] a[4]


Storing values into the Array
To store the array elements, we follow the following two methods. They are:
- Initialization of the array
- Reading the array elements

Initialization of the Array:-


While declaring an array, we can initialize it with some values. The general format to
initialize one dimensional array is as follows:

Syntax:-
datatype arrayname[size] = {V0, V1, …, Vsize-1} ;
Here, V0, V1, …, Vsize-1 are the initial values of the specified array. If we omit the values
then an array contains garbage values. The number of values must be less than or equal to the size
of the array. When there are few values then the remaining elements are assigned with zeros.
Ex:
a[0] a[1] a[2] a[3] a[4]
int a[5] = {78, 34, 98, 90, 124}; 
78 34 98 90 124

Reading the arrays elements: To read the array elements thru keyboard, we write and execute the
following example

for(i=0;i<n;i++)
scanf(“%d”,&num[i]);
Accessing elements of the Array :-
Once we store the elements of an array, we may access the elements of the array. To access
the array elements, we use the index numbers of the array. The index numbers are used to identify a
particular location of the array. The following example is used to accessing the elements of an array
and prints them on the screen.
main()
{
int a[]={ 5, 6, 9, 7, 3};
int i;
clrscr();

printf(“The Elements are \n”);


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

printf(“ %d \n”, a[i]);


getch();

Two-Dimensional Arrays
When an array uses only two subscripts then it is called “two-dimensional array”. A two-
dimensional array is useful for matrix operations.
Declaration of Two-Dimensional Array:-
The general format of declaring a two dimensional array is as follows:
Syntax:-
datatype arrayname[rowsize][columnsize] ;
In the above syntax,
 The datatype is any valid data type of ‘C’ language. An array can hold all the values based
on the specified data type.
The ‘arrayname’ is an identifier that specifies name of the array variable. All the elements
will share this variable name.
 The ‘rowsize’ indicates maximum number of rows and ‘columnsize’ indicates number of
columns in a row.
Example: int a[4][3];

Here, it reserves 12 (4 rows x 3 columns) integer type memory locations for the array ‘a’.
The conceptual view for the above declaration is as shown below:
a[4][3]

0 1 2

0
1
2
3
Initialization of Two Dimensional Array:-
While declaring an array, we can initialize it with some values. The general format to
initialize two dimensional array is as follows:
Syntax:-
datatype arrayname[rowsize][columnsize] = {{row1 values}, {row2 values}, …, } ;

Here, If we omit the values then an array contains garbage values. The number of values
must be less than or equal to the size of the array. When there are few values then the remaining
elements are assigned with zeros.
Example-1:
int a[2][3] = { {4, 6, 8}, {1, 3, 5}};

This example initializes the array ‘a’ with the given values as shown below:
a 0 1 2
0 4 6 8
1 1 3 5
Example-1:
int a[2][3] = { {4, 8}, {5}};
This example initialises the array ‘a’ with the given values as shown below:
a 0 1 2
0 4 8 0
1 5 0 0

Accessing of two dimensional arrays:-


Each two dimensional array element is referred or accessed by specifying the array name
followed by two subscripts. The subscripts must be enclosed within square brackets.
For example,
a[0][0] refers to the first element in the two dimensional
array. a[rowsize-1][colsize-1] refers to the last element of the
array.
The remaining elements can be accessed as a[0][1], a[2][3], a[1][2] and so on.
The two dimensional array that contains ‘m’ rows and ‘n’ columns can be read using loops
as follows:
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);

Differences between one-dimensional and two-dimensional arrays


One-Dimensional Array Two-Dimensional Array
A one-dimensional array is a group of elements A two-dimensional array is a group of one-
of same type. dimensional array of same type

A one-dimensional array must be declared by A two-dimensional array must be declared by


arrayname followed by only one subscript arrayname followed by 2 subscripts
A one-dimensional array is declared as A two-dimensional array is declared as
follows: datatype arrayname[size]; follows: datatype arrayname[rowsize]
[colsize];
Example: Example:
int num[4]; int num[3][4];
Here, variable ‘num’ can hold 4 values Here, variable ‘num’ can hold 12 (3x4) values
The conceptual view for the above example is The conceptual view for the above example is
as follows: as follows:

A one-dimensional array must be referred by A one-dimensional array must be referred by


arrayname followed by only one subscript arrayname followed by one or two subscripts
Initialisation of one-dimensional array is as Initialisation of two-dimensional array is as
follows: follows:
int num[4]={10, 20, 30, 40}; int num[2][2]={{10, 20}, {30, 40}};

Calculating the length of the array:- To find the length of the array, we use the sizeof() function.
In ‘C’ language, once we declare the array variable, the variable allocates maximum size of the
array which we given the size of the array. The following example is used to find out the size of the
array.

int a[50];
int n = sizeof(a);

Strings
Definition:- A string is a sequence of one or more characters. Any group of characters enclosed
within double quotes is a string constant. In ‘C’ language, strings are manipulated using arrays and
pointers.
Ex: “Hello” “Computer Science” etc.
A string is a one dimensional array of characters terminated by a null (\0) character. The null
character is stored at the end of array of characters to mark the end of the string. If an array is used
to store the strings then that array is often called “string variable”. A string that is not terminated by
‘\0’ is not really a string, but it is only a collection of characters.

Operations on strings:-
The common operations performed on strings are:
i. Reading and writing strings
ii. Combining strings together (concatenation)
iii. Copying one string to another
iv. Comparing strings for equality
v. Finding the number of characters in a string (length)

Declaring a String Variable:-


To manipulate strings, an array must be declared with character data type. A string can be
declared as follows:
Syntax:- char arrayname[size];
The ‘size’ is the number of characters in the array.
Example: char name[40]; char city[15]; etc.

Initializing a String Variable:


1. A string of characters can be stored in an array as
follows: Ex: 1. char city[6] =
{‘D’,’E’,’L’,’H’,’I’};

2. char city[6] =
“DELHI”; (OR)
char city[] = “DELHI”;
In the above examples, the ‘ C’ compiler automatically inserts ‘\0’ character at the end. So, the
conceptual view for the above examples is as shown below:
D E L H I \0
2. A string can be initialized using pointers as follows:
Ex: char *city = “DELHI”;

Here, it stores the string “DELHI” into memory and assigns the starting location address to
the pointer variable ‘city’. The conceptual view for the above example is as shown below:

city 4650 4651 4652 4653 4654 4655


4650 D E L H I \0

Array of Strings (or) Two-dimensional character type array:-


To store more than one string in the array, then the array can be declared as follows
char arrayname[size1][size2];
Here, ‘size1’ specifies the number of strings and ‘size2’ refers the number of characters in
each string.

Example: char city[3][10] = {“DELHI”,”BANGALORE”,”CHENNAI”};


This example reserves 3 memory locations to store 3 strings. Each string may contain 10
characters (10 bytes). The conceptual view for the above declaration is

City[0] D E L H I \0
City[1] B A N G A L O R E \0
City[2] C H E N N A I \0

scanf( ) and printf( ) functions:-


Strings can be read and write using formatted I/O functions by the format character “%s”.
While using “%s” character, the address operator and subscript should not be specified for the
array.
When %s character is used with scanf( ) function, it terminates its input at the first white
space character (white space characters are blanks, tabs and carriage return i.e.‘\n’). For example, if
we input “NEW DELHI”, then it takes only “NEW”.
Example:
#include<stdio.h>
#include<string.h>
void main( )
{
char name[30];
printf(“Enter a string “);
scanf(“%s”,name);
printf(“%s”,name);
}

gets( ) and puts( ) Functions:-


These functions are also used to read and write strings. The gets( ) function reads a string
upto carriage return i.e. ‘\n’ pressed. The puts( ) functions writes the specified string on the monitor.
These functions will not require any format character to read and write strings.
Example:
#include<stdio.h>
#include<string.h>
void main( )
{
char name[30];
printf(“Enter a string
“); gets(name);
puts(name);
}

Built-In String Functions


In ‘C’ language, there are several functions are used to manipulate strings. These
functions are included in “string.h” file. The following are some of the most commonly used
string functions:
1. strlen( ) Function:-
This function finds the length of the given string. It means it counts and returns the number
of characters present in the string. The output of this function is an integer.
Syntax:- strlen(string); Where ‘string’ is constant or array variable.

Example:
#include<stdio.h>
#include<string.h>
main( )
{
int n;
char name[10] = “ABCDE”;
n = strlen(name);
printf(“length = %d”, n);
}
Output : 5

2. strrev( ) Function:-
This function is used to reverse all the characters in the given string except null character.
Where ‘string’ is constant or array variable.

Syntax:- strrev(string);

Example:

#include<stdio.h>
#include<string.h>
main( )
{
char name[10] =
“ABCDE”; strrev(name);
puts(name);
}
Output : EDCBA

3. strlwr( ) Function:-
This function converts all the uppercase letters in the given string into lowercase.
Where ‘string’ is constant or array variable.

Syntax:- strlwr(string);

Example:

#include<stdio.h>
#include<string.h>
main( )
{
char name[10] = “aBcDe”;
strlwr(name);
puts(name);
}
Output : abcde

4. strupr( ) Function:-
This function converts all the lowercase letters in the given string into uppercase.
Where ‘string’ is constant or array variable.

Syntax:- strupr(string);

Example:

#include<stdio.h>
#include<string.h>
main( )
{
char name[10] = “aBcDe”;
strlwr(name);
puts(name);
}
Output : ABCDE

5. strcpy( ) Function:-
This function copies the contents of one string (source) to another string (destination). The
contents of the source string are unchanged. Where ‘string1’ is destination string and ‘string2’ is
source string. The contents of string2 are copied to string1.

Syntax:- strcpy(string1, string2);

Example:
#include<stdio.h>
#include<string.h>
main( )
{
char a[10] = “ABCDE”;
char b[10];
strcpy(b, a);
puts(b);
}
The above example copies the contents of ‘a’ to ‘b’. Hence the output is ABCDE.

6. strcat( ) Function:-
This function appends the contents of one string (source) to another string (destination).
This is called concatenation of two strings. The contents of the source string are unchanged.
Where ‘string1’ is destination string and ‘string2’ is source string. The contents of string2 are
appended to string1.
syntax:- strcat(string1, string2);
Example:
#include<stdio.h>
#include<string.h>
main( )
{
char a[30] = “ABC”;
char b[30] = “DEF”;
strcat(b, a);
puts(b);
}
The above example append the contents of ‘a’ to ‘b’. Hence the output is DEFABC
7. strcmp( ) Function:-
This function is used to compare two strings.
Syntax:- strcmp(string1, string2)
Here,
1. If string1 is equal to string2 then it returns value 0
2. If string1 is less than string2 then it returns a negative (less than 0) value.
3. If string1 is greater than string2 then it returns positive (greater than 0) value.

Example:
#include<stdio.h>
#include<string.h>
main( )
{
char a[30], b[30];
int c;
printf(“Enter First String”);
gets(a);
printf(“Enter Second String”);
gets(b);
c = strcmp(a, b);
if (c = = 0)
printf(“String1 and string2 are equal”);
else
if (c < 0)
printf(“String1 is less than string2”);
else
if (c > 0)
printf(“String1 is greater than string2”);
}
UNIT-IV : Pointers & User Defined Functions
Pointers
Definition:- A pointer is a variable that holds the memory address of a data item such as a variable,
an array element, etc.

The organization of memory is designed in such a way that it contains continuous locations
called memory cells to store data. The size of memory location that is assigned to each data value
depending on the type of data declared. A unique numeric address is allotted to each of these
memory locations for easy accessing of data. It is possible for the programmer to access this
memory address using a special variable called pointer.

Uses or Advantages of Pointers:-


1. Pointers provide the flexibility of creation of dynamic variables, accessing and manipulating the
contents of memory locations and releasing the memory occupied by dynamic variables which
are no longer needed.
2. Array elements can be easily accessed.
3. Arguments passed to a function can be modified. Thus making a function to return more than
one value. Simply it provides call-by-reference mechanism.
4. We can send arrays and strings to functions.
5. Dynamic data structures like linked list, binary trees and graphs can be created.
6. Memory can be efficiently used through dynamic memory allocation (DMA).
7. Execution of program will be faster.

For instance, let ‘P’ is a pointer variable that contains the address of another variable ‘Q’. then
‘P’ is said to be pointing to ‘Q’. If the address of ‘Q’ is 1625 then the value of ‘P’ would be 1625.
Using this address we can manipulate the value of ‘Q’. It can be as shown below:

Pointer variable P Q Variable of type int

Value of P 1625 50
Value of Q
Address of P 2956 1625 Address of Q

Declaring a Pointer Variable:-


A pointer declaration contains a base type and asterisk (*) followed by a variable. A pointer
variable is an unsigned integer and hence it occupies 2 bytes of memory. The general format for
declaring a pointer variable is as follows:
Syntax:-
datatype *variable;
Here, the datatype is the base type of the pointer. The base type defines the type of object
(variable) to which the pointer will point. The base type must match to the type of object to
which a pointer points.
Example:
int *p;
float *m;
The above declaration indicates that p is a pointer variable to hold the address of an integer
variable. The variable ‘m’ holds the address of a float variable.

Pointer Operators:-
‘C’ language provides two special operators to manipulate the data items directly from
memory location using pointer variables.
1. Address Operator (&):-
The address operator is used to get and assign the address of a variable to a pointer variable.
Ex: pv = &v;
Where ‘pv’ is a pointer variable which holds the address of the variable ‘v’. So ‘pv’ is a
pointer to ‘v’ that points to the location of ‘v’ as shown below:

Points
Address of v Value of v
to
pv v
The above diagram shows the relationship between ‘pv’ and ‘v’. Hence pv=&v and v=*pv.

2. Dereference Operator (or) Indirection Operator (*):-


a pointer is a variable that stores the address of another variable. The dereference
operator is also known as an indirection operator, which is represented by (*). When indirection operator
(*) is used with the pointer variable, then it is known as dereferencing a pointer. When we dereference a
pointer, then the value of the variable pointed by this pointer will be returned.
The asterisk (*) character is used as indirection operator. It is a unary operator that returns the value
located at the address. For example, v=*pv;
This statement assigns the value stored at address ‘pv’ into the variable ‘v’. Hence *pv can also be assumed
as *(&v) is equal to ‘v’.

Example: :
main( )
{
int a=50;
int *p;
p = &a;
printf(“Value of a = %d “,a);
printf(“Address of a = %u “,&a);
printf(“Value of p = %u”,p);
printf(“Address of p = %u”,&p);
printf(“Address of a = Value of p = %u”,p);
printf(“Value of a = *p = %d”,*p);
}
Output:
Value of a =
Address of a =
Value of p =
Address of p =
Address of a = Value of p =
Value of a = *p =

Pointer Assignment:-
Like simple variables, a pointer variable can also be assigned to another pointer variable.
Example:
main( ) 1468p a
50
{ 2565
int a=50; int *p, *m; p=&a;
1468
m = p;
printf(“Value of p = %u”,p); 1468 m
printf(“Value of m = %u”,m); 3789
}
Pointer Expressions and Pointer Arithmetic
Like other variables, pointer variables can be used in expressions and also construct the pointer arithmetic.
For example: if P1 and P2 are declared and initialized as pointer variables. Then construct the arithmetic
expression like the following.
X = *p1 * *p2;
Sum = *p1 + *p2;

*p2 = *p1 – 35;

In the above example, the values of pointer variables P1 and P2 are evaluated and
assigned the result to the variables.

Example:

main()
{
int *p1, *p2,x,sum,a,b;

a=20;

b=30;
p1=&a;
p2=&b;

x= *p1 * *p2;

sum = *p1 + *p2;

printf(“ Multiplication = %d\n”,x);


printf(“Addition=%d\n”,sum);

}
Pointers and arrays :-
There is a close relationship between pointers and arrays. The elements of an array can be
efficiently accessed by using pointers. ‘C’ Language provides two methods of accessing array
elements. They are pointer arithmetic method and array indexing method. However, pointer
arithmetic will be faster.
To access array elements, the address of first element (base address) of an array can be
assigned to the pointer variable and using this address we can access the remaining elements of that
array.
For example,
int a[10], *p;
p = &a;
Assigns the base address of the array variable ‘a’ to the pointer variable ‘p’. Now to access 5th
element of ‘a’, we can write either a[4] or *(p+4).

Example:
main( )
{
int a[20],i , n,
*p; clrscr( );
printf(“How many values
“); scanf(“%d”,&n);
p = a; /* assigns beginning address of ‘a’ to ‘p’
*/ for(i=0;i<n;i++)
scanf(“%d”,(p+i)); /* inputs value to array thru pointer */
for(i=0;i<n;i++)
printf(“%3d”,*(p+i)); /* displays value of array thru pointer */
}

Array of Pointers:-
A pointer can also be declared as an array. As a pointer variable always contains an address,
an array of pointers contains a collection of addresses. Like an array, the elements of an array of
pointers are also stored in the memory in contiguous memory locations.
The general form to declare an array of pointers is as follows:

Syntax:
datatype *arrayname[size];
Here ‘dataype’ is the base type of pointer array and the size indicates the number of
elements in the pointer array.

Example:
main( )
{
int a[5]={10,20,30,40,50}, i;
int *p[5];
for(i=0;i<5;i++)
p[i] = &a[i];
for(i=0;i<5;i++)
printf(“%u “,p[i]);
}
In the above example, the pointer variable ‘p’ holds the address of the elements of array
variable ‘a’. This can be as shown below:
a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50

1001 1003 1005 1007 1009

1001 1003 1005 1007 1009


p[0] p[1] p[2] p[3] p[4]

Pointer to Pointers:-
We can use a pointer to point another pointer that points to the target value. This is called
multiple indirection or pointer to pointer.
The value of pointer is the address of a variable that contains the desired value. In the case
of a pointer to pointer, the first pointer contains the address of a variable and the second pointer
contains the address of first pointer which points to the object that contains desired value.

Declaring a Pointer to Pointers:


The general format to declare a pointer to pointer is as follows:
datatype **variable;

Here the datatype is the base type of the variable to which the pointer is pointing. The
variable represents the name of the pointer variable.

Example:
int a=50, *p,
**m; p = &a;
m = &p;
The above example can be represented as shown below:

m p a

2002 1001 50

3003 2002 1001


Dynamic memory allocation (DMA)
Dynamic Memory Allocation means allocation of memory at run-time i.e. during program
execution. We can use DMA technique, when it is not known how much memory space is required.
‘C’ language provides various standard functions to manage memory efficiently. They are used to
allocating memory to the variables and to empty memory locations.

Memory management functions :-

1.malloc( ) Function:-
Using this function, we can allocate memory space to a variable. The space must be
specified in the form of bytes. This function returns NULL if the allocation of memory fails. It
means, if the memory is not sufficient to allocate then it returns NULL.
The general format of malloc( ) function is as follows:
Syntax:
pv = (type *) malloc(size);
Here ‘pv’ is pointer variable and ‘type’ is the data type of the variable. The size is a numeric
constant or expression that indicates the number of bytes allocated to the variable.
Example-1:
int *p;
p = (int *) malloc(4);
Here, it allocates 4 bytes of memory to the variable ‘p’. Hence we can use the variable ‘p’ as two
elements of ‘int’ type.

Example-2:
float *p;
p = (float *) malloc(sizeof(float));
Here, it allocates 4 bytes of memory to the variable ‘p’, because the size of float is 4
bytes. Example-3:
int *p, n=5;
p = (int *) malloc(n*sizeof(int));
This example allocates memory for 5 integers of two bytes each i.e. 10 bytes.

2.calloc( ) Function:-
This function is also used to allocate space to a variable. But it initializes all the elements
with zero. Normally this function is used to allocate space for arrays and structures.
Syntax:
pv = (type *) calloc(n, size);
Here ‘pv’ is pointer variable and ‘type’ is the data type of the variable. The ‘n’ is number of
elements and the size specifies the number of bytes for each element.

Example-1:
int *p;
p = (int *) calloc(1, 2);
This example creates only one memory location and allocates two bytes to that
element. Example-2:
int *p, n=5;
p = (int *) calloc(n, sizeof(int));
This example creates n elements of 2 bytes each i.e. 5x2 = 10 bytes.
3.free( ) Function:-
This function is used to remove (free) the allocated space of a variable. Once memory is
released, we must allocate memory space to that variable later.

Syntax:
free(pv);

Here, ‘pv’ is a pointer variable which is having some memory space.


Drawbacks of pointers:-
1. Uninitialized pointers might cause segmentation fault.
2. Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory
leak.
3. Pointers are slower than normal variables.
4. If pointers are updated with incorrect values, it might lead to memory corruption.

User Defined Data Types : Structures

A structure is a collection of data items of different data types or same data type that
are referenced under one name.
The structure concept provides a convenient way of keeping related information together.
The data items that form the structure are called members (Also called elements or fields). The
individual elements can be accessed and processed separately. We can define our own data type by
using structures.

Declaring a Structure:-
The keyword ‘struct’ is used to define a structure. The structure definition is as follows:
Syntax:
Struct tag
{

datatype member1;
datatype member2;
:
:
datatype member-n;

} var1, var2, …, var-n ;

In the above syntax,


 The tag is the name of the structure
 Member1, member2, …, member-n are the individual members of the structures. These are
nothing but variables.
 Var1, var2, …, var-n are the structure type variables.
Example:
Struct stud
{
int htno;
char name[30];
int m1, m2;
float avg;
} st1, st2;
The above example defines a structure called ‘stud’ and declares variables st1 and st2 of that
type.

Structure variables can also be declared separately as follows:


struct stud st1, st2;

In the above examples, for each variable i.e. st1 or st2, the conceptual view of memory
representation is as shown below:

2 bytes 30 bytes 2 bytes 2 bytes 4 bytes

St1.htno St1.name St1.m1 St1.m2 St1.avg


Accessing Structure Elements:-
Individual members of a structure are accessed through the use of dot (.) operator. This
operator is placed between a structure type variable and the field being used.
Syntax:-

Structurevariable . membername

For example, to access the members of ‘st’ variable declared in the above example are as follows:

St.htno accesses the member htno of st variable


St.name accesses the member name of st
variable.

Initializing structure type variables:


Like simple and array variables, structure type variables can also be initialised while they
are declaring.
Syntax:
struct tag var1={values}, var2={values}, ……, var-n = {values};
Here,
Var1, var2, …, var-n are the structure type variables. The values for the structure variables must be
enclosed within curly braces. The values must be separated by commas. The number and order of
values must be same to the number and order of members defined in the tag.
Example:
Struct stud st1={1,”ABC”,45,55}, st2={2,”XYZ”,90,89};
Structure Assignments:-
The information contained in one structure can be assigned to another structure of the same
type using assignment operator. We do not need to assign the values of each member separately.
Syntax:
Structurevariable1 = structurevariable2 ;

Example:
Struct temp
{
int a,b;
};
main( )
{
struct temp m,n;
printf(“Enter 2 values “);
scanf(“%d %d”,&m.a, &m.b);
n = m; /* structure assignment */
printf(“a=%d , b=%d “,n.a, n.b);
}

Array of structures :-
Like any other type, we can also declare an array of structures. To declare an array of
structures, we must first define a structure and then declare an array of that type.
Syntax:
Struct tag arrayname[size];
Example:
Struct student
{
int htno;
char name[20];
float avg;
} st[20];

The above example creates 20 elements of type ‘student’. The conceptual view of the above
declaration is as shown below:

htno name avg


St[0]
St[1]
St[2]
:
:
:
St[19]
To access an individual element in an array of structures, we use a subscript or index. Like
all array variables, arrays of structures also begin indexing at 0. The individual members are
accessed as follows:
St[0].htno, st[2].name, st[19].avg , …….

Self referential Structures :-


A structure which contain a member field that point to the same structure type is called self-
referential structure. In C, this kind of process is needed to implement linked- lists. The following
structure is represented as self-referential structure.

struct Node
{
int item;
struct Node *link;
};
The diagrammatic representation of the above structure is as follows.

Node

item link

Here the data is stored in the item field and the link is pointer to the next node.
Example:
struct Linked_List
{
int item;
struct Linked_List *link;
}Node;

main()
{
Node *head;
head = (Node *) malloc (sizeof(Node));
head item = 35;
headlink(Node *) malloc (sizeof(Node));
headlinkitem=55; headlinklink=NULL;
printf(“ % d \n”,headitem); printf(“
% d \n”,headlinkitem);

}
Differences between Structures and Arrays:-

Arrays Structures
1. An array is a group of elements of same type 1. A structure is a collection of data items may
that share a common name of different types referenced under one name

2. An array type variable can be defined using 2. A structure can be defined by using the
square brackets. keyword ‘struct’
Example: int a[20]; Example:
Struct stud
{
int htno;
char nm[5];
float avg;
} st;
3. The individual elements are accessed by 3. The individual members of the structure are
writing a value in square brackets after array accessed through the use of dot operator.
name. Example:
Example: st.htno refers to htno of
A[0] represents first element st st.nm refers to nm of st
th
A[3] represents 4 element

4. The conceptual view of the above array in 4. The conceptual view for the above structure
the memory is is

a[0] a[1] a[2] a[19] St.htno st.nm st.avg

5. Arrays can be initialised while they are 5. The structure members are initialised as
declaring as follows follows
int a[5]={1,3,5,6,2}; Struct stud st={1,”ABC”,75.25};

6. The direct assignment is not possible 6. Variables of same type structures can
between two array variables assigned directly
int a[5]={1,2,3,4,5}, b[5]; Struct stud st1={1,”ABC”,75}, st2;
b = a; is invalid assignment st2 = st1; is valid assignment

7. If we access the name of the array, it returns 7. If we access name of the structure, it returns
base address of the array the value of first element in the structure
User Defined Data Types : Unions

A union is a collection of data items of different data types or same data type that are
referenced under one name.
All the members of a union share the same storage area within the computer’s memory.
Unions are useful for the applications involving multiple members where values need not be
assigned to all of the members at one time.
When a union is declared, the compiler automatically allocates memory location to hold
largest data type of members in the union.
Declaring a Union:-

The keyword ‘union’ is used to define a union. The union definition is as follows:
Syntax:
union tag
{

datatype member1;
datatype member2;
:
:
datatype member-n;

} var1, var2, …, var-n ;

In the above syntax,


 The tag is the name of the union
 Member1, member2, …, member-n are the individual members of the union. These are
nothing but variables.
 Var1, var2, …, var-n are the union type variables.

Example:-
union temp
{
int a;
float b;
char c;
} m,
n;
The above example defines a union called ‘temp’ and declares variables ‘m’ and ‘n’ of that
type.
Union variables can also be declared separately as follows:
union temp m, n;
In the above examples, the union variables occupy 4 bytes of memory. Because the largest member
in the above example is ‘b’ of float data type.

The memory representation for the above declaration is as shown below:

m.a
m.b
m.c

In the above example, all the members i.e. a, b and c share same storage area i.e. 4 bytes of
memory.

Accessing Union Members:-


We can access the individual members of a union through the use of a dot operator. The
general format is as follows:
Unionvariable.member;
Example: m.a, m.b, ……

Differences between Structures and Unions:-

Structures Unions
1. Structure is a collection of data item 1. Union is also collection of data item may of
may of different data types referenced different data types referenced under one name
under one name

2. Structure is defined by ‘struct’ keyword 3. The union is defined by ‘union’ keyword


as as
Struct tag
union tag
{
{
datatype member1;
datatype member1;
datatype member1;
datatype member1;
:
:
datatype member-n;
} var1, var2, …, var-n; datatype member-n;
} var1, var2, …, var-n;

3. In a structure, memory is reserved for all 3. In a union, memory is reserved only for the
members of that structure largest member of that union
4. All members of structure cannot share 4. All members of structure can share the same
the same storage area storage area
5. All members of structure can be 5. All members of union cannot be accessed at a
accessed at a time time
6. We can store data for all members in the 6. We can store data for only one member of an
structure union
7. The structure variables can be initialized 7. The union variables cannot be initialized. But if
and can give values for all members we want to initialize, we can give value to the
Example: first member only
Struct temp m={10, 50.25, ‘M’}; Example:
Union temp m={10};

Enumeration data types

An enumeration data type is a derived (user-defined) data type which is similar to structures
and unions. Its members are constants. These constants represent values and they can be assigned to
corresponding enumerated variables.
Enumeration types are user-defined types that allows programmer to name a finite set of
elements which are called enumerators or enumeration constants or enumeration members.

Defining a Enumeration type:-


The general format for defining enumeration type is as follows:

Syntax:- enum tag {id1, id2, id3, ……, id-n};

Here, ‘tag’ is the name of enumeration type and id1, id2, id3, ……., id-n are identifiers
which represent enumeration constants. By default, ‘c’ compiler assigns integer values starting from
zero to each identifier automatically. But we can change these values.
Ex-1: enum grade {distinction, first, second, third} ;
In this example, ‘grade’ is the name of enumeration tag, and ‘distinction, first, second, third’
are the enumeration constants which assigns values 0, 1, 2, 3 respectively.
Ex-2:-
enum grade {distinction=10, first=20, second=30, third=40} ;
In this example, enumeration constants are assigned with values 10, 20, 30 and 40
respectively.
Note:
1. An enumeration constant cannot be read from the keyboard.
2. An enumeration constant can be assigned to any integer variable.
3. An enumeration constant can also be printed.

Declaring Enumeration Variables:


Once enumeration type has been defined, one or more variables of that type can be declared.
The declaration is as follows:

Syntax:- enum tag var1, var2, ..., var-n ;


Every variable of enumeration type occupies only two bytes of memory.
Ex: enum grade g;

Sample program:-

main( )
{
enum colour {red, blue, green, yellow};
enum colour c;
c = red; /* assigns ‘red’ i.e. the value 0 to the variable ‘c’
*/ if (c = = yellow)
printf(“yellow”);
else if (c = = red)
c=
blue; else if (c
= = 2)
} printf(“green”);
UNIT-V : Functions & Files
Definition:- A function is a self-contained program block that performs some specific task.
Every ‘C’ program consists of one or more functions. One of these functions must be called main( ).
In C, Functions are divided into two types. They are:
1. Standard or built-in functions 2. User-defined functions.

The use of user-defined functions allows a large program to be broken down into a number of
smaller functions (modules).

Uses of functions:-
There are several advantages to this modular approach, they are
 The use of function avoids the need for redundant (repeated) programming of the same
instructions.
 The functions can be accessed many times within a program by passing different values as
parameters.
 Functions improve the logical clarity of a program. That means such programs are easier to
write and debug.
 The use of functions also enables a programmer to develop a user-defined library of frequently
used modules. This library file can be included in any program.

Defining a Function:-
A user-defined function must be defined within a program before using it. If a program
contains multiple functions, their definitions may appear in any order, and they must be
independent of one another. One function definition cannot be included within another.
The definition of a function has 2 parts. They are (i) Function header and (ii) Function body.
The general form for defining a function is as
follows: Syntax:
returntype functionname(datatype arg1, datatype arg2, …, datatype arg-n)
{

function-body ;
[return(value);]
}

Here,
1. The ‘returntype’ represents the type of value of the item that is returned by the function to
its calling point. The default return type is ‘int’.
2. The ‘function name’ is an identifier that represents the name of user-defined function
3. Arg1, arg2, …, arg-n are the variables (arguments) that represent formal parameters of the
function. These are receiving values from the calling point. However, a function can be
defined without arguments.
4. The data types represent the type of arguments.
5. The function body may contain one or more statements. These statements can be
input/output, assignment and control statements etc.
6. The ‘return’ statement returns a value to the function’s calling point, if it is
used.
Example:-
float adding(int a, float b)
{
float c;
c = a + b;
return(c);
}

Calling (Accessing) a function:-


Once a function is defined, it can be called (accessed) by specifying its name followed by a
list of arguments (actual parameters) enclosed within parenthesis and separated by commas.
Whenever a function is called, the execution control is transferred to that function. After
completion of function execution, the control returns back to the calling point.
The general form for calling a function is as follows:
Syntax:-
functionname(arg1, arg2, …, arg-n) ;

Where, ‘function name’ is name of user-defined function that must be available in the program.
Arg1, arg2, …, arg-n are the values that are send to the function. These are referred as actual
arguments.
While accessing a function, the following points must be remembered:
i. The number and order of actual parameters and formal parameters must be same.
ii. When a function returns a value to its calling point then the returned value must be assigned
to a variable or it must be used in the output function.

Example-1:- A function without return type and parameters.


main( )
{
void message( );
clrscr( );
message( );
printf(“End of program”);
}
void message( )
{
printf(“Hello. This is a sample function”);
}

Example-2: A function with return type and parameters.


main( )
{
float adding(int a, float b);
int a;
float b, c;
clrscr( );
scanf(“%d %f”,&a,
&b); c = adding(a, b);
printf(“Result = %f”,c);
}

float adding(int a, float b)


{
return (a+b);
}
Function declaration / prototype:-
In ‘C’ language, the called function must be declared in the declaration section of the calling
function like any other variable. This declaration of function is called function prototype. It tells the
compiler the called function, the type of data that the function will actually return and the type and
number of arguments it takes.
However, function prototype is not required in the following cases:
1. When the return type is ‘int’
2. When a function is defined before main( ) function.
The general format of a function prototype is as follows:
Syntax:-

returntype functionname(datatype arg1, datatype arg2, …, datatype arg-n) ;


Here, the prototype declaration must match to the function header. However, the function
prototype consists of the dummy arguments list. These can be omitted but the argument data types
are essential.
Example:
main( )
{
float adding(int , float); /* Function Declaration or Function Prototype */
int a;
float b, c;
clrscr( );
scanf(“%d %f”,&a,
&b); c = adding(a, b);
printf(“Result = %f”,c);
}
float adding(int a, float b) /* Function Definition */
{
return (a+b);
}

Note:- If a function does not return anything, or it does not have any arguments to declare, then the
function can be declared using void as follows
Ex: void reading( void );
return statement:-
The return statement is used to return a value from a user-defined function to its calling
point. This statement can be used in the following ways:
Syntax-1: return ;
Syntax-2: return (value) ;

When a return statement is executed, the control returns back to the calling point. If a value
is given along with return statement, it replaces the value at the calling point. The value can be
constant, variable or expression. The value may or may not be enclosed within the parenthesis.
The return statement can return only one value to its calling point. The return statement can
occur anywhere and many times in the body of the function.
Examples:
1. return ;
2. return (25);
3. return 25;
4. return (x+y);
5. return x+y;

Passing parameters :-
Parameters are used for exchanging the information between the calling point and called
function. There are two types of parameters. They are (i) Actual Parameters and (ii) Formal
Parameters.
Actual Parameters:- The parameters that are included in function calling point are called “actual
parameters”. These are used to send values to the called function.

Formal Parameters:- The parameters that are included in function definition are called “formal
parameters”. These are used to receive values from the calling point.
While using actual and formal parameters the following rules must be followed:
1. The number of actual parameters must be equal to the number of formal parameters.
2. The data types of actual parameters must be same to their corresponding formal parameters.
3. The actual and formal parameters may or may not be having same names

Example:
-main( )
{
float adding(int , float);
int a = 15;
float b = 25.75, c;
clrscr( );
c = adding ( a, b);
Actual Parameters
printf(“Result = %f”,c);
}
float adding(int m, float n)
{ Formal Parameters
return (m+n);
}

Parameter Passing Techniques :-


Information is passed to a function from the calling point by using parameters. In ‘C’
language there are two types of methods used to send parameters to a function. They are :
(i) Call-by- value Method
(ii) Call-by-reference Method
i. Call-by-value Method:
In this method, we can send only values to a called function. Whenever a function is called
with parameters, the value of an argument is sent to the formal parameter.
Inside the function, the values of formal parameters can be used and changed according to
the need. But, when the control is returned back to its calling point, the changed values of formal
parameters are not transferred. This type of passing technique is called call-by-value mechanism.
Ex:-
main( )
{
int a=10, b=20;
void swap(int, int);
printf(“Before swapping, a=%d, b=%d”,a,b);
swap(a, b);
printf(“After swapping, a=%d, b=%d”,a,b);
}

void swap(int x, int y)


{
int temp;
temp =
x; x = y;
y = temp;
}
Output:
Before swapping, a=10,
b=20 After swapping, a=10,
b=20
ii. Call-By-Reference Method:
This method is also known as Call-by-address (or) call-by-location method. In this method,
we can send addresses of actual arguments to the called function. Whenever a function is called
with parameters, the address of an argument is sent to the formal parameter.
Inside the function, when the formal parameter is changed then value of actual argument is
also changed. This is method of passing technique is called call-by-reference method. This
technique is performed through pointers.
main( )
{
int a=10, b=20;
void swap(int *, int *);
printf(“Before swapping, a=%d, b=%d”,a,b);
swap(&a, &b);
printf(“After swapping, a=%d, b=%d”,a,b);
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output:
Before swapping, a=10,
b=20 After swapping, a=20,
b=10

Scope and lifetime of variables


(Local and Global Variables) :-

The place of declaration of variables specifies the scope and lifetime of variables. Based on
place of declaration, the variables are classified into two types. They are
1. Local (Internal or Private) variables
2. Global (External or Public) variables
Local Variables:-
The variables that are declared inside a function are called local variables. The local
variables are created when the function is called and destroyed (deleted) when function is finished
its execution.
The local variables are referred (accessed or used) only within the function in which they
are declared i.e. these variables’ lifetime is only within function in which they are declared.
Global Variables:-
The variables that are declared outside a function are called global variables. The global
variables are created at the beginning of the program and destroyed (deleted) when program is
completed. These variables’ lifetime is entire program.
The global variables are accessed in all functions within the program that follows the
declaration of these variables.

Example for Local and Global Variables:-

#include <stdio.h>
int x=10, y=30; /* Global to all functions
*/ main( )
{
void sample1(
); void
sample2( );
int a=10, b=10; /* Local to function main( ) */
a = a + x;
sample1( )
;
sample2( )
; b = b + y;
printf(“%d %d”,a,b);
}
int n=20; /* Global to the functions sample1 and sample2*/
void sample1( )
{
int m=30; /* Local to the function sample1( ) */
printf(“%d %d”,m, n);
}
void sample2( )
{
int k=20; /* Local to the function sample2( )
*/ printf(“%d %d”,k, n);
}

Storage classes
A storage class is used to declare variables. It tells the compiler the following points.
 The location of the variable i.e. where the variable would be created i.e. either in memory or
in CPU registers.
 The default initial value of the variable
 The scope of variable i.e. in which function the value of a variable would be available
 The life of the variable i.e. how long a variable exists

The following are various storage classes are used to declare variables in ‘C’ language.
1. Automatic Storage class (auto)
2. Register storage class (register)
3. Static storage class (static)
4. External storage class (extern)

The general format for declaring variables using storage class is as follows:

Storageclass datatype var1, var2, …., var-n ;


Automatic Storage Class:
Automatic variables are always declared within a function with the keyword ‘auto’. They
are local to the function in which they are declared. They are created when the function is called
and destroyed automatically when the function is completed.
A variable declared inside a function without storage class specification is, by default, an
automatic variable.

Example:
main( )
{
auto int x, y;

}
sample( )
{
auto float x, y;

Register Storage Class:-


The register variables are always declared within the function with the keyword ‘register’.
They are local to the function in which they are declared. They are created when the function is
called and destroyed automatically when the function is completed.
The register variables are created in C.P.U. registers. These variables can be accessed faster
than the variables stored in the memory. But only few variables can be created in the register,
because the number of CPU registers is limited.

Example:
main( )
{
register int x, y;
register char
ch;

}
sample( )
{
auto float x, y;
}

Static Storage Class:-


The static variables are always declared within a function with the keyword ‘static’. The
static variable holds its value within the function throughout the life of the program.
Example:
main( )
{
void sample( );
sample( );
sample( );
sample( );
}
void sample( )
{
auto int a=1;
static int b=1;
printf(“a=%d, b=%d \n”,a,b);
a++;
b++;
}
Output:
a=1,
b=1
a=1,
b=2
a=1,
b=3

External Storage Class:-


The external variables are always declared outside a function with the keyword ‘extern’.
These variables are global to all the functions in the program.
The variables declared outside a function without any storage class is, by default, external
variable. But, whenever we use the keyword ‘extern’, the variables must be initialised.

Example:
extern int a=1,
b=2; main( )
{
void sample( );
printf(“a=%d, b=%d \n”,a,
b); sample( );
printf(“a=%d, b=%d \n”,a, b);
}
void sample( )
{
a = a + 10;
b = b+20;
}
Output:
a=1, b=2
a=11, b=22

Recursion

Recursion is a process by which a function calls itself repeatedly. In the recursion process, a
function is repeated endlessly or until some specified condition has been satisfied. Recursion is
used for repetitive computations in which each action is started in terms of a previous result.
For Example, to find factorial of 5, it can be recursively computed as
follows: 5! = 5 x 4!
4! = 4 x 3!
3! = 3 x 2!
2! = 2 x 1!
1! = 1
In the same way, the factorial of n is recursively defined
as, N! = N * (N-1)! if N > 1
= 1 if N <=1

long int fact( int n)


{
if ( n <= 1 )
return (1) ;
else
return ( n * fact ( n-1) );
}
FILES

Definition :-
A file is a collection of bytes that contains some information permanently. A file is created
in secondary storage devices.

Use of Files :-
Normally, a program inputs and outputs values as handled through the variables, which are
created in primary memory. So the values given by a user are stored temporarily. Once program
execution is completed, the values are also automatically removed.
Hence to store data permanently in the memory, we can use files concept. A file is created
in the secondary memory device such as disk or tape. When a file is created, we can modify or
delete data present in the file as and when needed.

Terminology :-
In ‘c’ language, the information is stored in a file in the form of fields and records.
Field:- It is an elementary data item (int, float or char) that is used to store a single unit of data.
For example, EMPNO is a field name that represents employee number.

Record:- A set of fields is called a record. For example, a group of empno, empname,and salary
is a record.
File:- A file is collection of related records. For example, employee file contains employee records.

FILE datatype:-
To manipulate files in ‘c’ language, we must use FILE data type. It is a structure
datatype that is used to create file buffer area. The general format is as follows:

Syntax: FILE *fp;

Here, FILE is the name of data type and ‘fp’ is file pointer which will contain all the
information about the file.

Opening a File ( fopen( ) function):-


A file should be opened before it is used in the program. The fopen( ) function is used to
open a file. If the file open operation is success, this function returns a FILE pointer otherwise it
returns NULL.
The general format for opening a file is as follows:
Syntax: fp = fopen(filename,mode) ;

In the above syntax,


1. The ‘fp’ is file pointer that is declared earlier with FILE datatype.
2. The ‘filename’ is a sting that represents name of the file in the secondary memory.
3. The ‘mode’ is a string that contains special characters. It represents the purpose for which
the file is opened such as reading, writing and so on.
Examples:-
f1 = fopen(“student”,”r”);
f2 = fopen(“emp.dat”,”w”);
f3 = fopen(“sample.txt”,”a”);
Where f1, f2, f3 are the file pointers which are declared earlier as
follows: FILE *f1, *f2, *f3;

The following are different file modes used in ‘c’ language:

Mode Meaning
“r” Opens text file for reading
“w” Opens text file for writing
“a” Opens text file in append mode
“rb” Opens binary file for reading
“wb” Opens binary file for writing
“ab” Opens binary file for append
“r+” Opens text file for reading and writing
“w+” Opens text file for writing and reading

Closing a File ( fclose( ) function) :-

The opened file must be closed at the end of all input and output operations done on it. The
fclose( ) function is used to close an opened file. Once a file is closed, we cannot perform any
operation on that file until it is opened again.
Syntax: fclose(fp);

Here, ‘fp’ is file pointer that holds the opened file.

File Processing Functions or File Handling Functions


The following functions are used to manipulate data in the files.

fgetc() function:-
This function is used to read a single character from the file and stores it in a variable.

Syntax:- variable = fgetc(fp);

Here, ‘variable’ is a character type variable and ‘fp’ is file pointer.

fgets() function :-
This function is used to read the specified number of characters from the file and stores it in
a variable.

Syntax:- fgets(str, n, fp);


Here, ‘str’ is a string variable. ‘n’ is number of characters to be read from the file. ‘fp’ is file
pointer. It means, this function reads ‘n’ characters from the file ‘fp’ and stores it in the variable
‘str’.
Ex: fgets(nm, 10, fp);

fscanf() function:-
This function is used to read data items from the file and stores them into variables. It reads
values based on formatting characters specified. This function returns an integer if it is success
otherwise it returns zero. The general format is as follows:

Syntax:- fscanf(fp, format-string, variable-list) ;

Here, ‘fp’ is file pointer. The ‘format-string’ contains formatting characters. The ‘variable-
list’ contains one or more variables.

Ex: fscanf(fp, “%d %s %f”,&rno, snm, &avg);

fputc() function:-
This function is used to store a single character into file. The general format is as follows:

Syntax:- fputc(ch, fp);

Here, ‘ch’ is a character variable or constant and ‘fp’ is file pointer.

fputs() function:-
This function is used to store a string into the file.
Syntax:- fputs(string, fp);

Here, ‘string’ is a string constant or variable. ‘fp’ is file pointer.


Ex: fgets(nm, fp);

fprintf() function:-
This function is used to store data items into the file. It writes values based on formatting
characters specified. The general format is as follows:

Syntax:- fprintf(fp, format-string, variable-list) ;

Here, ‘fp’ is file pointer. The ‘format-string’ contains formatting characters. The ‘variable-
list’ contains one or more variables separated by commas.
Ex: fprintf(fp, “%d %s %f”,rno, snm, avg);

feof() function:-
This function checks whether end of file has been reached or not. It returns non-zero when
end of file is reached otherwise it returns zero.
Syntax:- feof(fp); where ‘fp’ is file pointer

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy