C Programming
C Programming
Sandip Khanal
Unit-1
Programming Language
Introduction to programming language
Programming language is the set of written symbols and codes that instruct the computer
hardware to perform specified tasks. It is simply the coded language used by programmers to
write instructions that a computer can understand to do what the programmer user wants.
Programming is a way to create a sequence of instructions to enable the computer to do
something.
If we want to get something done by a person, we will tell him what to do in a language that he
understands. Similarly, if we want to make the computer to do some task for us, we have to tell
the computer what to do in a language that the computer understands. To communicate with the
computer is to develop a third language- a language that can be understood by us and the
computer. This is what a programming language- a set of rules that provides a way of instructing
the computer to perform certain operations. Programming languages are said to be lower or
higher, depending on whether they are closer to the language the computer itself uses (lower,
which means 0s and 1s) or to the language that people use (higher, which means more like
English).
2
Example
Code Comment
0010 0001 0000 0100 Load first operand into AC
0001 0001 0000 0101 Add second operand to AC
0011 0001 0000 0110 Store sum in location 106
0111 0000 0000 0001 Halt computer
0000 0000 0101 0011 83 decimal
1111 1111 1111 1110 -2 decimal
0000 0000 0000 0000 Store sum here
Advantages
i. It is the only language, which is directly understood by the computer.
ii. Language translator is not required.
iii. Execution speed of the program developed in this language is faster.
iv. Use of hardware components like memory, processor is efficient.
Disadvantages
i. It is tedious, difficult and time consuming to develop and debug program.
ii. All operations codes have to be remembered.
iii. All memory address has to be remembered.
iv. It is machine dependent language, so program developed for a system may
not be used in another without modification.
v. Programmers require detailed knowledge of hardware architecture.
2. Assembly level language [2GL]
Assembly level language is also a low level language because to design a program
programmer requires detailed knowledge of hardware specification. This language
uses mnemonics code (symbolic operation code like ADD, SUB, DIV) in place of 0s
and 1s. The program is converted into machine code by assembler. The resulting
program is referred to as an object code. Although assembly language saves time,
reduce errors and easy to debug, it has certain limitations like, the programmer must
know its opcodes (operational codes) or mnemonics codes to perform any task.
The symbolic nature of assembly language greatly eased the programmer’s burden,
but programs were still very hard to write. Programmer was forced to think in terms
of the computer’s architecture rather than to the problem being solved. Coding in this
language is time consuming though it is easier than machine language.
Advantages
i. It is easier to develop and debug program compared to machine language
due to the use of mnemonics.
ii. Programming is simplified i.e programmer does not need to know the
exact storage location of data and instruction.
iii. Execution speed of the program developed in this language is faster than
high level language.
iv. Use of hardware components like memory, processor is efficient than high
level language.
3
v. It is useful for developing hardware oriented system software like device
driver, remote control system, microprocessor based devices, traffic light
system, robotics.
Disadvantages
i. Program developed in this language cannot be executed directly. It needs
to be translated into machine language code (object code).
ii. Additional software, assembler is required to translated program into
object code.
iii. It is also machine dependent language.
iv. Programmers require detailed knowledge of hardware architecture.
v. It doesn’t contain symbolic names for addressing memory location.
4
2. Object Oriented language [4GL]
It allows the users to specify what the output should be, without describing all the details
of how the data should be manipulated to produce the result. This is one step ahead from
3GL. These are result oriented and include database query languages. There are fewer
options for programmers but the programs are much easier to write than in lower level
languages. 4GL programs are also needed to be translated either by compiler or
interpreter. Examples of 4GL are: Visual Basic, C#, PHP, JAVA etc.
Objectives of 4GL are:
1. Increase the speed of developing programs.
2. Minimize user’s effort to obtain information from computer.
3. Reduce errors while writing programs that are easy to maintain.
Advantages
i. It is even easier to develop and debug program than procedure oriented
language.
ii. More advanced and user friendly software can be developed.
iii. Web based software can be developed.
iv. It is also machine independent language.
v. Programmer don’t require detail knowledge of hardware architecture and
programmers doesn’t require specifying the working process in detail.
Disadvantages
i. Program developed in this language cannot be executed directly. It needs to be
translated into machine language code (object code).
ii. An additional software, compiler or interpreter is required to translate
program into object code.
iii. Program execution will be even slower.
iv. It is difficult to develop hardware oriented software.
3. Natural language [5GL]
Natural language uses simple statement of common communication languages where we
could write statements that would look like normal sentences. For example, instead of
odd- looking code, we would write “ who are the salesmen with sales over RS 20,000 last
month?”. It is still in developing language named PROLOG is in use, which would
support 5GL to some extent.
Advantages
i. It will be even easier to develop and debug program.
ii. More advanced and user friendly software can be developed.
iii. It will also be machine independent language.
iv. Programmers will not require detail knowledge of hardware architecture and
programmers doesn’t require specifying the working process in detail.
5
Disadvantages
i. Program developed in this language cannot be executed directly. It also needs
to be translated into machine language code (object code).
ii. A language translator is required to translate program into object code.
iii. It is difficult to develop hardware oriented software.
Language Translator
Language translator is system software that translates instructions written in assembly or high
level language (source code) into machine language (object code). Program is developed in
assembly or high level language for the convenience of the programmer, but computer doesn’t
understand these statements directly. So, translator program is used which converts that
statements in computer executable format.
Different types of language translators are:
1. Assembler
2. Compiler
3. Interpreter
1. Assembler
Assembler is a translator that converts code of assembly language into the machine language.
The resulting program can be executed only when the assembly process is completed. It also
generates diagnostic error messages. In addition to translating, it also “assembles” the machine
language program in memory of the computer, and makes it ready for execution.
In an assembly language, the computer has to run the assembler, first translate the assembly
language (source code) into its equivalent machine language (object code), and then execute to
get the result. This means that the computer has to spend more time to get the result as compared
to machine language. Assembly language programming saves time and effort of a programmer.
6
2. Compiler
Compiler is a translator which translates high level program (source code) into machine
instruction (object code) at once and then it can be immediately executed anytime thereafter. A
compiler is so called, because it compiles a set of machine language instructions for every
program instruction of a high-level language.
Input Output
High level language program
Compiler Machine language program
As shown in the figure, the input to the compiler is the high-level language program (often
referred to as a source program), and its output is the machine language program (often referred
to as an object program). Since high-level language instructions are macro instructions, the
compiler translates each high-level language instruction into a set of machine language
instructions, rather than a single machine language instruction. Hence, there is a one to many
correspondence between the high-level language instructions of a source program, and the
machine language instructions of its equivalent object program. During the process of translation
of a source program into its equivalent object program by the compiler, the source program is not
being executed. It is only being converted into a form, which can be executed by the computer’s
processor.
Compilers are large programs, which reside permanently on secondary storage. When a source
program is to be translated, the compiler and the source program are copied from secondary
storage into the main memory of the computer. The compiler, being program, is then executed
with the source program as its input data. It generates the equivalent object program as its output,
which is normally saved in a file on secondary storage. Whenever there is a need to execute the
program, the object program is copied from secondary storage into the main memory of the
computer and executed. There is no need to repeat the compilation process every time we wish to
execute the program because object program stored on secondary storage is already in machine
language. We simply have to load the object program from the secondary storage into main
memory of the computer and execute it directly. Compilation is necessary whenever we need to
modify the program.
In addition to translating high-level language instructions into machine language instructions,
compilers also automatically detect and indicate certain types of errors in source programs.
These errors are referred to as syntax errors. A source program containing one or more errors
detected by the compiler will not be compiled into an object program. Compiler detect
grammatical (syntax) errors in the source program it cannot detect logical (semantic) error.
7
Features of compiler
1. It translates complete program at once if the program doesn’t contain syntax error.
2. It provide fastest method of translating a program.
3. In compiler, the syntax errors are found only after the compilation of the complete program.
4. Debugging can be complex and time consuming.
5. It saves object code for future reference. So, translation is not required for every time the
program is used.
6. Programming languages like C, C++, Java, COBOL and Pascal use compiler.
3. Interpreter
An interpreter is a translator which translates high level language into a machine language, one
line at a time and executes line of the program after it has been translated. It takes one statement
of a high-level language program, translates it into machine language instructions, and then
immediately executes the resulting machine language instructions.
Input Output
High level language program (Source Program) Interpreter Result of program execution
Since no object program is saved for future use, repeated interpretation (translation plus
execution) of a program is necessary for its repeated execution.
Features of interpreter
1. It translates one line statement at a time if the statement is free from syntax error.
2. It is slower for translation.
3. In translator, the syntax error is found only after interpretation of the complete statement.
4. Debugging is easier and faster.
5. It doesn’t save object code for future reference. So, translation is required for every time
before the program is used.
6. Most of the new programming language used interpreter.
7. It is usually a smaller program and requires less memory space.
8. Programming languages like BASIC, Visual Basic, C#, and PHP use interpreter.
Difference between compiler and interpreter
Compiler Interpreter
1. It translates the whole program into object 1. It translates one line or single statement of
code at a time. a program into object code at a time.
2. It traps the errors after compiling the 2. It traps the errors after translating a line of
complete program. the program at a time.
8
3. The translating process is incredibly faster. 3. The translating process is slower.
4. Compiler based program is difficult to 4. Interpreter based program is easy to code
code and debug. and debug.
5. It saves the object code for future 5. It does not save object code.
reference.
6. New programming languages doesn’t use 6. New programming languages use
compiler. interpreter.
7. It is usually a larger program and requires 7. It is usually a smaller program and requires
larger memory space. less memory space.
8. Examples of compiler based programming 8. Examples of interpreter based
language are C, C++, COBOL, Pascal, programming language are BASIC,
FORTAN etc. Visual
Basic, C#, PHP etc.
Program Errors
Errors are the mistakes in the program. Error can be in syntax or logic (concept/idea) of the
program. If a program contain error, it will either not produce output or may produce inaccurate
output. The process of detecting and connecting error is known as debugging.
Different types of errors are:
1. Syntax error
2. Logical (Semantic) error
3. Run time error
1. Syntax Error
A syntax error is the error in the syntax or format of the program. It happens when it does not
conform to the syntax of the programming language. For example in C language, whenever we
do not use semicolon in a simple statement causes syntax error. It is detected by language
translator at the translation process. If a program contains syntax error, it is not translated into
object code. So, it will not be executed and will not produce output. This type of error is easier,
faster and cheaper to debug. Experienced personnel’s are not required. Reference materials like
help file, book and documents are available for the syntax of the program.
Program
The set of instructions which command the computer to perform particular operation or a
specific task is called a program. Program is written in a programming language then translated
into machine code by a language processor so that the computer can execute tasks. The
programming language statements are the source program or source code. Then we compile the
source code and the result is called an object code. The object code consists of the values in
terms of 0s and 1s. Finally, this object code is linked with other library codes to create the
program.
11
2. Maintainability- It is the process of fixing program errors and improving the program. If a
program is easy to read and understand, then its maintenance will be easier.
3. Efficient- Program is said to be more efficient, if it takes less space and easily converted to
machine language.
4. Reliable- The user's actual needs will change from time-to-time, so program is said to be
reliable if works smoothly in every version.
5. Machine Independence- Program should be machine independent. Program written on one
system should be able to execute on any other without any changes.
6. Cost Effectiveness- Cost Effectiveness is the key to measure the program quality. Cost must
be measured over the life of the program and must include both cost and human cost of
producing these programs.
7. Flexible- Program should be written in such a manner that it allows to add new features
without changing the existing module.
Programming Paradigm
A programming paradigm is a fundamental style of building the structure and elements of a
program. The styles and capabilities of programming languages are defined by their paradigms.
Different types of paradigm are:
1. Imperative paradigm
The word 'imperative' can be used both as an adjective and as a noun. As an adjective it means
'expressing a command or plea'. In other words, asking for something to be done. As a noun, an
imperative is a command or an order. Some programming languages, such as the object oriented
language Beta, uses the word 'imperative' for commands in the language.
The 'first do this, next do that' is a short phrase which really in a nutshell describes the spirit of
the imperative paradigm. The basic idea is the command, which has a measurable effect on the
program state. The phrase also reflects that the order to the commands is important. 'First do that,
then do this' would be different from 'first do this, then do that'.
We use several names for the computational steps in an imperative language. The word
statement is often used with the special computer science meaning 'a elementary instruction in a
source language'. The word instruction is another possibility; we prefer to devote this word the
computational steps performed at the machine level. We will use the word 'command' for the
imperatives in a high level imperative programming language.
Characteristics:
a. Discipline and idea
Digital hardware technology and the ideas of Von Neumann
b. Incremental change of the program state as a function of time.
c. Execution of computational steps in an order governed by control
12
We call the steps for commands
13
3. Logical paradigm
The logic paradigm is dramatically different from the other three main programming paradigms.
The logic paradigm fits extremely well when applied in problem domains that deal with the
extraction of knowledge from basic facts and relations. The logical paradigm seems less natural
in the more general areas of computation.
Characteristics:
a. Discipline and idea
Automatic proofs within artificial intelligence
b. Based on axioms, inference rules, and queries.
c. Program execution becomes a systematic search in a set of facts, making
use of a set of inference rules
Characteristics:
15
1. Requirement Gathering and analysis − All possible requirements of the system to be
developed are captured in this phase and documented in a requirement specification
document.
2. System Design − The requirement specifications from first phase are studied in this phase
and the system design is prepared. This system design helps in specifying hardware and
system requirements and helps in defining the overall system architecture.
3. Implementation − With inputs from the system design, the system is first developed in
small programs called units, which are integrated in the next phase. Each unit is
developed and tested for its functionality, which is referred to as Unit Testing.
4. Integration and Testing − All the units developed in the implementation phase are
integrated into a system after testing of each unit. Post integration the entire system is
tested for any faults and failures.
5. Deployment of system − Once the functional and non-functional testing is done; the
product is deployed in the customer environment or released into the market.
6. Maintenance − There are some issues which come up in the client environment. To fix
those issues, patches are released. Also to enhance the product some better versions are
released. Maintenance is done to deliver these changes in the customer environment.
Application of Waterfall Model
Every software developed is different and requires a suitable SDLC approach to be followed
based on the internal and external factors. Some situations where the use of Waterfall model is
most appropriate are −
Ample resources with required expertise are available to support the product.
The advantages of waterfall development are that it allows for departmentalization and control.
A schedule can be set with deadlines for each stage of development and a product can proceed
through the development process model phases one by one.
16
Some of the major advantages of the Waterfall Model are as follows −
Easy to manage due to the rigidity of the model. Each phase has specific deliverables and
a review process.
Works well for smaller projects where requirements are very well understood.
The disadvantage of waterfall development is that it does not allow much reflection or revision.
Once an application is in the testing stage, it is very difficult to go back and change something
that was not well-documented or thought upon in the concept stage.
Not suitable for the projects where requirements are at a moderate to high risk of
changing. So, risk and uncertainty is high with this process model.
2. Iterative model
Iterative process starts with a simple implementation of a subset of the software requirements
and iteratively enhances the evolving versions until the full system is implemented. At each
iteration,
17
design modifications are made and new functional capabilities are added. The basic idea behind
this method is to develop a system through repeated cycles (iterative) and in smaller portions at
a time (incremental).
The following illustration is a representation of the Iterative and Incremental model −
In this incremental model, the whole requirement is divided into various builds. During each
iteration, the development module goes through the requirements, design, implementation and
testing phases. Each subsequent release of the module adds function to the previous release. The
process continues till the complete system is ready as per the requirement.
The key to a successful use of an iterative software development lifecycle is rigorous validation
of requirements, and verification & testing of each version of the software against those
requirements within each cycle of the model. As the software evolves through successive
cycles, tests must be repeated and extended to verify each version of the software.
Application of Iterative Model
Like other SDLC models, Iterative and incremental development has some specific applications
in the software industry. This model is most often used in the following scenarios −
18
There is a time to the market constraint.
A new technology is being used and is being learnt by the development team while
working on the project.
Resources with needed skill sets are not available and are planned to be used on contract
basis for specific iterations.
There are some high-risk features and goals which may change in the future.
Advantages
Some working functionality can be developed quickly and early in the life cycle.
Risks are identified and resolved during iteration; and each iteration is an easily
managed milestone.
During the life cycle, software is produced early which facilitates customer
evaluation and feedback.
Disadvantages
19
Although cost of change is lesser, but it is not very suitable for changing requirements.
System architecture or design issues may arise because not all requirements are gathered
in the beginning of the entire life cycle.
1. Identification
This phase starts with gathering the business requirements in the baseline spiral. In the
subsequent spirals as the product matures, identification of system requirements, subsystem
requirements and unit requirements are all done in this phase.
This phase also includes understanding the system requirements by continuous communication
between the customer and the system analyst. At the end of the spiral, the product is deployed in
the identified market.
2. Design
The Design phase starts with the conceptual design in the baseline spiral and involves
architectural design, logical design of modules, physical product design and the final design in
the subsequent spirals.
20
3. Construct or Build
The Construct phase refers to production of the actual software product at every spiral. In the
baseline spiral, when the product is just thought of and the design is being developed a POC
(Proof of Concept) is developed in this phase to get customer feedback.
Then in the subsequent spirals with higher clarity on requirements and design details a working
model of the software called build is produced with a version number. These builds are sent to
the customer for feedback.
The following illustration is a representation of the Spiral Model, listing the activities in each
phase.
Based on the customer evaluation, the software development process enters the next iteration and
subsequently follows the linear approach to implement the feedback suggested by the customer.
The process of iterations along the spiral continues throughout the life of the software.
21
Application
The Spiral Model is widely used in the software industry as it is in sync with the natural
development process of any product, i.e. learning with maturity which involves minimum risk
for the customer as well as the development firms.
New product line which should be released in phases to get enough customer feedback.
Significant changes are expected in the product during the development cycle.
Advantages
The advantage of spiral lifecycle model is that it allows elements of the product to be added in,
when they become available or known. This assures that there is no conflict with previous
requirements and design.
This method is consistent with approaches that have multiple software builds and releases
which allows making an orderly transition to a maintenance activity. Another positive aspect of
this method is that the spiral model forces an early user involvement in the system development
effort.
On the other side, it takes a very strict management to complete such products and there is a risk
of running the spiral in an indefinite loop. So, the discipline of change and the extent of taking
change requests is very important to develop and deploy the product successfully.
Development can be divided into smaller parts and the risky parts can be developed
earlier which helps in better risk management.
22
Disadvantages
Not suitable for small or low risk projects and could be expensive for small projects.
Process is complex
Prototype model refers to building software application prototypes which displays the
functionality of the product under development, but may not actually hold the exact logic of the
original software.
Prototype is a working model of software with some limited functionality. The prototype does
not always hold the exact logic used in the actual software application and is an extra effort to
be considered under effort estimation.
Prototyping is used to allow the users evaluate developer proposals and try them out before
implementation. It also helps understand the requirements which are user specific and may not
have been considered by the developer during product design.
23
internally in the actual software developed. While, the workarounds are used to give the same
look and feel to the customer in the prototype developed.
Prototypes can have horizontal or vertical dimensions. A Horizontal prototype displays the user
interface for the product and gives a broader view of the entire system, without concentrating on
internal functions. A Vertical prototype on the other side is a detailed elaboration of a specific
function or a sub system in the product.
The purpose of both horizontal and vertical prototype is different. Horizontal prototypes are
used to get more information on the user interface level and the business requirements. It can
even be presented in the sales demos to get business in the market. Vertical prototypes are
technical in nature and are used to get details of the exact functioning of the sub systems. For
example, database requirements, interaction and data processing loads in a given sub system.
Prototyping types
Throwaway/Rapid Prototyping
Throwaway prototyping is also called as rapid or close ended prototyping. This type of
prototyping uses very little efforts with minimum requirement analysis to build a prototype.
Once the actual requirements are understood, the prototype is discarded and the actual system is
developed with a much clear understanding of user requirements.
Evolutionary Prototyping
Evolutionary prototyping also called as breadboard prototyping is based on building actual
functional prototypes with minimal functionality in the beginning. The prototype developed
forms the heart of the future prototypes on top of which the entire system is built. By using
evolutionary prototyping, the well-understood requirements are included in the prototype and
the requirements are added as and when they are understood.
24
Incremental Prototyping
Incremental prototyping refers to building multiple functional prototypes of the various sub-
systems and then integrating all the available prototypes to form a complete system.
Extreme Prototyping
Extreme prototyping is used in the web development domain. It consists of three sequential
phases. First, a basic prototype with all the existing pages is presented in the HTML format.
Then the data processing is simulated using a prototype services layer. Finally, the services are
implemented and integrated to the final prototype. This process is called Extreme Prototyping
used to draw attention to the second phase of the process, where a fully functional UI is
developed with very little regard to the actual services.
Application
Software Prototyping is most useful in development of systems having high level of user
interactions such as online systems. Systems which need users to fill out forms or go through
various screens before data is processed can use prototyping very effectively to give the exact
look and feel even before the actual software is developed.
Software that involves too much of data processing and most of the functionality is internal with
very little user interface does not usually benefit from prototyping. Prototype development
could be an extra overhead in such projects and may need lot of extra efforts.
Advantages
Software prototyping is used in typical cases and the decision should be taken very carefully so
that the efforts spent in building the prototype add considerable value to the final software
developed. The model has its own pros and cons discussed as follows.
Since a working model of the system is displayed, the users get a better understanding of
the system being developed.
Reduces time and cost as the defects can be detected much earlier.
25
Disadvantages
Risk of insufficient requirement analysis owing to too much dependency on the prototype.
Practically, this methodology may increase the complexity of the system as scope of the
system may expand beyond original plans.
Developers may try to reuse the existing prototypes to build the actual system, even
when it is not technically feasible.
The effort invested in building prototypes may be too much if it is not monitored properly.
26
i. Survey the system study with collecting the inputs from various sources.
ii. Analyzing the current system (manual or automated) in depth and developing
possible solutions to the problem.
iii. Selecting the best solution and defining its function with feasibility study.
This phase begins when the need is identified for a new or modified information sstem. During
this phase, the system analyst thoroughly studies the organization’s current procedures and the
information systems used to perform organizational tasks. In system study, the first challenge is
to defines the problem accurately. With the problem accurately defined, the organization can
decide whether to undertake the system or not. When the decision is made to proceed, system
analyst investigates about the current system and its limitations.
At the end of this phase, the team of system analyst comes to conclude with new system to be
adopted. Then the detailed plans and schedules are drafted for making the new system through
feasibility study.
Feasibility study
Feasibility is the determination of whether or not a system or project is worth doing. The process
followed in making this determination is called a feasibility study. So, feasibility study is to
determine whether the whole process of system analysis leading to computerization would be
worthwhile for organization or not. It is a post phase of system study. Feasibility study is
conducted once the system goal is set. The feasibility study is basically the test of the proposed
system in its workability, meeting user’s requirement, effective use of resources and the cost
effectiveness. The main goal of feasibility study is not to solve the problem but to achieve the
possibility of the system. In the process of feasibility study, the cost/benefits analysis is
estimated with greater accuracy.
Needs of feasibility study
Conducting a feasibility study is a good practice for any system development. The feasibility
study outline and analyzes several alternatives or methods for achieving system success. So the
feasibility study helps to narrow the scope of the project to identify the best system.
Some of the reasons to conduct a feasibility study are:
1. It determines whether the system meets the goal of the clients or not.
2. It determines the strengths and limitations before starting to develop the system.
3. It focuses on the boundary of system’s outline.
4. It suggests new opportunities through the investigation process.
5. It enhances the probability of success by addressing and justifying factors prior on that could
affect the system.
6. It provides quality information for decision making.
7. It helps to increase investment in the system.
8. It provides documentation of the investigated system.
9. It allows new technologies and development areas for faster processing, more storage, and
lower costs than ever before.
27
10. It helps in obtaining fund from financial institutions and other sources.
Type of feasibility study
1. Technical feasibility study
During technical feasibility study, the system analyst identifies the existing computer systems
(hardware and software) of the concerned department and determines whether these technical
resources are sufficient for the proposed system or not. If they are not sufficient, the analyst
suggests the configuration of the computer systems that are required. Technical feasibility
includes:
It determines the technology needed for a system is available or not.
It determines how the technology can be well used within the system.
It identifies the correct personnel and correct equipment for the system including
hardware and software system.
2. Economical feasibility
Economical feasibility is the most important study that determines the cost and benefits of the
proposed system and compares with the budget. The cost of the system should not outweigh the
budget. The cost of the system includes the cost of hardware, software, development and
implementation. To ensure the new system will certainly lead to benefits outweighing the cost.
Cost benefit analysis is also carried out which includes:
The return of investments in the system.
Determines whether the system or project is affordable or not.
Identifies the financial benefits and cost benefit analysis associated with that system.
Determines whether the system’s goals can be achieved within the allocated fund.
3. Operational feasibility
During operational feasibility study, it is determined whether the system will operate in the way
that user wants. Operational feasibility depends upon human resources for the development and
implementation of the system. It is considered whether the qualified and experienced manpower
is available for development and implementation of the system. It is considered whether the
qualified and experienced manpower is available for development and implementation of the
system. User involvement is more required in determining the operational feasibility. This
feasibility study is carried out by a small group of people who are familiar with information
system techniques, who understand the parts of the business that are relevant to the system and
they are skilled in system analysis and design process. The operational feasibility is considered
with:
It determines the general skills, training and capabilities of the existing personnel.
It concerns with organizational structures, the business problems and their solutions.
It identifies how the system will fit in the current operations.
4. Social feasibility
Social feasibility is a determination of whether a proposed system will be acceptable to the
people or not. This determination typically examines the probability of the system being
accepted by the group directly affected by the proposed system change. Social feasibility
determines the impact of the system to employees. The result of the study is a report
recommending whether to proceed with other phases or not. If the answer is yes, then project
planning is done which establishes high level plan or schedule or system or project goals.
28
5. Legal feasibility
Information systems have a legal impact. First of all, there are copyright restrictions. For any
system that includes purchased components, one has to make sure that the license agreements are
not violated. For one thing this means installing only licensed copies. But license agreements and
copy protection can also restrict how you integrate the data and processes with other parts of the
system. If you are working with contract programmers, the ownership of the program source
code and nondisclosure agreements have to be worked out in advance.
Union contracts can add constraints to the information system on how workers are paid and how
their work is monitored. Legal requirements for financial reporting must be met. System
requirements for sharing data with partners could even run up against antitrust laws.
6. Time feasibility
It is necessary to determine whether the deadlines are mandatory or desirable. For instance, a
project to develop a system to meet new government reporting regulations may have a deadline
that coincides with when the new reports must be initiated. Penalties associated with missing
such a deadline may make meeting it mandatory. If the deadlines are desirable rather than
mandatory, the analyst can propose alternative schedules.
It is preferable (unless the deadline is absolutely mandatory) to deliver a properly functioning
information system two months late than to deliver an error-prone, useless information system on
time! While missing deadlines can be problematic, developing inadequate systems can be
terrible.
7. Behavioral feasibility
Behavioral feasibility includes a study of organizational behavior. It includes:
The behavioral approach of the management staffs and workers within the system in
the organization.
It concerns with fear of loss of job and lost identity, displacement of the manpower,
fear of technology.
2. System Analysis
System analysis is an important activity that takes place when new information system is being
changed. It follows the feasibility study and involves a detailed study of the current system,
leading to specifications of a new system. It is central part to the whole of system development.
System analysis is a detailed study of various operations performed by a system and their
relationships within and outside the system. During system analysis, data are collected from the
various available sources by using tools such as interview, on-site observation, questionnaire,
sampling, research and documentation.
Using the following steps it becomes easy to draw the exact boundary of the new system under
considerations:
Keeping in view the problems and new requirements.
Find out the pros and cons including new areas of the system.
All procedures, requirements must be analyzed and documented. System analysis include sub-
dividing the complex process involving the entire system, identification of data store and manual
processes. Finally, system analysis determines the shapes, form, strength, capability and even the
life of the system.
29
3. System Design
Design of an information system produces the details that clearly describe how a system will
meet the requirements, identified during system analysis. System specialist often refers to this
stage as logical design, in contrast to the process of developing program software, which is
referred to as physical design.
During this phase, the designer must design all the aspects of the system from the input and
output screen to reports, databases and processes of computing. Designer must provide the
physical specifics of the system designed, either as a model or as detailed documentation, to
guide those who will develop the new system.
To design the system, the team can use the top-down design or bottom-up design model. In top-
down design, the team member starts with a large picture and move to the details. They look at
major functions that the system must provide and break these down into smaller and smaller
activities. In bottom up design, the team starts with the details and then moves to the big picture.
This approach is applicable when the users have specific requirement for output.
Many system design tools are available to help teams through the steps of system design. Some
of them are algorithm, flowchart, pseudo code, context diagram, DFD (Data Flow Diagram),
decision table, decision tree, E-R (Entity-Relationship) diagram, prototyping and CASE
(Computer-Aided Software Engineering) tool.
4. System Development
During the development phase, the development play a key role, creating or customizing the
system. After designing the new system, defined procedures are transformed into the physical
system. In this phase technical writers also work with the developers to develop the technical
documents for the system. The technical documentation includes information about systems
features, the flow of system, the design and the layout of the necessary components. The major
goal of this phase is to translate the problem studied in the system analysis and design phase into
proper physical system. At the end of this phase, the system is ready for testing.
Programmer is also responsible for documenting the program, providing an explanation of how
and why certain procedure is coded in specific ways. Documentation is essential to test the
program and carry on maintenance once the application has been installed.
5. System Testing
System testing is a method of assessing the functionality of a software program. After
developing the whole components of the system, a test plan should be developed and all the
testing must be done according to that schedule. According to the test plan every components of
the system must be thoroughly checked. Errors are corrected so that there is no difference in
actual output and desired output. This phase is most costly, time consuming and complex. It is
process of verifying that the system fulfils the objective of development.
30
Different types of Tests
1. Inspections: A testing technique in which participants examine program code for
predictable language specific errors. Syntax, grammar, and some other routine errors can
be checked by automated inspection software. 60 to 90 percent of all software effects as
well as provide programmers with feedback that enables them to avoid making the same
types of errors in future work.
2. Desk checking: A testing technique in which the programmer or someone else who
understands the logic of the program works through the code with a paper and pencil. The
reviewer acts as the computer, mentally checking each step and its results for the entire
set of computer instructions.
3. Unit testing: Automated technique whereby each module is tested alone in an attempt to
discover any errors that may exist in the module’s code.
4. Integration testing: The process of bringing together more than one modules that a
program comprises for testing purposes.
5. System testing: The process of bringing together of all of the programs that a system
comprises for testing purposes. Programs are typically integrated in a top-down
incremental fashion. The system can be tested in two ways:
i. Black box testing: In Black box test (also called functional test) internal code of
the program are tested. It is called black box testing because the test cases are
totally hidden for the general users.
ii. White box testing: In white box test (also called glass box test) structure of the
program is tested. It called white box testing because the test cases are totally
visible to the general users and they can also make test cases.
6. Stub testing: A technique used in testing modules, especially where modules are written
and tested in a top down fashion, where a few lines of codes are used to substitute for
subordinate modules. Top-level modules contain many call to subordinate modules, we
may wonder how they can be tested if the lower-level modules haven’t been written yet.
This is called stub testing.
7. User acceptance testing: Once the system tests have been satisfactorily completed, the
system is ready for acceptance testing, which is testing the system in the environment
where it will eventually be used.
i. Alpha testing:
User testing of a completed information system using simulated data. The types of
tests performed during alpha testing include the following:
a. Recovery testing: Forces the software to fail in order to verify that recovery is
properly performed.
b. Security testing: Verifies that protection mechanisms built into the system will
protect it from improper penetration.
31
c. Stress testing: Tries to break the system (eg: what happens when a record is
written to the database with incomplete information or what happens under
extreme online transaction loads or with a large number of concurrent users).
d. Performance testing: Determines how the system performs in the range of
possible environments in which it may be used (eg: different hardware
configurations, networks, operating systems).
iii. Beta testing:
User testing of a completed information system using real data in the real user
environment. The intent of the beta test is to determine whether the software,
documentation, technical support and training activities work as intended. Beta
testing can be viewed as a rehearsal of the installation phase.
6. System implementation
The way of carrying out a developed system into working condition is called system
implementation. The users move from the older system to the new system to perform work.
Different ways of installation are:
1. Direct installation: Changing over from the old information system to a new one by
turning off the old system when the new one is turned on. Any errors resulting from the
new system will have a direct impact on the users. If the new system fails, considerable
delay may occur until the old system can again be made operational and business
transactions are reentered to make the database up to date. Direct installation can be very
risky. Direct installation requires a complete installation of the whole system. For a large
system, this may mean a long time until the new system can be installed, thus delaying
system benefits or even missing the opportunities that motivated the system request. It is
the least expensive installation method, and it creates considerable interest in making the
installation a success.
2. Parallel installation: Running the old information system and the new one at the same
time until management decides the old system can be turned off. All of the work done by
the old system is concurrently performed by the new system. Outputs are compared to
help determine whether the new system is performing as well as the old. Errors
discovered in the new system do not cost the organization much, if anything, because
errors can be isolated and the business can be supported with the old system. Because all
work is essentially done twice, a parallel installation can be very expensive, running two
systems implies employing two staffs to operate and maintain. A parallel approach can
also be confusing to users because they must deal with both systems. A parallel approach
may not be feasible, especially if the users of the system cannot tolerate redundant effort
or if the size of the system is large.
3. Pilot installation: It is also known as single-location installation. Rather than converting
all of the organization at once, single location installation involves changing form the
current to the new system in only one place or in a series of separate sites over time. The
32
single location may be a branch office, a single factory, or one department, and the actual
approach used for installation in that location may be any of the other approaches. The
key advantage to single location installation is that it limits potential damage and
potential cost by limiting the effects to a single site. Once management has determined
that installation has been successful at one location, the new system may be deployed in
the rest of the organization, possibly continuing with installation at one location at a time.
Problems with the system can be resolved before deployment to other sites. Even though
the single location approach may be simpler for users, it still places a large burden on
information system staff to support two versions of the system. Problems are isolated at
one site at a time. IS staff members can devote all of their efforts to success at the pilot
site. If different locations require sharing of data, extra programs will need to be written
to synchronize the current and new systems.
4. Phased installation: It is also called staged installation. Different parts of the old and
new systems are used in cooperation until the whole new system is installed. By
converting gradually, the organization’s risk is spread out over time and place. Also
phased installation allows for some benefits from the new system before the whole
system is ready. For example, a new data-capture methods can be used before all
reporting modules are ready. For a phased installation, the new and replaced systems
must be able to coexist and probably share data. Thus bridge programs connecting old
and new databases and programs often must be built. Sometimes the new and old systems
are so incompatible that pieces of the old system cannot be incrementally replaced so this
strategy is not feasible. A phased approach requires careful version control, repeated
conversions at each phase, and a long period of change, which may be frustrating and
confusing to users.
7. System Maintenance and Reviews
Correcting and upgrading process of the system is called system maintenance. Maintenance is
necessary to eliminate errors in the working system during its working life and to tune the system
to any variations in its working environment. System review is to see if the system has met the
objectives set for it or not. Different types of maintenance are:
1. Corrective maintenance: Corrective maintenance refers to changes made to repair
defects in the design, coding or implementation of the system. For example if we had
recently purchased a new home , corrective maintenance would involve repairs made to
things that had never worked as designed, such as a faulty electrical outlet or misaligned
door. More corrective maintenance problems surface soon after installation. When
corrective maintenance problems surface, they are typically urgent and need to be
resolved to curtail possible interruptions in normal business activities. Of all types of
maintenance, corrective accounts for as much as 75 percent of all maintenance activity. It
simply focuses on removing defects from an existing system without adding new
functionality.
2. Adaptive maintenance: Adaptive maintenance involves making changes to an
33
information system to evolve its functionality to changing business needs or to migrate it
to a different operating environment. Within a home, adaptive maintenance might be
34
adding storm windows to improve the cooling performance of an air conditioner.
Adaptive maintenance is less urgent than corrective maintenance because business and
technical changes typically occur over some period of time. Adaptive maintenance is
generally a small part of an organizations maintenance effort, but it adds value to the
organization.
3. Perfective maintenance: Perfective maintenance involves making enhancements to
improve processing performance or interface usability or to add desired, but not
necessarily required, system features. In home perfective maintenance would be adding a
new room. Many systems professionals feel that perfective maintenance is not really
maintenance but rather new development. Perfective maintenance usually is cost
effective during the middle of the system’s operational life. Early in systems operation,
perfective maintenance usually is not needed. Later, perfective maintenance might be
necessary, but have a high cost.
4. Preventive maintenance: Preventive maintenance involves changes made to a system to
reduce the chance of future system failure. An example of preventive maintenance might
be to increase the number of records that a system can process far beyond what is
currently needed or to generalize how a system sends a report information to a printer so
that the system can easily adapt to changes in printer technology. In our home example,
preventive maintenance could be painting the exterior to better protect the home from
severe weather conditions.
36
There are two type of flow chart:
a. Program flowchart
Program flowchart is pictorial representation of step involved in solving a particular procedure or
program. It is a system design tool used to check the flow of logic running in a program. It also
shows the logical sequence in which the steps are performed. It is detailed diagram showing how
individual processing steps will be performed within the computer to convert input data into the
desired result.
Symbols to draw program flowchart
S.N Symbol Function Meaning
1. Start/Stop Oval indicates START and
STOP of a program.
37
Example
Draw a flowchart to add two numbers.
start
Read two
numbers in
variable a and b.
c ← a+b
Display c.
stop
b. System flowchart
System flowchart is a diagram that shows a broad overview of the data flow and sequence of
operations in a system.
38
Symbols to draw system flowchart
Example
Draw the system flowchart for payroll processing system
Payroll processing
Tax file payroll data file General ledger file
3. Pseudo Code
Pseudo refers to “artificial” and “code” usually refers to a computer program to written in
programming language. It is used to formulate the processing steps of a program. A pseudo code
uses English phrases to describe the processing steps of a program or module. An important
feature of pseudo code is that it is not forced to follow the strict rules imposed by programming
language.
39
The only requirement is that the pseudo code is clear and unmistakable in sequence or statement
like in any major high level language.
Example
Write a pseudo code to determine whether entered number is positive or negative
input a number (n)
if(n>0)
then n is positive
else if n<0
then n is negative
else
n is zero
4. Context diagram
A context diagram is a zero level Data Flow Diagram (DFD), which express the scope of an
organizational system, its system boundaries, external entities that interact with the system and
the information flow. The context diagram doesn’t have a data store. The symbol represents the
entire information system, and we express it as process 0. Then we place the external entities
around the perimeter of the page and use data flows to connect the entities to the central process.
Example
Context diagram of a library membership system
Receipt
Data flow diagram is a pictorial representation of showing the flow of data into, around and out
of a system. Graphical representation of a system’s data and how the processes transform the
data is known as Data flow Diagram. DFD uses four basic symbols that represent process, data
flow, data store and external entity.
40
a. External entities: External entities represent the source of data as input to the system.
These are represented by rectangles.
b. Data store: Data stores represent stores of data within the system. Example computer
files or databases. An open-ended box represents a data store.
c. Process: Process transforms the input data into output data. Circles stand for a process
that converts data into information.
d. Data flow: Labeled arrows represent the movement of data from one component to the
other.
41
6. ER (Entity Relationship) Diagram
Entity Relation Diagram shows data in terms of the entities and relationships described by the
data. An entity is anything in real world system that can be uniquely identified. It can be a set of
person, place, objects, events or even concepts. For example students can be an entity. Every
entity instance, that is every student, can be recognized by their registration number or
citizenship number among other students. The descriptive property of an entity is called
attributes. For example, entity student can have attributes such as Registration number, name,
contact number and address. The registration number makes a student distinguishable among
other students, such attributes is called a key attribute. An entity cannot remain in isolation, there
can be associations among several entities.
The object of Entity Relation (ER) diagram is to model such relations among different entities.
The symbol used in ER diagram are as follows.
Symbol Name Uses
Rectangle To represent entity
42
Oval To represent attributes
Example
Draw an ER-diagram to show relationships between entity customer, order and product. Suppose
one customer places many orders and each order can have many products.
prod id
Cust id
description
name
1 ∞
customer products
orders
address
price
7. Decision table
A decision table allows an analyst to identify the exact course of actions for given conditions.
Decision table provides clear cut decisions, leading to a good program design. A decision table
generally consists of two parts. These are (a) condition (b) Action.
Decision table is a precise model of logic. Decision table, like if then else and switch case
statement associates conditions with actions to perform. But unlike the control structures found
in traditional
43
programming languages, decision table can associates many independent conditions with several
actions in an elegant way.
Condition stubs (the upper rows) describe the conditions or factors that will affect the
decision or policy.
Action stubs (the lower rows) describe, in the form of statements, the possible policy
actions or decisions.
Rules (the columns) describe which actions are to be taken under a specific combination
of conditions.
Example
Members of shopping mall are always entitled to a discount of 12% on all their purchases.
However, if any purchase exceeds Rs 12000, the member is entitled to a discount of 18%. Non
members aren’t normally given any discount. However, if their purchase exceeds Rs 12000, a
discount of 6% is given. Create a decision table for above condition.
Rule 1 Rule Rule Rule 4
2 3
Purchase is a member Y Y N N
Condition stubs
×
Purchase above Rs 12000 Y N Y N
×
18% Discount
×
12% Discount
Action stubs
×
6% Discount
No discount
8. Decision table
Decision tree is another way of presenting a potentially confusing situation in a clear, concise
and unmistakable manner and it can be used in decision making or analysis. It helps a system
analyst to study the relationship of conditions and actions. It looks like a tee with branches.
This decision tree does not work for complex system analysis. But simple decision tree can be
easily understood by non-technical users.
Example
Members of shopping mall are always entitled to a discount of 12% on all their purchases.
However, if any purchase exceeds Rs 12000, the member is entitled to a discount of 18%.
Non members aren’t normally given any discount. However, if their purchase exceeds Rs
12000, a discount of 6% is given. Create a decision tree for above condition.
44
Discount Policy
Purchase>12000 Purchase<=12000
Purchase>12000 Purchase<=1200
45
The
46
UML is a very important part of developing object oriented software and the software
development process which is independent of particular programming language and developing
process. The UML uses mostly graphical notation to express the design of software projects.
UML helps project teams communicate, explore potential designs and validate the architectural
design of the software.
11. Use Case
Use case diagram is used to capture the dynamic nature of a system. It consists of use cases,
actors and their relationships. Use case diagram is used at a high level design to capture the
requirements of a system. So it represents the system functionalities and their flow. Although the
use case diagrams are not a good candidate for forward and reverse engineering but still they are
used in a slightly differently way to model it.
Purpose of Use Case Diagram
Used to gather requirements of a system.
Used to get an outside view of a system.
Identify external and internal factors influencing the system.
Show the interacting among the requirements are actors.
The two main components of a use case diagram are use cases and actors.
An actor represents a user or another system that will interact with the system we are modeling.
A use case is an external view of the system that represents some action the user might perform
in order to complete a task.
Use case
Actor
Example
Draw the use case diagram for customers and banking process
47
Open account
Deposit money
Withdraw money
Close account
48
Unit-2
Programming Technique
Introduction to Programming Technique
Programming is the process of building and designing an executable computer program for
accomplishing a specific computing task. Technique is a systematic procedure, formula, or
routine by which a task is accomplished.
Top down approach
We know that a system is composed of more than one sub-systems and it contains a number of
components. Further, these sub-systems and components may have their onset of sub-system
and components and creates hierarchical structure in the system.
Top-down design takes the whole software system as one entity and then decomposes it to
achieve more than one sub-system or component based on some characteristics. Each sub-
system or component is then treated as a system and decomposed further. This process keeps on
running until the lowest level of system in the top-down hierarchy is achieved.
Top-down design starts with a generalized model of system and keeps on defining the more
specific part of it. When all components are composed the whole system comes into existence.
We starts with the abstract and continually subdivides it until it reaches the specific.
We look at the problem as a whole, it may seem impossible to solve because it is so complex.
For that we break the whole system into parts, then break the parts into parts. Soon each of the
parts will be easy to do.
Bottom up approach
The bottom up design model starts with most specific and basic components. It proceeds with
composing higher level of components by using basic or lower level components. It keeps
creating higher level components until the desired system is not evolved as one single
component. With each higher level, the amount of abstraction is increased.
49
Bottom-up strategy is more suitable when a system needs to be created from some existing
system, where the basic primitives can be used in the newer system.
Cohesion
50
Co-incidental cohesion - It is unplanned and random cohesion, which might be the
result of breaking the program into smaller modules for the sake of modularization.
Because it is unplanned, it may serve confusion to the programmers and is generally not-
accepted.
Logical cohesion - When logically categorized elements are put together into a module,
it is called logical cohesion.
Temporal Cohesion - When elements of module are organized such that they
are processed at a similar point in time, it is called temporal cohesion.
Procedural cohesion - When elements of module are grouped together, which are
executed sequentially in order to perform a task, it is called procedural cohesion.
Communicational cohesion - When elements of module are grouped together, which
are executed sequentially and work on same data (information), it is called
communicational cohesion.
Sequential cohesion - When elements of module are grouped because the output of
one element serves as input to another and so on, it is called sequential cohesion.
Functional cohesion - It is considered to be the highest degree of cohesion, and it is
highly expected. Elements of module in functional cohesion are grouped because they
all contribute to a single well-defined function. It can also be reused.
Coupling
Coupling is a measure that defines the level of inter-dependability among modules of a
program. It tells at what level the modules interfere and interact with each other. The lower the
coupling, the better the program.
Content coupling - When a module can directly access or modify or refer to the
content of another module, it is called content level coupling.
Common coupling- When multiple modules have read and write access to some
global data, it is called common or global coupling.
Control coupling- Two modules are called control-coupled if one of them decides the
function of the other module or changes its flow of execution.
Stamp coupling- When multiple modules share common data structure and work on
different part of it, it is called stamp coupling.
51
Data coupling- Data coupling is when two modules interact with each other by means of
passing data (as parameter). If a module passes data structure as parameter, then the
receiving module should use all its components.
Structured programming
Conventional programming, using high level languages such as COBAL, FORTAN known as
structural programming language (Procedure Oriented Programming). In procedure oriented
approach, the problem is viewed as a sequence of things to be done such as reading, calculating
and printing. A number of functions are written to accomplish these tasks. The primary focus is
on function.
52
Structured programming frequently employs a top-down design model, in which developers map
out the overall program structure into separate subsections. A defined function or set of similar
functions is coded in a separate module or submodule, which means that code can be loaded into
memory more efficiently and that modules can be reused in other programs. After a module has
been tested individually, it is then integrated with other modules into the overall program
structure.
Main Program
Function-4 Function-5
53
Write an algorithm to display 1 to
5. Step 1: START
Step 2: let i←1
Step 3: Display the value of i.
54
ii. Function should have a stopping condition (base criteria) and every time the function
calls itself it must be closer to base criteria.
Differences between Iteration and Recursion
Iteration Recursion
55
Unit-3
Basic concept of C
Introduction
C is programming language developed at AT and T’s Bell Laboratories of USA in 1970s. it was
designed and developed by Dennis Ritchie. C seems so popular because it is reliable, simple and
easy to use. C stands in between high level language and low level language. That is why it is
often called a middle level language. It is designed to have both: relatively good programming
efficiency and relatively good machine efficiency.
History of C
• C was developed at Bell Laboratories in 1972 by Dennis Ritchie.
• Its principles and ideas were taken from the earlier language B and B's earlier
ancestors BCPL and CPL.
• CPL ( Combined Programming Language ) was developed with the purpose of creating
a language that was capable of both high level, machine independent programming and
would still allow the programmer to control the behavior of individual bits of
information.
• Drawback of CPL was that it was too large for use in many applications.
• In 1967, BCPL ( Basic CPL ) was created as a scaled down version of CPL.
Features of C
1. Portability: we can easily transform a program written in C from one computer to
another with few or no changes and compile with appropriate compiler.
2. Faster and efficient: C is faster and more efficient than comparable program. For eg a
program to increment a variable from 0 to 15000 takes about 50 seconds in BASIC while
it takes 1 second in C.
56
4. Extendibility: C is basically a collection of functions that are supported by C library.
We can continuously add (or extend) our own functions to C library.
5. Flexible: It permits us to write any complex programs with the help of its rich set of in-
built functions and operators. It is also called middle-level language because it permits us
to write both application and system software.
Advantages
1. It is more efficient than unstructured code because of minimized branching of the code.
2. Correction of errors (debugging) is easier.
3. Adding new feature is easier and faster.
4. Maintenance the C code is easy due to readability of the code.
5. It is easier to interact with hardware.
6. It is easy to learn.
7. Program code is secured.
8. It is compact and efficient to use.
Disadvantages
1. The program takes more time to design and implement the software.
2. C coding techniques sometimes result in repeating code in a program.
3. C coding becomes less efficient if the sub-routines called frequently thereby killing the
time.
4. C doesnot have efficient garbage collection i.e. problem regarding memory clearance.
5. It doesn’t contain runtime checking.
6. There is no strict type checking (for example, we can pass integer value for floating data
type).
7. As the program extends it is very difficult to fix the bugs.
8. It does not support Object Oriented Programming (OOP) features, so to overcome C++
language was introduced.
Structure of C Program
Comments
Preprocessor directives
Global variables
main( ) function
{
local variables
statements
………………
57
………………
}
func1( )
{
local variables
statements
………………
………………
}
func2( )
{
local variables
statements
………………
………………
}
Anything written between /* and */ is called a comment. A comment is not an executable
statement and it is ignored by the compiler. It has no any effect on the behavior of the resulting
program. Comment serves as documentation for the human reader of the program.
Line that begins with the # (read as hash) sign is a preprocessor directive. It is mostly written at
the beginning of the program. It is not an executable code but indicates for the C preprocessor.
The C preprocessor is a tool which filters the source code before it is compiled. In this case, it
tells the compiler’s preprocessor that the contents of the file stdio.h should be included at the
place where #include appears. The file stdio.h is called a header file and it contains the
declaration needed to use standard input output operations [like printf(), scanf()].
Variable is the place to store the value. A variable type that is declared outside any function and
is accessible to all functions throughout the program.
The function main() is required in all C programs. The main() is the starting point of a C
program. It is independent from whether it is at the beginning, at the end or by the middle of the
program. Its content is always the first to be executed when a program starts and by default it is
last when the program ends.
A variable type that is declared inside the function and is accessible only to that function is called
local variable.
58
In C program, instructions are written in the form of statements. A statements is an executable
part of the program and causes the computer to carry out some action.
Compilation Process
Editor
An editor is a specialized word processor used to prepare source code in a programming
language (eg C, C++, Java and FORTAN). We write a computer program with words and
symbols that are understandable to human beings in the editor. We type the program directly into
a window on the screen and save the resulting text as a separate file. This is often referred to as
the source code. The custom is that the text of a C program is stored in a file with the
extension .c for C programming language.
Preprocessor
The preprocessor adds in standard pre-written code from include files we specify to
produce a complete source code or it is a program that removes all comments and modifies
source code according to directives supplied in the program. A preprocessor directives begins
with ‘#’ and it is an instruction to the program.
Compiler
The compiler produces object from source file for the target computer. The compiler
translates the preprocessed source code into machine language that consists sequence of 0s and
1s.
Linker
It combines object code of a program with necessary items (like library files) to form an
executable program. Often a program is so large that it is convenient to break it down into
smaller units with each part stored in a separate file. After compilation of the program files,
computer must somehow link these separate pieces to form a single executable program. This
linking is done by linker. The executable file will have extension .exe.
Executable file
The text editor produces .c source files, compiler converts this .c file to .obj (object) file,
and linker produces .exe (executable file) from .obj file. We can then run .exe files as an
application to generate output.
Block diagram of C program compilation process
59
C Preprocessor
The lines starting with the symbol # are known as preprocessor directives. When the
preprocessor finds a line starting with the symbol #, it considers it as a command for itself and
works accordingly. Some advantages of using preprocessor are:
1. Readability of the program is increased.
2. Program modification becomes easy.
3. Makes the program portable and
efficient. Some features of preprocessor
directives are:
i. Each processor directive starts with a # symbol.
ii. There can be only one directive on a line.
iii. There is no semicolon at the end of a line.
Header Files
A header file is a file containing C declarations and macro definitions to be shared between
several source files. We request the use of a header file in our program by including it, with the C
preprocessing directive ‘#include’.
System header files declare the interfaces to parts of the operating system. We include
them in our program to supply the definitions and declarations we need to invoke system
calls and libraries.
Our own header files contain declarations for interfaces between the source files of our
program. Each time we have a group of related declarations and macro definitions all or
most of which are needed in several different source files, it is a good idea to create a
header file for them.
Character set
A character set in C contains any alphabet, digit or special symbol used to represent information.
Following table shows the valid alphabets, numbers and symbols allowed in C.
Alphabets A, B, C,..........Y, Z
a, b, c,...............y, z
Digits 0,1,2,3,4,5,6,7,8,9
Special symbols ~ ` ! @ # % ^ & * () - _ + = | \ {} [] : ; ” ’<> , . ? /
Comments:
Any text or symbol /* to */ is ignored by the compiler is called comment. Comments are not tokens and
are not part of executable program. Comments are used for increasing readability of the program. They
explain the purpose of the program and are helpful in understanding the program. Comments are written
inside /* and */. There can be single line or multiple line comments. We can write comments anywhere in
the program except inside a string constant or a character constant.
60
Some examples of comments are:
// basic salary */(Single line comment)
/* this is a C program to calculate (multiple line comment)
Simple interest */
Comments can't be nested i.e. we can't write a comment inside another comment.
Tokens
C token includes:
Identifier
Keyword
Constant and variable
Operator
61
\v vertical 011 Moves the cursor to the next vertical tab
tab position
\t horizontal 009 Moves the cursor to the next horizontal
tab tab position
\\ backslash 092 Presents a character with backslash (\)
Delimiters
Delimiters are used for syntactic meaning in C. There are given below:
: Colon used for label
; semi-colon end of statement
() Parenthesis used in expressions
{} Curly Brackets used for block of statement
[] Square Brackets used for array
# Hash preprocessor directives
, Comma variable delimiter
Reserved Keywords
There are certain words that are reserved for doing specific tasks. These words are known as keywords
and they have standard, predefined meaning in C. They are always written in lowercase. There are only
32 keywords available in C which are given below:
auto break case char
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while
Identifiers
All the words that we will use in our C program will be either keywords or identifiers. Keywords are
predefined and cannot be changed by the user while identifiers are user defined words and are used to
give
62
63
names to entities like variables, arrays, functions, structures, etc. Rules for naming identifiers are given
below:
1. The name should consist of only alphabet (both upper and lower case), digits and underscore sign
(_).
2. The first character should be an alphabet or underscore.
3. The name should not be a keyword.
4. We cannot use space in between identifier.
5. Since C is case sensitive, the uppercase and lowercase letter are considered different for eg. Code,
code and CODE are three different identifiers.
6. An identifier name may be arbitrarily long. Some implementations of C recognize only the first 8
character, though most implementations recognize 31 characters. ANSI standard compilers
recognize 31 characters.
The identifiers are generally given meaningful names. Some examples of valid identifiers name-
salary a total_marks data2 _college NAME
Some example of invalid identifiers name are-
8ab First character should be an alphabet or underscore
char char is a keyword
sopan # # is a special character
avg no blank space is not permitted.
Each and every alphabet and punctuation symbols are called tokens.
Variables:
Variable is a name that can be used to store values. Variables can take different values but one at a time.
These values can be changed during the execution of the program. A data type is associated with each
variable. The data type of the variable decides what values it can take. The rules for naming variables are
same as that of naming identifiers.
Declaration of Variables:
It is necessary to declare a variable before it is used in the program. Declaration of a variable specifies its
name and data type. The type and range of values that a variable can store depends upon its data type. The
syntax of declaration of a variable is-
datatype variable name;
Here data type may be int, float, char, double etc. Some examples of declaration of variables are:
int x;
float salary;
char grade;
Here x is a variable of type int, salary is a variable of type float, and grade is a variable of type char. We
can also declare more than one variable in a single declaration. For example:
int x, y, z, total;
Here x, y, z and total are all variables of type int.
64
Initialization of Variables:
When a variable is declared it contains undefined value commonly known as garbage value. If we want
we can assign some initial value to the variable during the declaration itself, this is called initialization of
variables. For example:
int a = 5;
float x = 8.9, y = 10.5;
char ch = 'y';
double num = 0.15197e-7;
int l, m, n total = 0;
In the last declaration only variable total has been initialized.
Datatypes
C supports different types of data. Storage representation of these data types is different in memory. There
are four fundamental data types in C, which are int, char, float and double.
'char' is used to store and single character. 'int' is used to store integer value . 'float' is used for storing
single precision floating point number and 'double' is used for storing double precision floating point
number. We can use type qualifiers with these basic types to get some more types:
There are two types of type qualifiers:
i. Size qualifiers short, long
ii. Sign qualifiers signed, Unsigned
When the qualifiers unsigned is used the number is always positive and when signed is used number may
be positive or negative. If the sign qualifier is not mentioned, then by default signed qualifier is assumed.
The range of values for signed data types is less than that of unsigned types. This is because in signed
type, the leftmost bit is used to represent the sign, while in unsigned type this bit is also used to represent
the value.
The size and range of different data types on a 16-bit machine is given in the following table. The size and
range may vary on machines with different word size.
Basic data Data types with type Size (bytes) Range
types qualifiers
char char or signed char 1 -128 to 127
unsigned char 1 0 to 255
int int or signed int 2 -32768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2147483648 to
2147483647
unsigned long int 4
0 to 4294967295
65
float float 4 3.4E-38 to 3.4E+38
double double 8 1.7E -308 to 1.7E+308
long double 10 1.7E-4932 to 1.7E+4932
Constants
Constant is a value that cannot be changed during execution of the program. There are three types of
constant. Constants
Integer Real
Constant Constant
Integer Constant:
Integer constant are whole number which have no decimal point (.). There are three types of integer
constants based on different number systems. The permissible characters that can be used in these
constant are-
Decimal Constants 0,1,2,3,4,5,6,7,8,9 (Base = 10)
Octal Constants 0,1,2,3,4,5,6,7 (Base = 8)
Hexadecimal 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F (Base = 16)
constants
Some valid integer decimal constant are-
0
66
123
3705
23759
Some invalid decimal integer constant are-
Invalid Remarks
2.5 illegal character (.)
3#5 illegal character (#)
98 5 No blank space allowed
0925 first digit can't be zero
8,354 comma is not allowed
In octal integer constant, first digit must be 0. For example-
0, 05, 077, 0324
In hexadecimal integer constant, first two characters should be 0x or 0X. Some examples are as-
0X, 0X23, 0X515, 0XFFF, 0XAC
By default the type of integer constant is int. But if the value of integer constant exceeds the range
of values represented by int type, the type is taken to be unsigned int or long int. We can also
explicitly mention the type of the constant by suffixing it with l or L (for long), u or U (for
unsigned), ul or UL (for unsigned long). For example:
6453 integer constant of type int
45238722UL or 45238722ul integer constant of type unsigned long
6655u or 6655U integer constant of type unsigned
Real (floating point) constants:
Floating point constant are numeric constants that contain decimal point. Some valid floating point
constant are:
0.5
5.3
4000.0
0.0075
76847.
98.0973
For expressing very large or very small real constants, exponential (scientific) form is used. Here
the number is written in the mantissa and exponent form, which are separated by 'e' or 'E'. The
mantissa can be an integer or a real number, while the exponent can be only an integer (positive or
negative). For example the number 1800000 can be written as 1.8e6, here 1.8 is mantissa and 6 is
the exponent. Some more examples are as:
67
250000000 2.5 × 108 2.5e8
0.0000076 7.6 × 10-6 7.6e-6
-670000 -6.7 × 105 -6.7e5
By default the type of a floating point constant is double. We can explicitly mention the type of
constant by suffixing it with a f or F (for float type), l or L (for long double). For example-
2.3 e5 Token floating point constant of type double,
2.4 e-9 l or 2.4e-9L floating point constant of type long double,
3.52f or 3.52F floating point constant of type float.
Character Constant:
The character constant is a single character that is enclosed within single quotes. Some valid
character constants are:
'9' 'D' '$' '#'
Some invalid character constants are:
Invalid Remarks
'four' There should be only one character within quotes.
"d" Double quotes are not allowed
'' No character between single quotes.
y single quotes missing
Every character constant has a unique integer value associated with it. This integer is the numeric
value of the character in the machine's character code. If the machine is using ASCII (American
Standard Code for Information Interchange), then the character 'G' represents integer value 71 and
the character '5' represents value 53. Some ASCII values are:
A - Z ASCII value (65 - 90)
a - z ASCII value (97-122)
0 - 9 ASCII value (48-57)
; ASCII value (59)
ASCII values of all characters are given in Appendix A.
String Constants:
A string constants has zero, one or more than one character. A string constant is enclosed within
double quotes (" "). At the end of string, \0 is automatically placed by the compiler.
Some examples of string constants are:
"Kumar"
"593"
"8"
" "
68
"A"
Note that "A" and 'A' are different, the first one is a string constant which consist of character A and
\0 while the second one is a character constant which represents integer value 65.
Symbolic Constants:
If we want to use a constant several times then we can provide it a name. For example if we have to
use the constant 3.14159265 at many places in our program, then we can give it a name PI and use
this name instead of writing the constant value everywhere. These types of constants are called
symbolic constants or named constants.
A symbolic constant is a name that substitutes for a sequence of characters. The characters may
represent a numeric constant, a character constant or a string constant.
These constant are generally defined at the beginning of the program as:
#define name value
Here 'name' is the symbolic name for the constant, and is generally written in uppercase letters.
'value' can be numeric, character or string constant.
Some examples of symbolic constants are as-
# define MAX 100
#define PI 3.14159625
#define CH 'y'
#define NAME "ram"
In the program, these names will be replaced by the corresponding values. These symbolic
constants improve the readability and modifiability of the program.
Statements:
In C program, instructions are written in the form of statements. A statements is an executable part of the
program and causes the computer to carry out some action. Statements can be categorized as:
i. Expression statements
ii. Compound statements
iii. Selection statements (if, if…..else, switch)
iv. Iterative statements (for, while, do….while)
v. Jump statements (goto, continue, break, return)
vi. Label statements (case, default, label statement used in goto)
Simple Statement:
Simple statement consist of an expression followed by a semi colon. For example:
x = 5;
x = y - z;
func( a, b);
A statement that has only a semicolon is also known as null statement. For example:
; /*null statement*/
69
Compound Statement:
A compound statement consists of several statements enclosed within a pair of curly braces { }.
Compound statement is also known as block of statements. Note that there is no semicolon after the
closing brace. for example:
{
int l = 4, b = 2, h = 3;
int area, volume;
area = 2 * (l*b + b *h + l * h);
volume = l * b * h;
}
If any variable is to be declared inside the block then it can be declared only at the beginning of the block.
The variables that are declared inside a block can be used only inside that block; all other categories of
statements are discussed in further chapters.
Conversion Specification
While the data is being output or input, it must be notified with some identifier and their formal specifier.
Format specifiers are the character starting with % sign and followed with a character. It specifies the type
of data that is being processed. It is also called conversion specification.
Data types Format specifiers symbol
integer %d
unsigned integer %u
octal %o
hexadecimal %x
float (simple) %f
float (exponential) %e
character %c
string %s
long integer %ld
unsigned long integer %lu
double %lf
long double %Lf
70
Unit-4
Operators and Expressions
Introduction
1. Arithmetic operator:
Arithmetic operators are used for numeric calculations. They are of two types:
i. Unary arithmetic operator
ii. Binary arithmetic operators.
Binary operators require two operands. There are five binary arithmetic operands:
Operators Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
71
% Give the remainder in integer division
% (modulus operator) cannot be applied with floating point operands. There is no exponent
operator in C. However there is a library function pow ( ) to carry out an exponentiation
operation. Note that Unary plus and unary minus operators are different from the addition
and subtraction operators.
Integer Arithmetic:
When both operands are integers, then the arithmetic operation with these operands is
called integer arithmetic and the resulting value is always an integer. Let us take two
variables a and b. The value of a = 17 and b = 4. The results of the following operations
are:
Expressions Result
a+b 21
a–b 13
a*b 68
a/b 4 (decimal part truncates)
a%b 1 (remainder after integer division)
After division operation the decimal part will be truncated and result is only integer part of
quotient. After modulus operation the result will be remainder part of integer division. The
second operand must be non zero for division and modulus operations.
/* Program to understand the integer arithmetic
operation*/ #include<stdio.h>
void main ( )
{
int a = 17, b = 4;
printf ("Sum = %d\n", a +b );
printf ("Difference = %d\n", a - b);
printf ("Product = %d\n", a * b);
printf ("Quotient = %d\n", a / b);
printf ("Remainder = %d\n", a % b);
}
72
Output:
Sum = 21
Difference = 13
Product = 68
Quotient = 4
Remainder = 1
Output:
Sum = 15.50
Difference = 9.3
Product = 38.44
a/b = 4.0
73
Mixed Mode Arithmetic:
When one operand is of integer type and the other is of floating type then the arithmetic
operation with these operands is known as mixed mode arithmetic and the resulting value
is float type. If a = 12 and b = 2.5
Expression Result
a+b 14.5
a–b 9.5
a*b 30.0
a/b 4.8
Sometimes mixed mode arithmetic can help in getting exact result. For example the result
of expression 5/ 2 will be 2 since integer arithmetic is applied. If we want exact we can
make one of the operand float type. For example, 5.0/2 or 5/2.0 both will give result 2.5 .
2. Assignment operator
A value can be stored in a variable with the use of assignment operators. The assignment
operators “=” is used in assignment expression and assignment statements.
The operand on the left hand side should be a variable, while the operand on the right hand
side can be any variable, value or expression. The value of the right hand operand is
assigned to the left hand operand. Here are some examples of assignment expressions;
x = 8 /* 8 is assigned to x*/
y = 5 /* 5 is assigned to y*/
s = x + y - 2 /* value of expression x +y -2 is assigned to s*/
y = x /* value of x is assigned to y*/
x = y /*value of y is assigned to x*/
The value that is being assigned is considered as value of the assignment expression. For
example, x = 8 is an assignment expression whose value is 8.
We can have multiple assignment expressions also for example;
x = y= z= 20
Here all the three variable x, y, z will be assigned value 20, and the value of whole
expressions will be 20.
If we put a semicolon after the assignment expression, then it becomes an assignment
statement. For example these are assignment expressions;
x = 8;
y = 5;
s = x + y - 2;
x = y= z = 20;
74
When the variable on the left hand side of the assignment operator also occurs on right
hand side then we can avoid writing the variable twice by using compound assignment
operator. For example:
x = x +5
can be also written as x += 5
Here += is a compound assignment operator.
Similarly we have other compound assignment operators:
x -= 5 is equivalent to x = x - 5
y *= 5 is equivalent to y = y * 5
sum / = 5 is equivalent to sum = sum/5
k% = 5 is equivalent to k = k % 5.
3. Increment and Decrement operator
C has two useful operator increment ( ++ ) and decrement (--). These are unary operators
because they operate only the single operand. The increment operator (++) increments the
value of the variable by one and decrement operator (--) decrements the value of variable
by 1.
++x is equivalent to x = x + 1
--x is equivalent to x = x -1
These operators should be used only with variables; they can’t be used with constant for
expressions. For example the expression ++5 or ++(x+y+z) are invalid.
These operators are of two types:
i. Prefix increment / decrement - operator is written before operand. eg. ++x or --x
ii. Postfix increment/decrement - operator is written after operand eg. x++ or x --
Prefix Increment/decrement:
Here first the value of variable is incremented/decremented then the new value is used in
the operation. Let’s us take a variable x whose value is 3. The statement y = ++x; means
first increment of the value of x by 1, then assign the value of x to y. This single statement
is equivalent to these two statements;
x = x + 1;
y = x;
Hence, now the value of x is 4 and value of y is 4.
The statement y = --x; means first decrement the value of x by 1 then assign the value of x
to y. This single statement is equivalent to these two statements;
x = x - 1;
y=x
75
Hence, now the value of x is 3 and value of y is 3 .
/* Program to understand the use of prefix increment/decrement*/
#include <stdio.h>
void main ( )
{
int x = 8;
printf(“x = %d\t”, x);
prinff(“x = %d\t”, ++x); /*prefix increment*/
printf(“x = %d\t”, x);
printf(“x = %d\t”, --x); /*prefix decrement*/
printf(“x = %d”, x);
}
Output:
x=8 x=9 x=9 x=8 x=8
In the second printf statement, the first value of x is incremented and then printed; similarly
in the fourth printf statement, first the value of x is decremented and then printed.
Postfix Increment/Decrement:
Here first the value of variable is used in the operation and then increment/decrement is
performed. Let us take a variable whose value is 3.
The statement y = x ++; means first the value of x is assigned to y and then x is
incremented by 1. This statement is equivalent to these two statements;
y=x;
x = x + 1;
Hence, now value of x is 4 and value of y is 3.
The statement y = x--; means first the value of x is assigned to y and then x is decremented
by 1. This statement is equivalent to these two statements;
y = x;
x = x -1;
Hence, now the value of x is 3 and value of y is 4.
/* Program to understand the use of postfix increment/decrement*/
#include <stdio.h>
76
void main ( )
{
int x = 8;
printf(“x = %d\t”, x);
printf(“x = %d\t”, x++); /*postfix increment*/
printf(“x = %d\t”, x);
printf(“x = %d\t”, x--); /*postfix decrement*/
printf(“x = %d”, x);
}
Output:
x=8 x=8 x=9 x=9 x=8
In the second printf statement, first the value of x is printed and then incremented;
similarly in the fourth printf statement, first the value of x is printed and then decremented.
4. Relational operator
Relational operators are used to compare values of two expressions depending on their
relations. An expression that contains relational operator is called relational expression. If
the relation is true, then the value of relational expression is 1 and if the relation is false,
the value of expression is 0. The relational operators are:
Operator Meaning
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
Let us take two variables, a = 9 and b = 5, and form simple relational expression with them.
77
a != b True 1
a>b True 1
a >= b True 1
a == 0 False 0
b!=0 True 1
a>8 True 1
2 >4 False 0
/* Program to understand the use of relational operators*/
#include <stdio.h>
void main ( )
{
int a,b;
printf(“Enter values for a and b:”);
scanf(“%d%d”, &a, &b);
if(a<b)
printf(“%d is less than %d\n”, a,b);
if (a<=b)
printf(“%d is less than equal to %d\n”, a,b);
if (a==b)
printf (“%d is equal to %d\n”, a,b);
if (a !=b)
printf(“%d is not equal to %d\n), a,b);
if (a>b)
printf(“%d is greater than %d\n”, a,b);
if (a>=b)
printf(“%d greater than or equal to %d\n”, a,b);
}
Output:
Enter values for a and b : 12 7
12 is not equal to 7
12 is greater than 7
78
12 us greater than or equal to 7
It is important to note that assignment operator (=) and equality operator (= =) are entirely
different. Assignment operator (=) used for assigning value while equality operator (= =) is
used to compare two expressions.
5. Logical operator
An expression that combines two or more expressions is termed as a logical expression. For
combining these expressions we use logical operators. These operators return 0 for false and
1 for true. The operands may be constants, variables or expressions. C has three logical
operators.
Operator Meaning
&& AND
|| OR
! NOT
Here logical NOT is a unary operator while the other two are binary operators. Before
studying these operators let us understand the concept of true and false. In C any non zero
value is regarded as true and zero is regarded as false.
OR (| |) Operator
This operator gives the net result false, if both the conditions have the value false,
otherwise the result is true.
79
Condition 1 Condition 2 Result
False False False
False True True
True False True
True True True
Let us take three variables a = 10, b = 5 and c = 0
Consider the logical expression:
(a >=b) || (b>15)
This gives result true because one condition is true.
6. Conditional Operator
Conditional operator is a ternary operator (? and -) which requires three expressions as
operands. This is written as-
Test expression ? expression 1: expression2
Firstly the test expression is evaluated,
i. If testexpression is true (nonzero), then expression1 is evaluated and it becomes the
value of the overall conditional expression.
ii. If test expression if false(zero), then expression2 is evaluated and it becomes the value
of overall conditional expression.
For example consider this conditional expression-
a>b?a:b
80
Here first the expression a > b is evaluated, if the value is true then the value of variable a
becomes the value of conditional expression otherwise the value of b becomes the value of
conditional expression.
Suppose a = 5 and b = 8, and we use the above conditional expression in a statement as-
max = a > b ? a :b;
First the expression a> b is evaluated, since it is false so the value b becomes the value of
conditional expression and it is assigned to variable max.
In our next example we have written a conditional statement by putting a semicolon after
the conditional expression.
a < b ? printf(“a is smaller”) : printf(“b is smaller”);
Since the expression a < b is true, so the first printf function is executed.
/* Program to print the larger of two numbers using conditional operator */
#include<stdio.h>
void main ( )
{
int a, b, max;
printf(“Enter values for a and b:”);
scanf(%d %d”, &a, &b);
max = a > b ? a : b; /* ternary
operator*/ printf(“Larger of %d and %d is %d\n”,
a, b, max);
}
Output:
Enter the values for a and b : 12 7
Larger of 12 and 7 is 12
7. Comma Operator
The comma operator ( , ) is used to permit different expressions to appear in situations
where only one expression would be used. The expressions are separated by the comma
operator. The separated expressions are evaluated from left to right and the type and value
of the compound expression.
For example consider this expression-
a = 8, b = 7, c = 9, a + b + c
Here we have combined 4 expressions. Initially 8 is assigned to the variable a then 7 is
assigned to the variable b, 9 is assigned to variable c and after this a + b + c is evaluated
81
which becomes the value of whole expression. So the value of the above expression is 24.
Now consider this statement.
sum = (a = 8, b = 7, c = 9, a + b + c);
Here the value of the whole expression on right side will be assigned to variable sum i.e.
sum will be assigned value 24. Since precedence of comma operator is lower than that of
assignment operator hence the parentheses are necessary here. The comma operator helps
to make the code more compact, for example without the use of comma operator the above
task would have been done in 4 statements.
a = 8;
b = 7;
c = 9;
sum = a + b + c;
/* Program ro understand the use of comma operator */
#include <stdio.h>
void main ( )
{
int a, b, c, sum;
sum = ( a = 8, b = 7, c = 9, a + b + c);
printf(“Sum = %d\n”, sum);
}
Output:
Sum = 24
/* Program to interchange the value of two variables using comma operator */
#include<stdio.h>
void main ( )
{
int a = 8, b = 7, temp;
printf(“a = %d, b = %d\n”, a, b);
temp = a, a = b, b = temp;
printf (“a = %d, b = %d\n”, a, b);
}
82
Output:
a=8,b=7
a=7,b=8
8. Sizeof Operator
Size of is an unary operator. This operator gives the size of its operand in terms of bytes.
The operand can be a variable, constant or any data type (int, float, char etc). For example
sizeof(int) gives the bytes occupied by the int datatype i.e. 2.
/*Program to understand the size of operator*/
#include<stdio.h>
void main ( )
{
int var;
printf (“size of int = “%d”, sizeof(int));
printf(“size of float = “%d”, sizeof(float));
printf(“size of var = “%d”, sizeof(var));
printf(“size of an integer constant=%d”, sizeof(45));
}
Output:
size of int = 2
size of float = 4
size of var = 2
size of an interger constant = 2
Generally sizeof operator is used to make portable programs i.e. programs that can be run
on different machines. For example if we write our program assuming int to be of 2 bytes,
then it won’t run correctly on a machine on which int is of 4 bytes. So to make general
code that can run on all machines we can use sizeof operator.
9. Bitwise Operator
C has ability to support that manipulation of data at the bit level. Bitwise operators are
used for operations on individual bits. Bitwise operators operate on integers only. The
bitwise operators are as-
Bitwise operator Meaning
& bitwise AND
| bitwise OR
83
~ one’s complement
<< left shift
>> right shift
^ bitwise XOR
For evaluation of expressions having more than one operator, there are certain precedence
and associatively rules defined in C. Let us see what these rules and why are they required.
Consider the following expression-
2+3*5
Here we have two operators - addition and multiplication operators. If addition is
performed before multiplication then result will be 25 and if multiplication is performed
before addition then the result will b e 17.
In C language, operators are grouped together and each group is given a precedence level.
The precedence of all the operators is given in the following table. The upper row in the
table having higher precedence and it decreases as we move down the table. Hence the
operators with precedence level 1 have highest precedence and with precedence level 15
have lowest precedence. So whenever an expression contains more than one operator, the
operator with a higher precedence is evaluated first. For example in the above expression,
multiplication will be performed before addition since multiplication operator has higher
precedence than the addition operator.
84
Operator Description Precedence Associativity
Level
() Function call 1 Left to right
[] Array subscript
Arrow operator
. Dot operator
+ Unary Plus 2 Right to left
- Unary minus
++ Increment
-- Decrement
! Logical NOT
~ One's complement
* Indirection
& Address
(datatype) Type case
sizeof Size in bytes
* Multiplication 3 Left to right
/ Division
% Modulus
+ Addition 4 Left to right
- Subtraction
<< Left shift 5 Left to right
>> Right shift
< Less than 6 Left to right
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to 7 Left to right
!= Not equal to
& Bitwise AND 8 Left to right
^ Bitwise XOR 9 Left to right
| Bitwise OR 10 Left to right
&& Logical AND 11 Left to right
|| Logical OR 12 Left to right
?: Conditional operator 13 Right to left
= 14 Right to left
*= /= %=
+= -= Assignment Operators
&= ^= |=
<<=>>=
, Comma operator 15 Left to right
85
i. x= a + b < c
Here + operator has higher precedence than < and =, and < has more precedence than =, so
first a + b will be evaluated, then < operator will be evaluated, and at last the whole value
will be assigned to x. If initial values are a = 2, b = 6 and c = 9 then final value of x will be
1.
ii. x*=a+b
Here + operator has higher precedence than *=, so a + b will be evaluated before
compound assignment. This is interpreted as x = x*(a+b) and not as x = x * a+ b
If initial values are x = 5, a = 2 and b = 6, the final value of x will be 13.
iii. x = a <= b || b = = c
Here order evaluation of operators will be <=, ==, ||, =. If initial values are a = 2, b = 3 and
c = 4, then the final value of x will be 1.
In the above examples we have considered expressions that contain operators having
different precedence levels. Now consider a situation when two operators with the same
precedence occur in an expression.
For example-
5 + 16 / 2 * 4
Here / and * have higher precedence than + operator, so they will be evaluated before
addition. But / and * have same precedence, so which one of them will be evaluated first
still remains a problem. If / is evaluated before *, then the result is 37 otherwise the result
is 7. Similarly consider this expression-
20-7-5-2-1
Here we have four subtraction operators, which of course have the same precedence level.
If we decide to evaluate from left to right then answer will be 5 and if we evaluate from
right to left then the answer will be 17.
To solve these types of problems, an associativity property is assigned to each operator.
Associativity of the operators within same group is same. All the operators either associate
from left to right or from right to left. The associativity of all operators is also given in the
precedence table. Now again consider the above two expressions-
5 + 16 / 2 * 4
Since / and * operators associate from left to right so / will be evaluated before * and the
correct result is 37.
20 - 7 - 5 - 2 - 1
The subtraction operator associated from left to right so the value of this expression is 5.
86
The assignment operator associated from right to left. Suppose we have a multiple
assignment expression like this-
x=y=z=5
Here initially the integer value 5 is assigned to variable z and then value of expression z =
5 is assigned to variable y. The value of expression z = 5 is 5, so 5 is assigned to variable y
and now the value of expression y = z= 5 becomes 5. Now value of this expression is
assigned to x and the value of whole expression x = y = z = 5 becomes 5.
87
Unit-5
Input and Output
Introduction
A program needs to read data in variable names: input operation. Also data stored in variables
need to be displayed: output operation. C language provides functions to perform input/output
operations as printf(), scanf(), getchar(), putchar(), getc(), putc(), getch(), putch(), getche(),
gets(), puts() etc.
Formatted input/output
printf() can be used to output data of different types in different formats such as perform
rounding, aligning columns, right/left justification, inserting literal character, exponential format,
hexadecimal format, and fixed width and precision.
printf("control string", variable1, variable2,.............)
In this function the control string contains conversion specification characters and text. It should
be enclosed within double quoted. The name of variables should not be preceded by an
ampersand (&) sign. If the control string does not contain any conversion specification, then the
variable names are not specified.
scanf() Input data can be entered into the memory from a standard input device (keyboard). C
Provides the scanf ( ) library function for entering input data. This function can take all types of
values (numeric, character, string) as input. The scanf( ) function can be written as:
scanf ( "control string", address1, address2,…);
This function should have at least two parameters. First parameter is a control string which
contains conversion specification characters, it should be within double quoted. The conversion
specification characters maybe one or more; it depends on the number of variable we want to
input. The other parameters are addresses or variables. In the scanf( ) function at least one
address should be present. The address of a variable is found by preceding the variable name by
an ampersand (&) sign, This sign is called the address operator and it gives the starting address
of the variable name in the memory. A string variable is not preceded by & sign to get the
address.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
char name[10];
float marks;
clrscr();
printf("Enter rollno, name and marks ");
88
scanf("%d%s%f",&a,name,&marks);
89
printf("Rollno = %d rName = %s Marks =%f",a,name,marks);
getch();
}
Output
Unformatted Input/Output
getchar() and putchar()
The getchar() function reads the next character available from standard input device (typically a
keyboard) and returns the character read.
Syntax
variable_name=getchar();
The putchar() function can be used to write a single character to a standard output device
(typically a monitor).
Syntax
putchar(variable_name);
Example
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter a character ");
ch=getchar();
putchar(ch);
getch();
}
Output
getche()
getche() gets a character from console, and echoes to the screen i.e whatever input character is
given it gives out the character immediately.
Example
#include<stdio.h>
#include<conio.h>
void main()
91
{
char ch;
clrscr();
printf("Enter a character ");
ch=getche();
putch(ch);
getch();
}
Output
Formatted I/O
Formatted input and output means that data is entered and displayed in a particular format.
Through format specification, better presentation of result can be obtained. Formats for different
specifications are as:
Format for integer input
%wd
92
Here ‘d’ is the conversion specification character for integer value and ‘w’ is an integer number
specifying the maximum field width of input data. If the length of input is more than this
maximum field width then the values are not stored correctly. For example
scanf(“%2d%3d”,&a,&b);
i) When input data length is less than the given field width, then the input values are
unaltered and stored in given variables.
Input-
6 39
Result-
6 is stored in a and 39 is stored in b.
ii) When input data length is equal to the given field width, then the input values are
unaltered and stored in given variables.
Input-
27 489
Result-
27 is stored in a and 489 is stored in b.
iii) When input data length is more than the given field width, then the input values are
altered and stored in the variable as-
Input-
278 3479
Result-
27 is stored in a and 8 is stored in b and the rest of input is ignored.
Format for integer output
%wd
Here w is the integer number specifying the minimum field width of the output data. If the length
of the variable is less than the specified field width, then the variable is right justified with
leading blanks.
For example-
printf(“a=%3d, b=%4d”,a,b);
i) When the length of variable is less than the width specifier.
Input-
78 9
Output-
a = 7 8 , b = 9
The width specifier of first data is 3 while there are only 2 digits in it, so there is one
leading blank. The width specifier of second data is 4 while there is only 1 digit, so there are 3
leading blanks.
ii) When the length of the variable is equal to the width specifier.
93
Input-
263 1941
Output-
a = 2 6 3 , b = 1 9 4 1
iii) When the length of variable is more than the width specifier, then also the output is
printed correctly.
Input-
2691 19412
Output-
a = 2 6 9 1 , b = 1 9 4 1 2
94
5.9 is stored in x and 3.00 is stored in y.
Format for floating point numeric output
%w.nf
Here w is the integer number specifying the total width of the input data and n is the number of
digits to be printed after decimal point. By default 6 digits are printed after the decimal.
For example- printf(“x=%4.1f,y=
%7.2f”,x,y); value of variables-
8 5.9
Output:
x = 8 . 0 , y = 5 . 9 0
Value of variables-
25.3 1635.92
Output
x = 2 5 . 3 , y = 1 6 3 5 . 9 2
Value of variables-
15.231 65.875948
Output:
x = 1 5 . 2 , y = 6 5 . 8 8
95
Only first three characters of this input will be stored in the string, so the characters in the string
will be-
‘p’, ‘r’, ‘o’, ‘\0’
The null character (‘\0’) is automatically stored at the end.
Format for string output
%w.ns
Here w is the specified field width. Decimal point and ‘n’ are optional. If present then ‘n’
specifies that only first n characters of the string will be displayed and (w-n) leading blanks are
displayed before string.
printf(“%3s”,”programming”);
p r o g r a m m i n g
printf(“%10s”,”reeta”);
r e e t a
printf(“%.3s”,”programming”); p r o
printf(“%8.3s”,”programming”);
p r o
96
Unit-6
Control Structure
Introduction
In C programs, statements are executed sequentially in the order in which they appear in
the program, but sometimes we may want to use a condition for executing only a part of a
program. Also many situations arise where we may want to execute some statements several
times. Control statements enable us to specify the order in which the various instructions in the
program are to be executed. This determines the flow of control. Control statements define how
the control is transferred to other parts of the program. C language supports four types of control
statements, which are given below.
1. if……else
2. goto
3. switch
4. loop
a. while
b. do…….while
c. for
If Statement
The if statement is used to express conditional expressions. The general form of if
statement is;
For only one statement we don’t need braces.
if(condition)
statement;
For more than one statements we need braces;
97
if(condition)
{
statement1;
statement2;
……………………..
statementN;
}
Example
/* To find out commission*/
#include<stdio.h>
void main()
{
float sales, commission;
printf(“Enter total sales made:);
scanf(“%f” &sales);
if(sales >= 8000)
commission = 0.08 * sales;
printf(“commission is: %f” commission);
}
98
{
statement;
…………………;
}
Flowchart
Write a program to find whether a given
number is even or odd.
True False
#include<stdio.h>
Con? #include<conio.h>
void main()
{
statement statement int n;
clrscr();
printf("Enter a number\n");
scanf("%d",&n);
if(n%2==0)
printf("%d is even",n);
Next statement
else
printf("%d is odd",n);
getch();
}
Nesting if…............else statement
If we declare another if…else statement in the block of if or the else block. This is known as nesting
if….else statements.
Syntax:
Write a program to find largest among
if(condition)
any three given numbers.
{
#include<stdio.h>
if(condition) #include<conio.h>
statement; void main()
else {
statement; int a,b,c,large;
} clrscr();
printf("Enter three numbers\n");
else scanf("%d%d%d",&a,&b,&c);
{ if(a>b)
if(condition) {
Statement; if(a>c)
else large=a;
else
statement; large=c;
} }
else
{
if(b>c)
99
large=b;
else
large=c;
}
printf("Largest
number=%d",large);
getch();
}
else…if ladder
This is the type of nesting in which there is an if….else statement in every else part except the last
else part. This type of nesting is frequently used in programs and is also known as else if ladder.
flowchart
Syntax:
if(condition 1) F
statement 1; T Condition
Write a program to read the marks of four subjects then find total, percentage and
division according to given condition.
Percentage Division
p ≥ 80 Distinction
80 > p ≥ 70 First division
70 > p ≥ 50 Second division
50 >p ≥ 40 Third division
Otherwise Fail.
100
Assume each subject carrying 100 full marks and student must secure greater or equal to
40 in each subject for division.
#include<stdio.h>
#include<conio.h>
void main()
{
int s1,s2,s3,s4,total;
float per;
clrscr();
printf("Enter marks in 4 different subjects\n");
scanf("%d%d%d%d",&s1,&s2,&s3,&s4);
total=s1+s2+s3+s4;
printf("\nTotal marks:%d",total);
if(s1>=40&&s2>=40&&s3>=40&&s4>=40)
{
printf("\nResult:PASS");
per=total/4.0; printf("\nPercentage:
%f",per); if(per>=80) printf("\
nDivision:DISTINCTION"); else
if(per>=70) printf("\
nDivision:FIRST");
else if(per>=50) printf("\
nDivision:SECOND"); else
printf("\nDivision:THIRD");
}
else printf("\
nResult:FAIL"); getch();
}
goto
This is an unconditional control statement that transfer the flow of control to another part of the program .
The goto statements can be as-
Write a program to read a positive number
goto label; from user.
#include<stdio.h>
………..
#include<conio.h>
……… void main()
{
label: int n;
clrscr();
statements; again:
………………… printf("Enter a number\n");
scanf("%d",&n);
……………. if(n<0)
{
101
printf("Number is negative so
re-enter a number\n");
goto again;
}
getch();
}
Switch
This is a multi-directional condition control statements. Sometimes there is a need in program to make
choice among number of alternatives. For making this choice, we use the switch statements. This can be
written as:-
Syntax: Flowchart:
switch (expression)
{
case constant1:
statement 1; Switch expression
break;
case constant2:
statement 2;
break;
case constant3:
statement 3; T
Statement1;
break; case constant 1
default: break;
statement;
} F
T
Statement2;
case constant 2
break;
T
StatementN;
case constant N
break;
default
statement
Out of
switch
102
Write a program to print the day of the week Write a program to perform arithmetic
according to the number entered 1 for
calculation based on the operators
Sunday
entered by user.
……..7 for Saturday.
#include<stdio.h> + for addition, - for subtraction, * for
#include<conio.h> multiplication, / for division and % for
void main()
remainder.
{
int num; #include<stdio.h>
clrscr(); #include<conio.h>
printf("Enter a number\n"); void main()
scanf("%d",&num); {
switch(num) int a,b;
{ char op;
case 1: clrscr();
printf("Sunday"); printf("Enter operator\n");
break; scanf("%c",&op);
case 2: printf("Enter two numbers\n");
printf("Monday"); scanf("%d%d",&a,&b);
break; switch(op)
case 3: {
printf("Tuesday"); case '+':
break; printf("Sum =%d",a+b);
case 4: break;
printf("Wednesday"); case '-':
break; printf("Difference =%d",a-b);
case 5: break;
printf("Thusday"); case '*':
break; printf("Product =%d",a*b);
case 6: break;
printf("Friday"); case '/':
break; printf("Quotient =%d",a/b);
case 7: break;
printf("Saturday"); case '%':
break; printf("Remainder =%d",a%b);
default: break;
printf("Wrong input"); default:
} printf("Wrong operator");
getch(); }
} getch();
}
looping
Repetition/looping means executing the same section of code more than once until the given
condition is true. A section of code may either be executed a fixed number of times, or while
condition is true. C provides three looping statements:
1. for loop
2. while loop
103
3. do while loop
For loop
For statement makes programming more convenient to count iterations of a loop and works
well where the number of iterations of the loop is known before the loop entered. The
syntax is as follows:
for (initialization; test condition; loop update)
{
Statement(s);
}
Flowchart
initialization
false
condition
Loop update
True
Statement(s)
Out of loop
The main purposed is to repeat statement while condition remains true, like the while loop.
But in addition, for provides places of specify an initialization instruction and an increment
or decrement of the control variable instruction. So this loop is specially designed to
perform a repetitive action with counter.
For loop has the four parts and it works as:
1. Initialization is executed. Generally it is an initial value setting for a counter variable.
This is executed only once.
2. Condition is checked, if it is true the loop continues, otherwise the loop finishes and
statement is skipped.
3. Statements(s) are /are executed. As usual, it can be either a single instruction or a
block of instructions enclosed within curly brackets {}.
104
4. Finally, whatever is specified in the increment or decrement of the control variable field
is executed and the loop gets back to step 2.
Exercises
1. Write a program to print 1 to 10.
2. Write a program to print your name for 20 times.
3. Write a program to display factorial of any given number.
4. Write a program to display multiplication table for any given number.
5. Write a program to display following Fibonacci series upto n
terms. 0 1 1 2...............3 n terms
6. Write a program to check whether a given number is prime or composite.
7. Write a program to find the sum of odd numbers upto n.
8. Write a program to find the sum of natural numbers upto n.
9. Write a program to display the sum of squares of natural numbers upto n.
10. Write a program to find the sum of cubes of first 10 numbers.
11. Write a program to evaluate the sum of n terms of the following
series. 1/1 + 1/3 + 1/5 + 1/7 + ……..
While loop
while(condition)
Flowchart
{
statement(s);
loopupdate
statement; initialization
false
conditi
true
Statement(s) loop
update
Out of loop
105
Here, statement(s) may be a single statement or a block of statements.. The loop iterates while
the condition is true.
When the condition becomes false, program control passes to the line immediately following the
loop.
do while
In C, do...while loop is very similar to while loop. Only difference between these two
loops is that, in while loops, test expression is checked at first but, in do...while loop
code is executed at first then the condition is checked. So, the code are executed at least
once in do...while loops.
flowchart
do
{
statement(s);
loopupdate
statement;
initialization
condition
true
false
Out of loop
while do………while
2. Test condition is evaluated before the loop 2. Test condition is evaluated after the loop is
is executed executed.
106
3. It use keyword while. 3. It uses keywords do and while.
5. It doesn’t execute the body of loop until and 5. Body of the loop is always executed at
unless the condition is true. least once since the test condition is not
checked until end of the loop.
6. Flowchart 6. Flowchart
7. Syntax 7. Syntax
while(condition) do
{ {
statement(s); statement(s);
loopupdate statement; loopupdate statement;
} }while(condition);
8. Example 8. Example
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int i; int i;
i=1; i=1;
while(i<=5) do
{ {
printf("%d\n",i); printf("%d\n",i);
} } while(i<=5);
107
Exercise
break statement
break statement is used inside loops and switch statements. Sometimes it becomes necessary to
come out of loop before its termination. In such a situation, break statement is used to terminate
the loop. When break statement is encountered, loop is terminated and the control is transferred
to the statement immediately after the loop.
continue statement
continue statement is used when we want to go to the next iteration of the loop after skipping
some statements of the loop. It is generally used with a condition. When continue statement is
encountered all the remaining statements after continue in the current iteration are not
executed and loop continues with the next iteration.
Difference between break and continue statement
break statement continue statement
1. break statement is used to terminate the 1. continue statement is used to by-pass the
control from the switch case as well as in execution of the further statements.
the loop.
2. When the break statement encountered it 2. When the continue statement is
terminates the execution of the entire loop encountered it by-passes single pass of the
or switch case. loop.
3. It uses keyword break. 3. It uses keyword continue.
4. Syntax: break; 4. Syntax: continue;
5. Example: 5. Example:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int i; int i;
clrscr(); clrscr();
for(i=1;i<=10;i++) for(i=1;i<=10;i++)
{ {
if(i==5) if(i==5)
break; continue;
printf("%d\n",i); printf("%d\n",i);
} }
getch(); getch();
} }
108
outputs: outputs:
1 1
2 2
3 3
4 4
6
7
8
9
10
exit()
exit() is used to terminate the whole program. In other words it returns control to the
operating system.
Nested loop
When a loop is written inside the body of another loop, then it is known as nesting of loops. Any
type of loop can be nested inside any other loop.
Exercise
1. Write a program to display prime numbers from 100 to 500.
2. Write a program to display multiplication table from 1 to 20.
3. Write a program to display factorial of first 10 integer numbers.
109
Unit-7
Array
Introduction
Array is the collection of similar data types that can be represent by a single variable name. The individual
data items in an array are called elements. A data items is stored in memory in one or more adjacent
storage location dependent upon its type. The data types may be any valid data types like char, int or float.
The element of array share same variable name but each element has a different index of number known
as subscript. In c subscript starts from zero, here if age [10] is the variable name so the first element will
be age [0] and second age [1] and so on. Array can be single dimensional or multidimensional the array of
subscript determines the dimension of array. One dimensional has one subscript and two dimensional has
two subscript and so on.
Example: int marks[5] = {68, 85, 95, 63, 81};
Types of Array
110
Lower bound=0
111
Upper bound =size-1=10-1=9
Size =upper bound+1=10
Processing array element
For processing the arrays we generally use loop and the loop variable is used at the place of subscript. The
initial value of loop variable is taken 0 since array subscript start from zero.
Initialization of one dimensional array
We can explicitly initialize arrays at the time of declaration. The syntax for initialization of an array
is data_typearray_name[size]={value1,value2,…............valueN};
Here array_name is the name of the array variable, size is the size of the array and value1,
value2,…....valueN are the constant values which are assigned to the array elements one after another.
Example.
int marks[5]={55,59,78,87,65};
The values of the array elements after this initialization are
marks[0]=55, marks[1]=59, marks[2]=78, marks[3]=87, marks[4]=65
Exercise:
1) Write a program to read 10 numbers from user and display it on the screen.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[10],i;
clrscr();
for(i=0;i<10;i++)
{
printf("Enter elements of array\n");
scanf("%d",&arr[i]);
}
printf("Displaying array elements\n");
for(i=0;i<10;i++)
{
printf("%d\n",arr[i]);
}
getch();
}
2) Write a program to display smallest and largest element from N number of array elements.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[20],i,n,small,large;
clrscr();
printf("How many number of elements are there in array\n");
scanf("%d",&n);
for(i=0;i<n;i++)
112
{
printf("Enter elements of array\n");
scanf("%d",&arr[i]);
}
small=arr[0];
large=arr[0];
for(i=0;i<n;i++)
{
if(small>arr[i])
small=arr[i];
if(large<arr[i])
large=arr[i];
}
printf("Smallest element =%d and largest element =%d",small,large);
getch();
}
3) Write a program to search an element from N number of array elements.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[20],search,i,n;
clrscr();
printf("How many number of elements are there in array\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter elements of array\n");
scanf("%d",&arr[i]);
}
printf("Enter element to be searched\n");
scanf("%d",&search);
for(i=0;i<n;i++)
{
if(arr[i]==search)
{
printf("Search element found\n");
break;
}
}
if(i==n)
printf("Element not found\n");
getch();
}
4) Write a program to sort N numbers in ascending order (using bubble sort).
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[20],i,j,tem,n;
clrscr();
printf("How many elements are there in an array\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
113
printf("Enter elements\n");
scanf("%d",&arr[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(arr[j]>arr[j+1])
{
tem=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tem;
}
}
}
printf("\nsorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\n",arr[i]);
}
getch();
}
5) Write a program to sort N numbers in ascending order (using selection sort).
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[20],i,j,tem,n;
clrscr();
printf("How many elements are there in an array\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter elements\n");
scanf("%d",&arr[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
tem=arr[i];
arr[i]=arr[j];
arr[j]=tem;
}
}
}
printf("\nsorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\n",arr[i]);
}
getch();
}
114
B) Multidimensional Array
An array having more than one subscript is called multidimensional array. Two dimensional array have two
subscript, three dimensional array have three subscript and so on.
int a[2][3]={3,5,8,9,4,6};
Which means,
For processing 2-D array, we must use nested loop. The outer loop corresponds to the row and the inner
loop corresponds to the column.
Exercise
1. Write a program to read any 2×2 matrix and display it in appropriate format.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],i,j;
clrscr();
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("Enter elements of matrix\n");
scanf("%d",&a[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
getch();
}
115
2. Write a program to display the sum of all elements of any 3×2 matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][2],i,j,sum=0;
clrscr();
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("Enter elements of matrix\n");
scanf("%d",&a[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
sum=sum+a[i][j];
}
}
printf("Sum of all elements of matrix =%d",sum);
getch();
}
3. Write a program to display sum of diagonal elements of any given 3×3 matrix.
4. Write a program to display sum of each rows of any given n×m matrix.
5. Write a program to display transpose of any given n×m matrix.
6. Write a program to display sum of each columns of any given n×m matrix.
7. Write a program to display the sum of any given two n×m matrix.
8. Write a program to display the product of any given two n×m matrix.
String
String is an array of characters or alphabets. Each programming language has a set of character to
communicate with computers. These are:
(a) Alphabet: A, B, C,........ X, Y, Z and a, b, c.....x , y , z
(b) Digits: 1, 2, 3.......9 .
(c) Special Characters: /, * , ( ) , = , ' , □ etc .
116
“BIKAS”
“Microsoft Products”
" 521457 "
strlen ( )
This function returns the length of the string i.e. the number of characters in the string excluding the terminating
null character. It accepts a single argument, which is pointer to the first character of the string. For example
strlen(“sobaraj”) returns the value of 7. Similarly if s1 is an array that contains the name “deepa” then strlen(s1)
returns the value 5.
Syntax
strlen(string);
/*Program to understand the work of strlen() function*/
#include<stdio.h>
#include<string.h>
main( )
{
char str[20];
int length;
printf(“Enter the string:\n”);
scanf(“%s”, str);
length = strlen(str);
printf(“Length of the string is : %d\n”, length);
}
Output:
Enter the string : programming
Length of the string is : 11
strcmp ( )
This function is used for comparison of two strings. If the two strings match, strcmp( ) returns a value 0,
otherwise it returns a non-zero value. This function compares the string character by character. The
comparison stops when either the end of string is reached or the corresponding characters in the two
strings are not same. The non zero value returned on mismatch is the difference of the ASCII values of the
non matching characters of the two strings-
strcmp (s1, s2) returns a value-
117
> 0 when s1 > s2
Generally we don’t use the exact non zero value returned in case of mismatch. We only need to know its
sign to compare the alphabetical positions of the two strings. We can use this function to sort the strings
alphabetically.
Syntax
strcmp(string1,string2);
Output:
Enter the first string : Nepalgunj
Enter the second string : Gaindakot
Strings are not same
strcpy ( )
This function is used for copying one string to another string, strcpy(srt1, str2) copies str2 to str1. Here str2 is the
source string and str1 is destination string. If str2 = “programming” then this function copies “programming” into
str1. This function takes pointers to two strings as arguments and returns the pointer to first string.
Syntax
strcpy(destination_string,source_string);
118
void main( )
{
char str1[10], str2[10];
printf(“Enter the first string:”);
scanf(“%s”, str1);
printf(“Enter the second string:”);
scanf(“%s”, str2);
strcpy(str1, str2);
printf(“First string : %s \t\t Second string: %s\n”, str1, str2);
strcpy(str1, “Jomsom”)
strcpy(str2, “Kagbeni”)
printf(“First string : %s \t\t Second string: %s\n”, str1, str2);
}
Output:
Enter the first string : Balaju
Enter the second string : Pokhara
First string : Pokhara Second string : Balaju
First string : Jomsom Second string : Kagbeni
The programmer should take care that the first string has enough space to hold the second string.
The function calls like strcpy(“New”, strl) or strcpy(“New”, “York”) are invalid because “New” is a string constant
which is stored in read only memory and so we can’t overwrite it.
strcpy(“New”, str1); /*Invalid*/
strcpy(“New”, “York”); /*Invalid*/
strncpy( )
This function is used for copying n characters from source to destination.
Syntax
strncpy(destination_string,source_string,no_of_character);
Example
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20]="oxford college",str2[20];
clrscr();
strncpy(str2,str1,10);
printf("%s",str2);
getch();
}
119
Output
Oxford col
strcat( )
This function is used for concatenation of two strings. If first string is “King” and second string is “size” then after
using this function the first string becomes “Kingsize”.
strcat(str1, str2); /*concatenates str2 at the end of str1*/
The null character from the first string is removed, and the second string is added at the end of first string. The second
string remains unaffected.
This function takes pointer to two strings as arguments and returns a pointer to the first(concatenated) string.
/* Program to understand the work of strcat( ) function*/
#include<stdio.h>
#include<string.h>
void main( )
{
char str1[20], str2[20];
printf(“Enter the first string:”);
scanf(“%s”, str1);
printf(“Enter the second string:”);
scanf(“%s”, str2);
strcat(str1, str2);
printf(“First string:%s \t Second string: %s\n”, str1, str2);
strcat(str1, “_one”);
printf(“Now first string is : %s\n”, str1);
}
Output:
Enter the first string : data
Enter the second string : base
First string : database Second string : base
Now first string is : database_one
strrev( )
This function takes string as an argument and returns the string in reverse order.
strrev(string)
Example
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
120
{
char str[10];
clrscr();
printf("Enter a string\n");
scanf("%s",str);
printf("%s",strrev(str));
getch();
}
strupr( )
This function converts lowercase string to uppercase string. If any of the character, already in uppercase
then the function skips that character and converts the remaining character which is in lowercase.
strupr(string)
Example
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[10];
clrscr();
printf("Enter a string\n");
scanf("%s",str);
printf("%s",strupr(str));
getch();
}
strlwr( )
This function converts uppercase string to lowercase string. If any of the character, already in lowercase
then the function skips that character and converts the other remaining character which is in uppercase.
strlwr(string)
Example
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[10];
clrscr();
printf("Enter a string\n");
scanf("%s",str);
printf("%s",strlwr(str));
getch();
}
Exercise
1. Write a program to read N students name and display them in alphabetical order.
#include<stdio.h>
#include<conio.h>
121
#include<string.h>
void main()
{
char name[100][15],temp[15];
int i,j,n;
clrscr();
printf("How many students are there\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter name of student\n");
scanf("%s",name[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(name[i],name[j])>0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("Names in alphabetical order\n");
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
getch();
}
2. Write program to read a line of text and count no of vowel, no of consonant, no of digits and no
of spaces.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[100];
int spaces=0,vowel=0,digits=0,consonant=0,i;
clrscr();
puts("Enter a text\n");
gets(str);
strlwr(str); for(i=0;str[i]!='\
0';i++)
{
if(str[i]>='a'&&str[i]<='z')
{
if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u')
vowel++;
else
122
consonant++;
}
if(str[i]>='0'&&str[i]<='9')
digits++;
if(str[i]==32)
spaces++;
}
printf("vowels
=%d\nconsonant=%d\ndigits=%d\nSpaces=%d",vowel,consonant,digits,spaces);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[15],s2[15];
clrscr();
printf("Enter a string: ");
scanf("%s",s1);
strcpy(s2,s1);
strrev(s2);
if(strcmp(s1,s2)==0)
printf("%s is palindrome",s1);
else
printf("%s is not palindrome",s1);
getch();
}
123
Unit-8
User Defined Function
Introduction
A function is a self-contained sub program that is meant to be some specific, well defined
task. A C-program consists of one or more functions. If a program has only one function then it
must be the main() function.
Advantages of using function
1. Functions increases code reusability by avoiding rewriting of same code over and over.
2. If a program is divided into multiple functions, then each function can be
independently developed. So program development will be easier.
3. Program development will be faster.
4. Program debugging will be easier.
5. Function reduces program complexity.
6. Easier to understand logic involved in the program.
7. Recursive call is possible through function.
C programs have two types of functions-
i. Library Functions
ii. User defined Functions
i. Library function
Library functions are supplied with every C compiler. The source code of the library
functions is not given to the user. These functions are precompiled and the user gets only
the object code. This object code is linked to the object code of your program by the linker.
Different categories of library functions are grouped together in separate library files.
When we call a library function in our program, the linker selects the code of that function
from the library file and adds it to the program.
To use library function in our program we should know-
i. Name of the function and its purpose
ii. Type and number of arguments it accepts
iii. Type of the value it returns
iv. Name of the header file to be included
We can define any function of our own with the same name as that of any function in the C
library. If we do so then the function that we have defined will take precedence over the library
function with the same name.
124
Some examples are
Users can create their own functions for performing any specific task of the program. These types of
functions are called user defined functions. To create and use these functions, we should know about
these three things-
1. Function definition
2. Function declaration
3. Function call
Lets take an example of function to add two numbers.
#include<stdio.h>
#include<conio.h>
void sum(int,int); //function declaration
void main()
{
int a,b;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
sum(a,b); //function call
getch();
}
1. Function Definition
The function definition consists of the whole description and code of a function. It tells
what the function is doing and that are its inputs and outputs. A function definition consists
of two parts - a function header and a function body. The general syntax of a function
definition is-
return_type func_name(type1 arg1, type2 arg2,..............)
{
local variables declarations;
statements;
…………..
return(expression)
125
}
The first line in the function definition is known as the function header and after this the
body of the function is written enclosed in curly braces.
The return_type denotes the type of the value that will returned by the function. The
return_type is optional and if omitted, it is assumed to be int by default. A function can
return either one value or no value. If a function does not return any value then void should
be written in place of return_type.
func_name specifies the name of the function and it can be any valid C identifier. After
function name, the argument declarations are given in parentheses, which mention the type
and name of the arguments. These are known as formal arguments and used to accept
values. A function can take any number of left empty or void can be written inside the
parentheses.
The body of function is a compound statement (or block), which consists of declarations
variables, and C statements followed by an optional return statement. The variables declared
inside the function are known as local variables, since they are local to that function only, i.e.
they have existence only in the function in which they are declared, and they cannot be used
anywhere else in the program. There can be any number of valid C statements inside a function
body. The return statement is optional. It may be absent if the function does not return any
value.
3. Function call
A function is called by simply writing its name followed by the argument list inside the
parentheses.
126
the function call in the calling function. The code of a function is executed only when
it is
127
called by some other function. If the function is defined and not called even once then it’s
code will never be executed. A function can be called more than once, so the code is
executed each time it is called. The execution of a function finishes either when the
closing braces of the function body are reached or if return statement is encountered.
return statement
The return statement is used in a function to return a value to the calling function. It may also be
used for immediate exit from the called function to the calling function without returning a value.
This statement can appear anywhere inside the body of the function. There are two ways in
which it can be used-
return;
return (expression);
Here return is a keyword. The first form of return statement is used to terminate the function
without returning any value. The second form of return statement is used to terminate a function
and return a value to the calling function.
Function arguments
The calling function sends some values to the called function for communication; these values
are called arguments or parameters.
Actual argument
The arguments which are mentioned in the function call are known as actual arguments, since
these are the values which are actually sent to the called function. Actual arguments can be
written in the form of variables, constants or expressions or any function call that returns a value.
Formal argument
The name of the arguments, which are mentioned in the function definition are called formal or
dummy arguments since they are used just to hold the values that are sent by the calling function.
These formal arguments are simply like other local variables of the function which are created
when the function call starts and are destroyed when the function ends.
The order, number and type of actual arguments in the function call should match with the order, number
and type of formal arguments in the function definition.
128
1. Function with no arguments and no return value.
Example.
Program to add two numbers.
#include<stdio.h>
#include<conio.h>
void sum();
void main()
{
clrscr();
sum();
getch();
}
void sum()
{
int x,y,s;
printf("Enter two numbers\n");
scanf("%d%d",&x,&y);
s=x+y;
printf("Sum =%d",s);
}
2. Function with no argument and a return value.
Example.
Program to add two numbers.
#include<stdio.h>
#include<conio.h>
int sum();
void main()
{
int c;
clrscr();
c=sum(); printf("sum=
%d",c); getch();
}
int sum()
{
int x,y,s;
printf("Enter two numbers\n");
scanf("%d%d",&x,&y);
s=x+y;
return(s);
}
3. Function with argument and no return value
Example
Program to add two numbers.
129
#include<stdio.h>
#include<conio.h>
void sum(int,int);
void main()
{
int a,b;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
sum(a,b);
getch();
}
void sum(int x,int y)
{
int s;
s=x+y;
printf("Sum =%d",s);
}
4. Function with argument and return value
Example
Program to add two numbers.
#include<stdio.h>
#include<conio.h>
int sum(int,int);
void main()
{
int a,b,c;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
c=sum(a,b); printf("sum=
%d",c);
getch();
}
int sum(int x,int y)
{
int s;
s=x+y;
return(s);
}
Difference between library function and user defined function
130
2. Programmer can simply use this function 2. Programmer has to declare, define and use
by including respective header file. this function by themself.
3. The program using library function will be 3. The program using user defined function
usually short as the programmer doesn’t will be usually lengthy as the programmer
have to define the function. has to define the function.
4. Program development time will be faster. 4. Program development time will be usually
slower.
5. Program will be simple. 5. Program will be complex.
6. This function requires header file to use it. 6. This function requires function prototype
to use it.
main ( )
Execution of every C program always begin with the function main( ). Each function is called
directly or indirectly in main( ) and after all functions have done their operations, control returns
back to main( ). There can be only one main( ) function in a program.
The main( ) function is a user defined function but the name, number and type of arguments are
predefined in the language. The operating system calls the main function and main( ) returns a
value of integer type to the operating system. If the value returned in zero, it implies that the
function has terminated successively and any non zero returns value indicates an error. If no
return value is specified in main( ) then any garbage value will be returned automatically. Calling
the function exit( ) with an integer value is equivalent to returning that value from main( ). The
definition, declaration and call of main( ) function-
function declaration - by the C compiler
function definition - by the programmer
function call - by the operating system
Recursion
Recursion is a powerful technique of writing a complicated algorithm in an easy way. According
to this technique a problem is defined in terms of itself. The problem is solved by dividing it into
smaller problems, which are similar in nature to the original problem. These smaller problems
are solved and their solutions are applied to get the final solution of our original problem.
A function will be recursive, if it contain following features:
i. Function should call itself.
ii. Function should have a stopping condition (base criteria) and every time the function
calls itself it must be closer to base criteria.
Example.
1. Write a program to calculate factorial of any given number using recursive function.
131
#include<stdio.h>
#include<conio.h>
long int factorial(int);
void main()
{
int num;
long int fact;
clrscr();
printf("Enter a number\n");
scanf("%d",&num);
fact=factorial(num);
printf("Factorial of %d = %ld",num,fact);
getch();
}
132
clrscr();
printf("Enter value of a and n :");
scanf("%d%d",&a,&n);
p=power(a,n);
printf("%d raised to power %d is %d",a,n,p);
getch();
}
int power(int a,int n)
{
if(n==0)
return 1;
else
return(a*power(a,n-1));
}
Local variables
The variables that are defined within the body of a function or a block, are local variables. For
example.
func()
{
int a,b;
…….
……
}
Here a and b are local variables which are defined within the body of the function func(). Local
variables can be used only in those functions or blocks, in which they are declared. The same
variable name may be used in different functions. For example-
func1()
{
int a=2,b=4;
……….
……….
}
func2()
{
int a=15,b=20;
……….
……….
}
Here values of a=2 , b=4 are local to the function func1() and a=15, b=20 are local to the
function func2().
133
Global variables
The variables that are defined outside any function are called global variables. All functions in
the program can access and modify global variables. It is useful to declare a variable global if it
is to be used by many functions in the program. Global variables are automatically initialized
to 0 at the time of declaration.
Example-
#include<stdio.h>
#include<conio.h>
int a,b=5; //global variables
void func1();
void func2();
void main()
{
clrscr();
printf("Inside main() a=%d and b=%d\n",a,b);
func1();
func2();
getch();
}
void func1()
{
printf("Inside func1() a=%d and b=%d\n",a,b);
a=a+1;
b=b-1;
}
void func2()
{
printf("Inside func2() a=%d and b=%d",a,b);
}
134
}
void change(int x)
{
x=x+5;
}
Output:
Before calling function, a=15
After calling function, a=15
Output:
Before calling function, a=15
After calling function, a=20
135
gets(name);
function(name);
getch();
}
void function(char s[])
{
printf("College name = %s",s);
}
Output
136
{
int i,j,c[2][2];
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
Storage Classes
Storage classes is an attribute of a variable which specifies about four aspects of a variable:
1. Lifetime: Time between the creation and destruction of a variable.
2. Scope: Location where the variable is available for use.
3. Initial Value: Default value taken by an uninitialized variable.
4. Place of storage: Place in memory where the storage is allocated for the variable.
1. Automatic: All the variables declared inside a block/function without any storage class
specifier are called automatic variables. We may use the keyword auto to declare automatic
variables. The uninitialized automatic variables initially contain garbage value. The scope of
these variables is inside the function or block in which they are declared and they can’t be
used in any other function/block. They are named automatic since storage for them is
reserved automatically each time when the control enters the function/block and are released
automatically when the function/block terminates.
Example
#include<stdio.h>
#include<conio.h>
void func();
void main()
{
clrscr();
func();
func();
137
func();
getch();
}
void func()
{
int a=5;
printf("%d\n",a);
a++;
}
Output
5
5
5
2. External: The variables that have to be used by many functions and different files can be
declared as external variables. The initial value of an uninitialized external variable is zero.
We may use the keyword extern to declare external variables. The scope of these variables is
within the program and they can be used by any functions in that program.
Example
#include<stdio.h>
#include<conio.h>
void func();
int a=5;
void main()
{
clrscr();
func();
func();
func();
getch();
}
void func()
{
printf("%d\n",a);
a++;
}
Output
5
6
7
3. Static: The scope of a local static variable is same as that of an automatic variable. It can be
used only inside the function or block in which it is defined. The lifetime of a static variable
is till the end of the program. We use static to declare static variable. The uninitialized static
variables initially contain value zero.
Example
138
#include<stdio.h>
#include<conio.h>
void func();
void main()
{
clrscr();
func();
func();
func();
getch();
}
void func()
{
static int a=5;
printf("%d\n",a);
a++;
}
Output
5
6
7
4. Register: The scope, lifetime and initial value of register variables are same as that of
automatic variables. The only difference between the two is in the place where they are
stored. Automatic variables are stored in memory while register variables are stored in CPU
registers. The variables stored in registers can be accessed much faster than the variables
stored in memory.
Example
#include<stdio.h>
#include<conio.h>
void func();
void main()
{
clrscr();
func();
func();
func();
getch();
}
void func()
{
register int a=5;
printf("%d\n",a);
a++;
}
Output
139
5
5
5
The following table summarizes all the features of storage classes:
Keyword Place of Lifetime Scope Initial value Place of
declaration storage
Macros
A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-
processor, the block of code is communicated to the compiler before entering into the actual
coding (main ( ) function). A macro is defined with the preprocessor directive, #define.
Example
Write a macro to display area of circle
#include<stdio.h>
#include<conio.h>
#define area(r) 3.14*r*r
void main()
{
int rad;
clrscr();
printf("Enter radius of circle\n");
scanf("%d",&rad);
printf("Area of circle =%f",area(rad));
getch();
}
1. Macro make the code lengthy and the 1. Function is written only at one place,
compilation time increases. regardless of the number of times it is
called. So function makes the code smaller.
2. Macro makes program execution faster. 2. Function makes program execution slower.
3. Macro occupy more memory. 3. Function occupy less memory.
140
Unit-9
Pointers
Introduction
A pointer is a variable that stores the address of another variable. Memory can be visualized as an ordered
sequence of consecutively numbered storage locations. A data item stored in memory in one or more adjacent
storage locations depends upon its type. That is the number of memory locations required depends upon the
type of a variable. The address of a data item is the address of its first storage location. This address can be
stored in another data item and manipulated in a program. The address of a data item is a pointer to the data
item, and a variable that holds the address is called a pointer variable.
Advantages of pointer:
1. Pointers increase the execution speed and thus reduce the program execution time.
2. With the help of pointer we can handle any type of data structure.
3. By using pointers we can return multiple data from function.
4. By using pointer variable we can implement dynamic memory allocation.
5. Pointers provide an efficient tool for manipulating dynamic data structures such as structures, linked
lists, queues, stacks and trees.
6. Pointer reduce length and complexity of programs.
&: Address of
* : value at address of
Program to understand & and * operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int age=25,*page;
float sal=50000,*psal;
page=&age;
psal=&sal;
printf("\nAddress of age=%u and value of age=%d",page,*page);
printf("\nAddress of sal=%u and value of sal=%f",psal,*psal);
getch();
}
141
Declaration of pointer
Like all other variables it also has a name, has to be declared and occupies some space in memory. It is called
pointer because it points to a particular location in memory by storing the address of that location.
Syntax:
datatype *identifier
eg:
int age; //declaring a normal variable
int *ptr; //declaring a pointer variable
ptr=&age; //store the address of the variable age in the variable ptr.
Now ptr points to age or ptr is a pointer to age.
We’ve created a pointer ptr which becomes a variable that contains the address of another variable age.
ptr age
65528
65524 65524
25
Pointer arithmetic
All types of arithmetic operations are not possible with pointers. The only valid operations that can be
performed are as:
Pointer arithmetic is somewhat different from ordinary arithmetic. Here all arithmetic is performed relative to
the size of base type of pointer. For example if we have an integer pointer pi which contains address 1000 then
on incrementing we get 1002 instead of 1001. This is because the size of int data type is 2. Similarly on
decrementing pi, we will get 998 instead of 999. The expression (pi + 3) will represent the address 1006.
Program to understand pointer arithmetic
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,*pi;
float b=7.3,*pf;
char c='x',*pc;
clrscr(); pi=&a;
pf=&b;
pc=&c;
printf("\n Address of a=%u ",pi);
printf("\n Address of b=%u ",pf);
printf("\n Address of c=%u ",pc);
pi++;
142
pf++;
pc++;
printf("\n Address of a=%u ",pi);
printf("\n Address of b=%u ",pf);
printf("\n Address of c=%u ",pc);
getch();
}
Output
Syntax
datatype **identifier;
Eg:
int **pptr;
143
ppa pa a
1028 1024 5
In C, there is a strong relationship between arrays and pointers. Any operations that can be achieved by array
subscripting can also be done with pointers. The pointer version will, in general, be faster but for the beginners
somewhat harder to understand.
An array name is itself is an address, or pointer value, so any operation that can be achieved by array
subscripting can also be done with pointers as well. Pointers and arrays are almost synonymous in terms of how
they are used to access memory, but there are some important differences between them. A pointer which is
fixed. An array name is a constant pointer to the first element of the array. The relation of pointer and array is
presented in the following tables:
Address of array elements
&arr[0] arr
&arr[1] (arr+1)
&arr[i] (arr+i)
arr[0] *arr
arr[1] *(arr+1)
144
arr[i] *(arr+i)
arr[i][j] *(*(arr+i)+j)
int arr[5]={6,9,12,4,8};
This is stored in memory as-
Here 5000 is the address of first element, and since each element (type int) takes 2 bytes so address of next
element is 5002, and so on. The address of first element of the array is also known as the base address of the
array.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[100],i,n;
clrscr();
printf("How many elements are there: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter element: ");
scanf("%d",(arr+i));
}
printf("\n Printing array element:");
for(i=0;i<n;i++)
{
printf("\n %d",*(arr+i));
}
getch();
}
145
146
Output
Examples
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[100],n,i,j,temp;
clrscr();
printf("How many elements are there?: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter elements :");
scanf("%d",(arr+i));
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(*(arr+i)>*(arr+j))
{
temp=*(arr+i);
*(arr+i)=*(arr+j);
*(arr+j)=temp;
}
}
}
printf("\n Printing sorted elements:");
for(i=0;i<n;i++)
{
printf("\n %d",*(arr+i));
147
}
getch();
}
output
2. Write a program to find sum of all the elements of an array using pointers.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[100],n,i,sum=0;
clrscr();
printf("How many elements are there? ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter elements of array: ");
scanf("%d",(arr+i));
}
for(i=0;i<n;i++)
{
sum=sum + *(arr+i);
}
printf("\nSum of all elements of array =%d",sum);
getch();
}
148
output
3. Write a program to search an element from ‘n’ number of elements using pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[100],n,i,search;
clrscr();
printf("How many elements are there? ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter elements :");
scanf("%d",(arr+i));
}
printf("\n Enter an element to be searched: ");
scanf("%d",&search);
for(i=0;i<n;i++)
{
if(search==*(arr+i))
{
printf("\n %d is found in %d position",search,i+1);
break;
}
}
if(i==n)
printf("\n %d is not found",search);
getch();
}
149
Output
Example
1. Write a program to read any 2 by 3 matrix and display its element in appropriate format.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[2][3],i,j;
clrscr();
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\n Enter elements of matrix: ");
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",*(*(arr+i)+j));
}
printf("\n");
}
getch();
}
150
Output
char *ptr=”Programming”;
Here ptr is a char pointer which points to the first character of the string constant “programming” ie. ptr
contains the base address of this string constant.
Now let’s compare the strings defined as arrays and strings defined as pointers.
char str[]=”Chitwan”;
char *ptr=”Nawalparasi”;
These two forms may look similar but there are some differences in them. The initialization itself has different
meaning in both forms. In array form, initialization is a short form for-
char str[]={‘C’,’h’,’i’,’t’,’w’,’a’,’n’,’\0’}
while in pointer form, address of string constant is assigned to the pointer variable.
5220 5221
ptr
20
200 201 202 203 204 205 206 207 208 209 210 211
N a w a l p a r a s i \0
Here string assignments are valid for pointers while they are invalid for strings defined as arrays.
151
str = “Narayangarh” //invalid
ptr = ”Butwal” //valid
char *arrp[]={“white”,”red”,”green”,”yellow”,”blue”};
Here arrp is an array of pointers to string. We have not specified the size of array, so the size is determined by
the number of initializers. The initializers are string constant. arrp[0] contains the base address of string “white”
similarly arrp[1] contains the base address of string “red”.
100
w h i t e \0
2000
arrp[0] 106
100
arrp[1] 106 r e d \0
arrp[2] 110
arrp[3] 116 110
arrp[4] 123 g r e e n \0
116
y e l l o w \0
123
b l u e \0
152
Dynamic memory allocation
The memory allocation that we have done till now was static memory allocation. The memory that could be
used by the program was fixed i.e. we could not increase or decrease the size of memory during the execution of
program. In many applications it is not possible to predict how much memory would be needed by the program
at run time. For example if we declare an array of integers.
int emp[100];
In an array, it is must to specify the size of array while declaring, so the size of this array will be fixed during
runtime. Now two types of problems may occur.
1. The number of values to be stored is less than the size of array then there will be the wastage of memory.
2. If we want to store more values than the size of array then we can’t.
To overcome these problems we should be able to allocate memory at run time. The process of allocating
memory at the time of execution is called dynamic memory allocation. The allocation and release of this
memory space can be done with the help of some built-in-functions whose prototypes are found in alloc.h and
stdlib.h header files.
Pointers play an important role in dynamic memory allocation because we can access the dynamically allocated
memory only through pointers.
1. malloc ( )
dynamically. syntax:
pointer_variable=(datatype*) malloc(specified_size);
Here pointer_variable is a pointer of type datatype, and specified_size is the size in bytes required to be
reserved in memory.
2. calloc ( )
The calloc ( ) function is used to allocate multiple blocks of memory. It is somewhat similar to malloc ( )
function except for two differences. The first one is that it takes two arguments. The first argument specifies the
number of blocks and the second one specifies the size of each block. For example:
ptr= (int *) calloc (5, sizeof(int));
The other difference between calloc( ) and malloc( ) is that the memory allocated by malloc( ) contains garbage
value while the memory allocated by calloc( ) is initialized to zero.
3. realloc( )
The function realloc( ) is used to change the size of the memory block. It alters the size of the memory block
without losing the old data. This is known as reallocation of memory.
This function takes two arguments, first is a pointer to the block of memory that was previously allocated by
malloc( ) or calloc( ) and second one is the new size for that block. For example
ptr=(int*) realloc(ptr,newsize);
153
1. Program to understand dynamic allocation of memory.
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int *ptr,n,i;
clrscr();
printf("How many numbers do you want to entered: ");
scanf("%d",&n);
ptr=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
printf("\n Enter number: ");
scanf("%d",ptr+i);
}
printf("\nDisplaying elements: ");
for(i=0;i<n;i++)
{
printf("\n%d",*(ptr+i));
}
getch();
}
Output
2. Write a program to sort ‘n’ numbers in ascending order using dynamic memory.
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int *ptr,n,i,j,temp;
clrscr();
printf("How many numbers do you want to entered: ");
154
scanf("%d",&n);
ptr=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
printf("\n Enter number: ");
scanf("%d",ptr+i);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(*(ptr+i)>*(ptr+j))
{
temp=*(ptr+i);
*(ptr+i)=*(ptr+j);
*(ptr+j)=temp;
}
}
}
printf("\nDisplaying sorted elements: ");
for(i=0;i<n;i++)
{
printf("\n%d",*(ptr+i));
}
getch();
}
Output
155
clrscr();
a=5;
b=3;
func(a,b,&sum,&diff,&prod);
printf("sum=%d Difference=%d Product=%d",sum,diff,prod);
getch();
}
void func(int x,int y,int *s,int *d, int *p)
{
*s=x+y;
*d=x-y;
*p=x*y;
}
156
Unit-10
Structure
Introduction
A structure is a collection of logically related data items grouped together under a single name. In structure the
individual elements may differ in type, that’s why we can regard structure as a heterogeneous user-defined data
type. The data items enclosed within a structure are known as members.
struct struct_name
{
data_type mem1;
data_type mem2;
…………………
data_type memn;
};
The structure definition starts with keyword struct followed by an identifier which is a tag name. The tag
name is structure name and can be used for instantiating structure variable. struct_name is referred to as
structure name or structure tag name, and mem1, mem2, memn are known as structure members.
After the structure has been specified, the structure variable can be declared as standard data type:
Example
struct student
{
char name[15];
int roll;
float fee;
};
struct student st;
structvariable_name.member
157
Example
struct student
{
char name[15];
int roll;
float fee;
};
struct student st={“Sonia”,23,1450.50};
Write a program to read name, rollno and fee of a student and display it on screen using structure.
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
char name[15];
int roll;
float fee;
};
struct student st;
clrscr();
printf("Enter name rollno and fee of a student\n");
scanf("%s%d%f",st.name,&st.roll,&st.fee); printf("\
nDisplaying information\n");
printf("Name=%s \nRollno=%d \nFee=%f",st.name,st.roll,st.fee);
getch();
}
Output
Array of structures
We can declare array of structures where each element of array is of structure type.
Example
Define a structure containing members as roll no, name, course and semester and write program to input information
about ‘n’ students and display the name and course of all students.
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int roll;
char name[15];
158
char course[15];
char sem[15];
};
struct student st[100];
int i,n;
clrscr();
printf("\nHow many students are there: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter rollno, name, course and semester: "); scanf("%d%s%s
%s",&st[i].roll,st[i].name,st[i].course,st[i].sem);
}
printf("\nName\tCourse");
for(i=0;i<n;i++)
{
printf("\n%s\t%s",st[i].name,st[i].course);
}
getch();
}
Outpu
t
Nested structure
The members of a structure can be of any data type including another structure type i.e we can include a
structure within another structure. A structure variable can be a member of another structure. This is called
nesting of structure.
Syntax:
struct struct_name1
{
data_type mem1;
data_type mem2;
…………………
data_type memn;
};
struct struct_name2
{
159
data_type mem1;
data_type mem2;
…………………
struct_name1 structure_variable1;
data_type memn;
};
struct_name2 structure_variable2;
Example
Define a structure date having integer members to store day, month and year. Define another structure student having
members as rollno, name and date_of_birth. Now write a program to accept and display information about ‘n’
students.
#include<stdio.h>
#include<conio.h>
void main()
{
struct date
{
int year;
int month;
int day;
};
struct student
{
int roll;
char name[15];
struct date dob;
};
struct student st[100];
int i,n;
clrscr();
printf("\n How many students are there: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter rollno,name and date of birth in (year-month-day): ");
scanf("%d%s%d%d%d",&st[i].roll,st[i].name,&st[i].dob.year,&st[i].dob.month,&
st[i].dob.day);
}
printf("\nRollno\tName\tDOB(Year-Month-Day)");
for(i=0;i<n;i++)
{
printf("\n%d\t%s\t%d-%d-
%d",st[i].roll,st[i].name,st[i].dob.year,st[i].dob.month,st[i].dob.day);
}
getch();
}
160
Output
Pointer to structure
We can have pointer to structure, which can point to the starting address of a structure variable. These pointers
are called structure pointers. While accessing structure members through pointers we have to use arrow operator
(->) which is formed by hyphen symbol and greater than symbol.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
struct customer
{
int id;
char name[15];
char address[15];
};
struct customer cu={1,"Binod","Bharatpur"};
struct customer *ptr;
ptr=&cu;
clrscr();
printf("\n ID :%d",ptr->id); printf("\
n Name :%s",ptr->name); printf("\n
Address :%s",ptr->address); getch();
}
Output
161
Example
#include<stdio.h>
#include<conio.h>
void display(struct customer);
struct customer
{
int id;
char name[15];
char address[15];
};
void main()
{
struct customer cu={1,"Binod","Bharatpur"};
clrscr();
display(cu);
getch();
}
void display(struct customer c)
{
printf("\n ID :%d",c.id); printf("\
n Name :%s",c.name); printf("\n
Address :%s",c.address);
}
Outpu
t
Example
#include<stdio.h>
#include<conio.h>
struct customer
{
int id;
char name[15];
char address[15];
};
void display(struct customer c[]);
void main()
{
struct customer cu[3]={{1,"Binod","Bharatpur"},{2,"Nabin","Pokhara"},
{3,"Dibya","Kathmandu"}
};
clrscr();
display(cu);
162
getch();
163
}
void display(struct customer c[])
{
int i; printf("\nId\tName\
tAddress "); for(i=0;i<3;i++)
{
printf("\n%d\t%s\t%s",c[i].id,c[i].name,c[i].address);
}
}
Output
Write a program that reads names and ages of ‘n’ students into the computer and rearrange the names into
alphabetical order using the structure variables.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
struct student
{
char name[15];
int age;
};
struct student st[100],temp;
int i,j,n;
clrscr();
printf("How many students are there: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter student name and age: ");
scanf("%s%d",st[i].name,&st[i].age);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(st[i].name,st[j].name)>0)
{
temp=st[i];
st[i]=st[j];
st[j]=temp;
}
}
164
}
printf("\nName\tAge");
for(i=0;i<n;i++)
{
printf("\n%s\t%d",st[i].name,st[i].age);
}
getch();
}
Output
Write a C program to enter bid, title, price, pages of 100 book into structure variable called book and sort
them in descending order on the basis of their title with use of pointer.
#include<stdio.h>
#include<string.h>
struct BookDetails
{
int bid,price,pages;
char title[20];
};
void main()
{
int i,j;
struct BookDetails book[100],*temp;
struct BookDetails *ptr[100];
for(i=0;i<100;i++)
{
ptr[i]=&book[i];
}
for(i=0;i<100;i++)
{
printf("Enter id, title, price and pages of books ");
scanf("%d%s%d%d",&book[i].bid,book[i].title,&book[i].price,&book[i].pages);
}
for(i=0;i<99;i++)
{
165
for(j=i+1;j<100;j++)
{
if(strcmp(ptr[i]->title,ptr[j]->title)<0)
{
temp=ptr[i];
ptr[i]=ptr[j];
ptr[j]=temp;
}
}
}
printf("\n Sorted Data in Descending order\n");
for(i=0;i<100;i++)
{
printf("%d\t%s\t%d\t%d\n",ptr[i]->bid,ptr[i]->title,ptr[i]->price,
ptr[i]->pages);
}
}
Write a C program to store the player name, runs scored, wickets taken of 20 cricketers using structure
along with pointer then arrange the players in order of maximum wickets to minimum wickets they had
taken.
#include<stdio.h>
#include<string.h>
struct Circket
{
int runs,wickets;
char name[20];
};
void main()
{
int i,j;
struct Circket c[20],*temp;
struct Circket *ptr[20];
for(i=0;i<20;i++)
{
ptr[i]=&c[i];
}
for(i=0;i<20;i++)
{
printf("Enter name, runs scored and wickets taken by Cricketer: ");
scanf("%s%d%d",c[i].name,&c[i].runs,&c[i].wickets);
}
for(i=0;i<19;i++)
{
for(j=i+1;j<20;j++)
{
if(ptr[i]->wickets<ptr[j]->wickets)
{
temp=ptr[i];
ptr[i]=ptr[j];
ptr[j]=temp;
}
}
166
}
167
printf("\n Sorted Data in Descending order\n");
for(i=0;i<20;i++)
{
printf("%s\t%d\t%d\n",ptr[i]->name,ptr[i]->runs,ptr[i]->wickets);
}
}
Bit fields
The variables defined with a predefined width are called bit fields. A bit field can hold more than a single bit;
for example, if you need a variable to store a value from 0 to 7, then you can define a bit field with a width of 3
bits as follows –
struct
{
unsigned int age: 3;
}age;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
struct
{
unsigned age: 4;
}a;
clrscr();
a.age=3;
printf("%d\n",a.age);
a.age=8; printf("%d\
n",a.age); a.age=16;
printf("%d\n",a.age);
getch();
}
Output
Union
Union is a derived data type like structure which can contain members of different data type. Union members
share the same memory locations. Compiler allocates sufficient memory to hold the largest member in the
union. We can use only one member at a time. Union provides an efficient way of reusing the memory location
as only one of its members can be accessed at a time.
168
union union_name
{
data_type mem1;
data_type mem2;
…………………
data_type memn;
};
Like structure variable union variable is also needed to be declared for accessing members of union.
Syntax
Example
#include<stdio.h>
#include<conio.h>
void main()
{
union student
{
int roll;
char name[15];
};
union student st;
clrscr();
printf("\n Enter roll no: ");
scanf("%d",&st.roll); printf("
Rollno :%d",st.roll);
printf("\n Enter name: ");
scanf("%s",st.name);
printf(" Name :%s",st.name);
getch();
}
Output
169
4. Every element value’s are independent to each4. If any of the values of any element has been
other. changed there is direct impact to the other
elements values.
5. Memory allocation of every element is 5. Memory allocation is performed by sharing the
independent to each other thereby the memory memory with highest data type.
allocation is sum of every element.
6. All members can be accessed simultaneously. 6. Only one member is active at a time, so only one
member can be accessed at a time.
7. Syntax 7. Syntax
struct struct_name union union_name
{ {
………………… …………………
}; };
data_type mem1;
data_type mem2;
170
…………………
data_type memn;
};
171
Unit-11
Data File Handling
Concept of file
File is a collection of related data placed on the disk. C support the concept of files through which data can be
stored on the disk or secondary storage device. The stored data can be read whenever required.
printf
sca Memory
Input Output
fputc fgetc
fputs fgets
fprintf fscanf
fwrite fread
Opening a File
A file must be opened before any I/O operations performed on that file. The process of establishing a
connection between the program and file is called opening the file. A structure named FILE is defined in the file
stdio.h that contains all information about the file like name, status, buffer size, current position, end of file
status etc. All these details are hidden from the programming and the operating system takes care of all these
things.
A file pointer is a pointer to a structure of type FILE. Whenever a file is opened, a structure of type FILE is
associated with it and a file pointer that points to this structure identifies this file.
Eg:
FILE *fp;
172
Closing of file
The file that was opened using fopen ( ) function must be closed when no more operations are to be performed
on it. After closing the file, connection between file and program is broken.
On closing the file, all the buffers associated with it are flushed i.e all the data that is in the buffer is written to
the file. The buffers allocated by the system for the files are freed after the file is closed, so that these buffers
can be available for other files.
Although all the files are closed automatically when the program terminates, but sometimes it may be necessary
to close the file by using fclose( ) function.
Modes
The different file modes that can be used in opening file are:
1. “w” (write) If the file doesn’t exist then this mode creates a new file for writing, and if the
file already exists then the previous data is erased and the new data entered is
written to the file.
2. “a” (append) If the file doesn’t exist then this mode creates a new file and if the file already
exists then the new data entered is appended at the end of existing data. In this
mode, the data existing in the file is not erased as in “w” mode.
3. “r” (read) This mode is used for opening an existing file for reading purpose only. The
file to be opened must exist and the previous data of the file is not erased.
4. “w+” (write + read) This mode is same as “w” mode but in this mode we can also read and modify
the data. If the file doesn’t exist then a new file is created and if the file exists
then previous data is erased.
5. “r+” (read + write) This mode is same as “r” mode but in this mode we can also write and modify
existing data. The file to be opened must exist and the previous data of file is
not erased. Since we can add new data and modify existing data so this mode is
also called updata mode.
6. “a+” (append + read) This mode is same as the “a” mode but in this mode we can also read the data
stored in the file. If the file doesn’t exist, a new file is created and if the file
already exists then new data is appended at the end of existing data. We cannot
modify existing data in this mode.
173
Text mode
In text mode every digit or text are stored as a character and while reading the content back, the
conversion is required from character to appropriate format and takes lots of space.
Character I/O, string I/O, and formatted I/O use text mode.
If 3.14159 is stored in character mode file size would be 8 bytes (counts each character including
decimal and EOF).
Binary mode
In binary mode every digit or text is stored in binary format and while reading the content no conversion
is necessary and takes little space.
fread ( ) and fwrite ( ) are used in binary mode.
If 3.14159 is stored in character mode file size would be 4 bytes.
Input/Output Functions
The functions used for file input/output are
1. Character I/O
a. fputc( )
This function writes a character to the specified file at the current file position and then increments the file
position pointer.
b. fgetc( )
This function reads a single character from a given file and increments the file pointer.
c. getc( ) and putc( )
The operation of getc( ) and putc( ) are exactly similar to that of fgetc( ) and fputc( ) , the only difference
is that the former two are defined as macros while the latter two are functions.
2. Integer
I/O
a. putw( )
This function writes an integer value to the file pointed to by file_pointer.
b. getw( )
This function returns the integer value from the file associated with file_pointer.
3. String I/O
a. fputs( )
This function writes the null terminated string pointed by given character pointer to a file.
b. fgets()
This function is used to read characters from a file and these characters are stored in the string pointed
by a character pointer.
4. Formatted I/O
a. fprintf( )
This function is same as the printf( ) function but it writes formatted data into the file instead of the
standard output(screen). This function has same parameters as in printf( ) but it has one additional
parameter which is a pointer of FILE type, that points to the file to which the output is to be written.
b. fscanf( )
This function is similar to the scanf( ) function but it reads data from file instead of standard input, so it
has one more parameter which is a pointer of FILE type and it points to the file from which data will be
read.
5. Block Read/Write
a. fwrite( )
This function is used for writing an entire block to a given file.
174
b. fread( )
This function is used to read an entire block from a given file.
175
Output
Write a program to modify the record of student from a file named “student.txt”.
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int sno;
char name[10];
char add[10];
};
struct student st;
FILE *fp;
int n,i;
clrscr();
printf("No of students ");
scanf("%d",&n);
fp=fopen("student.txt","w+");
for(i=0;i<n;i++)
{
printf("Enter Symbolno, name and address ");
scanf("%d%s%s",&st.sno,st.name,st.add);
fwrite(&st,sizeof(st),1,fp);
}
rewind(fp); printf("\nSymNo\tName\
tAddress\n");
while(fread(&st,sizeof(st),1,fp)==1)
{
printf("%d\t%s\t%s\n",st.sno,st.name,st.add);
}
fclose(fp);
fp=fopen("student.txt","r+");
long int size=sizeof(st);
176
int mid;
printf("\nEnter Symolno of student to modify record ");
scanf("%d",&mid);
while(fread(&st,sizeof(st),1,fp)==1)
{
if(st.sno==mid)
{
printf("\nEnter name and address to modify ");
scanf("%s%s",st.name,st.add);
fseek(fp,-size,1);
fwrite(&st,sizeof(st),1,fp);
break;
}
}
rewind(fp); printf("\nSymNo\tName\
tAddress\n");
while(fread(&st,sizeof(st),1,fp)==1)
{
printf("%d\t%s\t%s\n",st.sno,st.name,st.add);
}
fclose(fp);
getch();
}
Output
177
fclose(fp);
rename("fil.txt","newfil.txt"); /* rename the file name to newfil.txt */
remove("newfil.txt"); /* removes(delete) file newfil.txt */
getch();
}
Write a program to copy contents of one file to another
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2;
char ch;
clrscr();
fp1=fopen("abc.txt","r");
fp2=fopen("xyz.txt","w");
while((ch=getc(fp1))!=EOF)
{
putc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
getch();
}
Program to understand fputc( ) and fgetc(
). #include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("abc.txt","w");
printf("Enter text (Press ctrl+z to stop reading character)\n");
while((ch=getchar())!=EOF)
{
fputc(ch,fp);
}
fclose(fp);
fp=fopen("abc.txt","r");
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
fclose(fp);
getch();
}
Output
178
#include<conio.h>
void main()
{
FILE *fptr;
char ch;
printf("\n Enter any character: ");
scanf("%c",&ch);
fptr=fopen("abc.txt","w");
putc(ch,fptr);
fclose(fptr);
fptr=fopen("abc.txt","r");
ch=getc(fptr);
printf("\n %c",ch);
getch();
}
Output
Output
179
Program to understand fputs( ) and fgets(
). #include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
char str[80];
fptr=fopen("abc.txt","w");
printf("Enter the text (Press ctrl+z to stop entering) \n"); while(gets(str)!
=NULL)
fputs(str,fptr);
fclose(fptr);
fptr=fopen("abc.txt","r");
while(fgets(str,80,fptr)!=NULL)
{
puts(str);
}
fclose(fptr);
getch();
}
Output
180
for(i=0;i<n;i++)
{
printf("\n Enter rollno and name of student: ");
scanf("%d%s",&st.roll,st.name); fprintf(fp,"\n%d
%s",st.roll,st.name);
}
fclose(fp);
fp=fopen("student.txt","r");
printf("\n Rollno\tName");
while(fscanf(fp,"%d%s",&st.roll,st.name)!=EOF)
{
printf("\n %d\t%s",st.roll,st.name);
}
fclose(fp);
getch();
}
Output
Write a C program to accept 100 numbers from user and store them in odd.txt file (if number is odd) or even.txt
file (if number is even) then display odd numbers reading from odd.txt file.
#include<stdio.h>
void main()
{
FILE *fp1,*fp2;
int i,value;
fp1=fopen("odd.txt","w+");
fp2=fopen("even.txt","w");
for(i=1;i<=100;i++)
{
printf("Enter number: ");
scanf("%d",&value);
if(value%2==1)
putw(value,fp1);
else
181
putw(value,fp2);
}
rewind(fp1);
while((value=getw(fp1))!=EOF)
{
printf("%d\n",value);
}
fclose(fp1);
fclose(fp2);
}
182
Unit-12
Introduction to graphics
In a C Program first of all you need to initialize the graphics drivers on the computer. This is done using the
initgraph method provided in graphics.h library.
Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered
driver) then putting the system intographics mode.Initgraph also resets all graphics settings (color, palette,
current position,viewport, etc.) to their defaults, then resets graphresult to 0
*graphdriver
Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of
the graphics_drivers enumeration type.
*graphmode
Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver =
DETECT, initgraph sets *graphmode to the highest resolution availablefor the detected driver. You can give
*graphmode a value using a constant of thegraphics_modes enumeration type.
*pathtodriver
Specifies the directory path where initgraph looks for graphics drivers (*.BGI) first.1.If they're not there,
initgraph looks in the current directory.2.If pathtodriver is null, the driver files must be in the current directory.
Graphics function
There are numerous graphics functions available in c. But let us see some to have an understanding of how and
where a pixel is placed in each when each of the graphics function gets invoked.
Function:
putpixel(x, y, color)
Purpose:
The functionality of this function is it put a pixel or in other words a dot at position x, y given in inputted
argument. Here one must understand that the whole screen is imagined as a graph. In other words the pixel at
the top left hand corner of the screen represents the value (0, 0).Here the color is the integer value associated
with colors and when specified the picture element or the dot is placed with the appropriate color associated
with that integer value.
183
Function:
Purpose:
The functionality of this function is to draw a line from (x1,y1) to (x2,y2).Here also the coordinates are passed
taking the pixel (0,0) at the top left hand corner of the screen as the origin. And also one must note that the line
formed is by using number of pixels placed near each other.
Function:
Function:
ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius);
Ellipse is used to draw an ellipse (x,y) are coordinates of center of the ellipse, stangle is the starting angle, end
angle is the ending angle, and fifth and sixth parameters specifies the X and Y radius of the ellipse.
Function:
use to draw an arc with center at (x, y) and given radius. start_angle is the starting point of angle and end_angle
is the ending point of the angle. The value of the angle can vary from 0 to 360 degree.
Function:
getpixel(x, y)
Purpose:
This function when invoked gets the color of the pixel specified. The color got will be the integer value
associated with that color and hence the function gets an integer value as return value. So the smallest element
on the graphics display screen is a pixel or a dot and the pixels are used in this way to place images in graphics
screen in C language.
Example
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
184
initgraph(&gd,&gm,"c:\\tc\\bgi");
circle(300,200,150);
setcolor(WHITE);
getch();
closegraph();
}
Output
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
line(90,70,60,100);
line(200,100,150,300);
setcolor(WHITE);
getch();
closegraph();
}
185
Output
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
rectangle(200,100,500,200);
setcolor(WHITE);
getch();
closegraph();
}
Output
186
Write a program to draw a triangle.
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
line(200,100,10,20);
line(10,20,50,60);
line(50,60,200,100);
setcolor(WHITE);
getch();
closegraph();
}
Output
Write a program to draw two concentric circles with centre (300,200) and radii 75 and 125.
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
circle(300,200,75);
circle(300,200,125);
setcolor(WHITE);
getch();
closegraph();
}
Output
187
Write a C program to generate following output using graphics functions.
BCA
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm; initgraph(&gd,&gm,"c:\\tc\\
bgi"); circle(100,100,500,300);
outtextxy(100,100,”BCA”);
setcolor(WHITE);
getch();
closegraph();
}
Output
188
Tribhuvan University
Faculty of Humanities and Social Sciences
OFFICE OF THE DEAN
2018
Bachelor in Computer Applications Full marks: 60
Course Title: C Programming Pass Marks: 24
Code No: CACS 151 Time: 3 hours
Semester: II
Centre: Symbol No:
Candidates are required to answer the questions in their own words as far as possible.
Group A
Attempt all the questions. [10×1=10]
1. Circle ( ) the correct answer in the following questions.
i. Which one of the following doesn’t require an & for the input in scanf()?
a) char name[10]; b) int name[10];
c) float name[10]; d) double name[10];
ii. What is memory size of float data type in C?
a) 4 Bytes b) 8 Bytes
c) Depends on the system/compiler d) Cannot be determined
iii. What will be the output of following C code?
#include<stdio.h>
int main()
{
int x=3,y; y=(+
+x)+(x++);
printf(“%d”, y);
return 0;
}
a) 6 b) 8 c) 7 d) 9
iv. Which keyword is used to come out of a loop only for that iteration?
a) break b) continue c) return d) void
v. Bitwise operators can operate upon
a) Double and chars b) floats and doubles
c) int and floats d) int and chars
vi. In C if you pass an array as an argument to a function, what actually gets passed?
a) Value of elements in an array b) First element in an array
c) The address of first element in an array d) The address of last element in an array
vii. Which operator is used to access the members of strucuture using strucuture variable?
a) Address operator (&) b) Dot operator (.)
c) Pointer operator (*) d) Arrow operator()
viii. Which function is used to record input from file?
a) ftell() b) fwrite() c) fprintf() d) fread()
ix. which of the following is the keyword used for storage class?
a) printf b) goto c) external d) break
x. What will be the size of following union declaration?
union test
{
int x;
char y;
float z;
}
a) 8 bytes b) 13 bytes c) 1 byte d) None of the following
Tribhuvan University
Faculty of Humanities and Social Sciences
OFFICE OF THE DEAN
2018
Group C
Attempt any TWO questions. [2×10= 20]
18. What is one dimensional array? How it is initialized? Write a C program to find [1+1+8]
the sum of two matrix of order m×n.
19. Define structure and union. Write a C program using structure that reads the [2+8]
records of students with members roll, name, address and makes and display the
record of students who have obtained greater than 250 marks.
20. What is function? List its advantages. Explain the concept of function call by [1+2+7]
value and function call by reference with example.
Tribhuvan University
Faculty of Humanities and Social Sciences
OFFICE OF THE DEAN
2020
Bachelor in Computer Applications Full marks: 60
Course Title: C Programming Pass Marks: 24
Code No: CACS 151 Time: 3 hours
Semester: II
Centre: Symbol No:
Candidates are required to answer the questions in their own words as far as possible.
Group A
Attempt all the questions. [10×1=10]
1. Circle ( ) the correct answer in the following questions.
i. Which compilation unit is responsible for adding header files content in the source code?
a) Linker b) Compiler c) Assembler d) Preprocessor
ii. What is the meaning of the following line of code?
void sum(int, int)
a) sum is function which takes int arguments
b) sum is a function which takes two int arguments and return void
c) it will produce compilation error
d) Can’t comment
iii. Which header file is essential for using strcmp() function?
a) string.h b) stringhs.h c) text.h d) strcmp.h
iv. Which of the following is not a branching statement in C?
a) return b) goto c) pointer d) continue
v. Array can be considered as set of elements stored in consecutive memory locations but having
………….
a) Same data type b) Different data type
c) Same scope d) None of the above
vi. If int a=5, b=8, then what will be the value of int c = b++ - a-- ?
a) 3 b) 4 c) 2 d) None of the above
vii. Suppose you are a piece of code, circle (100, 100, 50); in C, then what is meant by 50?
a) center b) diameter c) perimeter d) radius
viii. Suppose that the code:
struct student
{
char name[20];
int age;
char address[25];
}std;
Then what is the size of std?
a) 47 bytes b) 20 bytes c) 25 bytes d) None of the above
ix. Suppose you are given a piece of code:
int a=5, *b;
b= &a;
printf(“%u”,b);
Then, what will be the output?
a) 5 b) address of a c) address of b d) garbage value
x. Which of the following is not a valid file opening mode?
a) read b) write execute c) append
Tribhuvan University
Faculty of Humanities and Social Sciences
OFFICE OF THE DEAN
2020
4. Define an array? Write program to generate the following output using loop. [1+4]
1
12
12 3
12 3 4
12 3 4 5
5. Define operator. Explain any four types of operators available in C? [1+4]
BCA Program
Group C
Attempt any TWO questions. [2×10= 20]
9. What is union? Write a C program to enter bid, title, price, pages of 100 book into [2+8]
structure variable called book and sort them in descending order on the basis of
their title with use of pointer.
10. What is the use of data file in C? Write a C program to accept 100 numbers from [1+9]
user and store them in odd.txt file (if number is odd) or even.txt file (if number is
even) then display odd numbers reading from odd.dat file.
11. What do you mean by System Design Tools? Explain any four system design tools [2+8]
with suitable example.
Tribhuvan University
Faculty of Humanities and Social Sciences
OFFICE OF THE DEAN
2021
Bachelor in Computer Applications Full marks: 60
Course Title: C Programming Pass Marks: 24
Code No: CACS 151 Time: 3 hours
Semester: II
Centre: Symbol No:
Candidates are required to answer the questions in their own words as far as possible.
Group A
Attempt all the questions. [10×1=10]
1. Circle ( ) the correct answer in the following questions.
i. Among unary operation which operator represents increment?
a) -- b) ++ c) -+ d) !+
ii. If the function returns no value, then it is called ………..
a) Data type function b) Calling function
c) Main function d) Void function
iii. What are the C functions used to read or write a file in Binary Mode?
a) fprintf(), fscanf() b) fread(), rwrite()
c) read(), write() d) getw(), putw()
iv. An entire array is always passed by...................to a called function.
a) Call by value b) Address relocation
c) Call by reference d) Address restructure
v. What is actually passed if you pass a structure variable to a function?
a) Copy of structure variable b) Reference of structure variable
c) Starting address of structure variable d) Ending address of structure variable
vi. Choose a correct statement about C Escape Sequences.
a) \’ outputs one Single Quote. Right Single b) \” outputs one Double Quote.
Quote.
c) \\ produces one Visible Back Slash \. d) All the above.
vii. What is the keyword used to define a C macro?
a) def b) definition c) define d) defy
viii. What is the first step in C program building process?
a) Compiling b) Assembling c) Linking d) Preprocessing
ix. Choose a correct C statement about String functions?
a) strrev(“abcD”) returns Dcba.
b) strcmp(“abc”,”bcd”) returns a negative number
c) strcmp(“234”,”123”) returns a positive number
d) All the above
x. Choose a syntax for C Ternary Operator from the list.
a) Condition?expression1:expression2 b) Condition:expression1?expression2
c) Condition?expression1<expression2 d) Condition<expression1?expression2
Tribhuvan University
Faculty of Humanities and Social Sciences
OFFICE OF THE DEAN
2021
6. Write a C program to copy contents of student.txt file into another file called info.txt. [5]
7. Why do you use DMA instead of array? Explain DMA with suitable example. [2+3]
BCA
Group C
Attempt any TWO questions. [2×10= 20]
9. Write a C program to store the player name, runs scored, wickets taken of 20 [10]
cricketers using structure along with pointer then arrange the players in order of
maximum wickets to minimum wickets they had taken.
Sum=1+ + + + ⋯..............+
𝑥2
to3generate following series
𝑥 𝑥𝑛
10. Write a C program using function:
𝑥
[10]
1! 2! 3! 𝑛!
11. Define SDLC. Explain software process models. [2+8]