C Notes
C Notes
Programming in C
UNIT-1
Introduction to Computer:
Computer is an electronic device that is designed to work with Information. The term computer is
derived from the Latin term ‘computare’, this means to calculate or programmable machine.
Computer cannot do anything without a Program. It represents the decimal numbers through a
string of binary digits. Charles Babbage is called the "Grand Father" of the computer. The First
mechanical computer designed by Charles Babbage was called Analytical Engine. It uses read-
only memory in the form of punch cards.
Computer is an advanced electronic device that takes raw data as input from the user and processes
these data under the control of set of instructions (called program) and gives the result (output) and
saves output for the future use. It can process both numerical and non-numerical (arithmetic and
logical) calculations.
Classification of Computers
1. Analog Computers
Analog computers are used to process continuous data. Analog computers represent variables by
physical quantities. Thus any computer which solve problem by translating physical conditions
such as flow, temperature, pressure, angular position or voltage into related mechanical. Analog
computers are very much speedy. They produce their results very fast. But their results are
approximately correct. All the analog computers are special purpose computers.
2. Digital Computers
Digital computer represents physical quantities with the help of digits or numbers. These numbers
are used to perform Arithmetic calculations and also make logical decision to reach a conclusion,
depending on, the data they receive from the user.
3. Hybrid Computers
Various specifically designed computers are with both digital and analog characteristics combining
the advantages of analog and digital computers when working as a system. Hybrid computers are
being used extensively in process control system where it is necessary to have a close
representation with the physical world. The hybrid system provides the good precision that can be
attained with analog computers and the greater control that is possible with digital computers.
Classification of Computers According to Size
1. Super Computers
Large scientific and research laboratories as well as the government organizations have extra
ordinary demand for processing data which required tremendous processing speed, memory and
other services which may not be provided with any other category to meet their needs. Therefore
very large computers used are called Super Computers. These computers are extremely expensive
and the speed is measured in billions of instructions per seconds.
2. Main Frame Computers
The most expensive, largest and the most quickest or speedy computer are called mainframe
computers. These computers are used in large companies, factories, organizations etc. the
mainframe computers are the most expensive computers; they cost more than 20 million rupees. In
this computers 150 users are able to work on one C.P.U. The mainframes are able to process 1 to 8
bits at a time. They have several hundreds of megabytes of primary storage and operate at a speed
measured in nano second.
3. Mini Computers
Mini computers are smaller than mainframes, both in size and other facilities such as speed, storage
capacity and other services. They are versatile that they can be fitted where ever they are needed.
Their speeds are rated between one and fifty million instructions per second (MIPS). They have
primary storage in hundred to three hundred megabytes range with direct access storage device.
4. Micro Computers
These are the smallest range of computers. They were introduced in the early 70’s having less
storing space and processing speed. Micro computers of todays are equivalent to the mini
computers of yesterday in terms of performing and processing. They are also called “computer of a
chip” because its entire circuitry is contained in one tiny chip.
5. Laptop Computers
The smallest computer in size has been developed. This type of small computers look like an office
brief case and called "LAPTOP" computer. The laptops are also termed as "PORTABLE
COMPUTERS." Due to the small size and light weight, they become popular among the computer
users.
Generations of Computer:
The history of the computer goes back several decades however and there are five definable
generations of computers. Each generation is defined by a significant technological development
that changes fundamentally how computers operate.
1940 – 1956: First Generation – Vacuum Tubes
These early computers used vacuum tubes as circuitry and magnetic drums for memory. As a result
they were enormous, literally taking up entire rooms and costing a fortune to run. These were
inefficient materials which generated a lot of heat, sucked huge electricity and subsequently
generated a lot of heat which caused ongoing breakdowns. These first generation computers relied
on ‘machine language’ (which is the most basic programming language that can be understood by
computers).
1956 – 1963: Second Generation – Transistors
The replacement of vacuum tubes by transistors saw the advent of the second generation of
computing. Although first invented in 1947, transistors weren’t used significantly in computers
until the end of the 1950s. They were a big improvement over the vacuum tube, despite still
subjecting computers to damaging levels of heat. The language evolved from cryptic binary
language to symbolic (‘assembly’) languages. These meant programmers could create instructions
in words. About the same time high level programming languages were being developed (early
versions of COBOL and FORTRAN).
1964 – 1971: Third Generation – Integrated Circuits
The computers of third generation used Integrated Circuits (ICs) in place of transistors. A single IC
has many transistors, resistors, and capacitors along with the associated circuitry. This development
made computers smaller in size, reliable, and efficient. In this generation remote processing, time-
sharing, multiprogramming operating system was used. High-level languages (FORTRAN-II TO
IV, COBOL, PASCAL PL/1, BASIC, ALGOL-68 etc.) were used during this generation.
1972 – 2010: Fourth Generation – Microprocessors
This revolution can be summed in one word: Intel. The chip-maker developed the Intel 4004 chip in
1971, which positioned all computer components (CPU, memory, input/output controls) onto a
single chip. What filled a room in the 1940s now fit in the palm of the hand. The Intel chip housed
thousands of integrated circuits. The year 1981 saw the first ever computer (IBM) specifically
designed for home use and 1984 saw the Macintosh introduced by Apple. All the high-level
languages like C, C++, DBASE etc., were used in this generation.
2010- : Fifth Generation – Artificial Intelligence
Computer devices with artificial intelligence are still in development, but some of these
technologies are beginning to emerge and be used such as voice recognition. AI is a reality made
possible by using parallel processing and superconductors. Leaning to the future, computers will
be radically transformed again by quantum computation, molecular and nano technology. The
essence of fifth generation will be using these technologies to ultimately create machines which can
process and respond to natural language, and have capability to learn and organize themselves.
Anatomy Of A Computer
1. Input: This is the process of entering data and programs in to the computer system. You should
know that computer is an electronic machine like any other machine which takes as inputs raw data
and performs some processing giving out processed data. Therefore, the input unit takes data from
us to the computer in an organized manner for processing.
2. Storage: The process of saving data and instructions permanently is known as storage. Data has
to be fed into the system before the actual processing starts. It is because the processing speed of
Central Processing Unit (CPU) is so fast that the data has to be provided to CPU with the same
speed. Therefore the data is first stored in the storage unit for faster access and processing. This
storage unit or the primary storage of the computer system is designed to do the above
functionality. It provides space for storing data and instructions.
The storage unit performs the following major functions:
• All data and instructions are stored here before and after processing.
• Intermediate results of processing are also stored here.
3. Processing:
The task of performing operations like arithmetic and logical operations is called processing. The
Central Processing Unit (CPU) takes data and instructions from the storage unit and makes all sorts
of calculations based on the instructions given and the type of data provided. It is then sent back to
the storage unit.
4. Output: This is the process of producing results from the data for getting useful information.
Similarly the output produced by the computer after processing must also be kept somewhere inside
the computer before being given to you in human readable form. Again the output is also stored
inside the computer for further processing.
5. Control: The manner how instructions are executed and the above operations are performed.
Controlling of all operations like input, processing and output are performed by control unit. It
takes care of step by step processing of all operations inside the computer.
FUNCTIONAL UNITS
In order to carry out the operations mentioned in the previous section the computer allocates the
task between its various functional units. The computer system is divided into three separate units
for its operation. They are
1) arithmetic logical unit
2) control unit.
3) central processing unit.
It is very expensive.
Auxiliary Memory
Auxiliary memory is much larger in size than main memory but is slower. It normally stores system
programs, instruction and data files. It is also known as secondary memory. It can also be used as
an overflow/virtual memory in case the main memory capacity has been exceeded. Secondary
memories cannot be accessed directly by a processor. Characteristics of Auxiliary Memory are
following −
Non-volatile memory − Data is not lost when power is cut off.
Reusable − The data stays in the secondary storage on permanent basis until it is not
overwritten or deleted by the user.
Reliable − Data in secondary storage is safe because of high physical stability of secondary
storage device.
Convenience − With the help of a computer software, authorized people can locate and
access the data quickly.
Capacity − Secondary storage can store large volumes of data in sets of multiple disks.
Cost − It is much lesser expensive to store data on a tape or disk than primary memory.
Computer Software:
Computer software’s are divided in to two categories.
Computer Software
1 System Software
System software is a collection of programs that interfaces with the hardware. Some common
categories of system software are described as follows.
Language translator: It is system software that transforms a computer program written by a user
into a form that can be understood by the machine.
Operating system (OS) this is the most important system software that is required to operate a
computer system. An operating system manages the computer’s resources effectively, takes care of
scheduling multiple jobs for execution, and manages the flow of data and instructions between the
input/output units and the main memory. An operating system has become a part of computer
software with the advent of the third generation computers.
2 Application Software
Application software is written to enable the computer to solve a specific data processing task.
There are two categories of application software: pre-written software packages and user
application programs.
Ex:
Database management software
Spreadsheet software
Word processing, Desktop Publishing (DTP), and presentation software
Multimedia software
Data communication software
Statistical and operational research software
Introduction to Operating System:
Operating System is software that works as an interface between a user and the computer hardware.
The primary objective of an operating system is to make computer system convenient to use and to
utilize computer hardware in an efficient manner. The operating system performs the basic tasks
such as receiving input from the keyboard, processing instructions and sending output to the screen.
Various types of operating systems' are UNIX, MS-DOS, MS-Windows - 98/XP/Vista, Windows-
NT/2000, OS/2 and Mac OS.
The first, it manages the hardware and software resources of the computer system. These
resources include the processor, memory, disk space, etc
The second, it provides a stable, consistent way for applications to deal with the hardware
without having-to know all the details of the hardware.
Characteristics:
1) Operating System is a Collection of Programs those are Responsible for the Execution of
other Programs.
2) Operating System is that which Responsible is for Controlling all the Input and Output
Devices those are connected to the System.
3) Operating System is that which Responsible is for Running all the Application Software’s.
4) Operating System is that which Provides Scheduling to the Various Processes Means
Allocates the Memory to various Process those Wants to Execute.
5) Operating System is that which provides the Communication between the user and the
System.
Types of Operating System:
i) Multiuser OS:
In a multiuser OS, more than one user can use the same system at a same time through the multi I/O
terminal or through the network.
For example: windows, Linux, Mac, etc.
ii) Multiprocessing OS:
A multiprocessing OS can support the execution of multiple processes at the same time. It uses
multiple number of CPU. It is expensive in cost however the processing speed will be faster. It is
complex in its execution. Operating system like Unix, 64 bit edition of windows, server edition of
windows, etc. are multiprocessing.
iii) Multiprogramming OS:
In a multiprogramming OS more than one programs can be used at the same time. It may or may
not be multiprocessing. In a single CPU system, multiple program are executed one after another by
dividing the CPU into small time slice. Example: Windows, Mac, Linux,etc.
iv) Multitasking OS:
In a multitasking system more than one task can be performed at the same time but they are
executed one after another through a single CPU by time sharing. For example: Windows, Linux,
Mac, Unix,etc
v) Multithreading:
A program in execution is known as process. A process can be further divided into multiple sub-
processers. These sub-processers are known as threads. A multi-threading OS can divide process
into threads and execute those threads. This increases operating speed but also increases the
complexity. For example: Unix, Server edition of Linux and windows.
vi) Batch Processing:
A batch processing is a group of processing system in which all the required input of the entire
processing task is provided initially. The result of the entire task is provided after the completion of
all the processing. Its main functions are:
1. Multiple task are processed
2. User cannot provide input in between the processing
3. It is appropriate only when all the inputs are known in advance
4. It requires large memory
5. CPU ideal time is less
6. Printer is the appropriate output device
7. It is old processing technique and rarely used at present
Program Fundamentals:
1. Generations and Classifications of Programming Languages:
FIRST GENERATION OF PROGRAMMING LANGUAGE:
The first generation of programming language, or 1GL, is machine language. Machine language is
a set of instructions and data that a computer's central processing unit can execute directly. Machine
language statements are written in binary code, and each statement corresponds to one machine
action.
SECOND GENERATION PROGRAMMING LANGUAGE
The second generation programming language, or 2GL, is assembly language. Assembly language
is the human-readable notation for the machine language used to control specific computer
operations. An assembly language programmer writes instructions using symbolic instruction codes
that are meaningful abbreviations or mnemonics. An assembler is a program that translates
assembly language into machine language.
THIRD GENERATION PROGRAMMING LANGUAGE
The third generation of programming language, 3GL, or procedural language uses a series of
English-like words that are closer to human language, to write instructions.
High-level programming languages make complex programming simpler and easier to read, write
and maintain. Programs written in a high-level programming language must be translated into
machine language by a compiler or interpreter. PASCAL, FORTRAN, BASIC, COBOL,C and C++
are examples of third generation programming languages.
FOURTH GENERATION PROGRAMMING LANGUAGE
The fourth generation programming language or non-procedural language, often abbreviated as
4GL, enables users to access data in a database. A very high-level programming language is often
referred to as goal-oriented programming language because it is usually limited to a very specific
application and it might use syntax that is never used in other programming languages. SQL,
NOMAD and FOCUS are examples of fourth generation programming languages.
Advantages of 4GLs
Programming productivity is increased. One line of a 4GL code is equivalent to several lines
of a 3GL code.
System development is faster.
Program maintenance is easier.
End users can often develop their own applications.
Programs developed in 4GLs are more portable than those developed in other generation
languages.
Documentation is of improved order because most 4GLs are self-documenting.
FIFTH GENERATION PROGRAMMING LANGUAGE
The fifth generation programming language or visual programming language is also known as
natural language. Provides a visual or graphical interface, called a visual programming
environment, for creating source codes. Fifth generation programming allows people to interact
with computers without needing any specialized knowledge. People can talk to computers and the
voice recognition systems can convert spoken sounds into written words. Prolog and Mercury are
the best known fifth-generation languages.
During the process of translation, the compiler reads the source program statement- wise and
checks for syntax errors. In case of any error, the computer generates a printout of the same. This
action is known as diagnostics. There is another type of software that also does translation. This is
called an interpreter.
Compiling and Executing High-level Language Programs
The compiling process consists of two steps:
The analysis of the source program and the synthesis of the object program in the machine language
of the specified machine.
The analysis phase uses the precise description of the source programming language. A source
language is described using lexical rules, syntax rules, and semantic rules.
The second stage of translation is called syntax analysis or parsing. In this phase, expressions,
declarations, and other statements are identified by using the results of lexical analysis.
Interpreter:
A program that executes instructions written in a high-level language. There are two ways to run
programs written in a high-level language. The most common is to compile the program; the other
method is to pass the program through an interpreter.
An interpreter translates high-level instructions into an intermediate form, which it then executes. In
contrast, a compiler translates high-level instructions directly into machine language. Compiled
programs generally run faster than interpreted programs. Both interpreters and compilers are
available for most high-level languages.
Difference between Compiler and Interpreter:
Compiler Interpreter
It Scans the entire program before Translates and executes the program line
translating it into machine code by line.
Converts the entire program to machine The interpreter executes one line at a time,
code and executes program only when all after checking and correcting its syntax
the syntax errors are removed errors and then converting it to machine
code.
Slow in debugging or removal of mistakes Good for fast debugging.
from a program
Program execution time is less. Program execution time is more.
Linker
Linking resolves symbolic references between object programs. It makes object programs known to
each other. The features of a programming language influence the linking requirements of a
program. In FORTRAN/COBOL, all program units are translated separately. Hence, all
subprogram calls and common variable references require linking. PASCAL procedures are
typically nested inside the main program. Hence, procedure references do not require linking; they
can be handled through relocation. References to built-in functions however require linking. In C,
files are translated separately. Thus, only function calls that cross file boundaries and references to
global data require linking. Linking makes the addresses of programs known to each other so that
transfer of control from one subprogram to another or a main program takes place during execution.
Loader
Loading means physically placing the machine instructions and data into main memory, also known
as primary storage area. A loader is a system program that accepts object programs and prepares
them for execution and initiates the execution. The functions performed by the loader are:
Assignment of load-time storage area to the program
Loading of program into assigned area
Relocation of program to execute properly from its load time storage area
Linking of programs with one another
PROGRAMMING LANGUAGES:
To write a computer program, a standard programming language is used. A programming language
is composed of a set of instructions in a language understandable to the programmer and
recognizable by a computer. Programming languages can be classified as high-level, middle-level,
and low-level. High-level languages such as BASIC, COBOL (Common Business Oriented
Programming Language), and FORTRAN (Formula Translation Language) are used to write
application programs. A middle-level language such as C is used for writing application and system
programs. A low-level language such as the assembly language is mostly used to write system
programs. Low-level programming languages were the first category of programming languages to
evolve. Gradually, high-level and middle-level programming languages were developed and put to
use.
1 System Programming Languages
System programs or software’s are designed to make the computer easier to use. An example of
system software is an operating system consisting of many other programs that control input/output
devices, memory, and processor, schedule the execution of multiple tasks, etc.
2 Application Programming Languages
There are two main categories of application programs: business programs and scientific application
programs. Application programs are designed for specific computer applications, such as payroll
processing and inventory control. To write programs for payroll processing or other such
applications, the programmer does not need to control the basic circuitry of a computer. Instead, the
programmer needs instructions that make it easy to input data, produce output, perform
calculations, and store and retrieve data.
3 Low-level Languages
A low-level computer programming language is one that is closer to the native language of the
computer, which is 1’s and 0’s.
3.1 Machine language
This is a sequence of instructions written in the form of binary numbers consisting of 1’s and 0’s to
which the computer responds directly. The machine language is also referred to as the machine
code.
Advantage of machine language
The CPU directly understands machine instructions, and hence no translation is required. Therefore,
the computer directly starts executing the machine language instructions, and it takes less execution
time.
Disadvantages of machine language
1. Difficult to use:
It is difficult to understand and develop a program using machine language. For any- body
checking such a program, it would be difficult to forecast the output when it is executed.
2. Machine dependent
The programmer has to remember machine characteristics while preparing a program. As the
internal design of the computer is different across types, which in turn is determined by the actual
design or construction of the ALU, CU, and size of the word length of the memory unit.
3. Error prone
It is hard to understand and remember the various combinations of 1’s and 0’s representing data and
instructions. This makes it difficult for a programmer to concentrate fully on the logic of the
problem, thus frequently causing errors.
4. Difficult to debug and modify
Checking machine instructions to locate errors are about as tedious as writing the instructions.
Further, modifying such a program is highly problematic.
3.2 Assembly language
When symbols such as letters, digits, or special characters are employed for the operation, operand,
and other parts of the instruction code, the representation is called an assembly language
instruction. Such representations are known as mnemonic codes; they are used instead of binary
codes. A program written with mnemonic codes forms an assembly language program. This is
considered to be a second generation language (2GL).
Machine and assembly languages are referred to as low-level languages since the coding for a
problem is at the individual instruction level. Each computer has its own assembly language that is
dependent upon the internal architecture of the processor.
Advantage of assembly language
Writing a program in assembly language is more convenient than writing one in machine language.
Instead of binary sequence, as in machine language, a program in assembly language is written in
the form of symbolic instructions.
Disadvantages of assembly language
1. Assembly language is specific to particular machine architecture, i.e., machine dependent.
2. Programming is difficult and time consuming.
3. The programmer should know all about the logical structure of the computer.
4 High-level Languages
High-level programming languages such as COBOL, FORTRAN, and BASIC. Such languages
have instructions that are similar to human languages and have a set grammar that makes it easy for
a programmer to write programs and identify and correct errors in them.
Advantages of high-level programming languages
1. Readability
Programs written in these languages are more readable than those written in assembly and machine
languages.
2. Portability
High-level programming languages can be run on different machines with little or no change. It is,
therefore, possible to exchange software, leading to creation of program libraries.
3. Easy debugging
Errors can be easily detected and removed.
4. Ease in the development of software
Since the commands of these programming languages are closer to the English language, software
can be developed with ease. High-level languages are also called third generation languages
(3GLs).
CLASSIFICATION OF PROGRAMMING LANGUAGES:
1. Procedural Languages
1. Algorithmic languages
These are high-level languages designed for forming convenient expression of procedures, used in
the solution of a wide class of problems. In this language, the programmer must specify the steps
the computer has to follow while executing a program. Some of languages that fall in the category
are C, COBOL, and FORTRAN.
2. Object-oriented language
The basic philosophy of object- oriented programming is to deal with objects rather than functions
or subroutines as in strictly algorithmic languages. Objects are self-contained modules that contain
data as well as the functions needed to manipulate the data within the same module.
3. Scripting languages
These languages assume that a collection of useful programs, each performing a task, already
exists. It has facilities to combine these components to perform a complex task.
2. Problem-oriented Languages
These are high-level languages designed for developing a convenient expression of a given class of
problems.
3. Non-procedural Languages
Functional (applicative) languages
These functional languages solve a problem by applying a set of functions to the initial variables in
specific ways to get the answer. A program written in a functional language consists of function
calls together with arguments to functions. LISP, ML, etc. are examples of functional languages.
Logic-based programming language
A logic program is expressed as a set of atomic sentences, known as fact, and horn clauses, such as
if-then rules. A query is then posed. The execution of the program now begins and the system tries
to find out if the answer to the query is true or false for the given facts and rules. Such languages
include PROLOG.
ALGORITHMS:
Computer scientist Niklaus Wirth stated that
Program = Algorithms + Data
An algorithm is a finite set of well defined instructions or step by step procedure to solve a given
problem. An algorithm is a part of the plan for the computer program. In fact, an algorithm is ‘an
effective procedure for solving a problem in a finite number of steps’. It is effective, which means
that an answer is found and it has a finite number of steps.
Characteristics of an Algorithm
1) Input: It may accept zero or more inputs
2) Definiteness: Each instruction must be clear, well-defined and precise. There should not be any
ambiguity
3) Effectiveness: Each instruction must be simple and be carried out in a finite amount of time.
4) Finiteness: Algorithm should have finite sequence of instructions. That is, it Should end after a
fixed time. It should not enter into an infinite loop.
5) Output: It should produce at least one output.
Different ways of stating Algorithms:
Algorithms may be represented in various ways. There are four ways of stating algorithms.
These are as follows:
1. Step-form
2. Pseudo-code
3. Flowchart
4. Nassi-Schneiderman
1. Step-form:
In the step form representation, the procedure of solving a problem is stated with written
statements. Each statement solves a part of the problem and these together complete the solution.
The step-form uses just normal language to define each procedure. Every statement, that defines an
action, is logically related to the preceding statement.
1. Each algorithm will be logically enclosed by two statements START and STOP.
2. To accept data from user, the INPUT or READ statements are to be used.
3. To display any user message or the content in a variable, PRINT statement will be used.
Note that the message will be enclosed within quotes.
4. There are several steps in an algorithm. Each step results in an action. The steps are to be acted
upon sequentially in the order they are arranged or directed.
Example:
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
2. Pseudo-code:
Pseudocode is a method of describing computer algorithms using a combination of natural language
and programming language. However it differs from the step-form as it uses a restricted vocabulary
to define its action of solving the problem.
3. Flowchart and Nassi-Schneiderman:
Flowchart and Nassi-Schneiderman are graphically oriented representation forms. They use
symbols and language to represent sequence, decision, and repetition actions.
Some examples on developing algorithms using step-form:
1. Write the algorithm for addition of any two numbers.
1. START
2. PRINT “ENTER TWO NUMBERS”
3. INPUT A, B
4. C ← A + B
5. PRINT C
6. STOP
2. Construct the algorithm for interchanging the numeric values of two variables
1. START
2. PRINT “ENTER THE VALUE OF A & B”
3. INPUT A, B
4. C ← A
5. A ← B
6. B ← C
7. PRINT A, B
8. END
3. Write an algorithm that compares two numbers and prints either the message identifying
the greater number
1. START
2. PRINT “ENTER TWO NUMBERS”
3. INPUT A, B
4. IF A > B THEN
PRINT “A IS GREATER THAN B”
5. IF B > A THEN
PRINT “B IS GREATER THAN A”
6. IF A = B THEN
PRINT “BOTH ARE EQUAL”
7. STOP
1. START
2. PRINT “ENTER THREE NUMBERS”
3. INPUT A, B, C
4. IF A > B THEN
IF A > C THEN
PRINT A
ELSE
PRINT C
ELSE
IF B > C THEN
PRINT B
ELSE
PRINT C
5. STOP
5. Write an algorithm for calculating the factorial of a given number N.
1. START
2. PRINT “ENTER THE NUMBER”
3. INPUT N
4. F ←1
5. C ←1
6. WHILE C <= N
7. BEGIN
8. F← F * C
9. C ←C + 1
10. END
11. PRINT F
12. STOP
Flowchart:
A flow chart is a graphical or symbolic representation of a process. Each step in the process is
represented by a different symbol and contains a short description of the process step. The flow
chart symbols are linked together with arrows showing the process flow direction. Flowcharts are
generally developed in the early stages of formulating computer solutions.
Flowchart symbols:
Symbols are used to represent particular operations or data .
Flow lines indicate the sequence of operations (Top to down sequence).
Examples:
1. Draw the flowchart for addition of any two numbers.
C-LANGUAGE
Introduction:
C is a general-purpose high level programming language that was originally developed by Dennis
Ritchie for the UNIX operating system. It was first implemented on the Digital Equipment
Corporation PDP-11 computer in 1972.
History of C Language:
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in U.S.A.Dennis Ritchie is known as the founder of c
language. It was developed to overcome the problems of previous languages such as B, BCPL
etc.Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
C99 1999 Standardization Committee
The C programming language is a structure oriented programming language, developed at Bell
Laboratories in 1972 by Dennis Ritchie
C programming language features were derived from an earlier language called “B” (Basic
Combined Programming Language – BCPL)
C language was invented for implementing UNIX operating system
In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming
Language” and commonly known as K&R C
In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI
C”, was completed late 1988.
C89/C90 standard – First standardized specification for C language was developed by the
American National Standards Institute in 1989. C89 and C90 standards refer to the same
programming language.
C99 standard – Next revision was published in 1999 that introduced new features like advanced
data types and other changes.
6. Case sensitive
7. Compiler based
8. Modularity
9. Middle level language
10. Syntax based language
11. Use of Pointers
1. Simple
Every c program can be written in simple English language so that it is very easy to understand
and developed by programmer.
2. Platform dependent
A language is said to be platform dependent whenever the program is execute in the same
operating system where that was developed and compiled but not run and execute on other
operating system. C is platform dependent programming language.
3. Portability
It is the concept of carrying the instruction from one system to another system. In C Language file
contain source code, we can edit also this code. .exe file contain application, only we can execute
this file. When we write and compile any C program on window operating system that program
easily run on other window based system.
4. Powerful
C is a very powerful programming language, it have a wide verity of data types, functions, control
statements, decision making statements, etc.
5. Structure oriented
C is a Structure oriented programming language. Structure oriented programming language aimed
on clarity of program, reduce the complexity of code, using this approach code is divided into sub-
program/subroutines. These programming have rich control structure.
6. Modularity
It is concept of designing an application in subprogram that is procedure oriented approach. In c
programming we can break our code in subprogram.
For example we can write a calculator programs in C language with divide our code in
subprograms.
7. Case sensitive
It is a case sensitive programming language. In C programming 'break and BREAK' both are
different. If any language treats lower case latter separately and upper case latter separately than
they can be called as case sensitive programming language [Example c, c++, java, .net are
sensitive programming languages.] otherwise it is called as case insensitive programming
language [Example HTML, SQL is case insensitive programming languages].
8. Middle level language
C programming language can supports two level programming instructions with the combination
of low level and high level language that's why it is called middle level programming language.
9. Compiler based
C is a compiler based programming language that means without compilation no C program can
be executed. First we need compiler to compile our program and then execute.
10. Syntax based language
C is a strongly tight syntax based programming language. If any language follow rules and
regulation very strictly known as strongly tight syntax based language. Example C, C++, Java,
.net etc. If any language not follow rules and regulation very strictly known as loosely tight syntax
based language.
Example HTML.
11. Efficient use of pointers
Pointer is a variable which hold the address of another variable, pointer directly access to memory
address of any variable due to this performance of application is improve. In C language also
concept of pointer are available.
DEVELOPING PROGRAMS IN C:
There are mainly three steps:
1. Writing the C program
2. Compile the program
3. Executing the program.
For these steps, there requires some software components, namely an operating system, a text editor,
and the C compiler, assembler, and linker. The editor is used to create and modify the program code
while the compiler transforms the source program to object code. Operating system is responsible
for the execution of the program. There are several editors which provide a complete environment
for writing managing, developing, and testing your programs. This is sometimes called an integrated
development environment, or IDE.
Writing or editing the source program using a text editor or an IDE and saving it with .c
extension.
Programming Environment Most programming language compilers come with a specific c
editor that can provide facilities for managing the programs. Such an editor offers a complete
environment for writing, developing, modifying, deploying, testing, and debugging the
programs. Such software is referred to as an integrated development environment or IDE.
#include <stdio.h>
int main(void)
{
printf(“C is Sea\n”);
return 0;
}
There are a few important points to note about this program. These are common to all C programs.
/* A Simple C Program */: this is a comment line.
In C, the comments can be included in the program. The comment lines start with /* and terminate
with */. These statements can be put anywhere in the program. The compiler considers these as
non-executable statements.
#include <stdio.h> :
In C, all lines that begin with # are directives for the preprocessor, which means that all these
directives will be processed before the program is actually compiled. The #include directive
includes the contents of a file during compilation. The stdio.h header file contains information about
Input and Output Functions. Eg:- printf( ) & scanf( ).
int main(void):
Every C program contains a function called main. This is the starting point of the program. A C
program may contain one or more functions one of which must be main( ).When a C program is
executed, main( ) is where the action starts. Then, other functions maybe ‘invoked’ or called. int
Indicates an integer value is returned to the operating system from main( ). The main( ) is a user
defined function. main( ) is the first function in the program which gets called when the program
executes. The startup code c calls main( ) function. We can’t change the name of the main( )
function.
function is the logical end of the program. All statements in the declaration and executable part end
with a semicolon.
5. Subprogram section:
If the program is a multi-function program then the subprogram section contains all the user-
defined functions that are called in the main () function. User-defined functions are generally placed
immediately after the main () function, although they may appear in any order.
Example:
/* C basic structure program Documentation section*/
#include <stdio.h> /* Link section */
int main () /* Main Section */
{
printf (“Welcome to C language”);
return 0;
}
C Character Set:
As every language contains a set of characters used to construct words, statements etc., C language
also has a set of characters which include alphabets, digits and special symbols. C language
supports a total of 256 characters.
Every C program contains statements. These statements are constructed using words and these
words are constructed using characters from C character set. C language character set contains the
following set of characters...
1. Alphabets
2. Digits
3. Special Symbols
1. Alphabets
C language supports all the alphabets from English language. Lower and upper case letters together
supports 52 alphabets.
lower case letters - a to z
UPPER CASE LETTERS - A to Z
2. Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
3. Special Symbols
C language supports rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, back spaces and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell
backspace verticaltab etc.,
Every character in C language has its equivalent ASCII (American Standard Code for Information
Interchange) value.
C TOKENS:
C tokens are the basic buildings blocks in C language which are constructed together to write a C
program. Each and every smallest individual unit in a C program are known as C tokens. C tokens
are of six types. They are,
Keywords:
Keyword is a predefined or reserved word in C library with a fixed meaning and used to perform an
internal operation. You cannot use it as a variable name, constant name etc. There are only 32
reserved words (keywords) in C language. Every keyword must be written in lower case letters
only.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers:
Identifiers are the names you can give to entities such as variables, functions, arrays, structures
etc.Identifier names must be unique. For example: a, x, first
RULES FOR CONSTRUCTING IDENTIFIER NAME IN C:
1. The first character in an identifier must be an alphabet or an underscore and can be followed
only by any number alphabets, or digits or underscores.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct. That is, identifiers are case sensitive.
4. Commas or blank spaces are not allowed within an identifier.
5. Keywords cannot be used as an identifier.
6. Identifiers should not be of length more than 31 characters.
7. Identifiers must be meaningful, short, quickly and easily typed and easily read.
Valid identifiers: total sum average _x y_ mark_1 x1
Invalid identifiers :
1x - begins with a digit
CONSTANTS:
A constant is a named memory location which holds only one value throughout the program
execution.. In general constant can be used to represent as fixed values in a C program. Constants
are classified into following types.
Integer constants:
An integer constant refers to a sequence of digits. There are three types of integer constants,
namely, decimal integer, octal integer and hexadecimal integer.
Decimal integer consists of a set of digits from 0 to 9, preceded by an optional + or – sign.
Hexadecimal integers are a sequence of digits preceded by 0x or 0X. They may also includes
letters from A to F or from a to f. The letters represents the numbers from 10 to 15.
Examples, 0X2 0x9F 0Xbcd 0x
Real constants:
A floating point constant is a numeric constant that has either a fractional form or an exponent
form. For example: Real constants are used to represent distances, temperature etc. These quantities
are represented by numbers containing fractional parts.
Examples: 0.00832 -0.75 33.337
Single character constants:
A single character constant contains a single character enclosed within a pair of single quote marks.
Example: ‘5’ ‘X’ ‘;’
String constants:
A string constant contains a string of characters enclosed within a pair of double quote marks.
Examples: “Hello !” “1987” “?....!”
Variable:
A variable is a data name that may be used to store data value. A variable may take different value
at different times during execution. The variable might be belonging to any of the data type like int,
float, char etc.
Variable Declaration:
1. Variables should be declared in the C program before it use.
2. Memory space is not allocated for a variable while declaration.
Syntax: Data_type Variable_Name;
Example: int x; // Here int is data type and x is variable name
float a;
char b;
3. Except underscore (_) no other special symbol are allowed in the middle of the variable.
4. Maximum length of variable is 8 characters depend on compiler and operation system.
5. Every variable name always should exist in the left hand side of assignment operator
(invalid - 10=a; valid - a=10;).
6. Variable name should not be a keyword.
7. Uppercase and lowercase are significant.
Valid variable names:
int a;
int _ab;
int a30;
Invalid variable names:
int 2;
int a b;
int long;
DATA TYPES IN C:
Data types refer to the type and size of data associated with variables and functions. Data types are
used to define a variable before to use in a program.
In general every programming language is containing three categories of data types. They are
Fundamental or primitive data types or primary data types
Derived data types
User defined data types
5 == x==y x is equal to y
6 != x != y x is not equal to y
EXAMPLE:
#include <stdio.h>
void main()
{
int a=40,b=20;
printf("the Result is %d\n", a<b);
printf("the Result is %d\n", a>b);
printf("the Result is %d\n", a<=b);
printf("the Result is %d\n", a>=b);
printf("the Result is %d\n", a= =b);
printf("the Result is %d\n", a!=b);
}
4. Logical operators:
The Logical operators are used to combine more than one condition. There are 3 logical operators in
C language. They are, logical AND (&&), logical OR (||) and logical NOT (!).
S.no Operators Name Example Description
logical
1 && (x>5)&&(y<5) It returns true when both conditions are true
AND
logical It returns true when at-least one of the
2 || (x>=10)||(y>=10)
OR condition is true
It reverses the state of the operand “((x>5)
logical && (y<5))”
3 ! !((x>5)&&(y<5))
NOT If “((x>5) && (y<5))” is true, logical NOT
operator makes it false
int a = 5;
-- Decrement - Subtracts one from existing value
a--; ⇒ a = 4
The increment and decrement operators are used in front of the operand (++a) or after the operand
(a++). If it is used in front of the operand, we call it as pre-increment or pre-decrement and if it is
used after the operand, we call it as post-increment or post-decrement.
Pre-Increment or Pre-Decrement
In case of pre-increment, the value of the variable is increased by one before the expression
evaluation. In case of pre-decrement, the value of the variable is decreased by one before the
expression evaluation. That means, when we use pre increment or pre decrement, first the value of
the variable is incremented or decremented by one, then modified value is used in the expression
evaluation.
Example: a=10,b=20;
++a;
--b;
Post-Increment or Post-Decrement
In case of post-increment, the value of the variable is increased by one after the expression
evaluation. In case of post-decrement, the value of the variable is decreased by one after the
expression evaluation. That means, when we use post-increment or post-decrement, first the
expression is evaluated with existing value, then the value of the variable is incremented or
decremented by one.
Example: a=10,b=20;
a++;
b--;
6. Conditional Operators: (? :)
The Conditional operators return one value if condition is true and returns another value is
condition is false. This operator is also called as ternary operator. The conditional operators are ? , :
Syntax : Condition? true_value : false_value;
Example: A > 100 ? 0 : 1;
.In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
#include <stdio.h>
int main()
{
int x=10, y=20,z ;
z= (x>y)? x : y;
printf("z value is %d\n",z);
}
7. Bit wise operators:
These operators are used to perform bit operations. Decimal values are converted into binary values
which are the sequence of bits and bit wise operators work on these bits .
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
8. Special Operators:
S.no Operators Description
This is used to get the address of the variable.
1 &
Example : &a will give address of a.
This is used as pointer to a variable.
2 *
Example : * a where, * is pointer to the variable a.
This gives the size of the variable.
3 Sizeof ()
Example : size of (char) will give us 1.
Expression Evaluation-Precedence and Associativity
Evaluation of an expression in C is very important to understand. Operators have rules of
precedence and Associativity that are used to determine how expressions are evaluated.
When there is more than one operator occurring in an expression, it is the relative priorities of the
operators with respect to each other that will determine the order in which the expression will be
evaluated. This priority is known as precedence. The precedence of operators determines the order
in which different operators are evaluated when they occur in the same expression. Operators of
higher precedence are applied before operators of lower precedence.
Consider the following expression:
4+3*2
The operator ‘*’ has higher precedence than ‘+’, causing the multiplication to be executed first, then
the addition. Hence, the value of the expression is 10
But what happens when an expression consists of operators with same precedence. For
example
4 / 2 *3
The Associativity of operators determines the order in which operators of equal precedence are
evaluated when they occur in the same expression. The Associativity defines the direction, left-to-
right or right-to-left, in which the operator acts upon its operands. The value of the expression is 6.
Associativity
It represents which operator should be evaluated first if an expression is containing more than one
operator with same priority.
Operator Priority Associativity
{}, (), [] 1 Left to right
++, --, ! 2 Right to left
*, /, % 3 Left to right
+, - 4 Left to right
<, <=, >, >=, ==, != 5 Left to right
&& 6 Left to right
|| 7 Left to right
?: 8 Right to left
=, +=, -=, *=, /=, %= 9 Right to left
Example:
Type Conversions:
When variables and constants of different types are combined in an expression then they are
converted to same data type. The process of converting one predefined type into another is called
type conversion.
Type conversion in c can be classified into the following two types:
1. Implicit type conversion
2. Explicit type conversion
1. Implicit Type Conversion
When the type conversion is performed automatically by the compiler without programmer’s
intervention, such type of conversion is known as implicit type conversion or type promotion.
The compiler converts all operands into the data type of the largest operand.
The sequence of rules that are applied while evaluating expressions are given below:
All short and char are automatically converted to int, then,
1. If either of the operand is of type long double, then others will be converted to long double
and result will be long double.
2. Else, if either of the operand is double, then others are converted to double.
3. Else, if either of the operand is float, then others are converted to float.
4. Else, if either of the operand is unsigned long int, then others will be converted to unsigned
long int.
5. Else, if one of the operand is long int, and the other is unsigned int, then
1. if a long int can represent all values of an unsigned int, the unsigned int is converted
to long int.
2. Otherwise, both operands are converted to unsigned long int.
6. Else, if either operand is long int then other will be converted to long int.
7. Else, if either operand is unsigned int then others will be converted to unsigned int.
Example:
float x,y,z;
int result;
result=x*y*z/100+32/8-3*1.5
In the above statement some operands are int where as others are floats. During evaluation of the
expression the int would be promoted to floats and the result of the expression would be a float.
2. Explicit type conversion:
The type conversion performed by the programmer by posing the data type of the expression of
specific type is known as explicit type conversion. The explicit type conversion is also known as
type casting.
Type casting in c is done in the following form:
Syntax: (Data_type) expression;
where, Data_type is any valid c data type, and expression may be constant, variable or expression.
For example:
double y = 123;
int x = (int)y;
The following rules have to be followed while converting the expression from one type to another
to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.
Escape Sequences:
An escape sequence in C language is a sequence of characters that doesn't represent itself when
used inside string literal or character. It is composed of two or more characters starting with
backslash \. For example: \n represents new line.
UNIT-2
Input/output Functions
In almost every programming problem user need to enter some data to the program & want to get
some specific result from the program. In programming , the instruction used to perform the
function of Data Input from standard input unit such as Keyboard and to get Output on standard
Output unit such as Monitor are called Standard Input Output Functions .
In “C” language, these Input Output function can be categorize into two categories:-
Format string: It contain format specifiers starting with % sign , which tell the compiler the data
type of the Input .The following table show different format specifiers.
Format specifiers:-
Format specifiers begin with % sign and are used to tell the compiler to print the value store in
variable and also tell the data type format.
Integer %d
Short Signed %u
Short Unsigned %ld
Long Signed %lu
Long unsigned %x
Unsigned Hexadecimal %o
Float or Real %f
Double %lf
Character %c %c
String or array of characters %s
List of addresses of variable contain the memory addresses of variable where the Input is stored.
The memory addresses of variable can be given using of & symbol.
Eg. scanf(" %d ",&num );
Example program:
#include <stdio.h>
void main( )
{
int i;
float f;
char c;
printf("Enter an integer and a float, then Y or N\n> ");
scanf("%d%f%c", &i, &f, &c);
printf("You entered:\n");
printf(" %d, %f, %c\n", i, f, c);
}
2) Unformatted Input Output function :-
These are console Input Output Library function which deal with one character at a time and string
function for Array of characters (String).The unformatted Input and Output functions are can read
and write only character type of data.
The unformatted Input and Output functions are two types.
1. Character input and output functions
2. String input and output functions
1. Character input and output functions:
Character input functions are getchar( ), getche( ), getch( )
Character output functions are putchar( ),putch( )
1) getchar( ) function :- This is a un-formatted console Input function which is used to enter or
Input One character at a time from a standard Input device eg. Keyboard.
eg. char alphabet ;
alphabet = getchar() ;
/* In this , firstly we press a key which we want to enter (as say 'A') and we need to press Enter key
to move to the next instruction */
puts( ) function :-
This is an Unformatted String Output function. This is used to print the Content of string on the
standard Output device such as Screen.
let's discuss this function with the help of suitable example .
#include <stdio.h>
void main()
{
char name[ 15 ] ;
clrscr() ;
puts(" Enter name of 15 Characters ") ;
gets( name ) ; /* String Input */
puts(" The name Entered is ") ;
puts(" name ") ; /* String Output */
getch() ;
}
Output .
Enter name of 15 Characters HARSIMRAN SINGH
The name Entered is HARSIMRAN SINGH
Control Statements
When we run a program, the statements are executed in the order in which they appear in the
program. Also each statement is executed only once. But in many cases we may need a statement or
a set of statements to be executed a fixed no of times or until a condition is satisfied. Also we may
want to skip some statements based on testing a condition. For all these we use control statements.
Control statements are of two types – branching and looping.
Example:
#include <stdio.h>
void main( )
{
int x,y;
printf(“enter two values”);
scanf(“%d%d”,&x,&y);
if (x > y )
{
printf("x is greater than y");
}
}
2. if....else statement:
In if..else statement a group of statements are executed when condition is true. If condition is false,
then else part statements are executed.
Syntax:
if( expression )
{
statement block1;
}
else
{
statement block2;
}
If the 'expression' is true, the 'statement-block1' is executed, else 'statement-block1' is skipped and
'statement-block2' is executed.
Flowchart:
Example:
#include <stdio.h>
void main( )
{
int a,b;
printf(“enter two values”);
scanf(“%d%d”,&a,&b);
if (a > b )
{
printf("a is greater than b");
}
else
{
printf("b is greater than a");
}
}
3. Nested if else:
Nested if else statement is same like if else statement, where new block of if else statement is
defined in existing if or else block statement.
Syntax:
if (condition)
{
if(condition)
{
statement;
}
else
{
statement;
}
}
else
{
statement;
}
Example: find largest of three numbers.
#include <stdio.h>
void main()
{
int a,b,c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a>b)
{
if(a>c)
{
printf("%d is the largest number.", a);
}
else
{
printf("%d is the largest number.", c);
}
}
else
{
if(b>c)
{
printf("%.2lf is the largest number.", n2);
}
else
{
printf("%.2lf is the largest number.",n3);
}
}
}
4. Else If Statement :
As if else statement are too complicated for humans to write when they are nested more deeply. To
reduce this complication of statements else if clause can be used.
Syntax :
if (expression1)
{
Statements;
}
else if (expression2)
{
Statements;
}
.
.
.
else
{
Statements;
}
It is combination of if else statement, At the start if expression1 of if statement evaluates false, then
the program control moves downward till any of the else if statement evaluates true. After
evaluating true any of the else if statement it executes the statements and exits the clause.
Example ://Find whether input year is leap year or not
#include <stdio.h>
#include <conio.h>
void main()
{
int year;
clrscr();
printf("Enter the year:");
scanf("%d",&year);
if(year%400==0)
{
printf("It is a leap year");
}
else if(year%100==0)
{
printf("It is not a leap year");
}
else if(year%4==0)
{
printf("It is a leap year");
}
else
{
printf("It is not a leap year");
}
getch();
}
5. Switch Case Statement:
Switch case statement is used when user has multiple alternatives of codes to choose, depending
upon the value of single variable.
Syntax
switch (Expression)
{
case 1:
statement;
break;
case 2:
statement;
break;
case 3:
statement;
break;
default:
statement;
}
In the above syntax after case keyword constant (1, 2, 3) is considered as integer it may be character
too.
First integer expression is calculated then the value of integer or character is matched one after
another with constant values of case statements. When a match is found then that case section of
code is executed and if no match is found then default keyword code is executed.
Switch variable and case constant variables should be of same data type.
Value of switch variable should be assigned before entering the switch case.
Each case keyword is followed by a constant and a colon.
Every case section should end with break statement to end the switch case else it enters into
the next case.
Example: //Using switch case statement
#include <stdio.h>
#include <conio.h>
void main()
{
int choice;
clrscr();
printf("Select any option number from 1 to 4 : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("You have selected first option");
break;
case 2:
printf("You have selected second option");
break;
case 3:
printf("You have selected third option");
break;
case 4:
printf("You have selected fourth option");
break;
default:
printf("Invalid option selected");
break;
}
getch();
}
1. While statement:
The while statement continuously executes a block of statements while a particular condition is
true.
Syntax:
while(expression)
{
statement(s)
}
This must return a Boolean value. If the expression evaluates to true, the while statement executes
the statement(s) in the while block. The while statement continues testing the expression and
executing its block until the expression evaluates to false.
Example:
//Using while loop statement prints 1 to 5 numbers
#include <stdio.h>
#include <conio.h>
void main()
{
int i=1;;
clrscr();
while(i<=5)
{
printf("%d",i);
i++;
}
getch();
}
2. do..while:
The do..while loop is similar to the while loop with one important difference. The body of
do...while loop is executed once, before checking the test expression. Hence, the do...while loop is
executed at least once.
Syntax:
do
{
Statements;
........
}
while(condition);
statement(s);
#include <stdio.h>
void main()
{
int i, j, n;
printf("Enter the number of rows: ");
scanf("%d",&n);
for(i=1; i<=n; ++i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Jumping Statements:
C language provides us multiple statements through which we can transfer the control anywhere in
the program.
There are basically 3 Jumping statements:
1. break
2. continue
3. goto
1. Break Statements:
Break statement is used for terminates any type of loop e.g, while loop, do while loop or for loop.
The break statement terminates the loop of the body immediately and passes control to the next
statement after the loop. In case of inner loops, it terminates the control of inner loop only.
Break statement are mainly used with loop and switch statement. Often use the break statement
with the if statement.
Syntax:
break;
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
printf("%d \n",i);
if(i= =5)
{
break; //if value of i is equal to 5, it will break the loop
}
}
getch();
}
2. Continue statement:
C Continue statement is used to skip the rest of the current iteration in a loop and returns to the top
of the loop. The continue statement works like a shortcut to the end of the loop body.
Syntax:
continue;
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
{
continue; //if value of i is equal to 5, it will continue the loop
}
printf("%d \n",i);
}
getch();
}
3. goto statement:
By using goto statement we can transfer the control from current location to anywhere in the
program. To do all this we have to specify a label with goto and the control will transfer to the
location where the label is specified.
Syntax:
goto label;
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int age;
clrscr();
ineligible:
printf("You are not eligible to vote!\n");
printf("Enter you age:\n");
scanf("%d", &age);
if(age<18)
goto ineligible;
else
printf("You are eligible to vote!\n");
getch();
}
ARRAYS:
An array is a collection of similar data elements with the same name and same data type. The
elements in the array are stored in consecutive memory locations and are referenced by an index
number. In an array the index number will start from zero.
Arrays are two types:
1. Single Dimensional Arrays (or) One Dimensional Arrays
2. Multi Dimensional Arrays
Advantage of an array
Code Optimization: Less code is required.
Easy to traverse data: By using array easily retrieve the data of array.
Easy to sort data: Easily short the data using swapping technique
Random Access: With the help of array index you can randomly access any elements from
array.
1. Single Dimensional Arrays:
Single or One Dimensional array is used to represent and store data in a linear form. Array
having only one subscript variable is called One-Dimensional array
Declaration of an Array:
To declare an array in C you need to declare datatype and size of an array.
Syntax:
Data type array_Name [SIZE];
Example:
int b[5];
The declaration of an array tells the compiler that, the data type, name of the array, size of the array
and for each element it occupies memory space.
Initialization of an Array:
After declaration element of local array has garbage value. If it is global or static array then it will
be automatically initialize with zero. An array can be initialized in two ways:
1. Compile Time
2. Runtime.
1. Compile time Initialization:
Compile time initialization of array elements is same as ordinary variable initialization. The general
form of initialization of array is,
Syntax:
Datatype arrayname [size] = {value1, value2, value3…}
Example:
int b[5]={20,60,90, 100,120};
OR
int b[5];
b[0]=10;
b[1]=20;
b[2]=30;
b[3]=40;
b[4]=50;
Array subscript always start from zero which is known as lower bound and upper value is known as
upper bound and the last subscript value is one less than the size of array. Subscript can be an
expression i.e. integer value.
2. Run time Initialization:
An array can also be initialized at runtime using scanf( ) function. This approach is usually used for
initializing large array, or to initialize array with user specified values.
Example:
int a[10],i;
for (i=0;i<5;i++)
{
scanf("%d",&a[i]); //Run time array initialization
}
Accessing Array Elements:
We all know that array elements are randomly accessed using the subscript variable. Array can be
accessed using array-name and subscript variable written inside pair of square brackets [ ].
Example:
int a[3]={10,20,30};
printf(“%d”,a[0]);
printf(“%d”,a[1]);
printf(“%d”,a[2]);
OR
for(i=0; i<3; i++)
{
printf("Elements are %d”, a[i]);
}
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[4], i;
clrscr( );
printf("Enter element in to an array ");
for(i=0;i<4;i++)
{
scanf("%d",&a[i]); //Run time array initialization
}
Printf(“ The elements in an array are:\n”);
for(i=0;i<4;j++)
{
printf("%d\n", a[j]);
}
getch();
}
OR
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
scanf("%d",&a[i][j]); //Run time array initialization
}
}
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][4],i,j;
printf("Enter array element");
for(i=0;i<3;i++)
{
for(j=0; j < 4; j++)
{
scanf("%d", &a[i][j]);
}
}
for(i=0; i < 3; i++)
{
for(j=0; j < 4; j++)
{
printf("%d", a[i][j]);
}
}
getch();
}
Example Programs:
1. Write a program to find Smallest Element in Array.[single Dimensional array]
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[30], i, n, smallest;
clrscr( );
printf("\nEnter no of elements :");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
smallest = a[0];
for (i = 0; i < n; i++)
{
if (a[i] < smallest)
{
smallest = a[i];
}
}
printf("\nSmallest Element : %d", smallest);
}
2.Write a program to find largest Element in Array.[single Dimensional array]
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[30], i, n, largest;
clrscr( );
printf("\nEnter no of elements :");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
largest = a[0];
Output:
Enter no of elements: 5
11 55 33 77 22
Largest Element : 77
3.Write a program to search an Element in Array.[single Dimensional array]
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[100], search, i, n;
clrscr( );
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the number to search\n");
scanf("%d", &search);
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
{
printf("%d\n", number[i]);
}
getch( );
}
5. Write a program addition of two 3*3 matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int x[3][3],y[3][3],z[3][3],i,j;
clrscr( );
printf("ENTER ELEMENTS OF 1st MATRIX\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&x[i][j]);
}
}
printf("ENTER ELEMENTS OF 2nd MATRIX\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&y[i][j]);
}
}
printf("MATRIX [X]");
for(i=0;i<3;i++)
{
printf("\n\n");
for(j=0;j<3;j++)
{
printf(" %d",x[i][j]);
}
}
printf("\nMATRIX [Y]");
for(i=0;i<3;i++)
{
printf("\n\n");
for(j=0;j<3;j++)
{
printf(" %d",y[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
z[i][j]=x[i][j]+y[i][j];
}
}
printf("\n addition matrix is: ");
for(i=0;i<3;i++)
{
printf("\n\n");
for(j=0;j<3;j++)
{
printf(" %d",z[i][j]);
}
}
getch();
}
6. Write a program subtraction of two 3*3 matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int x[3][3],y[3][3],z[3][3],i,j;
clrscr( );
printf("ENTER ELEMENTS OF 1st MATRIX\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &x[i][j]);
}
}
printf("ENTER ELEMENTS OF 2nd MATRIX\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &y[i][j]);
}
}
printf("MATRIX [X]");
for(i=0;i<3;i++)
{
printf("\n\n");
for(j=0;j<3;j++)
{
printf(" %d", x[i][j]);
}
}
printf("\nMATRIX [Y]");
for(i=0;i<3;i++)
{
printf("\n\n");
for(j=0;j<3;j++)
{
printf(" %d", y[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
z[i][j]=x[i][j]-y[i][j];
}
}
printf("\n subtraction matrix is: ");
for(i=0;i<3;i++)
{
printf("\n\n");
for(j=0;j<3;j++)
{
printf(" %d", z[i][j]);
}
}
getch();
}
6. Write a program multiplication of two matrix
#include <stdio.h>
#include <conio.h>
void main()
{
int a[3][3], b[3][3], c[3][3],i, j, k;
clrscr( );
printf(" Enter elements of first matrix\n ");
for( i = 0; i < 3; i++ )
{
for( j = 0; j < 3; j++ )
{
printf(" \n Enter a[%d] [%d] element: ", i, j);
scanf(" %d ", &a[i] [j] );
}
}
STRINGS:
A String is a sequence of characters that is treated as a single data item and terminated by null
character '\0'. Remember that C language does not support strings as a data type. String is
nothing but array of characters in C language. Strings are always enclosed by double quotes.
Whereas, character is enclosed by single quotes in C.
Declaration & Initialization of strings:
Syntax:
Data_type Variable_Name [size];
Example:
char name[20] = { ‘j’ , ’a’ , ‘g’ , ‘r’ , ‘u’ , ‘t’ , ‘i’, ‘\0’};
(or)
char name[20] = “jagruti”;
(or)
char name[ ] = “jagruti”;
Difference between above declarations are, when we declare char as “name[20]”, 20 bytes of
memory space is allocated for holding the string value.
When we declare char as “name[ ]”, memory space will be allocated as per the requirement during
execution of the program.
String Input and Output Functions:
gets( ) and puts( ) are the string input and output functions.
gets():
gets() are used to get input as a string from keyword, using gets() we can input more than one word
at a time.
puts():
puts() are used to print output on screen, generally puts() function are used with gets() function
Using scanf( ) function Using gets( ) function
#include <stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
char name[ 10 ] ; char name[10];
clrscr() ; clrscr();
printf(" Enter any string ") ; printf("Enter any string: ");
scanf(" %s " , name ); gets(name);
/* We NOT use & operator for String (Array of printf("String are: ");
characters)*/ puts(name);
printf(“string is %s”,name); getch();
getch() ; }
}
1. strcat( ) function:
The strcat( ) function in C language concatenates two given strings. It concatenates source string at
the end of destination string.
Syntax
strcat ( destination,source );
Example :
strcat ( str2, str1 ); – str1 is concatenated at the end of str2.
strcat ( str1, str2 ); – str2 is concatenated at the end of str1.
Example:
#include <stdio.h>
#include <string.h>
void main( )
{
char source[ ] = "jagruti" ;
char target[ ]= " college" ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ;
strcat ( source,target ) ;
printf ( "\nTarget string after strcat( ) = %s", source ) ;
}
2. strlen( ) function:
strlen( ) function counts the number of characters in a given string and returns the integer value. It
stops counting the character when null character is found. Because, null character indicates the end
of the string in C.
Syntax:
variable = strlen(stringname);
Example:
int a=strlen(“jagruti”);
Example:
#include <stdio.h>
#include <string.h>
void main( )
{
int len;
char array[20]="jagruti" ;
len = strlen(array) ;
printf ( "\string length = %d \n" , len ) ;
}
3. strrev( ) function:
strrev( ) function reverses a given string in C language .
Syntax:
strrev(string);
Example:
strrev(“jagruti”);
Example:
#include<stdio.h>
#include<conio.h>
void main( )
{
char str[20];
clrscr();
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
getch();
}
4. strcpy( ) function:
strcpy( ) function copies contents of one string into another string.
Syntax:
strcpy ( destination, source );
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t be copied into
destination string.
Example:
#include <stdio.h>
#include <string.h>
void main( )
{
char source[ ] = "jagruti" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strcpy ( target, source ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
}
5. strcmp( ) function:
strcmp( ) function in C compares two given strings and returns zero if they are same.strcmp( )
function is case sensitive. i.e, “A” and “a” are treated as different characters.
Syntax:
strcmp(string1,string2);
Example:
#include <stdio.h>
void main()
{
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
UNIT-3
FUNCTIONS
A function is a self-contained block of program statements that performs a particular task. It is
often defined as a section of a program performing a specific job. A large C program is divided into
basic building blocks called C function. C function contains set of instructions enclosed by “{ }”
which performs specific operation in a C program. Actually, Collection of these functions creates a
C program.
Uses of C functions:
C functions are used to avoid rewriting same logic/code again and again in a program.
There is no limit in calling C functions to make use of same functionality wherever required.
We can call functions any number of times in a program and from any place in a program.
A large C program can easily be tracked when it is divided into functions.
The core concept of C functions are, re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability of very large C programs.
Types of Functions:
There are two types of functions in C programming:
1. Library functions are those functions which are defined by C library, example printf(),
scanf(), strcat() etc. You just need to include appropriate header files to use these functions.
These are already declared and defined in C libraries.
2. User-defined functions are those functions which are defined by the user at the time of
writing program. Functions are made for code reusability and for saving time and space.
User-defined functions:
User-defined functions are those functions which are defined by the user at the time of writing
program. Functions are made for code reusability and for saving time and space.
Elements of Functions:
1. Function Declaration
2. Function Definition
3. Function Calling
Syntax
return-type function-name (parameter-list);
Examples
int sum (int, int);
int add(float ,int);
Return-type
Return type specifies the type of value (int, float, char, double) that function is expected to return to
the program calling the function.
Function-name
Function name specifies the name of the function. The function name is any valid C identifier and
therefore must follow the same rule of formation as other variables in C.
Parameter-list
The parameter list declares the variables that will receive the data sent by calling program. They
often referred to as formal parameters. These parameters are also used to send values to calling
program.
2. Function Definition:
A function definition specifies the name of the function, the types and number of parameters it
expects to receive, and its return type. A function definition also includes a function body with the
declarations of its local variables, and the statements that determine what the function does.
Syntax:
return-type function-name (parameter-list)
{
Function-body;
}
The first line return-type function-name (parameter) is known as function header and the statement within
curly braces is called function body.
Return Type − A function may return a value. The return type is the data type of the
value the function returns. Some functions perform the desired operations without returning
a value. In this case, the return type is the keyword void.
Function Name − this is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
Function Body − the function body contains a collection of statements that define what the
function does.
Example:
int sum (int num1,int num2)
{
int num3;
num3 = num1 + num2 ;
return(num3);
}
3. Function Call:
Call a C function just by writing function name with opening and closing round brackets
followed with semicolon. If we have to supply parameters then we can write parameters inside pair
of round brackets. Parameters are optional.
Syntax:
Function name (Parameter1, Parameter2, Parameter n);
Example program:
#include<stdio.h>
#include<conio.h>
int sum(int, int); // function declaration
void main()
{
int a,b,c;
printf("\nEnter the two numbers : ");
scanf("%d%d",&a,&b);
c = sum(a,b); // function call
printf("\nAddition of two number is : %d",c);
getch();
}
int sum (int num1,int num2) // function definition
{
int num3;
num3 = num1 + num2 ;
return(num3);
}
2. CALL BY REFERENCE:
•In call by reference method, the address of the variable is passed to the function as parameter.
•The value of the actual parameter can be modified by formal parameter.
•Same memory is used for both actual and formal parameters since only address is used by both
parameters.
Example:
#include<stdio.h>
void swap(int *a, int *b); // function prototype, also called function declaration
int main()
{
int m = 22, n = 44;
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n); // calling swap function by reference
}
All C functions can be called either with arguments or without arguments in a C program. These
functions may or may not return values to the calling function. Now, we will see simple example C
programs for each one of the below.
Example:
#include<stdio.h>
#include<conio.h>
int add(int , int); // function declaration
void main ( )
{
int a,b,c;
clrscr( );
printf(“enter the two values”);
scanf(“%d%d”,&a,&b);
c=add(a,b); // function calling
#include<stdio.h>
#include<conio.h>
int add( ); // function declaration
void main ( )
{
int c;
c= add(); // function calling
printf(“the addition result is %d\n”,c);
getch();
}
void add( ) // function definition
{
int a,b;
printf(“enter the two values”);
scanf(“%d%d”,&a,&b);
return (a+b);
}
#include <stdio.h>
void main ()
{
int a=10, b=20,c; /* local variable declaration */
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
}
Global Variables:
Global variables are defined outside a function, usually on top of the program. Global variables
hold their values throughout the lifetime of your program and they can be accessed inside any of the
functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. The following program show how global
variables are used in a program.
Example
#include <stdio.h>
int g; /* global variable declaration */
void main ( )
{
int a=10, b=20; /* local variable declaration */
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
}
Scope Rules :
The region of the program over which the declaration of an identifier is accessible is called the
scope of the identifier. The scope relates to the accessibility, the period of existence, and the
boundary of usage of variables declared in a program. Scopes can be of four types.
block
file
function
function prototype
The following sections describe the scope associated with variables.
Block scope
This means that the identifier can only be used in the block in which it is declared. These variables
are created at the point of their declaration inside the block. Outside the block, these variables are
unknown and non-existent
Function scope
This applies only to labels. Normally labels are used with goto statement. It simply means that
labels can be used anywhere within the function in which they are defined. This includes use before
definition.
File scope
This means that the identifier can be used anywhere in the current file after the declaration of the
identifier. This applies to functions and all variables declared outside functions. File scope variable
is also known as global variable.
Function prototype scope
In order to improve readability and understandability, function prototypes are usually written
with ‘dummy’ variable names. For example
double max(double x, double y);
Storage Classes:
In C, the variables are declared by the type of data they can hold. The name of a variable is
associated with a memory location within the computer where the value assigned to the variable is
stored in the form of bits. During the execution of the program, these variables may be stored in the
registers of the CPU or the primary memory of the computer. To indicate where the variables would
be stored, how long they would exist, what would be their region of existence, and what would be
the default values ,C provides four storage class specifiers that can be used along with the data type
specifiers in the declaration statement of a variable. These four storage class specifiers are :
1. automatic
2. external
3. register
4. static
1. Automatic Variable:
A variable declared inside a function without any storage class specification, is by default an
automatic variable. They are created when a function is called and are destroyed automatically
when the function exits. Automatic variables can also be called local variables because they are
local to a function. Automatic variables are declared with auto keyword.
Example:
#include <stdio.h>
void main()
{
int a=10;
auto int b=10;//same like above
printf("%d %d",a,b);
}
2. External or Global variable:
A variable that is declared outside any function is an External variable. External variables remain
available throughout the entire program. One important thing to remember about global variable is
that their values can be changed by any function in the program. External variable are declare with
extern keyword.
Example:
3. Register variable:
Register variable inform the compiler to store the variable in register instead of memory. Register
variable has faster access than normal variable. Frequently used variables are kept in register. Only
few variables can be placed inside register. Register variables are declared with register keyword.
Example:
#include<stdio.h>
void main()
{
int num1,num2;
register int sum;
printf("\nEnter the Number 1 : ");
scanf("%d",&num1);
printf("\nEnter the Number 2 : ");
scanf("%d",&num2);
sum = num1 + num2;
printf("\nSum of Numbers : %d",sum);
}
4. Static variable:
A static variable tells the compiler to persist the variable until the end of program. Instead of
creating and destroying a variable every time when it comes into and goes out of scope, static is
initialized only once and remains into existence till the end of program. A static variables are
declared with static keyword.
Example:
#include <stdio.h>
void test(); //Function declaration
main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}
INLINE FUNCTION
C99 has added the keyword inline, which applies to functions. By preceding a function declaration
with inline, the compiler is instructed to optimize calls to the function. Typically, this means that
the function’s code will be expanded in line, rather than called. Below is a definition of such inline
function.
inline int sum(int x, int y)
{
return x+y;
}
The inline designation is only a hint to the compiler, suggesting that calls to the inline function
should be as fast as possible. The name comes from a compiler optimization called inline
expansion, whereby a call to a function is replaced by a copy of the function body. This eliminates
the overhead of the function call. There is no guarantee in general that the compiler will take note of
a function being declared as inline. It is free to ignore the request.
Recursion:
A recursive function is one that calls itself directly or indirectly to solve a smaller version of its task
until a final call which does not require a self-call.
Recursion is like a top–down approach to problem solving; it divides the problem into pieces or
selects one key step, postponing the rest. On the other hand, iteration is more of a bottom–up
approach; it begins with what is known and from this constructs the solution step by step.
What is needed for implementing recursion?
Decomposition into smaller problems of same type
Recursive calls must diminish problem size
Necessity of base case
Base case must be reached
It acts as a terminating condition. Without an explicitly defined base case, a recursive function
would call itself indefinitely.
It is the building block to the complete solution. In a sense, a recursive function determines its
solution from the base case(s) it reaches.
Example:
Finding Factorial
n * factorial(n-1)
Example: write a program to find Fibonacci series of a given number using recursion
#include<stdio.h>
int Fibonacci(int);
void main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
POINTERS
A pointer provides a way of accessing a variable without referring to the variable directly. The
mechanism used for this is the address of the variable. A program statement can refer to a variable
indirectly using the address of the variable. A pointer is a variable that holds the memory
address of another variable. C Pointer is used to allocate memory dynamically i.e. at run time.
Declaring a Pointer:
Just as any other variable in a program, a pointer has to be declared; it will have a value, a scope, a
lifetime, a name; and it will occupy a certain number of memory locations. The pointer operator
available in C is ‘*’, called ‘value at address’ operator. It returns the value stored at a particular
address. The value at address operator is also called ‘indirection’ operator. A pointer variable is
declared by preceding its name with an asterisk.
& symbol is used to get the address of the variable.
* Symbol is used to get the value of the variable that the pointer is pointing to.
Syntax:
Datatype * pointer_variable;
where, datatype is the type of data that the pointer is allowed to hold the address and
pointer_variable is the pointer variable name that is used to refer to the address of a variable of type
datatype.
Example:
int *b;
The above declaration indicates that b is a pointer type variable that points to int type data.
Initialization of Pointer variable:
Pointer Initialization is the process of assigning address of a variable to pointer variable. In C
language address operator & is used to determine the address of a variable. The & returns the
address of the variable associated with it.
Example:
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
Example program:
#include <stdio.h>
#include <conio.h>
void main()
{
int number=50;
int *p;
clrscr();
p=&number; //stores the address of number variable
printf("Address of number variable is %x \n", &number);
printf("Address of p variable is %x \n", p);
printf("Value of p variable is %d \n",*p);
getch();
}
Arrays and Pointer:
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address which gives location of the first element is also allocated by the
compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five elements
will be stored as follows
Here variable arr will give the base address, which is a constant pointer pointing to the element,
arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or
p = &arr[0]; //both the statements are equivalent.
String constants are written between double quotes. For example, “abc” is a character array of size
4, with the last element being the null character \0. Note that string constants are different from
character constants. For example, “a” and ‘a’ are not the same. The array “a” has two elements, the
first with value ‘a’ and the second with value ‘\0’.
#include <stdio.h>
int main()
{
char s[]=“Oxford”;
for(i=0;s[i]!=‘\0’;++i)
putchar(s[i]);
return 0;
}
Pointers to Pointers:
So far in the discussion, pointers have been pointing directly to data. C allows the use of pointers
that point to pointers, and these, in turn, point to data. For pointers to do that, we only need to add
an asterisk (*) for each level of reference. Consider the following declaration.
int a=5;
int *p; ¨ pointer to an integer
int **q; ¨ pointer to a pointer to an integer p=&a;
q=&p;
10 20 30
It can be seen from the diagram that there is no way of knowing in advance where the compiler is
going to put these numbers in memory. They may not even be stored in order.
Example:
#include<stdio.h>
void main( )
{
char *p1 = "Himanshu";
char *p2 = "jagruti";
char *p3 = "India";
char *arr[3];
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;
printf("\n p1 = [%s] \n",p1);
printf("\n p2 = [%s] \n",p2);
printf("\n p3 = [%s] \n",p3);
printf("\n arr[0] = [%s] \n",arr[0]);
printf("\n arr[1] = [%s] \n",arr[1]);
printf("\n arr[2] = [%s] \n",arr[2]);
}
Pointers to an Array:
Suppose we have an array of unsigned long values called v. We can declare a pointer to a simple
integer value and make it point to the array as is done normally.
int v[5] = {1004, 2201, 3000, 432, 500};
int *p = v;
printf(“%d \n”, *p);
This piece of code displays the number, which the pointer p points to, that is the first number in the
array, namely 1004.
p
1004 v[0]
2001 v[1]
3000 v[2]
432 v[3]
500 v[4]
The instruction p = v makes the pointer point to the address of the array. The number at this address
is the first element of the array; so that is the value produced when we access *p. p++ gives some
extra arithmetic instructions that lets us use the pointer to the array more flexibly.
p++
This instruction increases the pointer so that it points to the next element of the array. If it is
followed by the instruction printf(“%d \n”, *p); then it would display the number 2201, which is the
content of element v[1] (i.e., the second element)
2.calloc( ) function:
The name calloc stands for "contiguous allocation”. The calloc( ) function allocates multiple block
of requested memory. It initially initializes all bytes to zero. It returns NULL if memory is not
sufficient. The only difference between malloc( ) and calloc( ) is that, malloc() allocates single
block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets
all bytes to zero.
Syntax:
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements.
Example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of
float, i.e, 4 bytes.
Example Program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;
/* memory is allocated dynamically */
ptr = calloc( 20, sizeof(char) );
if( ptr = = NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( ptr," Jagruti degree college ");
}
printf("Dynamically allocated memory content : " \"%s\n", ptr );
free(ptr);
return;
}
3.realloc() function:
realloc() function modifies the allocated memory size by malloc () and calloc () functions to new
size. If enough space doesn’t exist in memory of current block to extend, new block is allocated for
the full size of reallocation, then copies the existing data to new block and then frees the old block
Syntax:
ptr=realloc(ptr, new-size);
Here, ptr is reallocated with size of new size.
Example Program:
#include <stdio.h>
#include <stdlib.h>
int main( )
{
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;
}
4. free() function:
free() function frees the allocated memory by malloc(), calloc(), realloc() functions and returns the
memory to the system.
Syntax:
free(ptr);
This statement causes the space in memory pointer by ptr to be deallocated.
Memory size can’t be modified while Memory size can be modified while execution.
execution. Example: array Example: Linked list
Difference between malloc() and calloc() functions in C:
malloc() calloc()
It allocates multiple blocks of requested
It allocates only single block of requested memory
memory
malloc() doesn’t initializes the allocated memory. calloc () initializes the allocated memory to
It contains garbage values zero
type cast must be done since this function returns Same as malloc () function
void pointer int *ptr;ptr = int *ptr;ptr = (int*)calloc(20,20,*sizeof(int)
(int*)malloc(sizeof(int)*20 ); );
UNIT-4
Structure:
As we know that Array is collection of the elements of same type, but many time we have to store
the elements of the different data types. Structure in c language is a user defined datatype that
allows you to hold different types of elements. Each element of a structure is called a member. You
can have different types of elements in it. It is widely used to store student information, employee
information, product information, book information etc.
Defining structure
The struct keyword is used to define structure. The struct statement defines a new data type, with
more than one member.
Syntax:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example:
struct employee
{
int id;
char name[50];
float salary;
};
Here, struct is the keyword, employee is the tag name of structure; id, name and salary are the
members or fields of the structure. Let's understand it by the diagram given below:
void main()
{
struct person person1, person2;
}
2. By declaring variable at the time of defining structure.:
struct person
{
char name[50];
int citNo;
float salary;
} person1, person2;
Example Program:
#include <stdio.h>
#include <conio.h>
struct employee
{
int id;
char name[50];
}e1; //declaring e1 variable for structure
void main( )
{
//store first employee information
e1.id=101;
e1.name=”jagruti”;
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
}
Output:
employee 1 id : 101
employee 1 name : jagruti
void main( )
{
//store first employee information
e1.id=101;
e1.name="mahesh"
e1.salary=56000;
//store second employee information
e2.id=102;
e1.name="kumar"
e2.salary=126000;
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);
//printing second employee information
printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
}
Output:
employee 1 id : 101
employee 1 name : mahesh
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : kumar
employee 2 salary : 126000.000000
Array of Structures:
There can be array of structures in C programming to store more information of different data types.
The array of structures is also known as collection of structures.
An example of structure with array that stores information of 5 students and prints it.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
int rollno;
char name[10];
};
void main()
{
int i;
struct student st[5];
clrscr();
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
getch();
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:venu
Enter Rollno:2
Enter Name:mahesh
Enter Rollno:3
Enter Name:kumar
Enter Rollno:4
Enter Name:santhosh
Enter Rollno:5
Enter Name:pawan
Union:
A union is quite similar to the structures in C. It also store different data types in the same memory
location. It is also a user defined data type same like structure.
Defining a union:
Union can be defined in same manner as structures, for defining union use union keyword where as
for defining structure use struct keyword.
Syntax:
union tagname
{
datatype member1;
datatype member2;
.......
.......
};
Example
union emp
{
int ID;
char name[10];
double salary;
}u;
Accessing members of an union:
The member of unions can be accessed in similar manner as Structure with union reference.
Suppose, we you want to access name variable in above example, it can be accessed as u.name.
Example:
#include <stdio.h>
union employee
{ int id;
char name[50];
}e1; //declaring e1 variable for union
void main( )
{
e1.id=101; //store first employee information
e1.name=”Mahesh”;
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
}
Enumeration Types:
An enum is a keyword it is an user defined data type. All properties of integer are applied on
Enumeration data type so size of the enumerator data type is 2 byte. It works like the Integer. It is
used for creating an user defined data type of integer. Using enum we can create sequence of
integer constant value.
Syntax
enum tagname {value1, value2, value3,....};
In above syntax enum is a keyword. It is a user defined data type. tag name is our own variable. tag
name is any variable name. value1, value2, value3,.... are creating set of enum values.
It is start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the
list. If constant one value is not initialized then by default sequence will be start from zero and next
to generated value should be previous constant value one.
Example
enum week {sun, mon, tue, wed, thu, fri, sat};
enum week today;
In above code first line is create user defined data type called week.
Week variable have 7 value which is inside { } braces.
today variable is declare as week type which can be initialize any data or value among 7 (sun,
mon,....).
Example Program
#include< stdio.h>
void main()
{
int i;
enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC};
clrscr();
for(i=JAN;i<=DEC;i++)
{
printf("\n%d",i);
}
}
Output :
01234567891011
Typedef:
typedef is a keyword used in C language to assign alternative names to existing types. It’s mostly
used with user defined data types.
Syntax:
typedef existing_name alias_name;
Example:
typedef int book;
The above statement defines a term book for an int type. Now this book identifier can be used to
define unsigned long type variables.
book a=10;
Example Program:
#include<stdio.h>
void main()
{
typedef int Number;
Number a = 40,b = 20,c;
c = a+b;
printf("Answer : %d",c);
}
Files in C:
A file represents a sequence of bytes on the disk where a group of related data is stored. File is
created for permanent storage of data. It is a readymade structure.
Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all. However,
if you have a file containing all the data, you can easily access the contents of the file using few
commands in C.
You can easily move your data from one computer to another without any change
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text
editors. When you open those files, you'll see all the contents within the file as plain text. You can
easily edit or delete the contents. They take minimum effort to maintain, are easily readable, and
provide least security and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they
store it in the binary form (0's and 1's).They can hold higher amount of data, are not readable easily
and provides a better security than text files.
Functions use in File Handling:
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the beginning point
Defining and Opening a File:
The fopen( ) function is used to create a new file or to open an existing file.
Syntax:
FILE *fp;
fp=fopen("filename", "mode");
Here fp declares a variable as a pointer to the data type FILE.
Here filename is the name of the file to be opened and mode specifies the purpose of opening the
file. Mode can be of following types,
mode description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
Closing a File:
A file must be close after completion of all operation related to file. For closing file we need fclose(
) function. The fclose( ) function is used to close an already opened file.
Syntax:
int fclose( FILE *fp );
Here fclose( ) function closes the file and returns zero on success, or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h.
Input/Output Operation on files:
In the above table we have discussed about various file I/O functions to perform reading and
writing on file. getc() and putc() are simplest functions used to read and write individual characters
to a file.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF)
{
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
fclose(fp);
}
Reading and Writing from File using fprintf() and fscanf():
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that, fprintf and fscanf
expects a pointer to the structure FILE.
Example:
#include <stdio.h>
void main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fprintf(fptr,"%d",num);
fclose(fptr);
}
Working with Binary File:
The operations performed on binary files are similar to text files since both types of files can
essentially be considered as streams of bytes. In fact, the same functions are used to access files in
C. When a file is opened, it must be designated as text or binary and usually this is the only
indication of the type of file being processed. To illustrate a binary file, consider the following
program containing a function, filecopy (), that is passed the names of the source and destination
files and then performs the copy operation just as the outlined steps. If there is an error in opening
either file, the function does not attempt the copy operation and returns -1 to the calling program.
When the copy operation is complete, the program closes both files and returns 0. The steps for
copying a binary file into another are as follows.
1. Open the source file for reading in binary mode.
2. Open the destination file for writing in binary mode.
3. Read a character from the source file. Remember, when a file is first opened, the pointer is at the
start of the file, so there is no need to position the file pointer explicitly.
4. If the function feof() indicates that the end of the source file has been reached, then close both fi
les and return to the calling program.
5. If end-of-file has not been reached, write the character to the destination file, and then go to step
3.
Example:
#include <stdio.h>
int filecopy(char *, char *);
int main()
{
char source[80], destination[80];
printf(“\nEnter source file:”);
fflush(stdin);
gets(source);
printf(“\nEnter destination fi le:”);
fflush(stdin);
gets(destination);
if(filecopy(source, destination) == 0)
puts(“\n Successfully copied”);
else
fprintf(stderr, “Error in copying...”);
return 0;
}
int filecopy(char *s, char *d)
{
FILE *ofp, *nfp;
int ch;
if((ofp = fopen(s, “rb”)) == NULL) /* Open the source file for reading in binary mode. */
return -1;
if((nfp = fopen(d, “wb”)) == NULL) /* Open the destination filefor writing in binary mode. */
{
fclose(ofp);
return -1;
}
while(1)
{
ch = fgetc(ofp);
if(!feof(ofp))
fputc(ch, nfp);
else
break;
}
fclose(nfp);
fclose(ofp);
return 0;
}
FILES OF RECORDS
Most C program files may be binary files, which can logically be divided into fixed-length records.
Each record will consist of data that conforms to a previously defined structure. In C, this structure
can be formed using a struct data type. The records are written into disk sequentially. This happens
because as each record is written to disk, the file position indicator is moved to the byte
immediately after the last byte in the record just written. Binary files can be written sequentially to
the disk or in a random access manner.
Working with Files of Records:
Using fscanf() and fprintf() The following structure records the code, name, and price of an item.
Using this structure a file of records can be processed. Here 0 is used as end-of-file marker
(logically) to indicate there are no records in the file.
Example:
#include <stdio.h>
void main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
}
RANDOM ACCESS TO FILES OF RECORDS:
For random access to files of records, the following functions are used.
1.fseek()
2.ftell()
3.rewind()
1.fseek() Function:
This function is used for setting the file position pointer at the specified bytes. fseek is a function
belonging to the ANCI C standard Library and included in the file <stdio.h>. Its purpose is to
change the file position indicator for the specified stream.
int fseek(FILE *stream_pointer, long offset, int origin);
Argument meaning
stream_pointer is a pointer to the stream FILE structure of which the position indicator should
be changed;
offset is a long integer which specifies the number of bytes from origin where the position
indicator should be placed;
Origin is an integer which specifies the origin position. It can be:
SEEK_SET: origin is the start of the stream
SEEK_CUR: origin is the current position
SEEK_END: origin is the end of the stream
Example:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct emprecord
{
char name[30];
int age;
float sal;
}emp;
void main()
{
int n;
FILE *fp;
fp=fopen("employee.dat","rb");
if (fp==NULL)
{
printf("/n error in opening file");
exit(1);
}
printf("enter the record no to be read");
scanf("%d",&n);
fseek(fp,(n-1)*sizeof(emp),0);
freed(&emp,sizeof(emp),1,fp);
printf("%s\t,emp.name);
printf("%d\t",emp.age);
printf("%f\n",emp.sal);
fclose(fp);
getch();
};
ftell() Function:
This function returns the current position of the file position pointer. The value is counted from the
beginning of the file.
Syntax :
long ftell (file * fptr);
Example:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct emprecord
{
char name[30];
int age;
float sal;
}emp;
void main()
{
FILE *fp;
fp=fopen("employee.dat","rb");
if (fp==NULL)
{ /*an error occurred while processing this directive*/
printf("/n error in opening file");
exit(1);
}
printf("position pointer in the beginning -> %1d ",ftell(fp));
while("fread(position pointer -> 1%d\n",ftell(fp));
printf("position pointer -> %1d\n",ftell(fp));
printf("%s\t",emp.name);
printf("%d\t",emp.age);
printf("%f",emp.sal);
}
printf("size of the file in bytes is %1d\n",ftell(fp));
fclose(fp);
getch();
}
rewind() function:
The rewind function sets the file position to the beginning of the file for the stream pointed to by
stream. It also clears the error and end-of-file indicators for stream.
Syntax
void rewind(FILE *stream);
OTHER FILE MANAGEMENT FUNCTIONS:
The copy and delete operations are also associated with file management. Though one could write
programs for them, the C standard library contains functions for deleting and renaming files.
Deleting a File:
The library function remove () is used to delete a fi le. Its prototype in stdio.h is
int remove(const char *filename);
The variable *filename is a pointer to the name of the file to be deleted. The only precondition is
that the specified file must not be open. If the file exists, it will be deleted and remove ( ) returns 0.
Example:
#include <stdio.h>
int main(void)
{
char file[80];
printf(“File to delete: ”); /* prompt for filename to delete */
gets(file);
if(remove(file) == 0) /* delete the file */
printf(“Removed %s.\n”,file);
else
perror(“remove”);
return 0;
}
Renaming a File:
The rename () function changes the name of an existing disk file. The function prototype in stdio.h
is as follows.
int rename(const char *oldname, const char *newname);
The filenames pointed to by oldname and newname. The only restriction is that both names must
refer to the same disk drive; a file cannot be renamed on a different disk drive. The function
rename() returns 0 on success, or -1 if an error occurs. Errors can be caused by the following
conditions.
The file oldname does not exist.
A file with the name newname already exists.
One tries to rename on another disk.
Example:
#include <stdio.h>
int main(void)
{
char oldname[80], newname[80];
printf(“File to rename:”); /* prompt for file to rename and new name */
gets(oldname);
printf(“New name:”);
gets(newname);
if(rename(oldname, newname) == 0) /* Rename the file */
printf(“Renamed %s to %s.\n”, oldname, newname);
else
perror(“rename”);
return 0;
}