0% found this document useful (0 votes)
7 views241 pages

Computer Programming Basics Explained

The document provides an overview of computer programming, covering the basics of computers, their components (hardware and software), and the distinction between system and application software. It explains the role of programming languages, classifying them into low-level and high-level languages, and discusses their advantages and disadvantages. Additionally, it highlights the importance of understanding computer fundamentals for effective use in various fields.

Uploaded by

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

Computer Programming Basics Explained

The document provides an overview of computer programming, covering the basics of computers, their components (hardware and software), and the distinction between system and application software. It explains the role of programming languages, classifying them into low-level and high-level languages, and discusses their advantages and disadvantages. Additionally, it highlights the importance of understanding computer fundamentals for effective use in various fields.

Uploaded by

9216 Binaya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Programming

Basics of Computer
Computers have become an important part of our daily lives and an integral part of the working
environment. Because of its accuracy and speed computers are used in banking, business, schools,
labs, home and at different engineering fields and industries. To understand todays fastest growing
technology it has been essential to know the basics of computer.

Introduction to Computer
The term computer is derived from word ‘compute’ which means to calculate. Computer is
basically a group of electronic devices that can accept data, conduct a series of arithmetic and
logical operations on it and give result of these operations as information that is useful to people.
It is a machine that performs pre-defined or programmed computations or control operations that
are expressible in numerical and logical form at a high speed and with great accuracy. In other
words, Computer is an electronic device capable of performing commands and these commands
are basically input, output, storage, arithmetic and logical operations.
A computer is a programmable electronic device that accepts raw data and instruction from

MKS
input device, process data and provides output as information in output device.
All the modern computers are digital and represents information in binary digits. They represent
data using two distinct values. In binary system we have only two digits (bits) – 0 and 1 to represent
data. Since the bit is a very small unit, virtually, it cannot convey much information while used
single. A combination of eight bits is called a byte. A byte is the fundamental unit of data
representation in computer. A byte can represent one character of data. Modern computers are
capable of processing more than one byte at a time.

Computer System
A computer system consists of two major components, namely, hardware and software. All
physical components that forms computer system are known as computer hardware. Software is
basically collection of different programs that tells computer’s hardware what to do.

Figure: - Computer System

Manish Kumar Shah(MKS) 1


1 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Hardware
All physical components that make up a computer is known as computer hardware. It includes all
components that we can see and touch i.e. processor, input devices like keyboard, mouse, output
devices like visual display unit (VDU), printer, speaker, connecting wires, casing, storage devices
etc. Block diagram depicting major components of computer is shown below:

Central Processing Unit

Control Unit

Arithmetic Logic Unit

MKS
Input Unit Output Unit

Memory Unit

Main Memory

Secondary Storage

Figure: - Computer Block Diagram

Computer hardware consists of different functional units: input unit, central processing unit (CPU)
which consists arithmetic logic unit (ALU) and control unit (CU), memory unit and output unit.
Computer accepts digital data from user with the help of input devices like mouse, keyboard,
microphone etc. Received data from user is either stored in the memory for later use or
immediately processed by the arithmetic and logic unit to carry out the desired operations. After
processing, processed output known as information is either stored in memory for later use or sent
Manish Kumar Shah(MKS) 2
2 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
to user with the help of output devices like monitor, printer, speaker etc. All the above mentioned
activities are controlled and coordinated by the control unit.

Software
Set of instructions that tells the computer hardware what to do is known as computer program.
This program or collection of such programs is known as computer software. Concept of software
is illustrated in following figure:

Instruction 1
Instruction 2
.
.

Instruction N
Program 1

MKS
Instruction 1 Software
Program 2
Instruction 2 .
. .
. Program N
Instruction N

Instruction 1
Instruction 2
.
.

Instruction N

Figure: - Illustration of Software


Software guides and tells computer hardware how to accomplish a task. Computer software can
be categorized into two broad categories as system software and application software as shown in
figure below.

Manish Kumar Shah(MKS) 3


3 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Figure: - Categories of Software


System software are set of programs which are used to control computer activity and computer
hardware. System software also provides platform for application software. Application software
are those programs which are designed to perform specific task and application software requires
system software for their existence. Relationship among hardware, different software and user is
shown in following figure.

MKS Users

Application Software

System Software

Hardware

Figure: - Relationship Among Hardware, Different Software and User


Manish Kumar Shah(MKS) 4
4 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
System Software
These are set of computer programs which are required for controlling and managing the hardware
resources of a computer system. System software is required for the proper functioning of the
computer. System software usually interacts with hardware and provides platform for running
application software. In general system software controls overall computer hardware and computer
activity at the same time providing service to user.
Different examples of system software are:
a) Operating System
An operating system is collection of computer programs that guides the computer hardware
to do different activities under variety of conditions. System software provides common
core services required for other software to run. It also performs resource management and
provides interface between the user and machine. The basic functions of operating systems
are:
- Process Management
- Memory Management
- File Management
- Device Management
- Security Management

MKS
- Creating User Interface

b) Device Drivers
Device drivers are set of computer program that controls the operation and functionality
of different devices. Computer system is generally associated with different devices such
as keyboard, mouse, monitor, printer. Functioning of these device is controlled by device
drivers. Each device in the computer system has a device driver associated with it for
proper functioning.

D Printer
R
I
Computer System V Monitor
E
R
S LAN

Figure: - Illustration of Device Drivers

Manish Kumar Shah(MKS) 5


5 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
c) Language Translators
Since computer understands language consisting 0s and 1s. Language translators are
computer programs which translates program written in programming language to machine
language consisting sequence of 0s and 1s.

Program Written in Machine


Programming Language Language Translators Understandable
(Source Code) Code

Figure: - Illustration of Language Translators

d) Utility Software
Like hardware, software in computer also needs maintenance. Utility software are
programs that are used to maintain, support, enhance and secure existing program. Example
of utility software includes back up software, antivirus, data recovery software, disk
management etc.

MKS
Application Software
These are set of computer programs which are designed to perform specific task. Application
software needs system software for its existence. User comes in contact with application software
to accomplish certain task and system software performs most of the tasks required for application
software in background. Most commonly used application software are:
a) Word Processors
These are used for creating documents such as letters, reports, articles etc. in required
format. Example includes Microsoft Word, Word Perfect etc.

b) Spreadsheets
These are used for storing records, simple graphical tools, accounting tools, simple
calculations and numerical operations on data. Spreadsheets consists rectangular grids
which contains different cells. Example includes Microsoft Excel, Google Spreadsheets
etc.

c) Image Editors
These applications are used for manipulation like rotation, cropping, zooming, changing
appearance, adjusting contrast etc. on images. Example includes Adobe Photoshop, Adobe
Illustrator, Picasa, Microsoft Paint etc.

d) Database Management System (DBMS)


These are used for storing, extraction and manipulation of data. Example includes
Microsoft Access, Oracle, MySQL etc.

Manish Kumar Shah(MKS) 6


6 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

e) Web Browsers
These are used for accessing world wide web (www). Example includes Google Chrome,
Firefox, Microsoft Edge etc.

Difference Between System Software and Application Software


Differences between system software and application software are tabulated as follow:
S.N. System Software Application Software

1. Set of computer programs that are Computer program that is designed to


designed to control computer hardware perform specific task.
and to provide service.

2. System software manages computer Application software manages their


resources and provides platform for the specific tasks to suit their needs.
execution of application software.

MKS
3. System software can exist as a lone Application software needs system
entity. software for its existence.

4. Examples: MS Windows, Mac OS, Examples: Web browsers, Word processor,


Unix, Linux etc. Image Editors, Spreadsheets etc.

Programming Language
Programming languages are the basic building blocks for all software, allowing people to tell
computers what to do and the means by which software are developed. A programming language
or computer language is a standardized communication technique for expressing instructions to a
computer. To communicate with computer, we need to use language which computer can
understand and process i.e. programs should be written in computer understandable languages
called programming languages. Programming language consists of a set of characters, symbols
and set of rules known as syntax rule. Programmer has to follow all specified rules strictly to get
desired results. In general, programming language is a set of syntactic and semantic rules used to
define computer programs.
Programming languages are generally classified in two categories; they are low level language &
high level language.

Manish Kumar Shah(MKS) 7


7 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Figure: - Categories of Programming Language

1. Low Level Language


A low level language is a programming language that is much closer to the hardware. It
requires a thorough knowledge of the hardware for which the program is being created. It
can be divided into two types, machine language and assembly language.

A) Machine Language

MKS
Computer understands only machine language that uses 0s and 1s. It is the lowest level
language that computer understands. In machine language different instructions are formed
by taking combinations of 0s and 1s. The computer converts all high level languages into
machine language before executing any statements. Machine language is written in binary
form that a computer can execute directly. These are also known as machine code or object
code. This language is not feasible for humans to use because it consists entirely of binary
numbers. If the word length of the machine is 16 bits (two byte) and we have to add two
numbers (say 2 and 4) then we have to remember binary number that is used for addition
(say 0100000011001100). This language is fastest in terms of execution in the sense that
it does not need to be translated.

Advantages of Machine Language


a) Translation Free: Machine language is the only language that computer understands.
Program written in languages other than machine language must be translated to
machine language. However, the program written in machine language can be directly
executed without any translation.
b) High Speed: Since program written in machine language need not to be translated and
hence conversion time is saved which enables execution of machine language program
extremely fast.

Manish Kumar Shah(MKS) 8


8 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Disadvantages of Machine Language
a) Machine Dependent: Program written in machine language are machine dependent
and hence program developed for one system does not execute on other system.
b) Complex Language for Programming: Since machine language consists only
sequence of 0s and 1s, so it is very difficult for programmer to remember and write
each instructions.
c) Error Prone: While programming using machine language everything need to be
expressed in sequence of 0s and 1s which is very tedious task. So errors are frequently
occurred while programming using machine language.
d) Time Consuming: Writing program in machine language is time consuming process.

B) Assembly Language
Instruction formed by using 1s and 0s i.e. using binary numbers are hard to remember and
it is tedious to program using it. In assembly language the binary bits are replaced by certain
keywords which are known as mnemonic. These mnemonics are in fact abbreviated letters
which are much easier to remember. In the above example, if 0100000011001100 is
instruction used to add two numbers, then ADD would be the easiest mnemonic to

MKS
remember for it. This language is easier to learn than machine language. An assembler is
used to convert assembly language into machine language. It is still faster as compared to
high level language but slower than lowest level language (Machine language) due to the
requirement of translation.

Assembly Language Machine Language


Program Assembler Program
(Source Code) (Object Code)

Figure: - Working of an Assembler

Advantages of Assembly Language


a) Easy to Understand and Use: Assembly language uses mnemonic codes which are
easy to use and remember. So, errors which can occur while writing program using
assembly language are less as compared to writing program using machine language.
Also, assembler provides a way to locate and correct errors.
b) Speed: Program written in assembly language executes faster than program written
high level language.

Manish Kumar Shah(MKS) 9


9 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Disadvantages of Assembly Language
a) Machine Dependent: Program written in assembly language are machine dependent
and hence program developed for one system does not execute on other system.
b) Difficult to Learn: Since assembly language is machine dependent so every type of
computer architecture requires a different assembly language. Programmer need to
study and understand different mnemonic code according to the architecture used.
c) Slow Program Development Time: Developing program in assembly language is
slow process as compared to high level language.

2. High Level Language


High level language is much closer to human language so it is more suitable to write code
in high level language. It is more or less independent of the particular type of computer
used (i.e. more portable) and has its own set of rules called syntax. Its main advantage is
that it is easier to read, write and maintain. The first high level programming languages
were designed in the 1950s. Now there are dozens of such languages available such as
BASIC, COBOL, C, C++, FORTRAN, LISP, PASCAL, prolog, etc. This language is lot
slower in terms of execution as compared to low level language. Compiler or interpreter is
used to convert high level language to machine language.

High Level

MKS
Language Program
(Source Code)
Compiler
or
Interpreter

Figure: - Working of Compiler/Interpreter


Machine Language
Program
(Object Code)

Advantages of High Level Language


a) Easy to Use and Understand: High level language uses English like words and they
are closer to natural language which makes easy to learn and understand. Programmer
need not to understand detailed computer architecture for writing programs using high
level language.
b) Machine Independent: Programs written in high level language are portable and
hence program written using high level language can be executed on any type of
computer with little or no modification at all.
c) Debugging is Easy: High level language makes easier to write and debug a program
and gives the programmer time to think about overall logic rather than thinking about
program code. Because of the use of compilers and interpreters, errors can be detected
and located easily.
d) Easy to Maintain Program: Modification and maintenance of program written in high
level language is easy compared low level language.

Manish Kumar Shah(MKS) 10


10 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Disadvantages of High Level Language


a) Poor Control on hardware: Since high level languages are away from hardware and
programmer does not need to be aware of hardware, accessing and controlling hardware
directly is difficult.
b) Slow Execution: Program written in high level language need to be translated to
machine language. This translation process increases the execution time of program.

A high level language can be further categorized into object oriented and procedural
programming language.

A) Procedure Oriented Programming Language


Procedural programming is based upon the idea of series of procedure calls. A programmer
writing program in this language can exactly specify a sequence of steps in order to perform
a particular task. Languages which express step-by-step algorithms written to solve a
problem are known as procedural languages. A procedure may be a program in itself that
may be called within a main program, a subroutine or another program. A programmer

MKS
knows exactly what is to be accomplished at the end of the program and uses a sequence
of algorithmic steps in order to achieve it. C language is example of procedure oriented
programming language.

B) Object Oriented Programming Language


In object oriented programming; the data (i.e. variables) and code are combined to form
objects. This allows more effective code duplication which is not the case when programs
are divided into subroutines (or functions). The required programming parts can be called
again and again within the program. Its main distinction with procedural programming is
that in procedural programming task is divided into subroutines, structures and functions.
Whereas in object oriented programming, data as well as functions and subroutines are
encapsulated to form objects. C++ language is example of object oriented programming
language.
Difference between Low Level Language and High Level Language
S.N. Low Level Language High Level Language
1. Low level programming languages are High level language programming
machine dependent that means program languages are machine independent that
written in low level language are not means program written in high level
portable. language are portable.
2. Low level language programs are faster High level language programs are slower
because they do not require much because they require translation.
translation.

Manish Kumar Shah(MKS) 11


11 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
3. Programming in low level language Programming in high level language do
require knowledge of the computer not require knowledge of the computer
hardware. hardware.
4. Debugging and testing is difficult. Debugging and testing is easier as
compared to low level language.
5. Low level languages are difficult to learn. High level languages are easy to learn.
6. Low level language provide no or less High level language provide high
abstraction from hardware. abstraction form hardware.
7. Example: Machine language and Example: C, Java, C++, Python etc.
Assembly language.

Generation of Programming Language


Programming languages are classified into five generations depending upon the power and
flexibility of programming styles.
1. First Generation Programming Language (1GL)
There was no strict demarcation between first and second generation languages in early
days of its creation. In fact, the terms were not used until third generation programming

MKS
language emerged. The first generation programming language consisted entirely of binary
numbers which were entered through the front panel switches of the computer system; thus,
they are appropriately named as machine level language. The main and perhaps the only
benefit in writing machine level language is that the code written by the user does not
require any translation and hence can run very fast and efficiently. This language is far
more difficult to learn than other generational programming languages and it is equally
difficult to trace errors, if any were to occur. Instructions (programs) are stored in memory
locations sequentially and therefore entire code needs to be changed if insertion or deletion
in the code needs to be made. Furthermore, this generation of programming language is
significantly less portable than other generation of languages.

2. Second Generation Programming Language (2GL)


Assembly level languages are suitably included in second generation of programming
language since their creation immediately followed the emergence of first generation
programming language. The tedious coding consisting entirely of numbers is somewhat
eliminated in this language, since certain mnemonics are used in place of numbers.
However, translation is required to convert these mnemonics into machine code. Therefore,
the coding process is slower than machine language. The language is specific to particular
processor or family thus less portable than other higher generational languages. Although
primitive, this language is still widely used to program microcontrollers, device drivers,
etc.

Manish Kumar Shah(MKS) 12


12 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
3. Third Generation Programming Language (3GL)
As a refined version of second generation programming language, the third generation
programming language emerged which brought a structured logic to the software, making
programming more user friendly. The high level languages of this generation are more
English-like in structure where each and every statement is taken from natural language.
The codes written in this language need to be translated, which is done by a compiler or
interpreter. Due to this translation process the codes run much slower. The codes are easier
to edit and debug and are machine independent. A programmer does not require the
hardware and details of the machine being programmed. Examples of 3GL are C, C++, C#,
PASCAL, FORTRAN, JAVA, etc.

4. Fourth Generation Programming Language (4GL)


The fourth generation programming language is one step ahead of the third generation
programming language. There are fewer options for the programmers, but the programs
are much easier to write and debug than 3GLs. There built in GUI (Graphical user
interfaces) objects like buttons, dropdown menus, add-ins, etc. and no separate code needs
to be written for them. These languages are particularly developed with the viewpoint of
solving a particular class of problem. Given the right kind of problem, the use of an

MKS
appropriate 4GL can be spectacularly successful. All 4GLs are designed to reduce
programming effort, the time it takes to develop software, and the cost of software
development. Compilers and interpreters are still needed to convert it into machine code.
Thus a single line code in this language is equivalent to more lines of coding in lower level
language. Therefore, the programs generated using these languages are larger and much
slower. For e.g. SQL, ORACLE, MATLAB, ColdFusion, CSS etc.

5. Fifth Generation Programming Language (5GL)


The fifth generation programming language uses human’s natural language as program
source code. It is designed to make the computer solve the problem without the
programmer. The programmer only needs to worry about what problems need to be solved
and what conditions need to be met, without worrying about how to implement a routine
or algorithm to solve them. Human languages by nature are full of ambiguity. A single
statement in natural language is intended to provide a particular meaning can serve to
present an entirely new meaning altogether. But this ambiguity cannot be handled by a
computer which requires specific and well defined instructions. Therefore, the use of 5GL
has not become a reality yet and is still in the research phase. 5GLs are mostly used in
artificial intelligence research. Prolog, OPS5, Mercury, etc. are examples of fifth
generation languages.

Manish Kumar Shah(MKS) 13


13 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Problem Solving Using Computer
Computer based problem solving is a systematic process of designing, implementing and using
programming tools during the problem solving stage. This method enables the computer system
to be more intuitive with human logic than machine logic. Final outcome of this process is software
tools which is dedicated to solve the problem under consideration. Software is just a collection of
computer programs and programs are a set of instructions which guides computer’s hardware.
These instructions need to be well specified for solving the problem. After its creation, the software
should be error free and well documented. Software development is the process of creating such
software, which satisfies end user’s requirements and needs.
The following six steps must be followed to solve a problem using computer.
1. Problem Analysis
2. Program Design – Algorithm, Flowchart and Pseudocode
3. Coding
4. Compilation and Execution
5. Debugging and Testing
6. Program Documentation
1. Problem Analysis

MKS
Problem analysis is the process of defining a problem and decomposing overall system into smaller
parts to identify possible inputs, processes and outputs associated with the problem. This task is
further subdivided into six subtasks namely:
a) Specifying the Objective
b) Specifying the Outputs
c) Specifying the Input Requirements
d) Specifying the Processing Requirements
e) Evaluating the Feasibility
f) Documenting the Problem Analysis
a) Specifying the Objective
First, we need to know what problem is actually being solved. Making a clear statement of the
problem depends upon the size and complexity of the problem. Smaller problems not involving
multiple subsystems can easily be stated and then we can move onto the next step of “Program
Design”. However, a problem interacting with various subsystems and series of programs require
complex analysis, in-depth research and careful coordination of people, procedures and programs.
b) Specifying the Outputs
Before identifying inputs required for the system, we need to identify what comes out of the
system. The best way to specify output is to prepare some output forms and required format for
displaying result. The best person to judge an output form is the end user of the system i.e. the one
who uses the software to his benefit. Various forms can be designed by the programmer which
must be examined to see whether they are useful or not.
c) Specifying the Input Requirements
Manish Kumar Shah(MKS) 14
14 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
After having specified the outputs, the input and data required for the system need to be specified
as well. One needs to identify the list of inputs required and the source of data. For example, in a
simple program to keep student’s record, the inputs could be the student’s name, address, roll-
numbers, etc. The sources could be the students themselves or the person supervising them.
d) Specifying the Processing Requirements
When output and inputs are specified, we need to specify process that converts specified inputs
into desired output. If the proposed program is to replace or supplement an existing one, a careful
evaluation of the present processing procedures needs to be made, noting any improvements that
could made. If the proposed system is not designed to replace an existing system, then it is well
advised to carefully evaluate another system that addresses a similar problem.
e) Evaluating the Feasibility
After the successful completion of all the above four steps one needs to see whether the things
accomplished so far in the process of problem solving are practical and feasible. To replace an
existing system one needs to determine how the potential improvements outperforms existing
system or other similar system.
f) Documenting the Problem Analysis

MKS
Before concluding the program analysis stage, it is best to record whatever has been done so far in
the first phase of program development. The record should contain the statement of program
objectives, output and input specifications, processing requirements and feasibility.
2. Program Design – Algorithm, Flowchart and Pseudocode
The second stage in software development or problem solving using computer cycle is program
design. This stage consists of preparing algorithms, flowcharts and pseudocodes. Generally, this
stage intends to make the program more user friendly, feasible and optimized. Programmer just
requires a pen and pencil in this step in which the tasks are first converted into a structured layout
without the involvement of computer. In structured programming, a given task is divided into
number of sub-tasks which are termed as modules. Each process is further divided until no further
divisions are required. This process of dividing a program into modules and then into sub-modules
is known as “top down” design approach. Dividing a program into modules (functions) breaks
down a given programming task into small, independent and manageable tasks.
Algorithms
An algorithm is an effective step-by-step procedure for solving a problem in a finite number of
steps. In other words, it is a finite set of well-defined instructions or step-by-step description of the
procedure written in human readable language for solving a given problem. An algorithm itself is
division of a problem into small steps which are ordered in sequence and easily understandable.
Algorithms are very important to the way computers process information, because a computer
program is basically an algorithm that tells computer what specific tasks to perform in what
specific order to accomplish a specific task.

Manish Kumar Shah(MKS) 15


15 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
The same problem can be solved with different methods. So, for solving the same problem,
different algorithms can be designed. In these algorithms, number of steps, time and efforts may
vary more or less.

Characteristics of an Algorithm
An algorithm must possess following characteristics:
1) Finiteness: An algorithm should have finite number of steps and it should end after a finite
time.
2) Input: An algorithm may have many inputs or no inputs at all.
3) Output: It should result at least one output.
4) Definiteness: Each step must be clear, well-defined and precise. There should be no any
ambiguity.
5) Effectiveness: Each step must be simple and should take a finite amount of time.
Guidelines for Developing Algorithm
1) An algorithm will be enclosed by START (or BEGIN) and STOP (or END).
2) To accept data from user, generally used statements are INPUT, READ, GET or OBTAIN.

MKS
3) To display result or any message, generally used statements are PRINT, DISPLAY, or
WRITE.
4) Generally, COMPUTE or CALCULATE is used while describing mathematical
expressions and based on situation relevant operators can be used.
Example:
Algorithm: Calculation of Simple Interest
Step1: Start
Step2: Read Principal (P), Time (T) and Rate (R)
Step3: Calculate I = (P*T*R)/100
Step4: Display I as Interest.
Step5: Stop
Advantages of Algorithm
1) Effective Communication: Since algorithm is written in English like language, it is simple
to understand step-by-step solution of the problems.
2) Easy Debugging: Well-designed algorithm makes debugging easy so that we can identify
logical error in the program.
3) Easy and Efficient Coding: An algorithm acts as a blueprint of a program and helps during
program development.
4) Independent of Programming Language: An algorithm is independent of programming
languages and can be easily coded using any high level language.
Manish Kumar Shah(MKS) 16
16 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Disadvantages of Algorithm
1) Developing algorithm for complex problems would be time consuming and difficult to
understand.
2) Understanding complex logic through algorithms can be very difficult.

Flowchart
A flowchart is basically pictorial or diagrammatic representation of an algorithm using standard
symbols. In other words, it is a graphical representation that explains the sequence of operations
to be performed in order to solve a problem under consideration.
Standard Flowchart Symbols
To express different operations in the flowchart various standard symbols are used. All symbols
are connected among themselves in order to show the flow of information and processing.
Different symbols as prescribed by American National Standard Institute (ANSI) which are
frequently required while drawing flowchart are tabulated below:
Flowchart Symbol Symbol Name Description

MKS
Terminal (Start or Stop) Terminals (Oval shapes) are used to
represent start and stop of the
flowchart.
Flow Lines or Arrow Flow lines are used to connect
symbols used in flowchart and
indicate direction of flow.

Input / Output Parallelograms are used to read


input data and output or display
information
Process Rectangles are generally used to
represent process. For example,
Arithmetic operations, Data
movement etc.
Decision Diamond shapes are generally used
to check any condition or take
decision for which there are two
answers, they are, yes (true) or no
(false).
Connector It is used connect or join flow lines.

Manish Kumar Shah(MKS) 17


17 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Annotation It is used to provide additional


information about another
flowchart symbol in the form of
comments or remarks.

Guidelines for Preparing Flowchart


1) Standard symbols should be used while drawing flowchart.
2) Ensure that flowchart has START (or BEGIN) and STOP (or END).
3) Flowchart should be neat, clean and easy to follow. There should be no any ambiguity.
4) The usual direction of flowchart is from top to bottom or from left to right.
5) The terminal symbol, that is, START/BEGIN or STOP/END should have only one flow
line.
6) Only one flow line should come out from process symbol.
7) Only one flow line should enter a decision symbol, but two or three flow-lines, one for
each possible answer, can leave the decision symbol.
8) If the flowchart is lengthy and complex connector symbol should be used to reduce the

MKS
number of flow lines.
9) Avoid intersection of flow lines.
10) Use annotation symbol to describe steps more clearly.
Example
Flowchart: Calculation of Simple Interest
Start

Read P, T, R

I = (P*T*R)/100

Print I

Stop

Manish Kumar Shah(MKS) 18


18 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Advantages of Flowchart
1) Effective Communication: Flowcharts are better way of communicating the logic of the
system.
2) Effective Analysis: Using flowchart problem can be analyzed more efficiently.
3) Easy Debugging and Efficient Testing: The Flowchart helps in debugging and testing
process.
4) Efficient Coding: The flowcharts are very useful during program development phase.
5) Proper Documentation: Flowcharts serves as a good program documentation, which is
needed for various purpose.
6) Efficient Program Maintenance: Maintenance of operating programs becomes easy with
the help of flowchart.
Disadvantages of Flowchart
1) Complex Logic: For complicated logic, flowchart becomes complex and clumsy.
2) Difficulty in Modifications: If change is required in the logic then flowchart needs to be
redrawn and requires a lot of time.
Comparison between Flowchart and Algorithm
S.N. Flowchart Algorithm

MKS
1 Flowchart is a graphical representation of An algorithm is step-by-step procedure for
an algorithm using standard symbols. solving a problem in a finite number of steps.
2 Various standard symbols are used for Various steps are used to write an algorithm.
drawing flowcharts.
3 For a complex problem it is difficult to For a complex problem it is easier to
maintain flowchart without using maintain flowchart without using automated
automated tools. tools.
4 Example: Example:
Flowchart: Addition of two numbers Algorithm: Addition of two numbers
Start Step1: Start
Step2: Read two numbers A and B
Read A, B
Step3: Calculate C = A+B
Step4: Display C as sum.
Step5: Stop
C = A+B

Print C

Stop

Manish Kumar Shah(MKS) 19


19 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Pseudocode
Pseudocode is structured English for describing algorithms concisely. It is made up of two words,
namely, pseudo meaning imitation and code meaning instructions. As the name suggests,
pseudocode does not obey the syntax rules of any particular programming language i.e. it is not a
real programming code. It allows the designer to focus on main logic without being distracted by
programming languages syntax.
Guidelines for Preparing Pseudocode
1) Pseudocode will be enclosed by START (or BEGIN) and STOP (or END).
2) Pseudocode should be concise so ignore unnecessary details.
3) To accept data from user, generally used statements are INPUT, READ, GET or OBTAIN.
4) To display result or any message, generally used statements are PRINT, DISPLAY, or
WRITE.
5) Generally used keywords are capitalized while preparing pseudocode.
Example
Pseudocode: Calculation of Simple Interest
1: START

MKS
2: READ P, T, R
3: I = (P*T*R)/100
4: PRINT I
5: STOP
Advantages of Pseudocode
1) It allows the designer to focus on main logic without being distracted by programming
languages syntax.
2) Since it is language independent, it can be translated to any computer language code.
3) It allows designer to express logic in plain natural language.
4) It is easier to write actual code using pseudocode.
5) Unlike algorithms, pseudocodes are concise so pseudocodes are more readable and easier
to modify.
Disadvantages of Pseudocode
1) There are no accepted standards for writing pseudocodes and designer use their own style
while writing pseudocodes.
2) Pseudocode cannot be compiled and executed so its correctness cannot be verified by using
computers.

3. Coding
In this stage, process of writing actual program takes place. A coded program is most popularly
referred to as a source code. The coding process can be done in any language (high level and low

Manish Kumar Shah(MKS) 20


20 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
level). The actual use of computer takes place in this stage in which the programmer writes a
sequence of instructions ready for execution. Here are some qualities of a good program.
1) Comment clauses in the program help to make the program readable and understandable
by people other than the original programmer.
2) It should be efficient.
3) It must be reliable enough to work under all reasonable conditions to provide a correct
output.
4) It must be able to detect unreasonable error conditions and report them to the end user or
programmer without crashing the system.
5) It should be easy to maintain and support after installation.

4. Compilation and Execution


Generally coding is done in high level language or low level language (assembly language). For
the computer to understand these languages, they must be translated into machine level language.
The translation process is carried out by a compiler/interpreter (for high level language) or an
assembler (for assembly language program). The machine language code thus created can be saved
and run immediately or later on.

MKS
In an interpreted program, each program statement is converted into machine code before program
is executed. The execution occurs immediately one statement at a time sequentially. BASIC is one
of the frequently used interpreted language. In contrast to interpreter, a compiler converts a given
source code into object code. Once an object code is obtained, the compiled programs can be faster
and more efficient than interpreted programs.
Difference Between Compiler and Interpreter
S.N. Compiler Interpreter
1 Compiler takes entire program as input. Interpreter takes single instruction as
input.
2 Intermediate object code is generated. Intermediate object code is not
generated.
3 Control statements execute faster. Control statements execute slower.
4 Memory requirement is more since Memory requirement is less since object
object code is generated. code is not generated.
5 Errors are displayed after entire Errors are displayed for every
program is checked. instruction that goes through
interpretation.
6 Example: C Compiler Example: BASIC Interpreter

Compilation Process
A source code must go through several steps before it becomes an executable program. In the first
step the source code is checked for any syntax errors. After the syntax errors are traced out a source

Manish Kumar Shah(MKS) 21


21 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
file is passed through a compiler which first translates high level language into object code (A
machine code not ready to be executed). A linker then links the object code with pre-compiled
library functions, thus creating an executable program. This executable program is then loaded
into the memory for execution. General compilation process is shown in Figure below:

MKS
Figure: - Compilation Process
5. Debugging and Testing
To understand debugging and testing more intuitively, lets first consider learning about different
types of error that occurs while programming.

Error
Error means failure of compilation and execution of the computer program or not getting expected
results after execution. Debugging and testing are systematic process during program development
cycle to avoid errors in the program. Different types of error that we encounter while programming
are listed below:

Manish Kumar Shah(MKS) 22


22 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
a) Syntax Error: Syntax error is a violation of programming rules while writing it. A syntax
error does not allow the code to run. Syntax error can be easily detected during the
compilation process using compiler.
b) Logical Error: Logical error occurs when a programmer has applied incorrect logic for
solving problem or left out a programming procedure. When logical error occurs program
executes but fails to produce a correct result.
c) Run Time Error: Run time error occurs during the execution of program. Stack overflow,
divide by zero, floating point error etc. are examples of runtime error.
Debugging
Debugging is the process of finding errors and removing them from a computer program, otherwise
they will lead to failure of the program. Even after taking full care during program design and
coding, some errors may remain in the program and these errors appear during compilation or
linking or execution. Debugging is generally done by program developer.

Testing
Testing is performed to verify that the completed software package functions or works according
to the expectations defined by the requirements. Testing is generally performed by testing team

MKS
which repetitively executes program with intent to find error. After testing, list of errors and related
information is sent to program developer or development team.
Difference Between Debugging and Testing
S.N. Debugging Testing
1 It is the process of fixing errors. It is the process of finding as many errors
as possible.
2 Debugging is done during program Testing is done during testing phase
development phase. which comes after development phase.
3 Debugging is done by program Testing is generally carried out by
developer. separate testing team rather than program
developer.

6. Program Documentation
The program documentation is the process of collecting information about the program. The
documentation process starts from the problem analysis phase to debugging and testing.
Documentation consists two types of documentation, they are:
1) Programmer’s Documentation
2) User Documentation

Manish Kumar Shah(MKS) 23


23 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
1. Programmer’s Documentation
Programmer’s documentation contains all the technical details. Without proper documentation it
is very difficult even for the original programmer to update and maintain the program. A
programmer’s documentation contains the necessary information that a programmer requires to
update and maintain the program. These information includes:
a) Program analysis document, with a concise statement of program’s objectives, outputs and
processing procedures.
b) Program design documents with appropriate flowcharts and diagrams.
c) Program verification documents for outlining, checking, testing and correction procedures
along with the list of sample data and results.
d) Log used to document future program revision and maintenance activity.

2. User Documentation
User documentation is required for the end user who installs and uses the program. It consists
instructions for installation of the program and user manual.

MKS

Manish Kumar Shah(MKS) 24


24 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Introduction to C
C is a computer programming language which means we can use C to create lists of instructions
for a computer to follow. C is one of thousands programming languages currently in use. C has
won widespread acceptance because it gives programmer maximum control and efficiency.
Historical Development of C
The C programming language is developed by Dennis Ritchie at AT&T Bell Laboratories in 1972.
It is named C because many features of C were derived from an earlier language called B. The
history of C languages goes back to 1960’s, when a number of computer languages were being
used for various purposes. COBOL (Common Business-Oriented Language) was being used for
commercial purposes, FORTRAN (Formula Translation) was being used for scientific and
engineering applications and so on.

MKS

Figure: History of C

Manish Kumar Shah(MKS) 25


25 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Most of the modern languages including ANSI (American National Standards Institute)/ISO
(International Organization for Standardization) C are derived from the algorithmic language
called ALGOL which was developed by international group and introduced in 1960’s. Martin
Richards in 1967 developed programming language called BCPL (Basic Combined Programming
Language) which was derived from ALGOL. Similarly, BCPL influenced development of
programming language called B by Ken Thompson in 1970. In 1972, Dennis Ritchie introduced
“Traditional C” and it was confined to use within Bell Laboratories until 1978. In 1978, Brian
Kernighan and Dennis Ritchie published a book called “The C Programming Language”. The book
was so popular and the use of C started spreading. C Language at that time is commonly referred
to as “K&R C”. In 1983, the American National Standards Institute formed a committee to produce
a C programming language standard. This “ANSI C” was completed in 1988, and was approved
in 1989. It was then approved by the International Organization for Standardization (ISO) in 1990.
Figure below shows the history of ANSI C.

Importance of C
- C is robust language and has rich set of built-in functions, data types and operators which
can be used to write any complex program.

MKS
- Program written in C are efficient due to availability of several data types and operators.
- C has the capabilities of an assembly language with the feature of high level language so it
is well suited for writing both system software and application software.
- C is highly portable language i.e. code written in one machine can be moved to other which
is very important and powerful feature.
- C supports low level features like bit level programming and direct access to memory using
pointer which is very useful for managing resource efficiently.
- C has high level constructs and it is more user friendly as its syntaxes approaches to English
like language.

Feature of C
- C Language is well suited for structured modular programming.
- Programs written in C are efficient and executes much faster.
- C is powerful and feature rich programming language with rich set of built-in functions,
data types and operators.
- C is highly portable language i.e. code written in one machine can be moved to other.
- C supports low level feature like bit level programming and direct access to memory using
pointer.
- C has only 32 keywords and several standard built-in functions which can be used for
developing different program.
- C has high level constructs and it is more user friendly.

Manish Kumar Shah(MKS) 26


26 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Advantages of C Language
- Small but powerful language
C is small but very powerful language. It has fewer keywords and commands which makes
it easy to learn and understand. It has very powerful operators and it has support for low
level features which can directly access to hardware of the computer system. This makes
C very powerful language.

- Portable Language
C program written in one computer system can be easily used in another computer system
with little or no modification.

- Medium Level Language


C is considered as medium level language because C has both low level features and high
level features. It allows direct manipulation memory addresses and also has capabilities of
high level language.

MKS
- Native Language of UNIX
C is native language of UNIX and UNIX is major operating system for workstations and
servers. Also many windows based software, database programs, graphic libraries are
written in C.
Applications of C Language
Initially, C language was used for developing operating systems but in recent years C has been
used as general purpose language because of its popularity. C language can be used for various
purposes and some use of C language might be in the development of:
- Operating Systems
- Language Compilers
- Language Interpreters
- Assemblers
- Text Editors
- Drivers
- Database Programs
- Utilities Software
C as Middle Level Language
C is considered as middle level language because it bridges the gap between low level
programming language and high level programming language by providing features of both high
level and low level language. C can be used to write both system software and application software.

Manish Kumar Shah(MKS) 27


27 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Middle level language are closely related to machine language as well as high level language which
is depicted in following Figure.

1.
2.
MKS
Figure: Position of C Language
C is considered as medium level language because of the following features:
C programming language supports inline assembly language programs.
Using inline assembly feature we can directly access system register.
3. C programming supports bit level programming and direct memory access.
4. C programming also supports high level language features.
5. C is more user friendly and syntaxes approaches to English like language.
C as System Programming Language
C language can be used develop system software as well as application software. C is not limited
to developing specific types of software. Since it is not hardware or system dependent, programs
written in C are portable. Compilers, Drivers and Operating System can be written using C
language. Due to its appropriateness for writing system software it can be called as “Systems
Programming Language”.

C as Structured Modular Programming Language


Structured programming is basically a programming paradigm aimed at improving readability and
quality of computer program by making use of subroutines or smaller modules. C is called
structured modular programming language because while solving large and complex problem, C
Manish Kumar Shah(MKS) 28
28 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
programming language divides the problem into smaller modules called functions. Each of these
functions has specific job. And entire problem is solved by collecting such functions or smaller
modules. Structured programming languages are simple and easy to understand because
programmers do not require to know complex design concepts to start a new program.
Basic Structure of C Program
Every C program is basically a group of different section that are used for different purpose. A
well-defined structured layout makes program more readable, easy to modify, consistent format
and self-documented. Basic structure of C program is shown in following Figure.

MKS

Figure: - Basic Structure of C Program

Manish Kumar Shah(MKS) 29


29 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Documentation Section
- Program Name
- Author
- Creation Date etc.
- For Example:
/* This program calculates area of circle
Author: Ramesh Bhandari
Date: November 27, 2017
*/
Header File Section
- This section is used for including different header file.
- For Example:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
Etc.

MKS
Definition Section
- This section is used to define symbolic constants.
- Generally capital letter is used to define symbolic constants
- For Example:
#define PI 3.141592
#define SIZE 10
#define GOLDENRATIO 1.618
Etc.
- Here PI, SIZE and GOLDENRATIO are symbolic constants.
Global Variable Declaration Section
- This section is used to declare global variables.
- Global variables are generally used in more than one function.
- For Example:
int a;
float b;
char c;
Etc.
main() Function Section
- Every C program must have main() function. It consists two parts, namely, local variable
declaration section and executable statement section, and these two parts must be in
between opening and closing braces.
Manish Kumar Shah(MKS) 30
30 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

1. Local Variable Declaration Part


# This section is used for declaring local variables which are to be used in
executable statement part.
# For Example:
int x;
float y;
char z;
Etc.
2. Executable Statement Section
# Executable statement section consists all the instructions to be executed.
# The program execution starts from opening brace of main() function and ends at
closing brace of main() function.
# The closing brace of main() function is logical end of program.
Sub Program Section
- Sub program section consists all of the user defined function.
Note: All of the section except main() section may be absent when they are not required. main()

MKS
is the unique section of C program from where execution starts. Use of more than one main() is
not allowed.
Executing a C Program (Steps in Converting C Program to an Executable Program)
Creating and executing C program requires at least four steps:
1. Create/Edit: First of all, we need to create a C program for execution. We use an editor to
create or edit source program (also known as source code). C program file has extension
.C (for examples: myprogram.c, hello.c, etc.)
2. Compile: After creating or editing source code we need to compile it by using compiler.
If compiler does not detect any errors in the program, then it produces object files. Object
file has extension .OBJ (for examples: [Link], [Link], etc.). If compiler detects
error in the program, then we need to return to step 1 to make correction in source code.
3. Link: Object files are not executable file so in order to make executable file we use linker.
If no errors occur, linker produces executable file having extension .EXE (for examples:
[Link], [Link], etc.)
4. Execute: After obtaining executing file we can run this just like other applications. We
need to test to determine whether it works properly or not. If application does not work
properly we need to return to step 1 for modifications.

The detailed flow-chart for executing C program is shown in following Figure:

Manish Kumar Shah(MKS) 31


31 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

MKS

Figure: Flowchart for Compilation and Execution of C Program

Manish Kumar Shah(MKS) 32


32 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
C Fundamentals
C Character Set
Programming language processes some kind of data and gives meaningful result known as
information. These data and information are represented by character set of a programming
language. A character is any alphabets, digits or special characters used to form words, numbers
or expressions. C programming language consists of following character set.
a. Alphabets: A – Z and a – z
b. Digits: 0,1,2,3,4,5,6,7,8,9
c. Special Characters: !,~, #, $, %, ^, &, *, (, ), -, _, =, +, {, }, [, ], :, ;, ‘, “, <, >, ., ?, |, \, /
d. White Space Characters: Space, Tab, Carriage Return, Form Feed and New Line.
Keywords and Identifiers
Keywords: Keywords are those words in C programming whose meaning is already known to the
compiler. Keywords have standard predefined meaning. Keywords are also known as reserved
words and we cannot alter the meaning of keywords. Keywords are basic building block for
developing C programs. There are only 32 keywords in standard C and these keywords must be
written in lowercase. 32 keywords in C are:

MKS
auto break continue char
const case do double
default else enum extern
for float goto if
int long return register
short signed static switch
struct sizeof typedef union
unsigned void volatile while

Identifiers:
In C programming, name given to variables, constants, functions, arrays and various other user
defined items are known as identifiers. It can also be defined as a set of combinations of one or
more letters or digits used to define constants, variables, functions etc. Identifiers are defined by
user and user should try to give meaningful name while using identifiers to increase the readability
of program.
Rules for creating valid identifiers in C programming language are listed below:
(i) In ANSI standard - 31 characters long identifier are allowed. (But some implementation
of C only recognizes 8 characters). It would be better to follow the rule of 8 characters.
(ii) While naming identifier first character should always be letter.
(iii) Both uppercase and lowercase letters may be used and are they are recognized as
differently. For example: COUNT and count are two different identifiers.
Manish Kumar Shah(MKS) 33
33 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
(iv) Only underscore (_) is allowed among special symbols and is treated as letter.
(v) Space and other symbols are not allowed and they are invalid.
(vi) We cannot use keywords as identifier.
(vii) Proper naming conventions should be followed for better readability of program.
Examples of Valid and Invalid Identifier:
Valid Identifier Invalid Identifiers
area a rea
test1 1test
my_count my-count
fx f(x)
for1 for (since it is keyword)

Data Types
To communicate with computer, we need to pass different data to the computer. Data passed to
the computer can be of different types, namely, a single character, an integer number, floating
point or fractional number, or string (collection of characters). In each case, memory is required

MKS
to store these data and size of memory required is different for each data types. Way of representing
different types of data during programming is known as data types. C supports several data types,
each of which are represented differently within computer’s memory. The memory requirement of
each data type will determine the possible range of values for that data type.
Data types available in C can be broadly classified in three categories:
(1) Primary Data Types
(2) Secondary or Derived Data Types
1. Primary Data Types
Primary data types are lowest level or independent data types which are used for actual data
representation in the memory of the computer. Primary data types are also known as fundamental
data types or basic data types or simple data types. In C, there are five fundamental data types,
they are:
(a) int
- int is used for creating integer data types. This type of data is used to store positive or
negative integer values in computer’s memory. For example: when we define integer
data types using int keyword then we can store numbers like 45, -70, 153, -371 etc.
- Required memory or size or storage space: 2 Bytes (16 bits) or 4 Bytes (32 bits).
(Note: Size required is not fixed.)
- Format specifier for int is: %d
- Value range for int occupying 2 Bytes in memory is: -32768 to 32767.
- Value range for int occupying 4 Bytes in memory is: -2147483648 to +2147483647.

Manish Kumar Shah(MKS) 34


34 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

(b) float
- float is used for creating real or floating point data types. This type of data is used for
storing real or floating point numbers in computer’s memory. For example: when we
define floating point or real data types using float keyword then we can store numbers
like 56.125, -37.34, 88.8888, -167.70 etc. It has precision of 6 digits after decimal
points.
- Required memory or size or storage space: 4 Bytes (32 bits).
- Format specifier for float is: %f
- Value range for float is: -3.4 x 1038 to 3.4 x 1038.

(c) char
- char is used for creating character data types. A character denotes any alphabet, digit,
or special symbol. This type data is used to store a single character in computer’s
memory. When we define character data type using char keyword then we can store
character like ‘a’, ‘+’, ‘H’, ‘*’, ‘4’ etc.
- Required memory or size or storage space: 1 Byte (8 bits).
- Format specifier for char is: %c

MKS
- Value range: -128 to 127.

(d) double
- double is used for creating real or floating point data types with greater precision. This
type of data is used for storing real or floating point numbers in computer’s memory.
For example: when we define floating point or real data types using double keyword
then we can store numbers like 567.1025, -307.34, 888.8998, -167.70 etc. It has
precision of around 14 digits after decimal points.
- Required memory or size or storage space: 8 Byte (64 bits).
- Format specifier for double is: %lf or %e
- Value range: -1.7 x 10308 to 1.7 x 10308.

(e) void
- void is used to define empty set containing no values.
- Required memory or size or storage space: 0 Byte (0 bit).
- Format specifier: None (It has no format).
- Value range: Value less (It has no value range).

Modifying Fundamental Data Types


The fundamental data types may have various modifiers preceding them. The type modifier alters
the meaning of the base or fundamental data type to yield a new type. We can use a modifier to

Manish Kumar Shah(MKS) 35


35 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
alter the meaning of the base type to fit various situations more precisely. In C, the lists of modifiers
are:
- signed
- unsigned
- short
- long
Some important points while using modifiers:
(i) signed, unsigned, short and long can be used with int.
Valid combinations are:
a) signed int
- Used to store both positive and negative integer values.
- Format specifier is: %d
- Memory requirement is: 2 Bytes (16 bits) or 4 Bytes (32 bits).
- Value range for signed int occupying 2 Bytes in memory is: -32768 to 32767.
- Value range for signed int occupying 4 Bytes in memory is: -2147483648 to
+2147483647.

MKS
b) unsigned int
- Used to store positive integer numbers.
- Format specifier is: %u
- Memory requirement is: 2 Bytes (16 bits) or 4 Bytes (32 bits).
- Value range for unsigned int occupying 2 Bytes in memory is: 0 to 65535.
- Value range for unsigned int occupying 4 Bytes in memory is: 0 to 4294967295.

c) short int
- Used to store both positive and negative integer numbers.
- Format specifier is: %d
- Memory requirement is: 2 Bytes (16 bits).
- Value range: -32768 to 32767.

d) long int
- Used to store both positive and negative integer numbers.
- Format specifier is: %ld
- Memory requirement is: 4 Byte (32 bits).
- Value range: -2147483648 to +2147483647.

e) unsigned short int


- Used to store positive integer numbers.
- Format specifier: %u
- Memory requirement: 2 Bytes (16 bits).
- Value range: 0 to 65535.
Manish Kumar Shah(MKS) 36
36 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

f) signed short int


- Used to store both positive and negative integer numbers.
- Format specifier: %d
- Memory requirement: 2 Bytes (16 bits).
- Value range: -32768 to 32767.
g) unsigned long int
- Used to store positive integer numbers.
- Format specifier: %lu
- Memory requirement: 4 Bytes (16 bits).
- Value range: 0 to 4294967295.

h) signed long int


- Used to store both positive and negative integer numbers.
- Format specifier: %ld
- Memory requirement: 4 Bytes (16 bits).
- Value range: -2147483648 to +2147483647.

MKS
(ii) signed and unsigned can be used with char.
Valid combinations are:
a) signed char
- Used to store a signed single character.
- Format specifier: %c
- Memory requirement: 1 Byte (8 bits).
- Value range: -128 to 127.

b) unsigned char
- Used to store an unsigned single character.
- Format specifier: %c
- Memory requirement: 1 Byte (8 bits).
- Value range: 0 to 255.

(iii) long can be used with double.


Valid combination is:
a) long double
- Used to store real or floating point numbers.
- Format specifier: %Lf
- Memory requirement: 10 Byte (80 bits).
- Value range: -1.7 x 104932 to 1.7 x 104932
Note: The amount of storage allocated is not fixed. American National Standard Institute (ANSI)
has the following rules:

Manish Kumar Shah(MKS) 37


37 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
short int <= int <= long int
float <= double <= long double

2. Secondary Data Types


Secondary data types are also known as derived data types. These data types are derived from the
basic or fundamental data types. C has following derived or secondary data types:
a) Array
- An array is a collection of data of similar data types.

b) Pointer
- Pointer is a variable used to hold the address of another variable.

c) Structure
- Structure is collection of data of different data types under one name.

d) Union
- Union is collection of data of different data types sharing common memory space.

MKS
(Note: Secondary data types will be discussed later in upcoming section)

Variables and Constants


Variables
- A variable is a named location in memory that is used to hold a value that may be
modified by the program.

- A variable is an identifier that is used to represent some specified type of information


within the designated portion of a program. The information (data items) must be
assigned to the variable at some point in the program. The data item can then be
accessed later in the program simply by referencing to the variable name.

- Thus, the information represented by the variable can change during the execution of
the program. So, quantity that may vary during program execution is called variable.
Each variable has a specific storage location in memory where its numerical value is
stored. These locations can contain integer, real, or character constants.

- Declarations of Variables:
In C programming, all variables that are used in the program should be declared at first
in variable declaration section.

Manish Kumar Shah(MKS) 38


38 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

General syntax for declaring variables is:

data_type variable_name;
or
data_type comma_separated_list_of variables;

For example:
1. int a;
2. int var1, var2, count;
3. float ram, size;
4. char ch, op, var3;

- Rules for creating valid variables


a) A variable name is any combination of 1 to 8 alphabets, digits, or underscore.
Some compilers allow variable names whose length could be up to 40
characters, still, it would be better to use the rule of 8 characters.

MKS
b) Both uppercase and lowercase letters may be used and are recognized as
distinct.
c) First character should always be letter.
d) Only underscore ( _ ) is allowed among special symbols and is treated as letter.
e) Space and other symbols are not valid.
f) Proper naming convention should be followed for better readability of program.
Constants
- In C program, there are some entities that do not change during the execution of
program. Any entity that don not change during program execution are known as
constants.
- Constants are fixed value that remain unchanged during the execution of a program.
There are different constants in C programming, they are:
a) Integer Constants
Rules for constructing Integer constants:
1. An integer constant must have at least one digit.
2. It must not have a decimal point.
3. It could be either positive or negative
4. If no sign precedes an integer constant is assumed to be positive.
5. No commas or blank spaces are allowed within an integer constant.

- Valid integer constants: 1345 3468 -9746


- Invalid integer constants: 11. 45,35 $12 025 x248

Manish Kumar Shah(MKS) 39


39 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

There are three types of integers that are allowed in C


a) Decimal constants (base 10)
b) Octal constants (base 8)
c) Hexadecimal constants (base 16)

Decimal integer constants:


- The allowable digits in a decimal integer constant are 0,1,2,3,4,5,6,7,8,9.
- The first digit should not be 0.
- Should at least one digit.
- Examples
Valid: 1334, -9746
Invalid: 11. 256, $78 025, x248
Octal integer constants:
- The allowable digits in a octal constant are 0,1,2,3,4,5,6,7
- Must have at least one digit and start with digit 0.
Examples:
Valid: 0245 -0476 +04013

MKS
Invalid: 25 (does not start with 0), 0387 (8 is not an octal digit),
04.32 (Decimal point is not allowed)

Hexadecimal integer constant:


- The allowable digits in a hexadecimal constant are
0,1,2,3,4,5,6,7,8,9, A, B, C, D, E, F
- Must have at least one digit and start with 0x or 0X.
Examples:
Valid: 0x14AF 0X34680 -0x2673E
Invalid: 0345 (Must start with 0x), 0x45H3 (H is not a hexadecimal digit)

b) Floating Point or Real Constants


- A floating point constant may be written in one or two forms called fractional
form or the exponent form.

Rules for constructing floating point / real constants:


1. A floating-point constant must have at least one digit to the left and right of
the decimal point.
2. It must have a decimal point.
3. It could be either positive or negative
4. If no sign precedes a floating point constant is assumed to be positive.
5. No commas or blank spaces are allowed.
6. When value is too large or small, can be expressed in exponential form
comprising mantissa and exponent. E or e should separate mantissa and
Manish Kumar Shah(MKS) 40
40 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
exponent. The mantissa may have up to 7 digits and the exponent may be
between -38 and +38.
- Example:
Valid: +325.34, 426.0, 32E-89, 35e+56
Invalid: 1 (decimal point missing), 1. (No digit following decimal digit)
-1/2 (Symbol / is illegal), .5 (No digit to the left of the decimal)
56,8.94 (Comma not allowed), -125.9e5.5 (exponent cannot be fraction)
0.158e+954 (exponent too large)

c) Character Constants
A character constant is a single alphabet, single digit, or a single special symbol
enclosed within single quotes. Remember golden rule: single character single
quote. Example: 'A', '5', '+', '?'
d) String Constants
A string constant is a sequence of alphanumeric characters enclosed in
double quotation marks whose maximum length is 255 characters. For
Example: “This is C and C++ Programming language.”, “green”, “My name
&&&!!! ???”, “$2525”

MKS
Declarations of Constants
In C programming, we can also make named memory location to hold constant value
that does not change during program execution. To use these type of constants we need
to declare them first.

General syntax for declaring constant is:

const data_type constant_name = constant_value;

For example:
1. const int a = 10;
2. const float pi = 3.141592;
3. const char op = ‘+’;

Manish Kumar Shah(MKS) 41


41 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Difference between variable and constants
S.N. Variables Constants
1. Variables are named memory Any entity that does not change during program
location whose value can change execution are referred to as constants. In C, we
during program executions. can have named memory as constant.

2. Syntax for creating variables is: General syntax for creating constant is:
data_type variable_name = value; const data_type constant_name = fixed_value;

3. For example: For example:


int num = 45; const float pi = 3.141592;
Here value of num can be changed Here value of pi cannot be changed during
during program execution. program execution.

4. Variables can be initialized after their Constants must be initialized at the time of
declaration i.e. declaration i.e.
Declaration: const float pi = 3.141592; is valid
float ratio; but we cannot do something like:
Initialization:

MKS
Declaration:
ratio = 3.4; const float pi;
Initialization:
pi = 3.4;

Escape Sequences
Escape sequences are also known as Backslash Character Constants. In C, backslash (\) is known
as escape character because it causes an escape from the normal interpretation of string, so that the
character is recognized as one having a special meaning. A backslash (\) followed by one or more
special character is known as escape sequence. The escape sequence is used to express some
action. Different escape sequences used in C are:
Escape Sequence Action
\n New Line
\t Horizontal Tab
\r Carriage Return (Takes the cursor to the beginning of line in which
it is currently placed)
\f Form Feed
\b Move cursor one position the left of its current position
\” Double Quote
\\ Display Backslash
\a Alert (It alerts by sounding the speaker inside computer)
\0 It represents NULL character

Manish Kumar Shah(MKS) 42


42 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Preprocessor Directives
Preprocessor directives are the special instructions which are executed before code passes through
the compilation process. Every C programs are checked for the preprocessor statements before
compiling and if any preprocessor statements are used in the program then they are processed first
and then preprocessed program is handed over to the compiler for further compilation. Since every
preprocessor statements are processed first and this is the reason for calling them preprocessor
directives. It begins with hash (#) symbol and do not require semicolon at the end.

One of the most important preprocessor directive is include which is used for including header
file.
For example:
#include<stdio.h>
#include<conio.h>
#include<math.h>
Similarly, #define is also commonly used preprocessor directive which is used for creating
symbolic constants.
For example:
#define PI 3.141592

MKS
#define SIZE 10

Other examples of preprocessor directives are: #if, #else, #endif, #undef etc.
Symbolic Constants
A symbolic constant is a name given to some numeric value, or a character constant or string
constant. Symbolic names are also known as constant identifiers. Preprocessor directive #define
is used for defining symbolic constants.
General syntax for the typedef statement is:

#define symbolic_constant_name value_of_the_constant


For examples:
#define PI 3.141592
#define GOLDENRATIO 1.6
#define MAX 500
Here PI, GOLDENRATIO, SIZE are symbolic constants.
Note: Symbolic constants names are written in uppercase by convention, but it is not required.

typedef Statement
In C programming, we can define new data type names by using keyword typedef. Here we are
not creating new data types but we are giving a new name to the existing data types. These new
names given to existing data types are also known as user defined data types.
General syntax for the typedef statement is:

typedef type new_name;


Manish Kumar Shah(MKS) 43
43 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Where,
type is any valid C data types and new_name is any valid C identifier.
For example:
1. typedef int myint;
Now we can use myint just like int i.e. myint a,b,c; creates a, b and c as integer
variables.
2. typedef double db;
Now we can use db just like double i.e. db x; creates x as double variable.

MKS

Manish Kumar Shah(MKS) 44


44 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Operators and Expression
Operators
Operators are those symbols that perform some specific task. Like, when we add two numbers we
generally use '+' sign. In programming also, to perform some specific task, compiler has assigned
some specific symbols. These symbols are called operators.
Operand
The data items that operators act upon are called operands. Some operators require one operand
to act upon, whereas some require more than one.
Expressions
An expression is a combination of operands and operators written according to the syntax of
language.
Example:

Operator

MKS
Expression
Y=A+B Operand

Since some operators require one operand, whereas some require more than one. Depending upon
the number of operands required by the operators, we can broadly divide operators into three
distinct categories.
1. Unary Operators
2. Binary Operators
3. Ternary or Conditional Operators
1. Unary Operators
C includes a class of operators that act upon a single operand to produce a new value. Such
operators are known as unary operators. Unary operators usually precede their single operand,
though some unary operators are written after their operand. Different unary operators are:
a. Unary Minus (-)

Manish Kumar Shah(MKS) 45


45 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
- The most common unary operator is unary minus, where a numerical constant, variable,
or expression is preceded by a minus sign.
- For example: -23.4, -34 etc.
b. Increment Operator (++)
- The increment operator causes its operand to be incremented by 1.
- This operator can be used in two ways i.e. as a post increment or pre increment.
- Post increment:
If a = 2 then a++ causes value of a to be incremented by one i.e. after executing a++
we get value of a =3.
- Pre Increment:
If a = 2 then ++a also causes value of a to be incremented by one i.e. after executing
++a we get value of a =3.
c. Decrement Operator (--)
- The decrement operator causes its operand to be decremented by 1.
- This operator can be used in two ways i.e. as a post decrement or pre decrement.
- Post Decrement:
If a = 2 then a-- causes value of a to be decremented by one i.e. after executing a-- we
get value of a =1.

MKS
- Pre Decrement:
If a =2 then --a also causes value of a to be decremented by one i.e. after executing --a
we get value of a =3.
d. sizeof() Opearator
- sizeof is keyword in C which is used find size occupied by different data types in
memory. This is also considered as unary operator.
- For example:
a. sizeof(int) gives value of 2.
b. If we declare variable like: float x; then sizeof(x) gives 4.
Program to illustrate Unary Operators
Program Output
#include<stdio.h>
#include<conio.h> Value of a = 4
Value of b = 2
void main()
{
int a=2, b=3;
clrscr();
a++;
b--;
++a;
b++;
--b;
printf("Value of a = %d\n",a);

Manish Kumar Shah(MKS) 46


46 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
printf("Value of b = %d", b);
getch();
}

2. Binary Operators
Binary operators act upon a two operands to produce a new value. Such, operators can be classified
into different categories.
General syntax for binary operators is:
operand1 operator operand2

a. Arithmetic Operators

MKS
- Arithmetic operators are the operators used to perform the arithmetic operations like
addition, subtraction, multiplication, division, and modulo operation.
- Different arithmetic operators are tabulated with examples:
Symbol Meaning Examples
+ Addition a=23 and b=10 then a+b is equal to 33.
- Subtraction a=23 and b=10 then a-b is equal to 13.
* Multiplication a=23 and b=10 then a*b is equal to 230.
/ Division a=23 and b=10 then a/b is equal to 2 (In Integer
division) and 2.3 (In Real Division)
% Modulo or Remainder a=23 and b=10 then a%b is equal to 3.
Note: Both operand should be integer while
using % operator.
- Arithmetic operators (except %) can be used in 3 modes:
Integer mode: where both the operands are integer.
Real mode: where both the operands are real.
Mixed mode: where one operand is integer and second operator is real.
- Result is always a floating point number for real mode and mixed mode. For integer
mode, result is always an integer number.

Manish Kumar Shah(MKS) 47


47 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
b. Relational Operators:
- These operators are very helpful for making decisions. Depending upon the condition,
it returns either 0 or 1. When the condition with these operators is true, 1 is returned. If
the condition is false, it returns 0.
- Different relational operators are tabulated with examples:
Symbol Meaning Examples
< Less than a=2 and b=3 then a<b gives True (1) similarly
b<a gives False (0)
> Greater than a=2 and b=2 then a>b gives False (0) similarly
b>a gives False (0)
<= Less than or equal to a=2 and b=2 then a<=b gives True(1)
>= Greater than or equal to a=3 and b=4 then a<=b gives True(1)
== Equal to a=9 and b=9 then a==b gives True(1)
similarly if a=8 and b=9 then a==b gives False
(0)
!= Not equal to a=9 and b=9 then a!=b gives False(0)
similarly if a=8 and b=9 then a!=b gives True
(1)

MKS
c. Logical Operators:
- These operators are generally used along with relation operators. Like relational
operators, output of these operators is either True (1) or False (0).
- Different logical operators are tabulated with examples:
Symbol Meaning Examples
&& Logical AND (2>3 && 4>3) Evaluates to False && True
Rule: which then evaluates to False (0).
False && False = False
False && True = False
True && False = False
True && True = True

|| Logical OR (2>3 || 4>3) Evaluates to False || True which


Rule: then evaluates to True (1).
False && False = False
False && True = True
True && False = True
True && True = True

! Logical NOT !(2>3) Evaluates to !(False) which then


Rule: evaluates to True (1).
! (False) = True
! (True) = False
Note: This is Unary
Operator
Manish Kumar Shah(MKS) 48
48 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
d. Assignment Operators
- Assignment operators are used when the value is to be assigned to an identifier, a
variable. With execution of assignment operators, value at the right is assigned to the
left. The destination variable loses the old value; i.e. old value is over ridden with the
new value. If previous value is also required; it should be saved in some other variables.
- Different Assignment operators are tabulated with examples:
Symbol Meaning Examples
= Assignment x=2, here value 2 is assigned to x.
+= Addition and Assignment a += b is equivalent to a = a+b
–= Subtraction and Assignment a - = b is equivalent to a = a-b
*= Multiplication and Assignment a *= b is equivalent to a = a*b
/= Division and Assignment a /= b is equivalent to a = a/b
%= Remainder and Assignment a %= b is equivalent to a = a%b

e. Bitwise Operators
- The bitwise operators are the bit manipulation operators. They can manipulate
individual bits.
- Different bitwise operators are tabulated with examples:

MKS
Symbol Meaning Examples
~ Bitwise Complement If a=01011 then ~a gives 10100
Note: This is Unary Operator
& Bitwise AND If a = 1001 and b=1111 then
a&b gives 1001
| Bitwise OR If a = 1001 and b=1111 then
A|b gives 1111
^ Bitwise XOR If a = 1001 and b=1111 then
a^b gives 0110
<< Bitwise Shift Left If a=1010 and b=1 then
a<<b gives 0100 (Left shifted by 1 and
0 is inserted at last)
>> Bitwise Shift Right If a=1111 and b=2 then
a>>b gives 0011 (Right shifted by 2
and two 0’s are inserted at the
beginning)

3. Ternary or Conditional Operator (?:)


Simple decision making statements can be carried out by using ternary operator (?:). The ternary
operator is also known as conditional operator since it takes three operands. The general syntax
for conditional operator is:
General syntax for conditional operator is:
Condition? True_Expression : False_Expresion;

Manish Kumar Shah(MKS) 49


49 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Working: In conditional operator, first Condition is evaluated to either TRUE or FALSE.
If the result of Condition is TRUE then True_Expression is executed. If the result of
Condition is FALSE then False_Expression is executed. Therefore, result of conditional
operator is the result of whichever expression is evaluated – the True_Expression or
False_Expression. Only one of the expression is evaluated in a conditional operator and
never both. Following flowchart illustrates the operation of conditional operator.

False True
Condition?

False_Expression True_Expression

MKS To next statement


(If Any)
Example1: Program to evaluate following mathematical expression using conditional
operator.
𝑓(𝑥) = 𝑓(𝑥) = { 2
𝑥 2 + 4,
𝑥 − 4,
𝑥<0
𝑥≥0
Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter x: 1.2↲
void main() f(1.2) = -2.56
{
float x,y; Run 2:
clrscr(); Enter x: -0.5↲
printf("Enter x: "); f(-0.5) = 4.25
scanf("%f",&x);
y = x<0 ? x*x+4 : x*x-4; Note: ↲ indicates enter is pressed.
printf("f(%f) = %f", x, y);
getch();
}

Example2: Program to evaluate following mathematical expression using conditional


operator.
Manish Kumar Shah(MKS) 50
50 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
7 𝑥
𝑥 + 4𝑒 − √𝑥, 𝑥<2
𝑓(𝑥) = { 6
𝑥 + 5 ln(𝑥) + 3√𝑥, 𝑥≥2

Program Output
#include<stdio.h>
#include<conio.h> Run 1:
#include<math.h> Enter x: 1↲
f(1) = 10.873127
void main()
{ Run 2:
float x,y; Enter x: 2.5↲
clrscr(); f(2.5) = 253.465500
printf("Enter x: ");
scanf("%f",&x); Note: ↲ indicates
y=x<2?pow(x,7)+4*exp(x)-sqrt(x):pow(x,6)+5*log(x) +3*sqrt(x); enter is pressed.
printf("f(%f) = %f", x, y);
getch();
}

MKS
Operator Precedence and Associativity
Operator Precedence:
Operator precedence describes the order in which C evaluates different operators in a complex
expression. For example, in the expression 𝑦 = 10 + 5 ∗ 20, which happens first? Addition or
Multiplication? Operator precedence tells us the execution order of different operator. Precedence
level of different operator is shown in Table 1, operators which are closest to top are executed first.
Therefore, in our example above, Multiplication is done before Addition because looking at Table
1 multiplication operator has higher precedence than addition.
Operator Associativity:
Operator associativity describes the order of execution of operators when they have same level of
precedence. For example, in the expression 𝑦 = 12 ∗ 20/5, which happens first? Multiplication
or Division? Associativity can be either left to right or right to left. Associativity of different
operator is shown in Table 1.
Therefore, in our example above, Multiplication is done before Division because Multiplication
and Division both have same precedence and have left to right associativity. So, evaluation starts
from left i.e. first multiplication and then division.
Note: Associativity is used only when operators are of same precedence need to be evaluated.
Table 1

Manish Kumar Shah(MKS) 51


51 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Operator Precedence Associativity
Parenthesis (), Brackets [] 1 Left to Right
++, --, unary minus (-), unary plus (+) 2 Right to Left
*, /, % 3 Left to Right
+, - 4 Left to Right
<, >, <=, >= 5 Left to Right
= =, != 6 Left to Right
&& 7 Left to Right
|| 8 Left to Right
Ternary ?: 9 Right to Left
=, +=, - =, *=, /=, %=, 10 Right to Left

MKS

Manish Kumar Shah(MKS) 52


52 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Input and Output Functions
Every C program performs three main functions i.e. it accepts data as input, processes data and
produces output. Input refers to accepting of data while output refers to the presentation of data.
Normally input is accepted form keyboard and output is displayed to screen. Input output
operations are most common task in every programming language. C languages has different of
input output functions for input-output operations. Out of different input output operations, in this
section, we mainly focus on formatted and unformatted input output functions.
Formatted Input Output Functions
Formatted input output functions accept or present the data in a particular format. The standard
library consists of different functions that perform output and input operations. Out of these
functions, printf() and scanf() are discussed in this section. These functions allow user to format
input output in desired format. printf() and scanf() can be used read any type of data (integer, real
number, character etc.).
printf() – formatted output function
printf() is formatted output function which is used to display some information on standard output
device. It is defined in standard header file stdio.h. So, to use printf(), we must include header file

MKS
stdio.h in our [Link] syntax for printf() is:
printf(“format_string”, comma_separated_list_of_variables);
or
printf(“format_string”, var1, var2, var3, …, varN);
Where format_string may contain:
- Characters that are simply printed as they are.
- Format specifier that begin with a % sign.
- Escape sequence that begin with \ sign.
The format string indicates how many arguments follow and what their types are. The arguments
var1, var2, …, varN are the variables whose values are formatted and printed according to format
specifications of the format string. The arguments must match in number, order and type with the
format specifications.
For example:
- printf(“Hello, world!”); displays “Hello, world!” to standard output device.

Manish Kumar Shah(MKS) 53


53 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Complete programs to illustrate printf():
Program1 Output
#include<stdio.h>
void main() Hello, World!
{
printf (“Hello, world!”);
}
Program2 Output
#include<stdio.h>
Value of a = 45
void main() Value of b = 56.600000
{
int a=45;
float b = 56.6;
printf (“Value of a=%d\n Value of %f”, a, b);
}

MKS
scanf() – formatted input functions
scanf() is formatted input function which is used to read formatted data from standard input device
and automatically converts numeric information to integers and floats. It is defined in stdio.h.
General syntax for scanf() is:
scanf(“format_string”, comma_separated_list_of_address_of_variables);
or
printf(“format_string”, &var1, &var2, &var3, …, &varN);
For examples:
- int a;
scanf(“%d”,&a); reads integer value and stores it to variable a.
- int a;
float b;
scanf(“%d%f”, &a, &b); reads integer and real or floating number and stores to a and b.

Manish Kumar Shah(MKS) 54


54 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Complete programs to illustrate scanf():
Program1 Output
#include<stdio.h> Enter value of a: 67↲
Inputted value of a = 67
void main()
{
int a; Note: ↲ indicates enter is
printf (“Enter value of a: ”); pressed.
scanf(“%d”, &a);
printf(“Inputted value of a = %d”, a);
}

Program2 Output
#include<stdio.h>
Enter value of a and b: 77↲
void main() 45.5↲
{ Value of a = 67
int a; Value of b = 45.500000

MKS
float b;
printf (“Enter value of a and b: ”);
scanf(“%d%f”, &a, &b);
printf(“Value of a = %d \n Value of b = %f”, a, Note: ↲ indicates enter is
b); pressed.
}

Unformatted Input Output Functions


Unformatted input output functions cannot control the format of reading and writing the data.
Unformatted input output functions are classified into two categories as:
a. Character input output functions

Character Input Functions:


i. getch():
getch() is character input functions. It reads a character from the keyboard but does not
echo the pressed character and returns character pressed. It is defined in header file conio.h.
General syntax for getch() is:
character_variable = getch();

Manish Kumar Shah(MKS) 55


55 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
ii. getche():
getche() is also a character input functions. It reads a character from the keyboard.
Difference between getch() and getche() is that getche() echoes pressed character. getche()
also returns character pressed like getch(). It is defined in header file conio.h.

General syntax for getche() is:


character_variable = getche();
iii. getchar():
getchar() is also a character input functions. It reads a character and accepts the input until
carriage return is entered (i.e. until enter is pressed). It is defined in header file stdio.h.

General syntax for getchar() is:


character_variable = getchar();

Character Output Functions:


i. putch():

MKS
The putch() function is used for printing character to a screen at current cursor location. It
is defined in header file conio.h.

General syntax for putch() is:


putch(character_variable);
i. putchar():
The putchar() function is aslo used for printing character to a screen at current cursor
location. It is defined in header file stdio.h.

General syntax for putchar() is:


putchar(character_variable);

Complete programs to illustrate unformatted character input output functions:


Program1 Output
#include<stdio.h>
#include<conio.h> Press any character:
void main() Pressed character is: e
{
char ch;
clrscr(); /* Clear the screen */ Note: while using getch()
printf(“Press any character: ”); pressed character is not

Manish Kumar Shah(MKS) 56


56 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
ch = getch(); echoed. Here pressed
printf(“\nPressed character is:”); character is e and it is
putch(ch); displayed by putch().
getch(); /* Holding output */
}

Program2 Output
#include<stdio.h>
#include<conio.h> Press any character: f
void main() Pressed character is: f
{
char ch;
clrscr(); /* Clear the screen */ Note: while using getche()
printf(“Press any character: ”); pressed character is also
ch = getche(); echoed. Here pressed
printf(“\nPressed character is:”); character is f and it is
putchar(ch); displayed by putchar()
getch(); /* Holding output */ later.
}

Program3
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
MKS Output
Run1:
Enter any character: R ↲

Character read is: R

clrscr(); /* Clear the screen */ Run2:


printf(“Enter any character: ”); Enter any character: Ram ↲
ch = getchar();
printf(“\nCharacter read is:”); Character read is: R
putchar(ch);
getch(); /* Holding output */ Note: ↲ indicates enter is pressed.
} In run2 input given was Ram but
only first character is read.

b. String (Collection of Character or Character Array) input output functions


String Input Functions:
gets():
gets() is string input functions. It reads string from the keyboard. It reads string until enter
is pressed. It is defined in header file stdio.h.
General syntax for gets() is:
gets(string_variable);

Manish Kumar Shah(MKS) 57


57 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
String Output Functions:
puts():
puts() is string output functions. It writes or prints string to screen. It is defined in header
file stdio.h.
General syntax for gets() is:
puts(string or string_variable);

Complete programs to illustrate unformatted character input output functions:


Program1 Output
#include<stdio.h>
#include<conio.h> Enter your name:
void main() Ramesh Bhandari ↲
{ Hello,
char name[100]; Ramesh Bhandari
clrscr(); /* Clear the screen */ Have a good day.
printf(“Enter your name:\n”);
gets(name);

MKS
puts(“Hello,”); Note: ↲ indicates enter is
puts(name); pressed.
puts(“Have a good day.”);
getch(); /* Holding output */
}

Writing Simple C Programs

1. Program to read two numbers and finding their sum.

Program Output
#include<stdio.h> Run1:
#include<conio.h> Enter the value of a: 13↲
void main() Enter the value of b: 17↲
{ Sum is 30
int a, b, s; /* Declaring variables */
clrscr(); /* Clear the screen */ Run2:
printf(“Enter the value of a: ”); Enter the value of a: 100↲
scanf(“%d”, &a); Enter the value of b: 107↲
printf(“Enter the value of b: ”); Sum is 207
scanf(“%d”, &b);
s = a+b;
printf(“Sum is %d”, s); Note: ↲ indicates enter is
getch(); /* Holding output */ pressed.
}

Manish Kumar Shah(MKS) 58


58 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
2. Program to find sum and average of given three numbers.
Program Output
#include<stdio.h> Enter three numbers:
#include<conio.h> 10↲
void main() 18.6↲
{ 16.4↲
float p, q, r, sum, avg; /* Declaring variables */ Sum = 45.000000
clrscr(); /* Clear the screen */ Average = 15.000000
printf(“Enter three numbers:\n ”);
scanf(“%f%f%f”, &p, &q, &r);
sum = p + q + r; Note: ↲ indicates enter is
avg = sum/3; pressed.
printf(“Sum = %f\n”, sum);
printf(“Average = %f”, avg);
getch(); /* Holding output */
}

3. Program to calculate simple interest.


Program Output

MKS
#include<stdio.h> Enter value of p, t and r:
#include<conio.h> 105000↲
void main() 7↲
{ 12↲
float p, t, r, si; /* Declaring variables */ Interest is: 88200.000000
clrscr(); /* Clear the screen */
printf(“Enter value of p, t and r:\n ”);
scanf(“%f%f%f”, &p, &t, &r); Note: ↲ indicates enter is
si = p*t*r/100; pressed.
printf(“Interest is : %f”, si);
getch(); /* Holding output */
}
4. Program to calculate compound interest.
Program Output
#include<stdio.h> Enter value of p, t and r:
#include<conio.h> 105000↲
#include<math.h> /* for pow() function */ 7↲
12↲
void main() Result is: 232121.562500
{
float p, t, r, ci, tmp; /* Declaring variables */
clrscr(); /* Clear the screen */ Note: ↲ indicates enter is
printf(“Enter value of p, t and r:\n ”); pressed.
scanf(“%f%f%f”, &p, &t, &r);
tmp = 1+r/100;
ci = p * pow(tmp, t);
Manish Kumar Shah(MKS) 59
59 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
printf(“Result is : %f”, ci);
getch(); /* Holding output */
}

Difference between formatted and unformatted input output functions:

S.N. Formatted Input Output Functions Unformatted Input Output Functions


1. These functions allow to supply input These functions are the most basic form of input
or display output in user desired and output and they do not allow to supply input
format. or display output in user desired format.
2. printf() and scanf() are examples for getch(), getche(), getchar(), gets(), puts(),
formatted input and output functions. putchar() etc. are examples of unformatted
input output functions.
3. Formatted input and output functions Unformatted input and output functions do not
contain format specifier in their syntax. contain format specifier in their syntax.
4. They are used for storing data more They are used for storing data more compactly.
user friendly.
5. Example: Example:

MKS
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a; char ch ;
clrscr(); clrscr();
printf(“Enter value of a:”); printf(“Press any character:”);
scanf(“%d”, &a); ch = getche();
printf(“ a = %d”, a); printf(“\nYou pressed :”
getch(); putchar(ch);
} getch();
Output: }
Enter value of a:5↲ Output:
a=5 Press any character: L
You pressed: L

Manish Kumar Shah(MKS) 60


60 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Control Statements
In most of the C programs we have encountered so far, the instructions that were executed in the
same order in which they appeared within the program (sequentially). Each instruction was
executed one and only once. Program of this type are very simple, since they do not include any
logical control structures. While programming, we often encounter a situation in which decisions
have to be made or repetitions are required. In realistic C programs, the program needs logical
condition to determine if certain conditions are true or false, they do require the repeated execution
of groups of statements and, they involve the execution of individual groups of statements on a
selective basis. And all these operations can be carried out using the various control statements
included in C.
In general, those statements which alters the flow of execution of program are known as control
statements. C Language has following decisions making statements:
1. Decision Making Statements or Branching Statements
a. if statement
b. if-else statement
c. if-else-if ladder
d. nested if-else

MKS
e. switch statement
f. Conditional Operator Statements
2. Looping Statements or Iteration Statements
a. for loop
b. while loop
c. do – while loop
1. Decision Making Statements or Branching Statements
In realistic C program, it may require a logical test to be carried out at some particular point within
the program. And depending on the outcome of the logical test, several possible actions will be
carried out, this is known as branching or decision making. Different decision making statements
are explained below:
a. if statement
if statement is very useful and easy to use for decision making. It allows a particular
statement or more than one statements (block of statements) to be executed only when
certain condition is fulfilled.
General Syntax for if statement is:

if (Condition)
{
Statements;
}
Note: In case of single statement within if block, curly braces can be omitted.
Manish Kumar Shah(MKS) 61
61 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Working:
In the above general syntax if the Condition is TRUE then the Statements within curly
braces (known as if block) below if is executed and control jumps to the next statements
following the if statement. The working of if statement can be illustrated by following
flowchart:
Flowchart:

False True
Condition?

Statements

MKS To next statement


(If Any)
Example: C Program to read a number from user and to increase it by 15 if it is greater
than 8 otherwise to keep as it is.
Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter a number: 10↲
void main() Output is 25
{
int num; Run 2:
clrscr(); Enter a number: -5↲
printf("Enter a number: "); Output is -5
scanf("%d", &num);
if(num>8)
{ Note: ↲ indicates enter is
num = num+15; pressed.
}
printf("Output is %d", num);
getch();
}

Manish Kumar Shah(MKS) 62


62 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
b. if-else statement
if-else statement first tests a condition then it allows us to take two possible action, one is
when condition is TRUE, and the other is when condition is FALSE.

General Syntax for if-else statement is:

if (Condition)
{
Statement1;
}
else
{
Statement2;
}

Note: In case of single statement within if and else block, curly braces can be omitted.

Working:
In the above general syntax if the Condition is TRUE then the Statement1 within curly

MKS
braces (known as if block) below if is executed and control jumps to the next statements
following the if-else statement. Thus, the Statement2 following the else is ignored. If the
Condition is FALSE, then the Statement1 below if is ignored and the Statement2 following
the else is executed. The working of if-else statement can be illustrated by following
flowchart:

Flowchart:

False True
Condition?

Statement1 Statement2

To next statement
(If Any)

Manish Kumar Shah(MKS) 63


63 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Example1: Program to check whether a given number is odd or even.
Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter a positive integer: 37↲
void main() 37 is ODD.
{
int num; Run 2:
clrscr(); Enter a positive integer: 88↲
printf("Enter a positive integer: "); 88 is EVEN.
scanf("%d", &num);
if(num%2 == 0)
{ Note: ↲ indicates enter is
printf("%d is EVEN."); pressed.
}
else
{
printf("%d is ODD.");
}
getch();

MKS
}

Example2: Program to find largest of given two numbers.


Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter two numbers:
void main() 21.5↲
{ 34.5↲
float a, b; 34.5 is Largest.
clrscr();
printf("Enter two numbers: \n"); Run 2:
scanf(" %f %f ", &a, &b); Enter two numbers:
if(a>b) 78↲
{ -90↲
printf("%f is Largest.", a); 78 is Largest.
}
else
{ Note: ↲ indicates enter is
printf("%f is Largest.", b); pressed.
}
getch();
}

Manish Kumar Shah(MKS) 64


64 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Example3: Program to check whether a given year is leap year or not.


Hint: Year divisible by 400, or, year divisible by 4 but not divisible 100, is a leap year.
Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter year: 2004↲
void main() 2004 is Leap Year.
{
int y; Run 2:
clrscr(); Enter year: 3000↲
printf("Enter year: "); 3000 is not Leap Year.
scanf(" %d ", &y);
if((y%400 == 0) || (y%4 == 0 && y%100 != 0)) Run 3:
{ Enter year: 2017↲
printf("%d is Leap Year.", y); 2017 is not Leap Year.
}
else Note: ↲ indicates enter
{ is pressed.
printf("%d is not Leap Year.", y);

MKS
}
getch();
}

Example4: Program to check whether a given character is ‘r’ or not.


Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter any character: r↲
void main() It is r.
{
char ch; Run 2:
clrscr(); Enter any character: m↲
printf("Enter any character: "); It is not r.
scanf("%c", &ch);
if(ch=='r') Run 3:
{ Enter any character: +↲
printf("It is r."); It is not r.
}
else
{
printf("It is not r."); Note: ↲ indicates enter is
} pressed.
getch();

Manish Kumar Shah(MKS) 65


65 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}

c. if-else-if ladder
if-else-if ladder is used when there are more than two possible action based on different
conditions.
General Syntax for if-else statement is:

if (Condition1)
{
Statement1;
}
else if(Condition2)
{
Statement2;
}
.
.
else if(ConditionN)

MKS
{
StatementN;
}
else
{
Default_Statement;
}

Working:
In the above general syntax if the Condition1 is TRUE then the Statement1 will be executed
and control goes to next statement in the program following if-else-if ladder. If Condition1
is FALSE then Condition2 will be checked, if Condition2 is TRUE then Statement2 will
be executed and control goes to next statement in the program following if-else-if ladder.
Similarly, if Condition2 is FALSE then next condition will be checked and the process
continues. If all the conditions in the if-else-if ladder are evaluated to FALSE, then
Default_Statement will be executed. The working of if-else-if ladder can be illustrated by
following flowchart:

Flowchart:

Manish Kumar Shah(MKS) 66


66 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Condition1?
False

False
True Condition2?

Statement1
True

Statement2 ConditionN?
False

True

StatementN

Default_Statement

MKS
To next statement
(If Any)

Example1: Program to find largest form three numbers given by user.


Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter three numbers:
void main() 12↲
{ 33↲
int a,b,c; -17↲
clrscr(); Largest = 33
printf("Enter three numbers: \n");
scanf("%d%d%d", &a, &b, &c); Run 2:
if(a>b && a>c) Enter three numbers:
{ -18↲
printf("Largest = %d", a); -31↲
} -17↲
else if(b>a && b>c) Largest = -17
{
printf("Largest = %d", b); Run 3:
} Enter three numbers:
else 118↲
{ 19↲
printf("Largest = %d", c); -87↲
} Largest = 118
getch();
Manish Kumar Shah(MKS) 67
67 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
} Note: ↲ indicates enter is
pressed.

Example2: Program to solve quadratic equation ax2 + bx + c = 0. Where coefficients a,b


and c are given by user.
Program Output
#include<stdio.h>
#include<conio.h> Run 1:
#include<math.h> Enter coefficients a, b and c:
1↲
void main() -4↲
{ 4↲
float a, b, c, d, r1, r2, rp, ip; Roots are real and equal.
clrscr(); Root1 = 2.000000
printf("Enter coefficients a, b and c: \n"); Root2 = 2.000000
scanf("%f%f%f", &a, &b, &c);
d = b*b - 4*a*c; Run 2:
if( d == 0) Enter coefficients a, b and c:
{ 1↲
r1 = -b / (2*a); -5↲

MKS
r2 = r1; 6↲
printf("Roots are real and equal.\n"); Roots are real and unequal.
printf("Root1 = %f\n", r1); Root1 = 3.000000
Root2 = 2.000000
printf("Root2 = %f", r2);
} Run 3:
else if(d > 0) Enter coefficients a, b and c:
{ 1↲
r1 = (-b + sqrt(d))/ (2*a); 2↲
r2 = ( -b - sqrt(d))/(2*a); 3↲
printf("Roots are real and unequal.\n"); Roots are imaginary.
printf("Root1 = %f\n", r1); Root1 = -1 + 1.414214 i
printf("Root2 = %f", r2); Root2 = -1 – 1.414214 i

}
else Note: ↲ indicates enter is
{ pressed.
rp = -b/(2*a);
ip = sqrt(-d)/(2*a);
printf("Roots are Imaginary.\n");
printf("Root1 = %f + %f i\n", rp, ip);
printf("Root2 = %f - %f i", rp, ip);
}
getch();
}

Manish Kumar Shah(MKS) 68


68 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Example3: Program to find largest from four numbers given by user.
Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter four numbers:
void main() 21.4↲
{ 54.4↲
float a,b,c,d, lg; 34.5↲
clrscr(); -67.5↲
printf("Enter four numbers:\n"); Largest = 54.400000
scanf("%f%f%f%f", &a, &b, &c, &d);

if(a>b && a>c && a>d) Note: ↲ indicates enter is


{ pressed.
lg = a;
}
else if(b>a && b>c && b>d)
{
lg = b;
}

MKS
else if(c>a && c>b && c>d)
{
lg = c;
}
else
{
lg = d;
}
printf("Largest = %f", lg);
getch();
}
Example4: Program to print weekday based on given number.
Program Output
#include<stdio.h> Run 1:
#include<conio.h> Enter day number: 4↲
void main() WEDNESDAY.
{
int day; Run 2:
clrscr(); Enter day number: 2↲
printf("Enter day number: "); MONDAY.
scanf("%d", &day);
if(day==1) Run 3:
{ Enter day number: 10↲
printf("SUNDAY."); INVALID DAY.
}
else if(day==2) Run 4:
{ Enter day number: -1↲

Manish Kumar Shah(MKS) 69


69 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
printf("MONDAY."); INVALID DAY.
}
else if(day==3)
{ Note: ↲ indicates enter is
printf("TUESDAY."); pressed.
}
else if(day==4)
{
printf("WEDNESDAY.");
}
else if(day==5)
{
printf("THURSDAY.");
}
else if(day==6)
{
printf("FRIDAY.");
}
else if(day==7)
{
printf("SATURDAY.");
}
else

MKS
{
printf("INVALID DAY.");
}
getch();
}

d. Nested if-else
In C programming, we can have if-else statement within another if-else statement. When
if-else statement comes within another if-else statement then this is known nesting of if-
else statement.
For example:
if (Condition1)
{
if(Condition2)
{
Statement1;
}
else
{
Statement2;
}
}
else
{
if(Condition3)
{
Statement3;
Manish Kumar Shah(MKS) 70
70 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
else
{
Statement4;
}
}

Working: In this example of nested if-else, it first tests Condition1, if this condition is
TRUE then it tests Condition2, if Condition2 evaluates to TRUE then Statement1 is
executed otherwise Statement2 will be executed. Similarly, if Condition1 is FALSE then
it tests Condition3, if Condition3 evaluates to TRUE then Statement3 is executed otherwise
Statement4 is executed. The working of nested if-else presented in this example can be
further illustrated by following flowchart.

Flowchart:

True False

MKS
Condition1?

True Condition2? False True Condition3? False

Statement1 Statement2 Statement3 Statement4

To next statement
(If Any)
Example: Program to find largest form three numbers given by user.
Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter three numbers:
void main() 12↲
{ 33↲
int num1, num2, num3; -17↲
clrscr(); Largest = 33
printf("Enter three numbers:\n");
scanf("%d%d%d",&num1, &num2, &num3); Run 2:

Manish Kumar Shah(MKS) 71


71 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
if(num1>num2) Enter three numbers:
{ -18↲
if(num1>num3) -31↲
{ -17↲
printf("Largest = %d", num1); Largest = -17
}
else Run 3:
{ Enter three numbers:
printf("Largest = %d", num3); 118↲
} 19↲
} -87↲
else Largest = 118
{
if(num2>num3)
{ Note: ↲ indicates enter is
printf("Largest = %d", num2); pressed.

}
else
{
printf("Largest = %d", num3);

MKS
}
}
getch();
}

e. switch statement
It first evaluates expression that is used with switch statement. Then, the control is
transferred to one of the several alternatives that matches the case constant. The value of
expression can be of type int and char but not of type float or double.
General syntax for switch statement is:

switch (Expression)
{
case Constant1: Statement1;
break;
case Constant2: Statement1;
break;
.
.
.
.
case ConstantN: Statement1;
break;
default: Default Statement;
break;
}

Manish Kumar Shah(MKS) 72


72 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Rules that must be remembered while using switch statement:
(i) Expression and constant must be of type either integer or character.
(ii) All the cases must be distinct.
(iii) The block of statement under default will be executed when none of the
cases match the value of expression.
(iv) The break statement causes exit from switch statement. If it is not present,
after executing the case which match the value of the expression, the
following other cases are executed.
Flowchart:
The working of switch statement is illustrated by following flowchart:

Evaluate Expression
False

Is True

MKS
Expression = Constant1 Statement1
?

False

Is True
Expression = Constant2 Statement2
?

False

Is True
Expression = ConstantN StatementN
?

False
Default Statement

To next statement
(If Any)

Manish Kumar Shah(MKS) 73


73 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Example1: Program to check whether a given number is odd or even using switch.
Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter positive integer: 21↲
void main() 21 is ODD.
{
int num, rem; Run 2:
clrscr(); Enter positive integer: 66↲
printf("Enter positive integer: "); 66 is EVEN.
scanf("%d", &num);
rem = num%2; Note: ↲ indicates enter is
switch(rem) pressed.
{
case 1: printf("%d is ODD.", num);
break;
default: printf("%d is EVEN.", num);
break;
}

MKS
getch();
}

Example2: Program to print weekday based on given number.


Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter day number: 3↲
int main() TUESDAY.
{
int day; Run 2:
clrscr(); Enter day number: -3↲
printf("Enter day number: "); INVALID DAY.
scanf("%d", &day);
switch(day) Run 3:
{ Enter day number: 6↲
case 1: printf("SUNDAY."); FRIDAY.
break;
case 2: printf("MONDAY.");
break; Note: ↲ indicates enter is
case 3: printf("TUESDAY."); pressed.
break;
case 4: printf("WEDNESDAY.");
break;
case 5: printf("THURSDAY.");

Manish Kumar Shah(MKS) 74


74 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
break;
case 6: printf("FRIDAY.");
break;
case 7: printf("SATURDAY.");
break;
default: printf("INVALID DAY.");
break;
}
getch();
return(0);
}

Example3: Simple Calculator.


Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Available Operations.
void main() + for Addition.
{ - for Subtraction.
float a,b, r; * for Multiplication.

MKS
char op; / for Division.
clrscr(); Which Operation?
printf("Available Operations.\n"); *↲
printf("+ for Addition.\n"); Enter two numbers:
printf("- for Subtraction.\n"); 13↲
printf("* for Multiplication.\n"); 17↲
printf("/ for Division.\n"); 13 * 17 = 221
printf("Which Operation?\n"); Run 2:
scanf("%c", &op); Available Operations.
+ for Addition.
switch(op) - for Subtraction.
{ * for Multiplication.
case '+': printf("Enter two numbers:\n"); / for Division.
scanf("%f%f",&a, &b); Which Operation?
r = a+b; ^↲
printf("%f + %f = %f", a, b, r); Invalid Operation.
break; Run 3:
case '-': printf("Enter two numbers:\n"); Available Operations.
scanf("%f%f",&a, &b); + for Addition.
r = a-b; - for Subtraction.
printf("%f - %f = %f", a, b, r); * for Multiplication.
break; / for Division.
case '*': printf("Enter two numbers:\n"); Which Operation?
scanf("%f%f",&a, &b); /↲
r = a*b; Enter two numbers:
printf("%f * %f = %f", a, b, r); 13↲
break; 17↲
Manish Kumar Shah(MKS) 75
75 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
case '/': printf("Enter two numbers:\n"); 12/21 = 0.571429
scanf("%f%f",&a, &b); Run 4:
if(b!=0) Available Operations.
{ + for Addition.
r = a/b; - for Subtraction.
printf("%f/%f = %f",a,b,r); * for Multiplication.
} / for Division.
else Which Operation?
{ /↲
printf("Division not possible."); Enter two numbers:
} 13↲
break; 0↲
default: printf("Invalid Operation."); Division not possible.
break;
} Note: ↲ indicates enter is
getch(); pressed.
}

f. Conditional operator statement


Simple decision making statements can be carried out by using conditional operator (?:).

MKS
The conditional operator is also known as ternary operator since it takes three operands.
The general syntax for conditional operator is:
General syntax for conditional operator is:

Condition? True_Expression : False_Expresion;


Working: In conditional operator, first Condition is evaluated to either TRUE or FALSE.
If the result of Condition is TRUE then True_Expression is executed. If the result of
Condition is FALSE then False_Expression is executed. Therefore, result of conditional
operator is the result of whichever expression is evaluated – the True_Expression or
False_Expression. Only one of the expression is evaluated in a conditional operator and
never both. Following flowchart illustrates the operation of conditional operator.

False True
Condition?

False_Expression True_Expression

To next statement
(If Any)

Manish Kumar Shah(MKS) 76


76 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Example1: Program to evaluate following mathematical expression using conditional
operator.
𝑥 2 + 4, 𝑥<0
𝑓(𝑥) = 𝑓(𝑥) = { 2
𝑥 − 4, 𝑥≥0

Program Output
#include<stdio.h>
#include<conio.h> Run 1:
Enter x: 1.2↲
void main() f(1.2) = -2.56
{
float x,y; Run 2:
clrscr(); Enter x: -0.5↲
printf("Enter x: "); f(-0.5) = 4.25
scanf("%f",&x);
y = x<0 ? x*x+4 : x*x-4;
printf("f(%f) = %f", x, y);
getch();
}

Program
#include<stdio.h>
MKS
Example2: Program to check whether a given number is odd or even using conditional
operator.

Output

#include<conio.h> Run 1:
Enter positive integer: 22↲
int main() EVEN
{
int num; Run 2:
clrscr(); Enter positive integer: 67↲
printf("Enter positive integer: "); ODD
scanf("%d", &num);
num%2==0? printf("EVEN") :
printf("ODD"); Note: ↲ indicates enter is
getch(); pressed.
return(0);
}

Example3: Program to evaluate following mathematical expression using conditional


operator.

Manish Kumar Shah(MKS) 77


77 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
7 𝑥
𝑥 + 4𝑒 − √𝑥, 𝑥<2
𝑓(𝑥) = { 6
𝑥 + 5 ln(𝑥) + 3√𝑥, 𝑥≥2

Program Output
#include<stdio.h>
#include<conio.h> Run 1:
#include<math.h> Enter x: 1↲
f(1) = 10.873127
void main()
{ Run 2:
float x,y; Enter x: 2.5↲
clrscr(); f(2.5) = 253.465500
printf("Enter x: ");
scanf("%f",&x); Note: ↲ indicates
y=x<2?pow(x,7)+4*exp(x)-sqrt(x):pow(x,6)+5*log(x) +3*sqrt(x); enter is pressed.
printf("f(%f) = %f", x, y);
getch();
}

MKS
2. Looping Statements or Iterative Statements
In C, the program may require that a group of statements be executed repeatedly, until some logical
condition has been satisfied this is known as looping or iteration. Sometimes the required number
of repetition is known in advance; and sometimes statements are executed until the logical
condition becomes true.
A loop generally consists of two section, namely, body of the loop and test condition. Test
condition performs a logical test whose result is either TRUE or FALSE. When the result of test
condition is TRUE, statements in the body of the loop are executed, otherwise, the loop is
terminated.
Depending on the position of the control statement in the loop, the loop statement is classified in
two categories, namely, pre-tested loop (also known as entry-controlled loop) and post-tested
loop (also known as exit-controlled loop). In pre-tested loop, test condition is evaluated before
the execution of loop. If the condition is TRUE then loop is executed, otherwise loop is terminated.
In post-tested loop, body of loop is executed unconditionally for the first time because condition
is tested after the execution of body of loop. If the condition is TRUE, then loop is executed again
otherwise loop is terminated.
Every loop consists three essential elements, they are:
1. Initialization: It sets initial value for the loop control variable before the statements within
the loop starts to execute.
2. Condition: It tests the condition to determine whether to execute the loop or not.

Manish Kumar Shah(MKS) 78


78 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
3. Update: It increases or decreases the loop control variable such that after some repetitions
condition will result FALSE and loop will be terminated.
C programming language has three types of loop: for, while and do-while loop. These are
explained below:
a. for loop
The for loop is most commonly used loop statement. It is pre-tested loop and it is used
when the number of repetitions (iterations) are known in advance. The syntax of the loop
consists three parts, they are, control variable initialization, condition and control variable
update. These three parts are separated by semicolon.

General syntax of for loop is:

for (control_variable_initialization; condition ; control_variable_update)


{
statement(s); //body of loop
}

Note: Curly braces are optional if body of loop consists single statement.

MKS
Working: In for loop control variable is initialized first. After initialization of control
variable, it tests condition. Based on the outcome of condition, loop is continued or
stopped. If the condition evaluates to FALSE, then loop will be terminated (goes to next
statement following loop). If the condition evaluates to TRUE, then statements within body
of loop are executed. After execution of statements, value of loop control variable is
updated and condition is checked again. And the process is repeated. Following flowchart
illustrates the operation of for loop.

Flowchart:

Manish Kumar Shah(MKS) 79


79 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

control_variable_initialization

False
condition?

True To next statement


(If Any)
statements

control_variable_update

Program
#include<stdio.h>
MKS
Example1: Program to print “Programming is fun.” 10 times.

Output

#include<conio.h> Programming is fun.


Programming is fun.
void main() Programming is fun.
{ Programming is fun.
int i; Programming is fun.
clrscr(); Programming is fun.
for(i=1;i<=10; i++) Programming is fun.
{ Programming is fun.
printf("Programming is fun.\n"); Programming is fun.
} Programming is fun.
getch();
}

Example2: Program to print “Programming is fun.” n times, where n is given by user.

Program Output

Manish Kumar Shah(MKS) 80


80 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h>
#include<conio.h> Enter n: 5↲
Programming is fun.
void main() Programming is fun.
{ Programming is fun.
int i, n; Programming is fun.
clrscr(); Programming is fun.
printf("Enter n: ");
scanf("%d", &n); Note: ↲ indicates enter is
for(i=1;i<=n; i++) pressed.
{
printf("Programming is fun.\n");
}
getch();
}

Example3: Program to find sum and average of n numbers given by user.


Program Output
#include<stdio.h>

MKS
#include<conio.h> Enter n: 4↲
Enter number-1: 12
void main() Enter number-2: 21
{ Enter number-3: 14
int i, n; Enter number-4: 47
float sum=0, avg, num; Sum is 94
clrscr(); Average is 23.5
printf("Enter n: ");
scanf("%d", &n);
Note: ↲ indicates enter is
for(i=1;i<=n; i++) pressed.
{
printf("Enter number-%d:",i);
scanf("%f",&num);
sum = sum + num;
}
avg = sum/n;
printf("Sum is %f\n", sum);
printf("Average is %f", avg);
getch();
}

Example4: Program to find sum of first n natural numbers.


Program Output

Manish Kumar Shah(MKS) 81


81 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h>
#include<conio.h> Enter n: 15↲
Sum is 120
void main()
{ Note: ↲ indicates enter is
int i, n, sum=0; pressed.
clrscr();
printf("Enter n: ");
scanf("%d", &n);

for(i=1;i<=n; i++)
{
sum = sum + i;
}
printf("Sum is %d\n", sum);
getch();
}

Example5: Program to find factorial of a given number.

MKS
Program Output
#include<stdio.h>
#include<conio.h> Enter number: 7↲
void main() Factorial of 7 is 5040
{
int i, n, f=1; Note: ↲ indicates enter is
clrscr(); pressed.
printf("Enter number: ");
scanf("%d", &n);

for(i=1;i<=n; i++)
{
f = f * i;
}
printf("Factorial of %d is %d", n, f);
getch();
}

Example6: Program to check whether a given number is prime or not.


Program Output
#include<stdio.h>
#include<conio.h> Run1:
void main() Enter number: 7↲
{ 7 is PRIME.
int i, n, count=0;
clrscr(); Run2:

Manish Kumar Shah(MKS) 82


82 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
printf("Enter number: "); Enter number: 78↲
scanf("%d", &n); 78 is NOT PRIME.

for(i=2; i<=n-1; i++) Note: ↲ indicates enter is


{ pressed.
if(n%i == 0)
{
count++;
}
}
if(count==0)
{
printf("%d is PRIME.", n);
}
else
{
printf("%d is NOT PRIME.", n);
}
getch();
}
Example7: Program to evaluate sum of series: S = 1-2+3-4+5- … to n terms, n given by

MKS
user.
Program Output
#include<stdio.h>
#include<conio.h> Run1:
Enter n: 5↲
void main() Sum is 3
{
int i, sum=0, n, sign=1; Run2:
clrscr(); Enter n: 10↲
printf("Enter n: "); Sum is -5
scanf("%d", &n);
for(i=1; i<=n; i++) Note: ↲ indicates enter is
{ pressed.
sum = sum + i * sign;
}
printf("Sum is %d", sum);
getch();
}

Example8: Program to evaluate sum of series: S = -0.5*2/3 + 1*3/5 - 1.5 * 4/7 + 2 * 4/9
- … to n terms, n given by user.
Program Output

Manish Kumar Shah(MKS) 83


83 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h>
#include<conio.h> Run1:
Enter n: 2↲
void main() Sum is 0.266667
{
int i, n; Run2:
float sum=0, a=0.5, b=2, c=3, sign = -1, Enter n: 10↲
term; Sum is 1.273990
clrscr();
printf("Enter n: "); Note: ↲ indicates enter is
scanf("%d", &n); pressed.
for(i=1; i<=n; i++)
{
term = a*b/c;
sum = sum + term*sign;
sign = -sign;
a = a+0.5;
b = b+1;
c = c+2;
}
printf("Sum is %f", sum);

MKS
getch();
}

b. while loop
while loop is pre-tested loop, it tests the expression before every repetition of the loop
body. Statements within body of loop are executed until some condition is satisfied. The
while loop looks like simplified version of the for loop. In its syntax it consists condition
but not control variable initialization and control variable update. However, loop control
variable must be initialized before condition is checked and loop body must also contain
control variable update to avoid infinite loop.

General syntax for while loop is:


control_variable_initialization;

while (condition)
{
statement(s);
control_variable_update;
}

Note1: control_variable_initialization and control_variable_update are not part of syntax


of while loop but necessary for proper working.
Note2: Curly braces are optional if loop body consist single statement.

Manish Kumar Shah(MKS) 84


84 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Working: In while loop control variable is initialized first. After initialization of loop
control variable, it tests condition. Based on the result of test condition, loop is continued
or stopped. If condition evaluates to FALSE, then loop will be terminated (goes to next
statement following loop). If condition evaluates to TRUE, then statements within body of
loop are executed along with control variable update. After execution of body of loop,
condition is checked again. And the process is repeated. Following flowchart illustrates the
operation of while loop.

control_variable_initialization

False
condition?

True To next statement


(If Any)

MKS
statements

control_variable_update

Example1: Program to display 1 to 10 using while loop.

Program Output
#include<stdio.h>
#include<conio.h> 1
2
void main() 3
{ 4
int i; 5
clrscr(); 6
i=1; 7
while(i<=10) 8
{ 9
printf("%d\n",i); 10
i++;
}
getch();
}

Manish Kumar Shah(MKS) 85


85 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Example2: Program to find sum of digit of a given number.

Program Output
#include<stdio.h>
#include<conio.h> Run1:
Enter number: 15234↲
void main() Sum is 15
{
int num, rem, sum=0; Run2:
clrscr(); Enter number: 6878↲
printf("Enter number: "); Sum is 29
scanf("%d", &num);
while(num!=0)
{ Note: ↲ indicates enter is
rem = num%10; pressed.
sum = sum + rem;
num = num/10;
}
printf("Sum is %d", sum);
getch();

MKS
}

Example3: Program to reverse a given number.


Program Output
#include<stdio.h>
#include<conio.h> Run1:
Enter number: 1234↲
void main() Reverse is 4321
{
int num, rem, rev=0; Run2:
clrscr(); Enter number: 6878↲
printf("Enter number: "); Reverse is 8786
scanf("%d", &num);
while(num!=0)
{ Note: ↲ indicates enter is
rem = num%10; pressed.
rev = rev*10 + rem;
num = num/10;
}
printf("Reverse is %d", rev);

Manish Kumar Shah(MKS) 86


86 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
getch();
}

Example4: Program to check whether a given number is Palindrome or not.


Program Output
#include<stdio.h>
#include<conio.h> Run1:
Enter number: 1234↲
void main() NOT PALINDROME
{
int num, rem, rev=0, copy; Run2:
clrscr(); Enter number: 1221↲
printf("Enter number: "); PALINDROME
scanf("%d", &num);
copy = num; Run3:
while(num!=0) Enter number: 3333↲
{ PALINDROME
rem = num%10;
rev = rev*10 + rem; Note: ↲ indicates enter is
num = num/10; pressed.

MKS
}
if(rev==copy)
{
printf("PALINDROME");
}
else
{
printf("NOT PALINDROME");
}
getch();
}

c. do-while loop
do-while loop is post-tested loop. The do-while loop is very similar to the while loop except
that the condition is checked at the end of the loop body. This guarantees that the loop is
executed at least once before terminating.
General syntax for do-while loop is:
control_variable_initialization;

do
{
statement(s);
control_variable_update;
} while (condition);

Manish Kumar Shah(MKS) 87


87 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Note1: control_variable_initialization and control_variable_update are not part of syntax
of do while loop but necessary for proper working.

Working: Control variable is initialized first. After initialization of control variable,


statements in body of loop are executed along with control variable update. After execution
of statements within body of loop, condition is checked. If result of the condition evaluates
to TRUE, then statements within body of loop are executed again otherwise loop will
terminate.

Flowchart:

control_variable_initialization

statements

MKS
control_variable_update

condition?
True

False

To next statement
(If Any)
Example1: Program to check whether a given number is Palindrome or not using do-
while.
Program Output
#include<stdio.h>
#include<conio.h> Run1:
Enter number: 1234↲
void main() NOT PALINDROME
{
int num, rem, rev=0, copy; Run2:
clrscr(); Enter number: 1221↲
printf("Enter number: "); PALINDROME
scanf("%d", &num);
copy = num; Run3:

Manish Kumar Shah(MKS) 88


88 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Enter number: 3333↲
do PALINDROME
{
rem = num%10; Note: ↲ indicates enter is
rev = rev*10 + rem; pressed.
num = num/10;
} while(num!=0);

if(rev==copy)
{
printf("PALINDROME");
}
else
{
printf("NOT PALINDROME");
}
getch();
}

Nested Loop

MKS
In C programming, like if statement, for statement can be nested. The one loop within another loop
is known as nested loop. We can have for loop within for, or while loop within for, or do-while
loop within while loop and so on. In general, we can have any loop within another looping
statement.
Following programs illustrates the concept of nested loop:
Program 1 Output
#include<stdio.h> i=1 j=1
#include<conio.h> i=1 j=2
i=1 j=3
void main() i=2 j=1
{ i=2 j=2
int i,j; i=2 j=3
clrscr(); i=3 j=1
for(i=1;i<=3;i++) i=3 j=2
{ i=3 j=3
for(j=1;j<=3;j++)
{
printf("i = %d\tj = %d\n", i,j);
}
}
getch();
}

Manish Kumar Shah(MKS) 89


89 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Program 2 Output
#include<stdio.h> 1 2 3 4
#include<conio.h> 1 2 3 4
1 2 3 4
void main() 1 2 3 4
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=4;j++)
{
printf("%d\t", j);
}
printf("\n");
}
getch();
}

Program 3 Output

MKS
#include<stdio.h> 1
#include<conio.h> 1 2
1 2 3
void main() 1 2 3 4
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("%d\t", j);
}
printf("\n");
}
getch();
}

Program 4 Output

Manish Kumar Shah(MKS) 90


90 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> 1
#include<conio.h> 2 2
3 3 3
void main() 4 4 4 4
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("%d\t", i);
}
printf("\n");
}
getch();
}

Program 5 Output
#include<stdio.h> 5

MKS
#include<conio.h> 5 4
void main() 5 4 3
{ 5 4 3 2
int i,j; 5 4 3 2 1
clrscr();
for(i=5;i>=1; i--)
{
for(j=5; j>=i; j--)
{
printf("%d\t", j);
}
printf("\n");
}
getch();
}

Program 6 Output

Manish Kumar Shah(MKS) 91


91 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> Enter n: 7↲
#include<conio.h> *
void main() * *
{ * * *
int i,j; * * * *
clrscr(); * * * * *
printf(“Enter n:”); * * * * * *
scanf(“%d”, &n); * * * * * * *
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf("*\t");
}
printf("\n");
}
getch();
}

Program 7 Output

MKS
#include<stdio.h> Enter the value of n: 8↲
#include<conio.h> *
***
void main() *****
{ *******
int i, j, n; *********
clrscr();
printf("Enter value of n:");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(j=1; j<=2*i-1; j++)
{
printf(" * ");
}
printf("\n");
}
getch();
}

Manish Kumar Shah(MKS) 92


92 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Program 8 Output
#include<stdio.h> Enter the value of n: 4↲
#include<conio.h> 1
101
void main() 10101
{ 1010101
int i, j, n;
clrscr();
printf("Enter value of n:");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
for(j=1; j<=n-i; j++)
{
printf(" ");
}
for(j=1; j<=2*i-1; j++)
{
printf("%d", j%2);
}
printf("\n");

MKS
}
getch();
}

break and continue


The break Statement
We have already encountered break statement while using switch statement. break can be also
used within loop. Like in switch statement, break when encountered within loop, it terminates loop
passing control to the first statement after loop. break statement is generally associated with if
statement.
Note: When break is encountered within nested loop then it terminates that loop where it is
encountered. For example, if we have two level nested loop and break is encountered within inner
loop then it terminates inner loop not outer loop i.e. control comes out from inner loop but stays
within outer loop.
General syntax for break statement is:
break;

Program to illustrate concept of break:


Program 1 Output

Manish Kumar Shah(MKS) 93


93 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> i=1
#include<conio.h> i=2
i=3
void main() i=4
{
int i;
clrscr();
for(i=1; i<=10; i++)
{
if(i==5)
{
break;
}
printf("i = %d\n",i);
}
getch();
}

Explanation: In this program when value of i is equal to 5 then break is executed and
control comes out from loop. So, we don’t get output 5,6,7,8,9 and 10 though it is set in
loop.

Program 2
#include<stdio.h>
#include<conio.h>

void main()
MKS Output
Run1
Enter positive integer number: 17↲
PRIME.

{ Run2
int i,n, flag=0; Enter positive integer number: 12↲
clrscr(); NOT PRIME.
printf("Enter positive integer number: ");
scanf("%d", &n);
for(i=2; i<=n/2; i++)
{
if(n%i==0)
{
flag=1;
break;
}
}
if(flag==0)
{
printf("PRIME.");
}
else
{
Manish Kumar Shah(MKS) 94
94 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
printf("NOT PRIME.");
}
getch();
}

Program 3 : break in nested loop Output


#include<stdio.h> i=2 j=1
#include<conio.h> i=3 j=1
i=3 j=2
void main()
{
int i, j;
clrscr();
for(i=1; i<=3; i++)
{
for(j=1; j<=3; j++)
{
if(i==j)

MKS
{
break;
}
printf("i=%d\tj=%d\n",i,j);
}
}
getch();
}

The continue Statement


The continue statement only works within loop. When continue is encountered within loop then
it forces the next iteration or repetition to take place by skipping all the statements after it in the
loop.
In for loop, continue causes the increment and control is transferred to test condition in the loop.
In while and do-while loops, continue passes the program control to test condition in the loop
without incrementing loop control variable. So, care must be taken while using continue within
while and do-while loops to prevent infinite looping.
General syntax for continue statement is:
continue;

Manish Kumar Shah(MKS) 95


95 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Note: When continue is encountered within nested loop then it passes control to test condition of
that loop where it is encountered like in break.
Program to illustrate concept of continue:
Program 1 Output
#include<stdio.h> i=5
#include<conio.h> i=6
i=7
void main() i=8
{ i=9
int i; i = 10
clrscr();
for(i=1; i<=10; i++)
{
if(i<5)
{
continue;
}
printf("i = %d\n",i);
}

MKS
getch();
}

Explanation: In this program when value of i is less than 5 then continue is executed and
which prevents printf() statement to be executed since control is transferred to test
conditions. So, we don’t get output for those value of i which are less than 5.
Program 2 : continue in nested loop Output
#include<stdio.h> i=1 j=1
#include<conio.h> i=2 j=2
void main() i=3 j=3
{
int i, j;
clrscr();
for(i=1; i<=3; i++)
{
for(j=1; j<=3; j++)
{
if(i != j)
{
continue;
}
printf("i=%d\tj=%d\n",i,j);
}
}
getch();
}
Manish Kumar Shah(MKS) 96
96 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Difference between break and continue statement


S.N. break continue
1. break when encountered within loop then continue when encountered within loop then
terminates the loop. it forces next iteration of loop to take place
by passing program control to test condition
of loop.
2. Syntax: break Syntax: continue
3. break can be used within switch statement continue is always used within loop only.
or looping statement.
4. Example: 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<=8; i++) for(i=1; i<=8; i++)
{ {

MKS
if(i==5) if(i<5)
{ {
break; continue;
} }
printf("i = %d\n",i); printf("i = %d\n",i);
} }
getch(); getch();
} }
Output is: Output is:
i=1 i=5
i=2 i=6
i=3 i=7
i=4 i=8

goto and Labels


The goto statement is used to alter unconditionally the normal sequence of program execution by
transferring control to some other part of the program. Syntax for goto is:
goto some_label;
Here, the goto statement requires a label to specify the place where program control is to be
transferred. some_label can be any valid C identifier followed by colon.
Program to illustrate concept of continue:
Program Output

Manish Kumar Shah(MKS) 97


97 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> Enter number: 5↲
#include<conio.h> ODD.
Check another
void main() number? (Enter y
{ for yes)
int num; y↲
char ch; Enter number: 8↲
clrscr(); EVEN.
up: Check another
printf("\nEnter number: "); number? (Enter y
scanf("%d", &num); for yes)
if(num%2==0) n↲
{
printf("EVEN.");
}
else
{
printf("ODD.");
}
printf("\nCheck another number? (Enter y for yes)\n");
scanf(" %c", &ch);

MKS
if(ch=='y')
{
goto up;
}
getch();
}

The exit() Function


exit() function is library function defined in header file stdlib.h and is used to terminate program
i.e. when exit() function gets executed then program is terminated. While using exit() function
some integer value is passed i.e. like exit(0) or exit(1) or exit(some_integer_value). Generally
exit(0) indicates successful termination of program and other than 0 value indicates unsuccessful.

General syntax for exit() function is:


exit ( some_integer_value );

Program to illustrate concept of exit() function:


Program Output

Manish Kumar Shah(MKS) 98


98 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> Run1
#include<conio.h> Enter a and b:
3
void main() 4
{ a/b = 0.750000
float a,b;
clrscr(); Run2
printf("Enter a and b:\n"); Enter a and b:
scanf("%f%f ", &a, &b); 3
if(b==0.0) 0
{ Division not possible.
printf("Division not possible.");
getch();
exit(0);
}
printf("a/b = %f ", a/b);
getch();
}

MKS
Solved Programs with Algorithm and Flowchart
1. Program to find factorial of a given number
Program Output
#include<stdio.h> Enter n: 5↲
#include<conio.h> Factorial is 120
void main()
{ Note: ↲ indicates enter is pressed.
int i,f=1,n;
printf(“Enter n: ”);
scanf(“%d”, &n);
for(i=1; i<=n; i++)
{
f = f*i;
}
printf(“Factorial is : %d”, f);
getch();
}

Flowchart

Manish Kumar Shah(MKS) 99


99 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Start

Read N

I=1
F=1

Is
I N
? No

Yes

F=FxI Display F

MKS
I=I+1
Stop

Algorithm
Step 1: Start
Step 2: Read value of N
Step 3: Set F=1 and I=1
Step 4: Calculate F = F * I
Step 5: I = I+1
Step 6: If I<=N then goto step 4 otherwise goto step 7
Step 7: Print value of F
Step 8: Stop

2. Program to check whether a given number is odd or even.


Program Output
#include<stdio.h> Enter n: 5↲
#include<conio.h> ODD
void main()
{
int n;
printf(“Enter n: ”);
scanf(“%d”, &n);
if(n%2==0)
Manish Kumar Shah(MKS) 100
100 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
{
printf(“EVEN”);
}
else
{
printf(“ODD”);
}
getch();
}

Flowchart
Start

Read N

Is
MOD(N,2)=0
?

MKS
Print ODD Print EVEN

Stop

Algorithm
Step 1: Start
Step 2: Read value of N
Step 3: If MOD(N,2)=0 then print “EVEN” otherwise print “ODD”
Step 4: Stop
Solved Programs
1. Program to check whether a given number is prime or not.
Program Output

Manish Kumar Shah(MKS) 101


101 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> Run1
#include<conio.h> Enter number: 17↲
void main() PRIME
{
int num,i,count=0; Run2
clrscr(); Enter number: 12↲
printf("Enter number: "); NOT PRIME
scanf("%d",&num);
for(i=2; i<=num-1; i++)
{
if(num%i==0)
{
count++;
}
}
if(count==0)
{
printf("PRIME");
}
else
{

MKS
printf("NOT PRIME");
}
getch();
}
2. Program to generate prime numbers between 1 and 100.
Program Output
#include<stdio.h> 2 3 5 7 11 13 17
#include<conio.h> 19 23 29 31 37 41
43 47 53 59 61 67
void main() 71 73 79 83 89 97
{
int i,j,count;
clrscr();
for(i=2; i<100; i++)
{
count=0;
for(j=2; j<=i-1; j++)
{
if(i%j==0)
{
count++;
}
}
if(count==0)
{
printf("%d\t", i);

Manish Kumar Shah(MKS) 102


102 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
}
getch();
}

3. Program to generate prime numbers between min and max, where min and max are
given by user and min<=max.
Program Output
#include<stdio.h> Enter min and max:
#include<conio.h> 10↲
20↲
void main() 11 13 17
{
int i,j,count,min,max;
clrscr();
printf(“Enter min and max:\n”);
scanf(“%d%d”, &min, &max);
for(i=min; i<max; i++)
{

MKS
count=0;
for(j=2; j<=i-1; j++)
{
if(i%j==0)
{
count++;
}
}
if(count==0)
{
printf("%d\t", i);
}
}
getch();
}

4. Program to generate first 10 prime numbers.


Program Output

Manish Kumar Shah(MKS) 103


103 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> 2 3 5 7 11 13 17
#include<conio.h> 19 23 29

void main()
{
int i=2,j,count, pcount=0;
clrscr();
while(pcount<10)
{
count=0;
for(j=2; j<=i-1; j++)
{
if(i%j==0)
{
count++;
}
}
if(count==0)
{
printf("%d\t", i);
pcount++;

MKS
}
i++;
}
getch();
}

5. Program to generate first n prime numbers, where n is given by user.


Program Output
#include<stdio.h> Enter n: 15↲
#include<conio.h> 2 3 5 7 11 13 17
19 23 29 31 37 41
void main() 43 47
{
int i=2,j,count, pcount=0,n;
clrscr();
printf(“Enter n: ”);
scanf(“%d”, &n);
while(pcount<n)
{
count=0;
for(j=2; j<=i-1; j++)
{
if(i%j==0)
{
count++;
}
Manish Kumar Shah(MKS) 104
104 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
if(count==0)
{
printf("%d\t", i);
pcount++;
}
i++;
}
getch();
}

6. Program to find sum of first digit and last digit of a given number.
Program
#include<stdio.h>
#include<conio.h>

void main()
{
int num, rev=0, fd, ld, rem, sum;

MKS
clrscr();
printf("Enter number: ");
scanf("%d",&num);
ld = num%10;
while(num!=0)
{
rem = num%10;
rev = rev*10+rem;
num = num/10;
}
fd = rev %10;
sum = fd + ld;
printf("Sum is : %d", sum);
getch();
}

7. Program to check whether a given three-digit number is Armstrong number or not.


Program
#include<stdio.h>
#include<conio.h>

void main()
{
int num, sum=0, rem, numcopy;
clrscr();
printf("Enter three digit number:\n");

Manish Kumar Shah(MKS) 105


105 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
scanf("%d", &num);
numcopy = num;
while(num != 0)
{
rem = num%10;
sum = sum + rem*rem*rem;
num = num/10;
}
if(numcopy == sum)
{
printf("%d is Armstrong.", numcopy);
}
else
{
printf("%d is not Armstrong.", numcopy);
}
getch();
}

8. Program to check whether a given number is Armstrong number or not. (For any digit

MKS
number)
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int num, count=0, sum=0, numcopy, rem;
clrscr();
printf("Enter number:\n");
scanf("%d", &num);
numcopy = num;
while(num != 0)
{
count++;
num = num/10;
}
num = numcopy;
while(num != 0)
{
rem = num % 10;
sum = sum + pow(rem, count);
num = num/10;
}
if(sum == numcopy)
{
Manish Kumar Shah(MKS) 106
106 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
printf("%d is Armstrong.", numcopy);
}
else
{
printf("%d is not Armstrong.", numcopy);
}
getch();
}

9. Program to generate Armstrong number between min and max, where min and max
are given by user and min<=max.
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i, min, max, num, count=0, sum=0, rem;
clrscr();

MKS
printf("Enter min and max:\n");
scanf("%d%d", &min, &max);
for(i=min; i<=max; i++)
{
num=i;
count = 0;
while(num != 0)
{
count++;
num = num/10;
}
num = i;
sum = 0;
while(num != 0)
{
rem = num % 10;
sum = sum + pow(rem, count);
num = num/10;
}
if(sum == i)
{
printf("%d\t", i);
}
}
getch();
}

Manish Kumar Shah(MKS) 107


107 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
10. Program to generate n Fibonacci terms, where n is given by user.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int n, a=1, b=1, next, i;
clrscr();
printf("Enter n: ");
scanf("%d", &n);
printf("%d\t%d\t",a,b);
for(i=1; i<=n-2; i++)
{
next = a + b;
printf("%d\t", next);
a = b;
b = next;
}
getch();
}

#include<stdio.h>
#include<conio.h>
void main()
MKS
11. Program to find HCF (GCD) and LCM of two numbers.
Program

{
int num1, num2, a,b,temp,hcf,lcm;
clrscr();
printf("Enter two numbers:\n");
scanf("%d%d",&num1,&num2);
a=num1;
b=num2;
while(b!=0)
{
temp=b;
b=a%b;
a=temp;
}
hcf=a;
lcm=(num1*num2)/hcf;
printf("HCF = %d\nLCM = %d\n",hcf,lcm);
getch();
}

Manish Kumar Shah(MKS) 108


108 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

12. Program to find sum of digit until it reduces to single digit. Also display sum it each
step. Hint: if 456 is given number then step1 = 4+5+6=15, step2 = 1+5=6.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num, sum, step=1, rem;
clrscr();
printf("Enter number:\n");
scanf("%d", &num);
do
{
sum = 0;
while(num!=0)
{
rem = num % 10;
sum += rem;
num = num/10;
}
num=sum;
printf("Step-%d = %d\n",step, sum);

MKS
step++;
} while(num>9);
getch();
}

Manish Kumar Shah(MKS) 109


109 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Functions
C programs are highly dependent on functions. Functions are the basic building blocks of C
programs. Every C program is combination of one or more functions. Execution of program
written in C starts from unique function known as main() function and it calls other functions
directly or indirectly to share the programming task.
Till now we have seen functions like printf(), scanf(), pow(), sqrt(), clrscr() etc. These types of
functions are already defined, compiled and stored in different header file of standard C library.
To use these types of functions all we need to do is to include their respective header file to the
program. These types of functions are known as library functions or built-in functions and are
the part of C compiler. In C programming, we can have another type of functions known as user
defined functions which are written by programmers according to their requirement at the time of
writing a program.
Classification of C Functions
C functions are broadly classified into two major categories:
1. Library or Built – in Functions
2. User Defined Functions

MKS
1. Library or Built – in Functions
Library functions are those type of functions which are already defined, compiled and stored in
different header file of standard C library. Library functions are part of C compiler and ships with
compiler. We can use these functions as required by including their respective header file and we
need not to worry about their source code or how they accomplish their tasks. Examples of library
functions are: printf(), scanf(), sin(), sqrt(), getch() etc.
2. User Defined Functions
Major advantage of C language is that we can create our own functions as required. The functions
which are defined by the programmers according to their requirement are known as user defined
functions. Unlike library functions, programmers can modify user defined functions according to
their requirement and understand the internal working of functions. In this chapter we take a broad
look at user defined functions.
Difference Between Library Functions and User Defined Functions
S.N. Library Functions User Defined Function
1. Functions which are already defined, Those functions which are defined by
compiled and stored in different programmers according to their need are known
header file of C Library are known as as User Defined Functions.
Library Functions.
2. These functions cannot be modified These functions can be modified by user.
by user.

Manish Kumar Shah(MKS) 110


110 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
3. Users do not know the internal Users understand the internal working of these
working of these type of functions. type of functions.
4. For Example: For Example:
printf(), scanf(), getch(),
clrscr(), pow() etc. void message()
{
printf(“Welcome to C.”);
}

Here message() is user defined function.

Need for User Defined Functions


While writing C programs, till now, we have created single list of instructions within main()
functions and such programs are known as monolithic program – i.e. program containing a large
single list of instructions. These types of programs are very difficult to understand, debug, test and
maintain. So to avoid these difficulties we use user defined functions. User defined function is also
known as sub-program and has clearly defined objective and interface with other functions in the
program. Which makes it very easy to understand, debug, test and maintain. Reduction in program
size is another reason for using user defined functions. Any sequence of statements which are

MKS
repeatedly used in a program can be combined together to form a user defined function and this
function can be called as many times as required thus saving both time and space.
Advantage of User Defined Functions
Advantages of using user defined functions in C programming are listed below:
a. Reduction in Program Size: Since any sequence of statements which are repeatedly used
in a program can be combined together to form a user defined functions. And this functions
can be called as many times as required. This avoids writing of same code again and again
reducing program size.
b. Reducing Complexity of Program: Complex program can be decomposed into small sub-
programs or user defined functions.
c. Easy to Debug and Maintain: During debugging it is very easy to locate and isolate faulty
functions. It is also easy to maintain program that uses user defined functions.
d. Readability of Program: Since while using user defined function, a complex problem is
divided in to different sub-programs with clear objective and interface which makes easy
to understand the logic behind the program.
e. Code Reusability: Once user defined function is implemented it can be called or used as
many times as required which reduces code repeatability and increases code reusability.

Manish Kumar Shah(MKS) 111


111 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Defining and Using User Defined Functions
Basically a user defined function is a sub-program which groups a number of program statements
into a single unit for accomplishing specific task and assigns it a name. To use user defined
function, three steps are involved, they are:
1. Function Prototype or Function Declaration
2. Function Definition
3. Function Call
1. Function Prototype or Function Declaration
Like any variable in a C program it is necessary to declare a function before it’s use. Declaration
of function informs the compiler about the existence of function and it will be defined and used
later. This declaration of function is also known as function prototype. In C programming, function
can be declared using following syntax.
General syntax for declaring function prototype is:

return_type function_name(type1 var1, type2 var2, ...... , typeN varN);

Here,
MKS
a) return_type can be any valid C data types.
b) function_name can be any valid C identifiers.
c) type1, type2, ...., typeN can be any valid C data types and var1, var2, ....,
varN can be any valid C variables.

Function prototype gives following information about user defined functions:


a) List of data that should be passed to user defined function for its operation with their data
types. In the syntax, comma-separated list of variables along with their data types ( i.e
type1 var1, type2 var2, ......, typeN varN ) within parentheses after
function_name is this list. This list is also known as formal arguments or formal
parameters.
(Note: If this list is empty (i.e. function without arguments) then it should be noted that
function does not require any data for its operations.)

b) Type of value that user defined function returns when it is called or used. This is indicated
by return_type at the beginning of the function prototype.
(Note: If void is used in the place of return_type then it indicates that function does not
return anything)
Function Prototypes Examples:
Manish Kumar Shah(MKS) 112
112 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Example 1:

float my_sum(float x, float y);

Here, my_sum() is user defined function and it takes two arguments of type float and when it is
called or used it returns a value of float type.
Example 2:
void message();
Here, message() is user defined function and it does not take any arguments for its operations and
it does not return any value when it is called or used.
Example 3:

double fact(int x);

Here, fact() is user defined function and it takes one argument of type int and when it is called or
used it returns a value of double type.

MKS
(Note: If return_type is avoided then in C int is considered as default return type)

2. Function Definition
In C programming, a user defined function must be defined before it is called or used in the
program. Function definition consists all the code required for its implementation.
General syntax for function definition is:

return_type function_name(type1 var1, type2 var2, ...... , typeN varN)


{
statement1;
statement2;
.
.
.
satementN;

return statement;
}

Function Definition Examples:


Now we write function definition for the all the examples that are used while declaring function
prototypes.

Manish Kumar Shah(MKS) 113


113 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Example 1:
float my_sum( float x, float y)
{
float sum;
sum = x + y;
return(sum);
}

Here, my_sum() is user defined function which takes two arguments of type float. When it is called
or used then it receives data on variable x and y. After receiving data, it processes these data
according to requirement and finally it returns a value of type float using return keyword. Value
is always returned to that portion from where it is called or used.
In this example, values are received in x and y, we add them and store in variable sum and finally
we return value of sum.
Example 2:
void message()
{
printf(“Welcome to C Programming!”);
}

MKS
Here, message() is user defined function which does not take any arguments. When it is called or
used then it prints message “Welcome to C Programming!”. After printing message then
program control is transferred back to that portion of program from where it is called or used.
Alternatively, we can use return keyword without returning any value to transfer control from
called function to calling function like this:
void message()
{
printf(“Welcome to C Programming!”);
return;
}

Example 3:

double fact(int x)
{
double f=1;
int i;
for(i=1; i<=x; i++)
{
f = f*i;
}
return(f);
}

Manish Kumar Shah(MKS) 114


114 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Here, fact() is user defined function which takes one argument of type int. When it is called or
used then it receives data on variable x. After receiving data, it processes these data according to
requirement and finally it returns a value of type double using return keyword. Value is always
returned to that portion from where it is called or used.
In this example, value is received in x, then user defined function computes factorial of x and
stores it in f and finally it returns value of f.
3. Function Call
After declaring and defining user defined function, it can be used when needed. Generally, user
defined function is used by calling or invoking it by passing required data, if necessary, for its
functioning. Using function by providing data required for its functioning is known as function
call.
General syntax for function call is:

function_name( var1, var2, ...... , varN );

MKS
Here, var1, var2, ......, varN contains some value that are being passed to user defined
functions. Since these variables contain actual data which are required for the functioning of user
defined function. This comma separated list of variables which contains actual value is known as
actual arguments.
Function Call Examples:
Now we make function call for all the functions that are declared and defined in the examples of
function prototype and function definition sections.
Example 1:

float num1=12.34, num2=34.67, result;

result = my_sum( num1, num2 ); /* This is function call */

Here user defined function my_sum() is called with two values num1 and num2 which are of type
float because function my_sum() requires two values of type float for its functioning which is
defined and declared in prototypes and definition sections. After calling my_sum() function, values
of num1 (i.e. 12.34) and num2 (i.e. 34.67) will be copied to variable x and y (Confused? From
where x and y came? See function definition for my_sum() in examples section of function
definition above. These are the formal arguments used in function definition which are used for
receiving data). Here variable result of type float is also used because my_sum() is declared and
defined in such a way that it finally returns a value of float type. Value returned by my_sum()
function is assigned to variable result.

Manish Kumar Shah(MKS) 115


115 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Example 2:

message();

Here user defined function message() is called without any arguments because, in prototype and
definition section, it is declared and defined in such a way that it does not require any arguments.
Similarly, no variable is used to assign value returned by function because prototypes of this
function tells that it does not return any value when called (i.e. void is used in return_type).
Example 3:

int num = 5;
double res;

res = fact( num ); /* This is function call */

Here user defined function fact() is called with value of num which is of type int because function
fact() requires a value of type int for its functioning which is defined and declared in prototypes
and definition sections. After calling fact() function, value of num (i.e. 5) will be copied to variable
x (Confused? From where x came? See function definition for fact() in examples section of

MKS
function definition above. This is the formal argument used in function definition which is used for
receiving data). Here variable res of double types is also used because fact() is declared and
defined in such a way that it finally returns a value of double type. Value returned by fact()
function is assigned to variable res.
Now, we combine all these examples that are discussed in function prototype, function definition
and function call to make a complete program.
Program 1:
/*
Program: Sum of two numbers using user defined function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

float my_sum(float x, float y); /* Function Prototype */

void main()
{
float num1=12.34, num2=34.67, result;
clrscr();
result = my_sum(num1, num2); /* Function Call */
printf("Sum is : %f.",result);
getch();
}

Manish Kumar Shah(MKS) 116


116 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

float my_sum(float x, float y) /* Function definition */


{
float sum;
sum = x + y;
return(sum);
}
Output
Sum is : 47.010000.

Program 2:
/*
Program: Displaying some message using user defined function
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

void message(); /* Function Prototype */

MKS
void main()
{
clrscr();
message(); /* Function Call */
getch();
}

void message() /* Function Definition */


{
printf("Welcome to C Programming!");
}
Output
Welcome to C Programming!

Program 3:
/*
Program: Factorial of a number using user defined function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

double fact(int x); /* Function Prototype */

Manish Kumar Shah(MKS) 117


117 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
void main()
{
int num=5;
float res;
clrscr();
res = fact(num); /*Function Call */
printf("Factorial is : %lf.", res);
getch();
}

double fact(int x) /* Function Definition */


{
int i;
double f=1;
for(i=1;i<=x;i++)
{
f = f*i;
}
return(f); /* Returning calculated factorial */
}
Output
Factorial is : 120.000000.

Formal Arguments MKS


More on Formal Arguments, Actual Arguments and return Keyword

Comma separated list of variables along with their types used in function definition through which
function receives data when called from other function are known as formal arguments or formal
parameters. In program1 above float x, float y in function definition are formal arguments.
Similarly, in program2 above int x in function definition is formal argument.
Actual Arguments
Comma separated list of variables that are used in function call through which function sends data
from calling function to called function are known as actual arguments or actual parameters. In
program1 above num1, num2 used in function call i.e. my_sum(num1, num2) are actual
arguments. Similarly, in program2 above num used in function call i.e. fact(num) is actual
argument.
return Keyword
The return() statement has two purposes. First, executing it immediately transfers control from
the function back to the calling function. And second, whatever is inside the parentheses following
return is returned as a value to the calling function. The return statement may or may not include
an expression. If return contains no parameters, then this return is used to transfer the control used
only with void else if return has got argument having bracket or without bracket then this return is
Manish Kumar Shah(MKS) 118
118 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
returning a value to the calling portion of the function. There is no restriction on the number of
return statements that may be present in a function. Also the return statement need not be always
being present at the end of the called function.
Note: Using a return keyword only one value can be returned from a function.
General syntax for return is:
return;
or
return(some_value);
or
return some_value;
or
return(some_expression);
or
return some_expression;

Working of a User Defined Function


1. Once a user defined function is declared, defined and called, it takes some data from the
calling function and returns a value to the called function.

MKS
2. The detail of inner working of a user defined function is unknown to the rest of the program.
Wherever a function is called, control passes to the called function and working of calling
function is stopped until the execution of called function. When the execution of called
function is completed, control is transferred back to calling function and executes the next
statement.
3. The values of actual arguments passed by the calling are received by the formal arguments
of the called function. The actual arguments in the calling function must agree in number,
order and type with the formal arguments in the function declaration and function
definition. Any mismatch will produce the unexpected result.
4. The function operates on formal arguments and send back the result to the calling function
using return keyword.
Rules that must be Followed while Declaring and Defining User Defined Function
a. A function prototype declaration must appear at the beginning of the program following
the #include statement. In a function prototype the type of the function and the type of each
formal argument must be specified. The variable names used for formal arguments in a
function prototypes are arbitrary; they may even be blanks. Each function prototype must
be terminated by a semicolon.
b. A function name may be any valid identifier. The type of the function specifies the type of
the quantity which will be returned to the calling program.
c. Each formal arguments type must be specified. For example float add(int a,b,c) is invalid
and should be in the form float add(int a, int b, int c).

Manish Kumar Shah(MKS) 119


119 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
d. Within a function definition other variables may be declared and used. Such variables are
local to the function and are not known outside the body of the function.
e. Within a function definition one cannot define another function.
Rules that must be Followed while Calling a Function
a. The actual arguments in the calling function must agree in number, order and type with the
formal arguments in the function declaration.
b. Copies of the values of actual arguments are sent to the formal arguments and the function
is executed. Thus the actual arguments remain unchanged.
c. A return statement in the body of the function returns a value to the calling function. The
type of expression used in return statement must match with the return_type of the function
declared. There may be functions without return statement. In such a case the function must
be declared as void.
d. A function can return only one value.
Category of Functions
Basically a user defined function is defined based on whether the arguments are present or not and
whether a user defined function returns a value or not. Based on the arguments and return types

MKS
present, user defined functions are classified into four categories.
1. Function with arguments and return value.
2. Function with arguments and no return value.
3. Function with no arguments and return value.
4. Function with no arguments and no return value.
1. Function with arguments and return value
In this type of user defined function, the values of actual arguments are transferred to formal
arguments and function returns a value to the calling function. This is illustrated diagrammatically
in following Figure:

Values of arguments

Calling Function Called Function


Returned Value

Figure: Illustration of function with arguments and return value.


Example: Program to find ax, where x is integer, to illustrate user defined function with arguments
and return vale.
/*
Program: Finding a^x using user defined function.
Author: Ramesh Bhandari

Manish Kumar Shah(MKS) 120


120 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

double my_pow(float b, int e); /* Function Prototype */

void main()
{
float a;
int x;
double res;
clrscr();
printf("Enter value of a: ");
scanf("%f", &a);
printf("Enter value of x: ");
scanf("%d",&x);
res = my_pow(a,x); /* Function Call */
printf("Result is: %lf.",res);
getch();
}

double my_pow(float b, int e) /* Function Definition */

MKS
{
int i;
double p=1;
for(i=1; i<=e; i++)
{
p = p*b;
}
return(p); /* Returning computed value */
}

Output
Enter value of a: 2.5↲
Enter value of x: 4↲
Result is: 39.062500.

2. Function with arguments and no return value


In this type of user defined function, the values of actual arguments are transferred to formal
arguments and function does not return a value to the calling function. This is illustrated
diagrammatically in following Figure:

Manish Kumar Shah(MKS) 121


121 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Values of arguments

Calling Function Called Function


No Value is Returned

Figure: Illustration of function with arguments and no return value.


Example: Program to check whether a given number is prime or not to illustrate user defined
function with arguments and no return vale.
/*
Program: Prime check using user defined function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

void prime_check(int n); /* Function Prototype */

MKS
int main()
{
int num;
clrscr();
printf("Enter any integer number: ");
scanf("%d", &num);
prime_check(num); /* Function Definition */
getch();
return(0);
}

void prime_check(int n) /* Function Definition */


{
int i, flag=0;
for(i=2; i<=n/2;i++)
{
if(n%i == 0)
{
flag=1;
break;
}
}

if(flag == 0 && n>1)


{
printf("%d IS PRIME.",n);
}
else
{
printf("%d IS NOT PRIME.",n);

Manish Kumar Shah(MKS) 122


122 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
}
Output
Run1
Enter any integer number: 17↲
17 IS PRIME.

Run2
Enter any integer number: -8↲
-8 IS NOT PRIME.

3. Function with no arguments and return value


In this type of user defined function, no arguments are used and function returns a value to the
calling function. This is illustrated diagrammatically in following Figure:

No Arguments

MKS
Calling Function Called Function
Returned Value

Figure: Illustration of function with arguments and no return value.


Example: Program to find sum of digit of a given number to illustrate user defined function with
no arguments and return vale.
/*
Program: Sum of digit of a number using user defined function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

int sum_of_digit(); /* Function Definition */

int main()
{
int s;
clrscr();
s = sum_of_digit(); /* Function Call */
printf("Sum of digit is %d.", s);
getch();
return(0);

Manish Kumar Shah(MKS) 123


123 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}

int sum_of_digit() /* Function Definition */


{
long int num;
int rem, sum=0;
printf("Enter number: ");
scanf("%ld", &num);
while(num != 0)
{
rem = num % 10;
sum += rem;
num /= 10;
}

return(sum); /* Returning computed sum of digit */


}
Output
Enter number: 123456789↲
Sum of digit is 45.

4. Function with no arguments and no return value

MKS
In this type of user defined function, no arguments are used and function does not return a value
to the calling function. This is illustrated diagrammatically in following Figure:

No Arguments

Calling Function Called Function


No Value is Returned

Figure: Illustration of function with no arguments and no return value.


Example: Program to convert given decimal number to binary number to illustrate user defined
function with no arguments and no return vale.
/*
Program: Decimal to Binary using user defined function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

void binary(); /* Function Prototype */

int main()
{
Manish Kumar Shah(MKS) 124
124 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
clrscr();
binary(); /* Function Call */
getch();
}

void binary() /* Function Definition */


{
long int i,dec, bin=0, rem, num, base=1;
printf("Enter decimal number: ");
scanf("%ld",&dec);
num = dec;
while(num!=0)
{
rem = num%2;
bin = bin+base*rem;
num = num/2;
base = base*10;
}
printf("Decimal (%ld) = Binary (%ld)",dec, bin);
}
Output
Enter decimal number: 727↲
Decimal (727) = Binary (1011010111)

Nesting of Function

MKS
In C programming, nesting of user defined function is allowed. It does not mean that a function
can be defined inside another function but by nesting we mean that calling of a function by another
function, which in turns can call another function and so on.
For example, main() function can call user defined function function1(), which calls function2
which calls function3() and so on.
Example: Program to find nCr, where n and r are given by user and n>r, to illustrate nesting of
function.
/*
Program: Finding nCr to illustrate nesting of function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

long int comb(int m, int n); /* Function Prototype to Find Combination */


long int fact(int a); /*Function Prototype to Calculate Factorial */

void main()
{

Manish Kumar Shah(MKS) 125


125 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
int n,r;
long int result;
clrscr();
printf("Enter value of n and r:\n");
scanf("%d%d", &n, &r);
result = comb(n,r); /* Function Call */
printf("%d C %d = %ld",result);
getch();
}

long int comb(int m, int n) /* Function Definition to Find Combination */


{
long int nf, rf,n_rf;
nf = fact(m); /* This is Nesting of Function */
rf = fact(n); /* This is Nesting of Function */
n_rf = fact( m – n ); /* This is Nesting of Function */
return( nf/(n_rf * rf)); /* Returning Computed Value to main() */
}

long int fact(int a) /* Function Definition to Calculate Factorial */


{
long int f=1;
int i;
for(i=1; i<=a; i++)

MKS
{
f *= i;
}
return(f);
}

Output
Enter value of n and r:
12↲
7↲
12 C 7 = 792

Recursive Function
In C programming, a function is allowed to call itself. A function which calls itself directly or
indirectly again and again until some specified condition is satisfied is known as recursive
function.
Recursion is the process of defining something in terms of itself. Recursion has many negatives.
It repeatedly invokes the mechanism, and consequently increases the overhead of function calls.
This repetition can be expensive in terms of both processor time and memory space. Each recursive
call causes another copies of the function, these set of copies can consume considerable memory
space.

Manish Kumar Shah(MKS) 126


126 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Example 1: Program to find factorial of a given number recursively to illustrate recursive
function.
/*
Program: Factorial of a given number using recursive function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/
#include<stdio.h>
#include<conio.h>
int fact(int n); /* Function Definition */
void main()
{
int num, res;
clrscr();
printf("Enter positive integer: ");
scanf("%d",&num);
res = fact(num); /* Normal Function Call */
printf("%d! = %d" ,num ,res);
getch();
}
int fact(int n) /* Function Definition */
{
int f=1;

MKS
if(n <= 0)
{
return(1);
}
else
{
f = n * fact(n-1); /* Recursive Function Call as fact() calls itself */
return(f);
}
}
Output
Enter positive integer: 5↲
5! = 120

Illustration of Recursion using above example:

Manish Kumar Shah(MKS) 127


127 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

main() fact(int n ) fact(int n ) fact(int n )


num = 5 returns: returns: returns:
res = fact(5 ) f = 5 * fact(4 ) f = 4 * fact(3 ) f = 3 * fact(2)
4x3x2x1x1 3x2x1x1
5x4x3x2x1x1 2 x 1 x1
fact(int n ) fact(int n )
fact(int n)
returns: returns: returns:
f=1 f = 1 * fact(0) f = 2 * fact(1)

1x1
1

Figure: Illustration of Recursive Function.


Example 2: Program to find ax, where a and x given by user and a is integer, recursively to
illustrate recursive function.

MKS
/*
Program: a^x using recursive function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

float power(float b, int e); /* Function Prototype */

void main()
{
int x;
float a ,r;
clrscr();
printf("a = ");
scanf("%f", &a);
printf("x = ");
scanf("%d", &x);
r = power(a,x); /* Normal Call */
printf("Result is %f", r);
getch();
}

float power(float b, int e) /* Function Definition */


{
if (e <= 0)
{
return(1);
}

Manish Kumar Shah(MKS) 128


128 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
else
{
return( b * power(b, e-1) ); /* Recursion as power() calls itself */
}
}
Output
a = 2.5↲
x = 3↲
Result is 15.62500

Example 3: Program to find nth term of Fibonacci series recursively to illustrate recursive
function.
/*
Program: Nth term of Fibonacci series using recursive function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

MKS
int fib(int n); /* Function Prototype */

int main()
{
int a, r;
clrscr();
printf("Which term?: ");
scanf("%d", &a);
r = fib(a); /* Normal Function Call */
printf("%dth term of Fibonacci series is %d." ,a,r);
getch();
return(0);
}

int fib(int n) /* Function Definition */


{
if(n == 1)
{
return(1);
}
else if(n == 2)
{
return(1);
}
else
{
return( fib(n-1) + fib(n-2) ); /* Recursive call as fib() calls itself */
}
}

Manish Kumar Shah(MKS) 129


129 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Output
Which term?: 9↲
9th term of Fibonacci series is 34.

Example 4: Program to generate Fibonacci series up to n terms, where n is given by user.


#include<stdio.h>
#include<conio.h>

int fib(int n); /* Function Prototype */

int main()
{
int t, r;
clrscr();
printf("How many terms?: ");
scanf("%d", &t);
for(i=1;i<=t;i++)
{
r = fib(i); /* Normal Function Call */
printf(“%d\t”, r);
}

MKS
getch();
return(0);
}

int fib(int n) /* Function Definition */


{
if(n == 1)
{
return(1);
}
else if(n == 2)
{
return(1);
}
else
{
return( fib(n-1) + fib(n-2) ); /* Recursive call as fib() calls itself */
}
}

Output
How many terms? 5↲
1 1 2 3 5

Example 5: Program to find sum of digit of a given number recursively.

Manish Kumar Shah(MKS) 130


130 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h>
#include<conio.h>

long int sod(long int x);

void main()
{
long int n,r;
printf("Enter number:\n");
scanf("%ld",&n);
r = sod(n);
printf("Sum of digit of %ld is %ld.", n, r);
getch();
}

long int sod(long int x)


{
if(x==0)
{
return(0);
}
else
{
return(x%10 + sod(x/10));

MKS
}
}

Output
Enter number:
67458↲
Sum of digit of 67458 is 30.

Recursion vs Iteration
1. Both Iteration and Recursion are based on control statements: Iteration uses a repetition
statement (such as for, while, do-while); Recursion uses a selection statement such as (if,
if-else, or switch).
2. Both Iteration and Recursion involves repetition: Iteration explicitly uses a repetition
statement; Recursion achieves repetition through repeated function calls.
3. Both Iteration and Recursion involve a termination test: Iteration terminates when the loop
continuation condition fails; Recursion terminates when a base case is recognized.
4. Both Iteration and Recursion can occur infinitely: An infinite loop occurs in the iteration
if the loop continuation test never becomes false (e.g. for(i=1; i>0; i++)); Infinite recursion
occurs if the recursion step does not reduce the problem each time in a manner that
converges on the base case.

Manish Kumar Shah(MKS) 131


131 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Macros
We have already seen that the #define statement can be used to define symbolic constants within
a program. At the beginning of a compilation process, all symbolic constants are replaced by their
equivalent text. Thus, symbolic constants provide a form of shorthand notation that can simplify
the organization of a program.
The #define statement is used to define macros.
Example 1: Program to find area of rectangle to illustrate macro.
/*
Program: Simple Macro to Calculate Area of Rectangle.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

#define area length*breadth /* This is Macro */

void main()

MKS
{
int length, breadth;
clrscr();
printf("Enter length and breadth:\n");
scanf("%d%d",&length, &breadth);
printf("Area is: %d", area);
getch();
}

Output
Enter length and breadth:
12↲
8↲
Area is 96

Example 2: Program to find area of to illustrate macro.


/*
Program: Simple Macro with Argument to Calculate Area of Circle.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/

#include<stdio.h>
#include<conio.h>

#define area(x) 3.141592*x*x /* This is Macro with Arguments */

Manish Kumar Shah(MKS) 132


132 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

void main()
{
float r, a;
clrscr();
printf("Enter radius: ");
scanf("%f",&r);
a = area(r);
printf("Area is: %f", a);
getch();
}
Output
Enter radius: 3.5↲
Area is: 38.484502

Though macro calls are like function calls, they are not really the same thing. In a macro call the
preprocessor replaces the macro template with its macro expansion. Whereas, in a function call
the control is passed to a function along with certain arguments, some calculations are performed
in the function and a useful value is returned back from the function. Usually macros make the
program run faster but increases the program size, whereas the function make the program smaller

MKS
and compact.
If we use macro hundred times in a program, the macro expansion goes into our source code at
hundred different places, thus increasing the program size. On the other hand, if a function is used,
then even if it is called from hundred different places in the program, it would take the same
amount of space in the program.
So, if the macro is simple and sweet like in our examples, it makes a nice shorthand and avoids
the overheads associated with function calls. On the other hand, if we have a fairly large macro
and it is used fairly often, replace macro with a function.
Local and Global Variables
Local Variables
Those variables which are defined within some function and are accessible to that function only
are called Local Variables. These are also known as internal or automatic variables. For local
variables default value is unpredictable and sometimes termed as garbage value. Scope (where
they can be used) of local variables is always local to that block where they are defined. Life of
local variable is until control is within the function or block.
Global Variables
Those variables which are defined outside of function block and are accessible to entire program
are known as Global Variables. For global variables default value is Zero (0). Scope (where they
can be used) of global variables is global i.e. they can be used anywhere in program. Life of global
variable is until program exits.
Manish Kumar Shah(MKS) 133
133 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Static Variables
Static variables are also defined within a function like local variables. Scope of these variables is
also local to that block where they are defined. Important thing about static variables is: though
they have the same scope as local variables, in case of static variables content is retained
throughout the program. Which means the static variables are not destroyed on exit from function,
their value is preserved and becomes available again when the function is called next time. Life of
static variable is until program exits.

Difference Between Local and Global Variables


S.N. Local Variables Global Variables
1. Those variables which are defined within Those variables which are defined outside of
some function and are accessible to that function block and are accessible to entire
function only are called Local Variables. program are known as Global Variables.
2. Scope is local to that block or function Scope is global i.e. they can be used anywhere
where they are defined. in the program.
3. Default value is unpredictable Default value is Zero (0).

MKS
(garbage).
4. Example: Example:
#include<stdio.h> #include<conio.h>
void main() int a=10,b;
{ void main()
int x=23, y=4; {
printf(“x = %d and y=%d”,x,y); printf(“a = %d and b=%d”,a,b);
} }
Here x and y are local variables. Here a and b are global variables.

Manish Kumar Shah(MKS) 134


134 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Array
Introduction
An array is a collection of homogeneous (same type) elements, which are stored in the consecutive
memory locations under a common variable name. It is also known as subscripted or indexed
variable because specific elements of an array are accessed by the name of an array and an index
or subscript within square brackets. In C Language, array index always starts from 0. The
individual values in an array are called array elements.
Arrays are classified in two categories:
1. One Dimensional Array
2. Multi-Dimensional Array
1. One Dimensional Array
The number of indexes used to access particular elements in an array is known as dimension of an
array. So, one dimensional array requires only one index to represent and use them. One
dimensional arrays are also known as Vectors.

MKS
a. Declaration of One Dimensional Array
Like other variables in C, array must be declared before we use it. Declaring the name and
type of an array and setting size i.e. the number of element that can be stored in an array is
known as array declaration. While declaring an array we must define name, type and size
of an array. Here size indicates the maximum number of elements that can be stored.
General Syntax for Declaring One Dimensional Array

data_type array_name[size];

For Example:
1. int arr[5];
Here arr is name of an array, size is 5 i.e. it can store 5 different integers value and its type
is int. Declared array arr can be illustrated using following diagram.

arr[0] arr[1] arr[2] arr[3] arr[4]

arr

Index → 0 1 2 3 4

Note: In C, array index starts from 0 and in this example array size is 5 so index ranges
from 0 to 4. In general array index ranges from 0 to size-1.
Manish Kumar Shah(MKS) 135
135 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

2. float a[8];
Here a is name of an array, size is 8 i.e. it can store 8 different real numbers and its type is
float.

b. Initialization of One Dimensional Array


Assigning values of one dimensional array elements at the time of its declaration is known
initialization of one dimensional array.
General Syntax for Initialization of one Dimensional Array

data_type array_name[size] = { comma_separated_list_of_values };

For Example:
1. int arr[5] = { 11, 23, 8, -19, 10 };
Here arr is name of an array, size is 5 i.e. it can store 5 different integer values and its type

MKS
is int. Declared and initialized array arr can be illustrated using following diagram.

arr[0] arr[1] arr[2] arr[3] arr[4]

arr 11 23 8 -19 10

Index → 0 1 2 3 4

After this initialization we can access each element by using array name and index within
square brackets like this:
arr[0] gives 11, arr[1] gives 23, arr[2] gives 8, arr[3] gives -19 and arr[4] gives 10

Similarly, this array can be initialized alternatively like this:


int arr[] = { 11, 23, 8, -19, 10 };

Note: Here size of array is not given, in this case compiler automatically sets its size
according to number of elements given.

So, writing int arr[] = { 11, 23, 8, 19, 10 }; is equivalent to writing int
arr[5] = { 11, 23, 8, 19, 10 };

2. float a[8] = { 75.5, 80, 78.5, 90.5};

Manish Kumar Shah(MKS) 136


136 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Here a is name of array and its size has been set to 8 but only 4 values are given. This
is allowed in C. Other values can be set later but memory is reserved for 8 elements.
This can be illustrated as:

a [0] a [1] a [2] a [3] a [4] a[5] a[6] a[7]

a 75.5 80 78.5 90.5

Index → 0 1 2 3 4 5 6 7

But remember! we can’t do something like this:


float a[3] = { 75.5, 80, 78.5, 90.5};
In this case array size is set to 3 but 4 values are given, this will produce error.

c. Program to Illustrate Declaration and Initialization of One Dimensional Array

Program1 Output

MKS
#include<stdio.h> Value of arr[0] is 11
#include<conio.h> Value of arr[1] is 23
Value of arr[2] is 8
void main() Value of arr[3] is -19
{ Value of arr[4] is 10
int arr[5] = {11,23,8,-19,10};
clrscr();
printf("Value of arr[0] is %d\n", arr[0]);
printf("Value of arr[1] is %d\n", arr[1]);
printf("Value of arr[2] is %d\n", arr[2]);
printf("Value of arr[3] is %d\n", arr[3]);
printf("Value of arr[4] is %d\n", arr[4]);
getch();
}

Program2 Output

Manish Kumar Shah(MKS) 137


137 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

#include<stdio.h> arr[0] = 11
#include<conio.h> arr[1] = 23
arr[2] = 8
void main() arr[3] = -19
{ arr[4] = 10
int i, arr[5] = {11,23,8,-19,10};
clrscr();

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


{
printf(“arr[%d] = %d\n”, i, arr[i] );
}
getch();
}
d. Reading, Processing and Writing of One Dimensional Array
Generally, for loop is used for reading, processing and writing of one dimensional array.
Reading Example:
Following structure is used for reading an array content.
int a[5], i;

MKS
for (i=0; i<5; i++)
{
printf(“a[%d] = ”, i);
scanf(“%d”, &a[i]);
}
After execution of this, array content will be read to a[0], a[1], a[2], a[3] and a[4].
Processing Example:
for (i=0; i<5; i++)
{
a[i] = 10+i;
}
After execution of this, array content will be, a[0] =10, a[1]=11, a[2]=12, a[3]=13 and
a[4]=14.
Writing Example:
for (i=0; i<5; i++)
{
printf(“%d\t”, a[i]);
}
After execution of this, array content will be displayed.
Note: These are just examples. While writing program similar structures will be used
based on problem being solved.
e. Different programs to illustrate concept of one dimensional array.

Manish Kumar Shah(MKS) 138


138 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Example1: Write a program in C to read an array containing 5 numbers and display its
content.
Program Output
#include<stdio.h> Enter 5 numbers:
#include<conio.h> arr[0] = 11↲
arr[1] = 25↲
void main() arr[2] = 85↲
{ arr[3] = -19↲
int i, arr[5]; arr[4] = 121↲
clrscr(); Array content is:
/* Reading Array */ arr[0] = 11
printf(“Enter 5 numbers:\n”); arr[1] = 25
for (i=0; i<5; i++) arr[2] = 85
{ arr[3] = -19
printf(“arr[%d] = ” , i ); arr[4] = 121
scanf(“%d”, &arr[i]);
}
/* Displaying array content */
printf(“Array content is:\n”);
for (i=0; i<5; i++)

MKS
{
printf(“arr[%d] = %d\n”, i, arr[i] );
}
getch();
}

Example2: Write a program in C to read an array containing n numbers and find sum
and average of given numbers.
Program Output
#include<stdio.h> Enter n: 4↲
#include<conio.h> Enter numbers:
a[0] = 11.5↲
void main() a[1] = 5.5↲
{ a[2] = 8.5↲
float a[100], sum=0, avg; a[3] = 10.5↲
int i, n; Sum is 36.000000
clrscr(); Average is 9.000000
printf("Enter n: ");
scanf("%d", &n);
/* Reading array */
printf("Enter numbers:\n");
for(i=0; i<n; i++)
{
printf("a[%d] = ", i);
scanf("%f", &a[i]);

Manish Kumar Shah(MKS) 139


139 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
/* Finding sum */
for(i=0; i<n; i++)
{
sum = sum + a[i];
}
/* Calculating average */
avg = sum/n;
/* Displaying Result */
printf("Sum is %f\n", sum);
printf("Average is %f", avg);
getch();
}

Example3: Write a program in C to read an array containing n positive integer numbers


and count odd and even numbers.

MKS
Program Output
#include<stdio.h> Enter n: 9↲
#include<conio.h> Enter numbers:
void main() num[0] = 21↲
{ num[1] = 11↲
int num[100], i, n, odd=0, even=0; num[2] = 13↲
clrscr(); num[3] = 12↲
printf("Enter n: "); num[4] = 33↲
scanf("%d", &n); num[5] = 22↲
/* Reading array */ num[6] = 67↲
printf("Enter numbers:\n"); num[7] = 76↲
for(i=0; i<n ; i++) num[8] = 88↲
{ Even Count = 4
printf("num[%d] = ", i); Odd Count = 5
scanf("%d", &num[i]);
}
/* Counting Odd and Even */
for(i=0; i<n ; i++)
{
if(num[i]%2 == 0)
{
even = even + 1;
}
else
{
odd = odd + 1;
}

Manish Kumar Shah(MKS) 140


140 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
/* Displaying Result */
printf("Even Count = %d\n", even);
printf("Odd Count = %d", odd);
getch();
}

Example4: Write a program in C to read an array containing n numbers and find largest
element from an array.
Program Output
#include<stdio.h> Enter n: 5↲

MKS
#include<conio.h> Enter numbers:
void main() a[0] = 21↲
{ a[1] = 0↲
float a[50], lg; a[2] = -78↲
int i, n; a[3] = 77↲
clrscr(); a[4] = 9↲
printf("Enter n: "); Large = 77
scanf("%d", &n);
/* Reading array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d] = ",i);
scanf("%f", &a[i]);
}
/* Finding large */
lg = a[0];
for(i=0;i<n;i++)
{
if(a[i]>lg)
{
lg = a[i];
}
}
printf("Large = %f", lg);
getch();
}

Manish Kumar Shah(MKS) 141


141 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Example5: Write a program in C to read an array containing n numbers and find
smallest element from an array.
Program Output
#include<stdio.h> Enter n: 5↲
#include<conio.h> Enter numbers:
void main() a[0] = 21↲
{ a[1] = 0↲
float a[50], sm; a[2] = -78↲
int i, n; a[3] = 77↲
clrscr(); a[4] = 9↲
printf("Enter n: "); Small = -78
scanf("%d", &n);
/* Reading array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d] = ",i);
scanf("%f", &a[i]);
}
/* Finding small */

MKS
sm = a[0];
for(i=0;i<n;i++)
{
if(a[i]<sm)
{
sm = a[i];
}
}
printf("Small = %f", sm);
getch();
}

2. Multi-Dimensional Array
So far we have manipulated one dimensional array i.e. with one index. In C programming, we can
have two or more (multi) dimensional array with two or more index. The two dimensional array is
also known as Matrix. And for now we will discuss two dimensional array.
A two dimensional array is a grid having rows and column in which each elements is specified by
two indexes. Two dimensional array is simplest form of multi-dimensional array. Two dimensional
array requires two index to represent and use them.
a. Declaration of Two Dimensional Array
Like one dimensional array, two dimensional array must be declared before we use it.
Declaring the name and type of an array and setting row and column size in an array is

Manish Kumar Shah(MKS) 142


142 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
known as array declaration for two dimension. While declaring an array we must define
name, type, row size and column size of an array.
General Syntax for Declaring Two Dimensional Array

data_type array_name[row_size][column_size];

For Example:
1. int a[3][3];
Here a is name of an array, row size is 3 and column size is 3 i.e. it can store 3*3 = 9
different integers value and its type is int. Declared array a can be illustrated using
following diagram.
0 1 2
0 a[0][0] a[0][1] a[0][2]
1 a[1][0] a[1][1] a[1][2]

MKS
2 a[2][0] a[2][1] a[2][2]

2. float m[4][4];
3. int num[2][2];

b. Initialization of Two Dimensional Array


Assigning values of two dimensional array elements at the time of its declaration is known
initialization of two dimensional array.
General Syntax for Initialization of two Dimensional Array

data_type array_name[row_size][column_size] = { { comma_separated_list }, { comma_separated_list } …}

For Example:
1. int a[3][3] = {{12,13,14},{22,23,24},{32,33,34}};
Declared and initialized array a can be illustrated using following diagram.
0 1 2
0 12 13 14
1 22 23 24
2 32 33 34

Manish Kumar Shah(MKS) 143


143 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
2. float f[2][2] = {{2.4, 4.5},{3.9, -8.8}};

c. Reading, Processing and Writing of Two Dimensional Array


Generally, nested for loop is used for reading, processing and writing of two dimensional
array.
Reading Example:
Following structure is used for reading an array content.
int a[3][3], i,j;
for (i=0; i<3; i++)
{
for{j=0; j<3; j++)
{
printf(“a[%d][%d] = ”, i,j);
scanf(“%d”, &a[i]);
}
}

After execution of this, array content will be read to a[0][0], a[0][1], a[0][2],
a[1][0], a[1][1], a[1][2], a[2][0], a[2][1] and a[2][2].

MKS
Processing Example:
for (i=0; i<3; i++)
{
for{j=0; j<3; j++)
{
a[i][j] = i+j;
}
}

After execution of this, array content will be a[0][0]=0, a[0][1]=1, a[0][2]=2,


a[1][0]=1, a[1][1]=2, a[1][2]=3, a[2][0]=2, a[2][1]=3 and a[2][2]=4.
Writing Example:
for (i=0; i<3; i++)
{
for{j=0; j<3; j++)
{
printf(“%d\t”, a[i][j]);
}
printf(“\n”);
}

After execution of this, array content will be displayed.

Manish Kumar Shah(MKS) 144


144 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Note: These are just examples. While writing program similar structures will be used
based on problem being solved.

d. Programming Examples to illustrate two dimensional array.


Example1: Write a program in C to read 3X3 matrix and display the content.
Program Output
#include<stdio.h> Enter matrix elements:
#include<conio.h> m[0][0]=2↲
m[0][1]=1↲
void main() m[0][2]=5↲
{ m[1][0]=6↲
int m[3][3],i,j; m[1][1]=3↲
clrscr(); m[1][2]=6↲
/* Reading Matrix */ m[2][0]=7↲
printf("Enter matrix elements:\n"); m[2][1]=8↲
for(i=0;i<3;i++) m[2][2]=5↲
{ Matrix is:
for(j=0;j<3;j++) 2 1 5

MKS
{ 6 3 6
printf("m[%d][%d]=",i,j); 7 8 5
scanf("%d",&m[i][j]);
}
}
/* Displaying matrix */
printf("Matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",m[i][j]);
}
printf("\n");
}
getch();
}
Example2: Write a program in C to add two 2X2 matrix.
Program Output

Manish Kumar Shah(MKS) 145


145 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> Enter first matrix:
#include<conio.h> a[0][0]=1↲
void main() a[0][1]=2↲
{ a[1][0]=3↲
int a[2][2],b[2][2], s[2][2],i,j; a[1][1]=4↲
clrscr(); Enter second matrix:
/* Reading First Matrix */ b[0][0]=11↲
printf("Enter first matrix:\n"); b[0][1]=12↲
for(i=0;i<2;i++) b[1][0]=13↲
{ b[1][1]=14↲
for(j=0;j<2;j++) Added Matrix is:
{ 12 14
printf("a[%d][%d]=",i,j); 16 18
scanf("%d",&a[i][j]);
}
}
/* Reading Second Matrix */
printf("Enter second matrix:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)

MKS
{
printf("b[%d][%d]=",i,j);
scanf("%d",&b[i][j]);
}
}
/* Adding */
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
s[i][j] = a[i][j] + b[i][j];
}
}
/* Displaying matrix */
printf("Added Matrix is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",s[i][j]);
}
printf("\n");
}
getch();
}

Manish Kumar Shah(MKS) 146


146 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Example3: Write a program in C to add two 3X3 matrix.


Program Output
#include<stdio.h> Enter first matrix:
#include<conio.h> a[0][0]=1↲
void main() a[0][1]=1↲
{ a[0][2]=1↲
int a[3][3],b[3][3], s[3][3],i,j; a[1][0]=1↲
clrscr(); a[1][1]=1↲
/* Reading First Matrix */ a[1][2]=1↲
printf("Enter first matrix:\n"); a[2][0]=1↲
for(i=0;i<3;i++) a[2][1]=1↲
{ a[2][2]=1↲
for(j=0;j<3;j++) Enter second matrix:
{ b[0][0]=11↲
printf("a[%d][%d]=",i,j); b[0][1]=11↲
scanf("%d",&a[i][j]); b[0][2]=11↲
} b[1][0]=11↲
} b[1][1]=11↲

MKS
/* Reading Second Matrix */ b[1][2]=11↲
printf("Enter second matrix:\n"); b[2][0]=11↲
for(i=0;i<3;i++) b[2][1]=11↲
{ b[2][2]=11↲
for(j=0;j<3;j++) Added Matrix is:
{ 12 12 12
printf("b[%d][%d]=",i,j); 12 12 12
scanf("%d",&b[i][j]); 12 12 12
}
}
/* Adding */
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
s[i][j] = a[i][j] + b[i][j];
}
}
/* Displaying matrix */
printf("Added Matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",s[i][j]);
}
printf("\n");
Manish Kumar Shah(MKS) 147
147 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
getch();
}

Example4: Write a program in C to read 3X3 matrix and find largest element.

Program Output
#include<stdio.h> Enter Matrix:
#include<conio.h> m[0][0]=112↲
m[0][1]=211↲
void main() m[0][2]=-455↲
{ m[1][0]=233↲
float m[3][3], lg; m[1][1]=323↲

MKS
int i,j; m[1][2]=-900↲
clrscr(); m[2][0]=222↲
/* Reading Matrix */ m[2][1]=34↲
printf("Enter Matrix:\n"); m[2][2]=11↲
for(i=0;i<3;i++) Largest is 323.000000
{
for(j=0;j<3;j++)
{
printf("m[%d][%d]=",i,j);
scanf("%f",&m[i][j]);
}
}
/* Finding largest */
lg = m[0][0];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(m[i][j]>lg)
{
lg = m[i][j];
}
}
}
printf("Largest is %f", lg);
getch();
}
Manish Kumar Shah(MKS) 148
148 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Array and User Defined Functions (Passing Array to User Defined Functions)
In C programming, the arrays can be passed to user defined function like any other simple
variables. An arrays can be passed to function with its name only i.e. without any subscript while
calling function, and with the size of the array in formal arguments of user defined function along
with some other arguments if required.
Unlike normal variable, when an array content is changed from user defined function that change
is also reflected in original array content.

-
-
-
MKS
Important points while working with array and user defined function:
Only array name is passed while calling function.
Array name along with size and square brackets are used in formal arguments.
Once an array content is changed from user defined function, original array content is also
changed.
Program to illustrate array and user defined function:
1. Finding standard deviation of given data.
Hint: Standard deviation formula for n values is:
∑𝑛−1(𝑥 − 𝑥̅ )2
√ 𝑖=0 𝑖
𝑛

#include<stdio.h>
#include<conio.h>
#include<math.h>

/* Function prototype */
float stddev(float a[100], int n);

void main()
{
float a[100], sd;
int i,n;
Manish Kumar Shah(MKS) 149
149 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
clrscr();
printf("Enter how many data?\n");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("a[%d] = ",i);
scanf("%f", &a[i]);
}
/* Function call */
sd = stddev(a,n);
printf("Standard deviation is: %f", sd);
getch();
}

/* Function definition */
float stddev(float a[100], int n)
{
float sum1=0, sum2=0, res, mean;
int i;
for(i=0; i<n; i++)
{

MKS
sum1 = sum1 + a[i];
}
mean = sum1/n;
for(i=0; i<n; i++)
{
sum2 = sum2 + (a[i]-mean) * (a[i]-mean);
}
res = sqrt(sum2/n);
return(res);
}

Output:
Enter how many data?
3
a[0] = 1
a[1] = 2
a[2] = 3
Standard deviation is: 0.816497

Explanation: In this example array is passed to user defined function stddev() and which
calculates standard deviation of given data and returns result i.e. standard deviation. So return
type is set.
2. Incrementing each value in array by 5 using user defined function.

Manish Kumar Shah(MKS) 150


150 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h>
#include<conio.h>

/* Function prototype */
void addfive(int a[100], int n);

void main()
{
int a[100],n,i;
clrscr();
printf("Enter value of n: ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("a[%d] = ", i);
scanf("%d", &a[i]);
}
addfive(a,n);
printf("Data after incrementing by five:\n");
for(i=0; i<n; i++)
{

MKS
printf("%d\t", a[i]);
}
getch();
}
/* Function definition */
void addfive(int a[100], int n)
{
int i;
for(i=0; i<n; i++)
{
a[i] = a[i]+5;
}
}
Output:
Enter value of n: 5
a[0] = 10
a[1] = 5
a[2] = 15
a[3] = 20
a[4] = 25
Data after incrementing by five:
15 10 20 25 30
Explanation: In this example array is passed to user defined function addfive() and which
increments each value by five. This function doesn’t return anything but array content is changed

Manish Kumar Shah(MKS) 151


151 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
from user defined function so that change is also reflected back in main() function. So, on printing
array content after calling addfive() function, we get incremented result.
Solved Programming Examples: One Dimensional Array
1. Write a program in C to read an array containing 5 numbers and display its content.
#include<stdio.h>
#include<conio.h>

int main()
{
int arr[5], i;
clrscr();
/* Reading Array */
printf("Enter numbers:\n");
for(i=0;i<5;i++)
{
printf("arr[%d]=",i);
scanf("%d",&arr[i]);
}

MKS
/* Displaying Array Content */
printf("Array content is:\n");
for(i=0;i<5;i++)
{
printf("%d\t",arr[i]);
}
getch();
return(0);
}

2. Write a program in C to read an array containing n elements and find sum and average
of given numbers.
#include<stdio.h>
#include<conio.h>

int main()
{
float arr[5], sum=0.0, avg;
int i, n;
clrscr();
printf("Enter n:\n");
scanf("%d", &n);

/* Reading Array */

Manish Kumar Shah(MKS) 152


152 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("arr[%d]=",i);
scanf("%f",&arr[i]);
}

/* Finding sum and average */


for(i=0;i<n;i++)
{
sum = sum + arr[i];
}
avg = sum/n;

/* Displaying Result */
printf("Sum = %f\n",sum);
printf("Average = %f", avg);
getch();
return(0);
}

#include<stdio.h>
#include<conio.h>
#include<math.h>
MKS
3. Write a program in C to read an array containing n numbers and find standard
deviation.

int main()
{
float a[5], sum1=0.0, sum2=0.0, mean, sd;
int i, n;
clrscr();
printf("Enter n:\n");
scanf("%d", &n);
/* Reading Array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%f",&a[i]);
}
/* Finding sum1 and mean */
for(i=0;i<n;i++)
{
sum1 = sum1 + a[i];
}

Manish Kumar Shah(MKS) 153


153 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
mean = sum1/n;
/* Finding sum2 and standard deviation */
for(i=0;i<n;i++)
{
sum2 = sum2 + (a[i] - mean)*(a[i] - mean);
}
sd = sqrt(sum2/n);
/* Displaying result */
printf("Standard deviation = %f", sd);
getch();
return(0);
}

4. Write a program in C to count number of even numbers and odd numbers in a given
array.
#include<stdio.h>
#include<conio.h>

int main()

MKS
{
int arr[100], i, n, ecount=0, ocount=0;
clrscr();
printf("Enter n:");
scanf("%d", &n);
/* Reading Array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("arr[%d]=",i);
scanf("%d",&arr[i]);
}
/* Calculating even and odd count */
for(i=0;i<n;i++)
{
if(arr[i]%2==0)
{
ecount++;
}
else
{
ocount++;
}
}
/* Displaying result */
printf("Even count = %d\n",ecount);
printf("Odd count = %d", ocount);

Manish Kumar Shah(MKS) 154


154 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
getch();
return(0);
}

5. Write a program in C to read an array containing n elements and find sum of all odd
numbers and even numbers.
#include<stdio.h>
#include<conio.h>

int main()
{
int arr[100], i, n, esum=0, osum=0;
clrscr();
printf("Enter n:");
scanf("%d", &n);
/* Reading Array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)

MKS
{
printf("arr[%d]=",i);
scanf("%d",&arr[i]);
}
/* Calculating even and odd count */
for(i=0;i<n;i++)
{
if(arr[i]%2==0)
{
esum = esum + arr[i];
}
else
{
osum = osum + arr[i];
}
}
/* Displaying result */
printf("Even sum = %d\n",esum);
printf("Odd sum = %d", osum);
getch();
return(0);
}

6. Write a program in C to read an array containing n numbers and reverse this array.

Manish Kumar Shah(MKS) 155


155 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h>
#include<conio.h>

int main()
{
int a[100], temp, i, n;
clrscr();
printf("Enter n:");
scanf("%d", &n);
/* Reading Array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d",&a[i]);
}
/* Reversing */
for(i=0;i<n/2;i++)
{
temp = a[i];
a[i] = a[n-1-i];

MKS
a[n-1-i] = temp;
}
/* Displaying result */
printf("Reversed array is:\n");
for(i=0;i<n;i++)
{
printf("%d\t", a[i]);
}
getch();
return(0);
}

7. Write a program in C to read an array containing n elements and sort this array in
ascending order.
#include<stdio.h>
#include<conio.h>

int main()
{
float a[100], temp;
int i, j, n;
clrscr();
printf("Enter n:");
scanf("%d", &n);
/* Reading Array */

Manish Kumar Shah(MKS) 156


156 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%f",&a[i]);
}
/* Sorting array in ascending order */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
/* Displaying result */
printf("Array in ascending order is:\n");

MKS
for(i=0;i<n;i++)
{
printf("%f\t", a[i]);
}
getch();
return(0);
}

8. Write a program in C to read an array containing n elements and sort this array in
descending order.
#include<stdio.h>
#include<conio.h>

int main()
{
float a[100], temp;
int i, j, n;
clrscr();
printf("Enter n:");
scanf("%d", &n);
/* Reading Array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);

Manish Kumar Shah(MKS) 157


157 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
scanf("%f",&a[i]);
}
/* Sorting in descending order */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
/* Displaying result */
printf("Array in descending order is:\n");
for(i=0;i<n;i++)
{
printf("%f\t", a[i]);
}

MKS
getch();
return(0);
}

9. Write a program in C to read an array containing n numbers and find largest element
from an array.
#include<stdio.h>
#include<conio.h>

int main()
{
float a[100], lg;
int i, n;
clrscr();
printf("Enter n:");
scanf("%d", &n);
/* Reading Array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%f",&a[i]);
}
/* Finding large */

Manish Kumar Shah(MKS) 158


158 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
lg = a[0];
for(i=0;i<n;i++)
{
if(a[i]>lg)
{
lg = a[i];
}
}
/* Displaying result */
printf("Large = %f", lg);
getch();
return(0);
}

10. Write a program in C to read an array containing n numbers and find smallest element
from an array.
#include<stdio.h>
#include<conio.h>

int main()

MKS
{
float a[100], sm;
int i, n;
clrscr();
printf("Enter n:");
scanf("%d", &n);
/* Reading Array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%f",&a[i]);
}
/* Finding small */
sm = a[0];
for(i=0;i<n;i++)
{
if(a[i]<sm)
{
sm = a[i];
}
}
/* Displaying result */
printf("Small = %f ", sm);
getch();
return(0);
}

Manish Kumar Shah(MKS) 159


159 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

11. Write a program in C to read an array containing n elements and find third smallest
element from an array.
#include<stdio.h>
#include<conio.h>

int main()
{
float a[100], temp;
int i, j, n;
clrscr();
printf("Enter n (>3):");
scanf("%d", &n);
/* Reading Array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{

MKS
printf("a[%d]=",i);
scanf("%f",&a[i]);
}
/* Sorting array in ascending order */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
/* Displaying result */
printf("Third smallest = %f ",a[2]);
getch();
return(0);
}

12. Write a program in C to read an array containing n numbers and find second largest
element from an array.

Manish Kumar Shah(MKS) 160


160 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h>
#include<conio.h>

int main()
{
float a[100], temp;
int i, j, n;
clrscr();
printf("Enter n (>2):");
scanf("%d", &n);
/* Reading Array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%f",&a[i]);
}
/* Sorting array in ascending order */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)

MKS
{
if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
/* Displaying result */
printf("Second largest = %f ",a[n-2]);
getch();
return(0);
}

13. Write a program in C to read an array containing n elements. Also read position and a
number then insert this number to the given position.
#include<stdio.h>
#include<conio.h>

void main()
{
int a[100], i, n, pos, num;
clrscr();
printf("Enter n:\n");

Manish Kumar Shah(MKS) 161


161 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
scanf("%d", &n);
/* Reading array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d", &a[i]);
}
/* Displaying original array */
printf("Given array is:\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
/* Reading number and position */
printf("\nEnter number to be inserted:\n");
scanf("%d", &num);
printf("Enter position to insert:\n");
scanf("%d", &pos);
/* Insertion */
for(i=n;i>=pos;i--)

MKS
{
a[i] = a[i-1];
}
a[pos-1] = num;

/* Displaying final array */


printf("Array after insertion is:\n");
for(i=0;i<=n;i++)
{
printf("%d\t",a[i]);
}
getch();
}

14. Write a program in C to read two arrays having m and n elements then merge these two
arrays into one single array.
#include<stdio.h>
#include<conio.h>

void main()
{
int a[100], b[100],r[200],i, m, n, pos;
clrscr();
/* Reading first array */
printf("Enter m:\n");

Manish Kumar Shah(MKS) 162


162 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
scanf("%d", &m);
printf("Enter elements of first array:\n");
for(i=0;i<m;i++)
{
printf("a[%d]=",i);
scanf("%d", &a[i]);
}
/* Reading second array */
printf("Enter n:\n");
scanf("%d",&n);
printf("Enter elements of second array:\n");
for(i=0;i<n;i++)
{
printf("b[%d]=",i);
scanf("%d", &b[i]);
}
/* Merging */
for(i=0;i<m;i++)
{
r[i] = a[i];
}

MKS
for(i=0;i<m+n;i++)
{
r[m+i] = b[i];
}
/* Displaying merged array */
printf("Merged array is:\n");
for(i=0;i<m+n;i++)
{
printf("%d\t",r[i]);
}
getch();
}

15. Write a program in C to read an array containing n integer numbers then sort this array
into ascending order if it has more number of even numbers otherwise sort in descending
order.

#include<stdio.h>
#include<conio.h>

void main()
{
int a[100], temp, i, j, n, ecount=0, ocount=0;
clrscr();
/* Reading array */
printf("Enter n:\n");
Manish Kumar Shah(MKS) 163
163 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
scanf("%d", &n);
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d", &a[i]);
}
/* Counting odd and even */
for(i=0;i<n;i++)
{
a[i]%2==0?ecount++:ocount++;
}
/* sorting */
if(ecount>ocount)
{
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{

MKS
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
else
{
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
/* Displaying result */
printf("Final array is:\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);

Manish Kumar Shah(MKS) 164


164 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
getch();
}

16. Write a program in C to read an array containing n numbers and find average of
numbers using user defined function.
#include<stdio.h>
#include<conio.h>

/* Function prototype */
float average(float a[100], int n);

void main()
{
float a[100], res;
int i, n;
clrscr();
printf("Enter n:\n");
scanf("%d", &n);
/* Reading array */

MKS
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%f", &a[i]);
}
/* Function Call */
res = average(a,n);
printf("Average = %f", res);
getch();
}
/* Function definition */
float average(float a[10], int n)
{
int i;
float sum=0.0;
for(i=0;i<n;i++)
{
sum = sum + a[i];
}
return(sum/n);
}

17. Write a program in C to read an array containing n numbers and find standard deviation
using user defined function. Use two different user defined function one for calculating
mean and one to calculate standard deviation.

Manish Kumar Shah(MKS) 165


165 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h>
#include<conio.h>
#include<math.h>

/* Function prototypes */
float stddev(float a[100], int n);
float mean(float a[100], int n);

void main()
{
float a[100], res;
int i, n;
clrscr();
printf("Enter n:\n");
scanf("%d", &n);
/* Reading array */
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%f", &a[i]);
}

MKS
/* Function Call */
res = stddev(a,n);
/* Displaying result */
printf("Standard deviation = %f", res);
getch();
}
/* Function definition for stddev */
float stddev(float a[10], int n)
{
int i;
float fsum=0.0, m;
m = mean(a,n);
for(i=0;i<n;i++)
{
fsum = fsum + (a[i]-m)*(a[i]-m);
}
return(sqrt(fsum/n));
}
/* Function definition for mean */
float mean(float a[10], int n)
{
int i;
float sum=0.0;
for(i=0;i<n;i++)
{
sum = sum + a[i];
}

Manish Kumar Shah(MKS) 166


166 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
return(sum/n);
}

18. Write a program in C to read an array containing n elements and sort this array in
ascending order using user defined function and display sorted array from main
function.
#include<stdio.h>
#include<conio.h>

/* Function prototype */
void asc_sort(int a[100], int n);

void main()
{
int a[100], i, n;
clrscr();
printf("Enter n:\n");
scanf("%d", &n);
/* Reading array */

MKS
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d", &a[i]);
}
/* Function Call */
asc_sort(a,n);
/* Displaying sorted array */
printf("Array in ascending order is:\n");
for(i=0;i<n;i++)
{
printf("%d\t", a[i]);
}
getch();
}
/* Function definition for asc_sort */
void asc_sort(int a[10], int n)
{
int i, j, temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
Manish Kumar Shah(MKS) 167
167 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
a[j] = temp;
}
}
}
}

19. Write a program in C to read an array containing n elements and reverse this array using
user defined function and display reversed array from main function.
#include<stdio.h>
#include<conio.h>

/* Function prototype */
void reverse(int a[100], int n);

void main()
{
int a[100], i, n;
clrscr();
printf("Enter n:\n");

MKS
scanf("%d", &n);
/* Reading array */
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d", &a[i]);
}
/* Function Call */
reverse(a,n);
/* Displaying reversed array */
printf("Reversed array is:\n");
for(i=0;i<n;i++)
{
printf("%d\t", a[i]);
}
getch();
}
/* Function definition for reverse */
void reverse(int a[10], int n)
{
int i, temp;
for(i=0;i<n/2;i++)
{
temp = a[i];
a[i] = a[n-1-i];
a[n-1-i] = temp;
}

Manish Kumar Shah(MKS) 168


168 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}

20. Write a program in C to read an array containing n elements and find the largest element
from an array using user defined function.
#include<stdio.h>
#include<conio.h>

/* Function prototype */
float large(float a[100], int n);

void main()
{
float a[100], res;
int i, n;
clrscr();
printf("Enter n:\n");
scanf("%d", &n);
/* Reading array */

MKS
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%f", &a[i]);
}
/* Function Call */
res = large(a,n);
/* Displaying result */
printf("Large = %f", res);
getch();
}
/* Function definition for large */
float large(float a[10], int n)
{
float lg = a[0];
int i;
for(i=0;i<n;i++)
{
if(a[i]>lg)
{
lg = a[i];
}
}
return(lg);
}

Manish Kumar Shah(MKS) 169


169 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
21. Write a program in C to read an array containing n elements. Also read position and
then delete array element from given position.
#include<stdio.h>
#include<conio.h>

void main()
{
int a[100], i, n, pos;
clrscr();
printf("Enter n:\n");
scanf("%d", &n);
/* Reading array */
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d", &a[i]);
}
/* Displaying original array */
printf("Given array is:\n");

MKS
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
/* Reading number and position */
printf("\nEnter position of deletion:\n");
scanf("%d", &pos);
/* Deletion */
for(i=pos-1;i<n-1;i++)
{
a[i] = a[i+1];
}
a[n-1]=0;
/* Displaying final array */
printf("Array after deletion is:\n");
for(i=0;i<n-1;i++)
{
printf("%d\t",a[i]);
}
getch();
}

Solved Programming Examples: Two Dimensional Array


1. Write a program in C to read 2x3 matrix and display the content read in matrix form.

Manish Kumar Shah(MKS) 170


170 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h>
#include<conio.h>

void main()
{
int i,j, a[2][3];
clrscr();
printf("Enter matrix elements:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%d", &a[i][j]);
}
}
printf("Matrix read is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{

MKS
printf("%d\t",a[i][j]);
}
printf("\n");
}
getch();
}

2. Write a program in C to read m x n matrix and display the content in matrix form.
#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,m,n;
float a[10][10];
clrscr();
printf("Enter row and column size:\n");
scanf("%d%d", &m, &n);
printf("Enter matrix elements:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);

Manish Kumar Shah(MKS) 171


171 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
}
printf("Matrix read is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%f\t",a[i][j]);
}
printf("\n");
}
getch();
}

3. Write a program in C to read m x n matrix and find sum and average of elements in
the matrix.
#include<stdio.h>
#include<conio.h>

void main()

MKS
{
int i,j,m,n;
float a[10][10], sum=0.0, avg;
clrscr();
printf("Enter row and column size:\n");
scanf("%d%d", &m, &n);
printf("Enter matrix elements:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sum = sum + a[i][j];
}
}
avg = sum/(m*n);
printf("Sum = %f\n", sum);
printf("Average = %f", avg);
getch();
}

Manish Kumar Shah(MKS) 172


172 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

4. Write a program in C to read m x n matrix and find largest element from matrix.
#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,m,n;
float a[10][10], lg;
clrscr();
printf("Enter row and column size:\n");
scanf("%d%d", &m, &n);
printf("Enter matrix elements:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);

MKS
scanf("%f", &a[i][j]);
}
}
lg = a[0][0];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>lg)
{
lg = a[i][j];
}
}
}
printf("Largest = %f\n", lg);
getch();
}

5. Write a program in C to read m x n matrix and find smallest element from matrix.
#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,m,n;

Manish Kumar Shah(MKS) 173


173 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
float a[10][10], sm;
clrscr();
printf("Enter row and column size:\n");
scanf("%d%d", &m, &n);
printf("Enter matrix elements:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
sm = a[0][0];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]<sm)
{
sm = a[i][j];

MKS
}
}
}
printf("Smallest = %f\n", sm);
getch();
}

6. Write a program in C to read square matrix of order n and find sum of principal
diagonal elements.
#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,n;
float a[10][10], sum=0.0;
clrscr();
printf("Enter order of matrix:\n");
scanf("%d", &n);
printf("Enter matrix elements:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);

Manish Kumar Shah(MKS) 174


174 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
{
sum = sum + a[i][j];
}
}
}
printf("Sum = %f\n", sum);
getch();
}
7. Write a program in C to read square matrix of order n and find sum of both diagonal
elements.
#include<stdio.h>
#include<conio.h>

MKS
void main()
{
int i,j,n;
float a[10][10], sum=0.0;
clrscr();
printf("Enter order of matrix:\n");
scanf("%d", &n);
printf("Enter matrix elements:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j || i+j==n-1)
{
sum = sum + a[i][j];
}
}
}
printf("Sum = %f\n", sum);

Manish Kumar Shah(MKS) 175


175 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
getch();
}

8. Write a program in C to read square matrix of order n and replace all principal
diagonal elements by largest element in matrix.
#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,n;
float a[10][10], lg;
clrscr();
printf("Enter order of matrix:\n");
scanf("%d", &n);
printf("Enter matrix elements:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{

MKS
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
lg = a[0][0];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>lg)
{
lg = a[i][j];
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
{
a[i][j] = lg;
}
}
}
printf("Resultant matrix is:\n");
for(i=0;i<n;i++)

Manish Kumar Shah(MKS) 176


176 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
{
for(j=0;j<n;j++)
{
printf("%0.2f\t", a[i][j]);
}
printf("\n");
}
getch();
}
9. Write a program in C to read square matrix for order n and transpose it. Display
transposed matrix in matrix form.
#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,n;
float a[10][10], tmp;
clrscr();
printf("Enter order of matrix:\n");

MKS
scanf("%d", &n);
printf("Enter matrix elements:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
tmp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = tmp;
}
}
printf("Transposed matrix is:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%f\t", a[i][j]);
}
printf("\n");

Manish Kumar Shah(MKS) 177


177 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
getch();
}
10. Write a program in C to add two mxn matrix.
#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,m,n;
float a[10][10], b[10][10], sum[10][10];
clrscr();
printf("Enter row and column size:\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);

MKS
scanf("%f", &a[i][j]);
}
}
printf("Enter elements of second matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("b[%d][%d]=",i,j);
scanf("%f", &b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sum[i][j] = a[i][j]+b[i][j];
}
}
printf("Added matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%f\t", sum[i][j]);
}
printf("\n");

Manish Kumar Shah(MKS) 178


178 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
getch();
}
11. Write a program in C to multiply two 3x3 matrix.
#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,k;
float a[3][3], b[3][3], mul[3][3];
clrscr();
printf("Enter elements of first matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}

MKS
}
printf("Enter elements of second matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("b[%d][%d]=",i,j);
scanf("%f", &b[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
mul[i][j] = 0;
for(k=0;k<3;k++)
{
mul[i][j] = mul[i][j] + a[i][k]*b[j][k];
}
}
}
printf("Multiplied matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%f\t", mul[i][j]);

Manish Kumar Shah(MKS) 179


179 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
printf("\n");
}
getch();
}
12. Write a program in C to multiply two p x q and q x r matrix.
#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,k,r1,c1,r2,c2;
float a[3][3], b[3][3], mul[3][3];
clrscr();
printf("Enter row and column of first matrix\n");
scanf("%d%d", &r1, &c1);
printf("Enter row and column of second matrix\n");
scanf("%d%d", &r2, &c2);
if(c1==r2)
{

MKS
printf("Enter elements of first matrix:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
printf("Enter elements of second matrix:\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("b[%d][%d]=",i,j);
scanf("%f", &b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
mul[i][j] = 0;
for(k=0;k<r2;k++)
{
mul[i][j] = mul[i][j] + a[i][k]*b[k][j];
}

Manish Kumar Shah(MKS) 180


180 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
}
printf("Multiplied matrix is:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%f\t", mul[i][j]);
}
printf("\n");
}
}
else
{
printf("Dimension do not match for multiplication.");
}
getch();
}

13. Write a program in C to read m x n matrix and find largest element from it using user
defined functions.

MKS
#include<stdio.h>
#include<conio.h>

float large(float a[10][10], int m, int n);

void main()
{
int i,j,m,n;
float a[10][10], res;
clrscr();
printf("Enter row and column size:\n");
scanf("%d%d", &m, &n);
printf("Enter matrix elements:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
res = large(a,m,n);
printf("Largest = %f\n", res);
getch();
}

Manish Kumar Shah(MKS) 181


181 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
float large(float a[10][10], int m, int n)
{
int i,j;
float lg = a[0][0];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>lg)
{
lg = a[i][j];
}
}
}
return(lg);
}

14. Write a program in C to read m x n matrix and find smallest element from it using user
defined functions.

#include<stdio.h>
#include<conio.h>

MKS
float small(float a[10][10], int m, int n);

void main()
{
int i,j,m,n;
float a[10][10], res;
clrscr();
printf("Enter row and column size:\n");
scanf("%d%d", &m, &n);
printf("Enter matrix elements:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
res = small(a,m,n);
printf("Smallest = %f\n", res);
getch();
}

Manish Kumar Shah(MKS) 182


182 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
float small(float a[10][10], int m, int n)
{
int i,j;
float sm = a[0][0];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]<sm)
{
sm = a[i][j];
}
}
}
return(sm);
}

15. Write a program in C to read square matrix of order n and find sum of both diagonals
using user defined function.

MKS
#include<stdio.h>
#include<conio.h>

float diagsum(float a[10][10], int n);

void main()
{
int i,j,n;
float a[10][10], res;
clrscr();
printf("Enter order of matrix:\n");
scanf("%d", &n);
printf("Enter matrix elements:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
res = diagsum(a,n);
printf("Sum = %f\n", res);
getch();
}

float diagsum(float a[10][10], int n)

Manish Kumar Shah(MKS) 183


183 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
{
int i,j;
float s=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j || i+j==n-1)
{
s = s+ a[i][j];
}
}
}
return(s);
}

16. Write a program in C to read square matrix of order n, transpose it using user defined
function and display transposed matrix from main() function.
#include<stdio.h>
#include<conio.h>

MKS
void transpose(float a[10][10], int n);

void main()
{
int i,j,n;
float a[10][10];
clrscr();
printf("Enter order of matrix:\n");
scanf("%d", &n);
printf("Enter matrix elements:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
transpose(a,n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%f\t",a[i][j]);
}
printf("\n");

Manish Kumar Shah(MKS) 184


184 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
getch();
}

void transpose(float a[10][10], int n)


{
int i,j;
float tmp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
tmp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = tmp;
}
}
}

17. Write a program in C to multiply two p x q and q x r matrix using user defined
functions.

MKS
#include<stdio.h>
#include<conio.h>

void multiply(int r1, int c1, int r2, int c2);

void main()
{
int i,j,k,r1,c1,r2,c2;
clrscr();
printf("Enter row and column of first matrix\n");
scanf("%d%d", &r1, &c1);
printf("Enter row and column of second matrix\n");
scanf("%d%d", &r2, &c2);
multiply(r1,c1,r2,c2);
getch();
}

void multiply(int r1, int c1, int r2, int c2)


{
int i,j,k;
float a[10][10], b[10][10], mul[10][10];
if(c1==r2)
{
printf("Enter elements of first matrix:\n");
for(i=0;i<r1;i++)
{

Manish Kumar Shah(MKS) 185


185 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
for(j=0;j<c1;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f", &a[i][j]);
}
}
printf("Enter elements of second matrix:\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("b[%d][%d]=",i,j);
scanf("%f", &b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
mul[i][j] = 0;
for(k=0;k<r2;k++)

MKS
{
mul[i][j] = mul[i][j] + a[i][k]*b[k][j];
}
}
}
printf("Multiplied matrix is:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%f\t", mul[i][j]);
}
printf("\n");
}
}
else
{
printf("Dimension do not match for multiplication.");
}
}

18. Write a program in C to find determinant of 2 x 2 matrix.


#include<stdio.h>
#include<conio.h>

Manish Kumar Shah(MKS) 186


186 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
void main()
{
float a[2][2], det;
int i,j;
clrscr();
/* Input Part */
printf("Enter 2 x 2 matrix:\n");
for(i=0;i< 2;i++)
{
for(j=0;j< 2;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f",&a[i][j]);
}
}
det = a[0][0]*a[1][1] - a[1][0]*a[0][1];
/* Displaying Output */
printf("Determinant is %f",det);
getch();
}

#include<conio.h>
#define SIZE 10

void main()
MKS
19. Write a program in C to find determinant of n x n matrix.
#include<stdio.h>

{
float a[SIZE][SIZE], det=1.0,ratio;
int i,j,k,n;
clrscr();
/* Input Part */
printf("Enter Order:\n");
scanf("%d",&n);
printf("Enter %d x %d matrix:\n\n",n,n);
for(i=0;i< n;i++)
{
for(j=0;j< n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f",&a[i][j]);
}
}
/* Converting matrix to upper triangular */
for(i=0;i< n;i++)
{

Manish Kumar Shah(MKS) 187


187 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
for(j=0;j< n;j++)
{
if(j>i)
{
ratio = a[j][i]/a[i][i];
for(k=0;k< n;k++)
{
a[j][k] = a[j][k] - ratio * a[i][k];
}
}
}
}
/* Calculating Determinant */
for(i=0;i< n;i++)
{
det = det * a[i][i];
}
/* Displaying Output */
printf("Determinant is %f",det);
getch();
}

MKS
20. Write a program in C to read square matrix of order n, find average of elements and
then replace each element by 1 if it is greater than average otherwise replace by 0.
#include<stdio.h>
#include<conio.h>

void main()
{
float a[10][10],avg, sum=0.0;
int i,j,n;
clrscr();
printf("Enter n:\n");
scanf("%d",&n);
printf("Enter matrix:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%f",&a[i][j]);
sum = sum + a[i][j];
}
}
avg = sum/(n*n);
for(i=0;i<n;i++)

Manish Kumar Shah(MKS) 188


188 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
{
for(j=0;j<n;j++)
{
if(a[i][j]>avg)
{
a[i][j] = 1;
}
else
{
a[i][j] = 0;
}
}
}
printf("Resultant matrix is:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%0.1f\t", a[i][j]);
}
printf("\n");

MKS
}
getch();
}

Manish Kumar Shah(MKS) 189


189 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

String (Character Array)


String or character array is collection of character enclosed in double quotation. In C programming,
every string is terminated by NULL character i.e. ‘\0’. Each character of string is stored as one
elements of array so character array must be declared one character longer than size of the character
array that we wish to store to accommodate place for NULL character.
1. Declaration of String Variables
String variable or character array is declared just like numeric array. Syntax for declaring string
is:

char string_name[size];

For examples:
a. char name[20]; Here name is string variable and it can store 20 characters.

MKS
b. char str[50]; Here str is string variable and it can store 50 characters.
2. Initialization of String Variables
Initialization of string is the process of assigning initial value to string variable. String can be
initialized in three ways.
a. By directly assigning string using double quotation.
General syntax for assigning some string value to string variable is:

char string_name[size] = “String_Value”;

For examples:
i. char name[12] = “Programming”; Here string variable name stores string
“Programming”. After initializing string like this, name[0] gives P, name[1] gives
r, name[2] gives o, and so on.
ii. char str[20] = “Cat”; Here string variable str stores string “Cat”. While
declaration size 20 is set but only four characters are stored. But we can’t do
something like this: char str[4] = “Apple”; because here size is reserved for 4
characters but more than 4 characters are initialized which will produce error.

Manish Kumar Shah(MKS) 190


190 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
b. By using comma separated list of character bounded in curly braces.

char string_name[size] = {character1, charcater2, character3….}

For examples:
i. char name[12] = {‘P’,’r’,’o’,’g’,’r’,’m’,’m’,’i,’n’,’g’,’\0’};
ii. char str[20] = {‘C’,’a’,’t’};
c. By individually assigning each character.
These same string can also be initialized as follow:
For examples:
i. char name[12];
name[0] = ‘P’;
name[1] = ‘r’;
name[2] = ‘o’;
name[3] = ‘g’;
name[4] = ‘r’;

MKS
name[5] = ‘a’;
name[6] = ‘m’;
name[7] = ‘m’;
name[8] = ‘i’;
name[9] = ‘n’;
name[10] = ‘g’;
name[11] = ‘\0’;
ii. char str[20];
str[0] = ‘C’;
str[1] = ‘a’;
str[2] = ‘t’;
str[3] = ‘\0’;
3. Reading and Writing String
a) Reading and Writing using formatted input output functions
String can be read and displayed using formatted input output functions printf() and
scanf().
General syntax for reading string is:

scanf(“%s”, string_variable);

For string, %s is used as format specifier.

Manish Kumar Shah(MKS) 191


191 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Examples:
i. char name[30];
scanf(“%s”, name); reads string to string variable name.
ii. char str1[10], str2[30];
scanf(“%s%s”, str1, str2); reads two string to string variables str1 and
str2.
Note: While reading string using scanf() string content after space will
not be read. To read string including space we need to use %[^\n]s instead
of %s.

Similarly, general syntax for writing string is:

printf(“%s”, string or string_variable);

Examples:
i. char name[30] = “Programming”;
printf(“%s”, name); displays output as “Programming”.

MKS
ii. char str1[10] = “Cat”, str2[30]= “Ball”;
printf(“str1 = %s and str2 = %s”, str1, str2); displays output as “str1 =
Cat and str2 = Ball”

b) Reading and Writing using unformatted input output functions

String can be read and displayed using unformatted input output functions puts() and
gets().
General syntax for reading string is:

gets(string_variable);

Examples:
iii. char name[30];
gets(name); reads string to string variable name.
iv. char str1[10], str2[30];
gets(str1);
gets(str2); reads two string to string variables str1 and str2.

Similarly, general syntax for writing string is:

puts( string or string_variable);

Manish Kumar Shah(MKS) 192


192 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Examples:
iii. char name[30] = “Programming”;
puts(name); displays output as “Programming”.
iv. char str1[10] = “Cat”, str2[30]= “Ball”;
puts(str1);
puts(“and”);
puts(str2); displays output as
“Cat
and
Ball”
4. Program to illustrate reading and writing of string
Program1 Output
Enter name:
#include<stdio.h> Ramesh↲
#include<conio.h> Hello Ramesh, have a nice time

void main()

MKS
{
char name[30];
clrscr();
printf("Enter name:\n");
scanf("%s", name);
printf("Hello %s, have a nice time.", name);
getch();
}

Program2 Output
Enter name:
#include<stdio.h> Ramesh Bhandari↲
#include<conio.h> Given name is:
Ramesh Bhandari
void main()
{
char name[30];
clrscr();
printf("Enter name:\n");
gets(name);
puts("Given name is:");
puts(name);
getch();
}

Manish Kumar Shah(MKS) 193


193 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
5. String handling function
Strings are an important aspects of programming. We can use string to write message to the user
and read text directly to make interactions with users go smoothly. In this section, we look at some
of these string handling functions.
The standard library of C contains many useful string-handling functions. The function prototypes
for these string handling functions are defined in standard header file string.h. This header file
must be included when using string handling functions.
Some useful string handling functions:
i. String Length
- Using string handling function: strlen()
Function strlen() returns the number of characters in string, excluding the null characters.
General syntax for strlen() is:

integer_variable = strlen(string or string_variable);

MKS
Program to illustrate concept of strlen():
Program Output
#include<stdio.h> Enter string:
#include<conio.h> Welcome to C↲
#include<string.h> Length of given string is: 12
void main()
{
char str[30];
int len;
clrscr();
printf("Enter string:\n");
gets(str);
len = strlen(str);
printf("Length of given string is: %d", len);
getch();
}

- Without using string handling function


Program Output
#include<stdio.h> Enter string:
#include<conio.h> Welcome to C↲
Length of given string is: 12
void main()
{

Manish Kumar Shah(MKS) 194


194 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
char str[30];
int i, len=0;
clrscr();
printf("Enter string:\n");
gets(str);
for(i=0;str[i]!='\0';i++)
{
len++;
}
printf("Length of given string is: %d", len);
getch();
}

- Using user defined function


Program Output
#include<stdio.h> Enter string:
#include<conio.h> Welcome to C↲
Length of given string is: 12
int mystrlen(char str[30]);

MKS
void main()
{
char str[30];
int i, len;
clrscr();
printf("Enter string:\n");
gets(str);
len = mystrlen(str);
printf("Length of given string is: %d", len);
getch();
}
int mystrlen(char str[30])
{
int i, len=0;
for(i=0;str[i]!='\0';i++)
{
len++;
}
return(len);
}

ii. String Copy


- Using string handling function: strcpy()
Function strcpy() is used to copy content of one string variable to another string variable
i.e. strcpy(string2, string1) copies content of string1 to string2.
Manish Kumar Shah(MKS) 195
195 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Note: Always second argument is copied to first argument.

General syntax for strcpy() is:

strcpy ( string2, string1);

Program to illustrate concept of strcpy():


Program Output
#include<stdio.h> Enter string:
#include<conio.h> Welcome to C↲
#include<string.h> Copied string is: Welcome to C
void main()
{
char str1[30], str2[30];
clrscr();
printf("Enter string:\n");
gets(str1);
strcpy(str2, str1);

MKS
printf("Coped string is: %s”, str2);
getch();
}

- Without using string handling function


Program Output
#include<stdio.h> Enter string:
#include<conio.h> Welcome to C↲
Copied string is: Welcome to C
void main()
{
char str1[30], str2[30];
int i;
clrscr();
printf("Enter string:\n");
gets(str1);
for(i=0;str1[i]!='\0';i++)
{
str2[i] = str1[i];
}
str2[i] = '\0';
printf("Copied string is: %s", str2);
getch();
}

Manish Kumar Shah(MKS) 196


196 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

- Using user defined function


Program Output
#include<stdio.h> Enter string:
#include<conio.h> Welcome to C↲
Copied string is: Welcome to C
void mystrcpy(char str2[30], char str1[30]);

void main()
{
char str1[30], str2[30];
int i;
clrscr();
printf("Enter string:\n");
gets(str1);
mystrcpy(str2, str1);
printf("Copied string is: %s", str2);
getch();
}

MKS
void mystrcpy(char str2[30], char str1[30])
{
int i;
for(i=0;str1[i]!='\0';i++)
{
str2[i] = str1[i];
}
str2[i] = '\0';
}

iii. String Comparison


- Function strcmp() is used to compare two strings. This function returns 0 if strings are
same otherwise it returns some integer value other than 0.
General syntax for strcmp() is:

integer_variable = strcmp( string1, string2);

Program to illustrate concept of strcmp():


Program Output

Manish Kumar Shah(MKS) 197


197 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> Run1:
#include<conio.h> Enter first string:
#include<string.h> Welcome to C↲
Enter second String:
void main() Welcome to C↲
{ Given strings are same.
char str1[40], str2[40];
int d; Run2:
clrscr(); Enter first string:
printf("Enter first string:\n"); Welcome↲
gets(str1); Enter second String:
printf("Enter second string:\n"); Welcome to C↲
gets(str2); Given strings are different.
d = strcmp(str1, str2);
if(d==0)
{
printf("Given strings are same.");
}
else
{
printf("Given strings are different.");

MKS
}
getch();
}
- Without using string handling function
Program Output
#include<stdio.h> Run1:
#include<conio.h> Enter first string:
Welcome to C↲
void main() Enter second String:
{ Welcome to C↲
char str1[40], str2[40]; Given strings are same.
int d,i, len1=0, len2=0, flag=0;
clrscr(); Run2:
printf("Enter first string:\n"); Enter first string:
gets(str1); Welcome↲
printf("Enter second string:\n"); Enter second String:
gets(str2); Welcome to C↲
/* Finding length of first string */ Given strings are different.
for(i=0;str1[i]!='\0';i++)
{
len1++;
}
/* Finding length of first string */
for(i=0;str2[i]!='\0';i++)
{
len2++;

Manish Kumar Shah(MKS) 198


198 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
if(len1!=len2)
{
printf("Given strings are different.");
}
else
{
for(i=0;i<len1;i++)
{
if(str1[i]!=str2[i])
{
flag=1;
break;
}
}
if(flag==0)
{
printf("Given strings are same.");
}
else
{

MKS
printf("Given strings are different.");
}
}
getch();
}

- Using user defined function


Program Output
#include<stdio.h> Run1:
#include<conio.h> Enter first string:
Welcome to C↲
int mystrcmp(char str1[40], char str2[40]); Enter second String:
Welcome to C↲
void main() Given strings are same.
{
char str1[40], str2[40]; Run2:
int d; Enter first string:
clrscr(); Welcome↲
printf("Enter first string:\n"); Enter second String:
gets(str1); Welcome to C↲
printf("Enter second string:\n"); Given strings are different.
gets(str2);
d = mystrcmp(str1, str2);
if(d==0)
{
printf("Given strings are same.");
Manish Kumar Shah(MKS) 199
199 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}
else
{
printf("Given strings are different.");
}
getch();
}
int mystrcmp(char str1[40], char str2[40])
{
int d,i, len1=0, len2=0, flag=0;
/* Finding length of first string */
for(i=0; str1[i]!='\0'; i++)
{
len1++;
}
/* Finding length of first string */
for(i=0; str2[i]!='\0'; i++)
{
len2++;
}
if(len1!=len2)

MKS
{
return(1);
}
else
{
for(i=0;i<len1;i++)
{
if(str1[i]!=str2[i])
{
flag=1;
break;
}
}
if(flag==0)
{
return(0);
}
else
{
return(1);
}
}
}

Manish Kumar Shah(MKS) 200


200 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
iv. String Concatenation
- Function strcat() is used to concatenate two strings. Concatenation is the process of
merging content of one string to another string. Function strcat(str1, str2);
concatenates content of string str2 after content of str1.
General syntax for strcat() is:

strcat( string1, string2);

Program to illustrate concept of strcat():


Program Output
#include<stdio.h> Enter first string:
#include<conio.h> Ram↲
#include<string.h> Enter second String:
Shyam↲
void main() Concatenated string is: RamShyam
{
char str1[50], str2[50];

MKS
clrscr();
printf("Enter first string:\n");
gets(str1);
printf("Enter second string:\n");
gets(str2);
strcat(str1,str2);
printf("Concatenated string is: %s", str1);
getch();
}
- Without using string handling function
Program Output
#include<stdio.h> Enter first string:
#include<conio.h> Ram↲
Enter second String:
void main() Shyam↲
{ Concatenated string is: RamShyam
char str1[50], str2[50];
int i, len=0;
clrscr();
printf("Enter first string:\n");
gets(str1);
printf("Enter second string:\n");
gets(str2);

/* Calculating length of first string */


for(i=0;str1[i]!='\0';i++)

Manish Kumar Shah(MKS) 201


201 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
{
len++;
}
/* Concatenating second string to first string */
/*
for(i=0;str2[i]!='\0';i++)
{
str1[len+i] = str2[i];
}
str1[len+i]='\0';
printf("Concatenated string is: %s", str1);
getch();
}

- Using user defined function


Program Output
#include<stdio.h> Enter first string:
#include<conio.h> Ram↲
Enter second String:
void mystrcat(char str1[40], char str2[40]); Shyam↲

MKS
Concatenated string is: RamShyam
void main()
{
char str1[50], str2[50];
int i, len=0;
clrscr();
printf("Enter first string:\n");
gets(str1);
printf("Enter second string:\n");
gets(str2);
mystrcat(str1, str2);
printf("Concatenated string is: %s", str1);
getch();
}
void mystrcat(char str1[40], char str2[40])
{
int i, len=0;
/* Calculating length of first string */
for(i=0;str1[i]!='\0';i++)
{
len++;
}
/* Concatenating second string to first string */
for(i=0;str2[i]!='\0';i++)
{
str1[len+i] = str2[i];
}
Manish Kumar Shah(MKS) 202
202 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
str1[len+i]='\0';
}

v. Converting to Lower Case


- Function strlwr() is used to convert all uppercase letter in string to lower case i.e.
strlwr(str) converts all uppercase letter in string str to lowercase.
General syntax for strlwr() is:

strlwr( string);

Program to illustrate concept of strlwr():


Program Output
#include<stdio.h> Enter string:
#include<conio.h> WeLcOmE To C 101. ↲
#include<string.h> String in lowercase is:
welcome to c 101.

MKS
void main()
{
char str[40];
clrscr();
printf("Enter string:\n");
gets(str);
strlwr(str);
printf("String in lowercase is:");
puts(str);
getch();
}
- Without using string handling function
Program Output
#include<stdio.h> Enter string:
#include<conio.h> WeLcOmE To C 101. ↲
void main() String in lowercase is:
{ welcome to c 101.
char str[40];
int i;
clrscr();
printf("Enter string:\n");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(str[i]>='A'&& str[i]<='Z')
{

Manish Kumar Shah(MKS) 203


203 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
str[i] = str[i]+32;
}
}
printf("String in lowercase is:\n");
puts(str);
getch();
}

- Using user defined function


Program Output
#include<stdio.h> Enter string:
#include<conio.h> WeLcOmE To C 101. ↲
void mystrlwr(char str[40]); String in lowercase is:
void main() welcome to c 101.
{
char str[40];
int i;
clrscr();
printf("Enter string:\n");

MKS
gets(str);
mystrlwr(str);
printf("String in lowercase is:\n");
puts(str);
getch();
}
void mystrlwr(char str[40])
{
int i;
for(i=0;str[i]!='\0';i++)
{
if(str[i]>='A'&& str[i]<='Z')
{
str[i] = str[i]+32;
}
}
}

vi. Converting to Uppercase


- Function strupr() is used to convert all lowercase letter in string to uppercase i.e.
strupr(str) converts all lowercase letter in string str to uppercase.
General syntax for strupr() is:

strupr( string);

Manish Kumar Shah(MKS) 204


204 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Program to illustrate concept of strupr():


Program Output
#include<stdio.h> Enter string:
#include<conio.h> WeLcOmE To C 101. ↲
#include<string.h> String in lowercase is:
void main() WELCOME TO C 101.
{
char str[40];
clrscr();
printf("Enter string:\n");
gets(str);
strupr(str);
printf("String in uppercase is:");
puts(str);
getch();
}
- Without using string handling function

MKS
Program Output
#include<stdio.h> Enter string:
#include<conio.h> WeLcOmE To C 101. ↲
void main() String in lowercase is:
{ WELCOME TO C 101.
char str[40];
int i;
clrscr();
printf("Enter string:\n");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(str[i]>='A'&& str[i]<='Z')
{
str[i] = str[i]+32;
}
}
printf("String in uppercase is:\n");
puts(str);
getch();
}

- Using user defined function


Program Output

Manish Kumar Shah(MKS) 205


205 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> Enter string:
#include<conio.h> WeLcOmE To C 101. ↲
void mystrlwr(char str[40]); String in lowercase is:
void main() WELCOME TO C 101.
{
char str[40];
int i;
clrscr();
printf("Enter string:\n");
gets(str);
mystrlwr(str);
printf("String in uppercase is:\n");
puts(str);
getch();
}
void mystrlwr(char str[40])
{
int i;
for(i=0;str[i]!='\0';i++)
{
if(str[i]>='A'&& str[i]<='Z')

MKS
{
str[i] = str[i]+32;
}
}
}

Manish Kumar Shah(MKS) 206


206 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
6. String Patterns
a) Write a program in C to generate following pattern.

Program
#include<stdio.h>
#include<conio.h>

void main()
{
char str[]="NePaL";
int i,j;

MKS
clrscr();
for(i=0;i<5;i++)
{
for(j=0;j<5-i;j++)
{
printf(" ");
}
for(j=0;j<2*i+1;j++)
{
printf("%c", str[i]);
}
printf("\n");
}
getch();
}

b) Write a program in C to generate following pattern.

Manish Kumar Shah(MKS) 207


207 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char str[]="NEPAL";
int i,j;
clrscr();
for(i=0;i<5;i++)
{
for(j=0;j<5-i;j++)
{
printf(" ");
}
for(j=0;j<=i;j++)
{
printf("%c", str[j]);
}
printf("\n");
}
getch();

MKS
}

c) Write a program in C to generate following pattern.

Program
#include<stdio.h>
#include<conio.h>
void main()
{
char str[]="ePhYr";
int i,j;
clrscr();
printf(" Z\n");
for(i=0;i<5;i++)
{
Manish Kumar Shah(MKS) 208
208 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
for(j=0;j<5-i;j++)
{
printf(" ");
}
for(j=0;j<2*i+1;j++)
{
printf("%c", str[i]);
}
printf("\n");
}
getch();
}
d) Write a program in C to generate following pattern using unformatted ouptpu
function only.

Program
#include<stdio.h>
MKS
#include<conio.h>
void main()
{
char str[]="ePhYr";
int i,j;
clrscr();
puts(" Z");
for(i=0;i<5;i++)
{
for(j=0;j<5-i;j++)
{
putchar(' ');
}
for(j=0;j<2*i+1;j++)
{
putchar(str[i]);
}
putchar('\n');
}

Manish Kumar Shah(MKS) 209


209 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
getch();
}

MKS

Manish Kumar Shah(MKS) 210


210 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Structure
Structure is a collection of heterogeneous (i.e. of different types) data items which are referenced
by a single name. Structure is also known as records. A structure is a convenient way of grouping
several data items together.
In C programming language, we can create and use data types other than the basic or fundamental
data types. These are known as user defined data types. Structures are created by using struct
keyword and can be defined as a user defined data types.
Declaration of Structure
The general syntax for declaring structure is:
struct structure_name
{
data_type member1;
data_type member2;
data_type member3;
.
.

MKS
.
data_type memberN;
};
Where structure_name and member can be any valid C identifier, data type can be any valid C
data types. Structure name is also known as tag. When we declare a structure, new data type is
defined. After declaring structure, structure variables can be created by using keyword struct and
structure_name.
General syntax for creating structure variables after declaring structure is:

struct structure_name var1, var2, var3, …., varN;

For Example:
struct student
{
char name[30];
int roll;
float marks;
};
In this example, student is name of structure and it has three members, namely, name, roll and
marks. Now struct student is name of new data type which can be used to create new structure
variables. For example:

Manish Kumar Shah(MKS) 211


211 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

struct student s1, s2, s3;

Where s1, s2 and s3 are structure variables.


Structure variables can also be created at the time of structure declaration. General syntax for
declaring structure variables at the time of structure declaration is:
struct structure_name
{
data_type member1;
data_type member2;
data_type member3;
.
.
.
data_type memberN;

} var1, var2, var3, …., varN;

For Example:

MKS
struct student
{
char name[30];
int roll;
float marks;
}s1, s2, s3;
While using structure, the typedef feature is quite useful for defining structures, since it avoids the
need to repeatedly write struct keyword. Using typedef, we can refer the structure more concisely.
Structures defined using typedef are also known as user defined structure type.
The general syntax for declaring user defined structure type is
typedef struct
{
data_type member1;
data_type member2;
data_type member3;
.
.
.
data_type memberN;

} new_type;

Manish Kumar Shah(MKS) 212


212 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Here new_type is the name of new data type created and structure variables can be created using
new_type alone i.e. we don’t need struct keyword.

For example:
typedef struct
{
char name[30];
int roll;
float marks;
}student;
In this example student is new type and structure variables can be created using student, For
example:

student s1, s2, s3;

MKS
Initialization of Structure Variable
Assigning value to the structure variable at the time declaration of structure variable is known as
initialization of structure variables. Structure variables can be initialized by using the notation used
for array initialization.
For example
If structure is declared like this:
struct student
{
char name[30];
int roll;
float marks;
};
Then structure variables can be created and initialized like this:

struct student s1 = {“Parijat”, 13, 80.5};


struct student s2 = {“Suyogbir”, 17, 60};
struct student s3 = {“Sakambari”, 19, 50.5};

Accessing Structure Elements

Manish Kumar Shah(MKS) 213


213 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Individual structure elements can be accessed by using the . (dot) operator and along with structure
variables. The general syntax for accessing structure variables is:

structure_variable . member_name
For example
If structure is declared like this:
struct student
{
char name[30];
int roll;
float marks;
};
And, structure variables are created and initialized like this:

struct student s1 = {“Parijat”, 13, 80.5};


struct student s2 = {“Suyogbir”, 17, 60};
Then,

[Link] gives 80.5


similarly,
MKS
[Link] gives “Parijat”
[Link] gives 13

[Link] gives “Suyogbir”


[Link] gives 17
[Link] gives 60

Program to Illustrate use of Structure


1. Program to illustrate declaration and initialization of structure.
Program Output

Manish Kumar Shah(MKS) 214


214 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h>
#include<conio.h> Student detail is:
/* Declaration of structure */ Name : Parijat
struct student Roll : 17
{ Marks : 80.500000
char name[30];
int roll;
float marks;
};

void main()
{
/* Declaration and initialization of structure variable */
struct student s1 = {"Parijat", 17, 80.5};
clrscr();
printf("Student detail is:\n");
printf("Name : %s\n", [Link]);
printf("Roll : %d\n", [Link]);
printf("Marks : %f\n", [Link]);
getch();
}

#include<stdio.h>
#include<conio.h>
MKS
2. Program to illustrate reading data in structure variable and displaying the content.
Program

/* Declaration of structure */
struct student
Output
Enter name, roll and marks of student:
Suyogbir ↲
18 ↲
56.5 ↲
{ Student detail is:
char name[30]; Name: Suyogbir
int roll; Roll: 18
float marks; Marks: 56.500000
};

void main()
{
/* Declaration of structure variable */
struct student s1;
clrscr();
printf("Enter name, roll and marks of student:\n");
scanf("%s%d%f",[Link], &[Link], &[Link]);
printf("Student detail is:\n");
printf("Name : %s\n", [Link]);
printf("Roll : %d\n", [Link]);
printf("Marks : %f\n", [Link]);
getch();
}
Manish Kumar Shah(MKS) 215
215 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

3. Program to add two complex number using structure.


Program Output

#include<stdio.h> Enter real and imaginary part for


#include<conio.h> first:
/* Declaration of structure */ 2↲
typedef struct 3↲
{ Enter real and imaginary part for
float real; second:
float imag; 1↲
}complex; -1↲
Result is: 3.00 + 2.00 i
void main()
{
/* Declaration of structure variables */
complex c1, c2, c3;
clrscr();
printf("Enter real and imaginary part for first:\n");
scanf("%f%f", &[Link], &[Link]);

MKS
printf("Enter real and imaginary part for second:\n");

scanf("%f%f", &[Link], &[Link]);


[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
printf("Result is: %0.2f + %0.2f i", [Link], [Link]);
getch();
}

4. Program to multiply two complex number using structure


Program Output
#include<stdio.h> Enter real and imaginary part for
#include<conio.h> first:
/* Declaration of structure */ 2↲
typedef struct 3↲
{ Enter real and imaginary part for
float real; second:
float imag; 1↲
}complex; -1↲
Result is: 5.00 + 1.00 i
void main()
{
/* Declaration of structure variables */
complex c1, c2, c3;
clrscr();
printf("Enter real and imaginary part for first:\n");

Manish Kumar Shah(MKS) 216


216 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
scanf("%f%f", &[Link], &[Link]);
printf("Enter real and imaginary part for second:\n");

scanf("%f%f", &[Link], &[Link]);


[Link] = [Link] * [Link] – [Link] * [Link];
[Link] = [Link] * [Link] + [Link] * [Link];
printf("Result is: %0.2f + %0.2f i", [Link], [Link]);
getch();
}

5. Program to read start and stop time in hh:mm:ss and calculating difference between
them (Assume inputs are in correct format).
Program Output
#include<stdio.h> Enter hh, mm and ss for start:
#include<conio.h> 1↲
/* Declartion of structure */ 50↲
typedef struct 55↲
{ Enter hh, mm and ss for stop
int hh; 4↲

MKS
int mm; 12↲
int ss; 45↲
}time; Difference is: 2:21:50

void main()
{
/* Declaration of structure variables */
time start, stop, diff;
clrscr();
printf("Enter hh, mm and ss for start:\n");
scanf("%d%d%d", &[Link], &[Link], &[Link]);
printf("Enter hh, mm and ss for stop:\n");
scanf("%d%d%d", &[Link], &[Link], &[Link]);
if([Link]<[Link])
{
[Link] += 60;
[Link] -= 1;
}
if([Link]<[Link])
{
[Link] += 60;
[Link] -= 1;
}
[Link] = [Link] - [Link];
[Link] = [Link] - [Link];
[Link] = [Link] - [Link];
printf("Difference is: %d:%d:%d", [Link], [Link], [Link]);

Manish Kumar Shah(MKS) 217


217 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
getch();
}

6. Program to add two distances in feet and inch system using structure.
Program Output
#include<stdio.h> Enter feet and inch of first
#include<conio.h> distance:
/* Structure Declaration */ 5
typedef struct 9
{ Enter feet and inch of second
int feet; distance:
int inch; 6
}distance; 11
Result is 12 feet and 8 inch
void main()
{
distance d1, d2, res;
clrscr();

MKS
printf("Enter feet and inch of first distance:\n");
scanf("%d%d", &[Link], &[Link]);
printf("Enter feet and inch of second distance:\n");
scanf("%d%d", &[Link], &[Link]);
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
if([Link]>=12)
{
[Link]++;
[Link] = [Link]-12;
}
printf("Result is %d feet and %d inch", [Link], [Link]);
getch();
}

Nested Structure (Structure within Structure)


In C programming, we can have member of a structure itself as a structure. This is also referred to
as structure within structure and such type of structures are known as nested structure.
For Example:

Manish Kumar Shah(MKS) 218


218 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
struct address
{
int houseno;
char street[20];
int stateno;
};
struct student
{
char name[30];
int roll;
struct address adr; /* structure within structure or nested structure */
};
struct student st; /* structure variable */
Now, the elements of nested structures are accessed from outermost to innermost with the help of
. (dot) operator. For example, to access houseno, we use [Link], similarly for street, we
use [Link], and so on.
Program to Illustrate Concept of Nested Structure

Program

MKS
#include<stdio.h>
#include<conio.h>
/* Declaration of structure */
struct address
{
int houseno;
char street[20];
int stateno;
};
/* Declaration of structure */
struct student
{
char name[30];
int roll;
struct address adrs; /* Nested structure */
};

void main()
{
struct student stud;
clrscr();
printf("Enter name and roll number of student:\n");
scanf("%s%d",[Link], &[Link]);
printf("Enter street name, house number and state number:\n");
scanf("%s%d%d",[Link], &[Link], &[Link]);
printf("Student detail is:\n");
printf("Name: %s\tRoll: %d\n", [Link], [Link]);
printf("Address:%s, House no. -%d, state: %d",[Link], [Link], [Link]);
getch();

Manish Kumar Shah(MKS) 219


219 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}

Output:

Enter name and roll number of student:


Ramesh↲
17↲
Enter street name, house number and state number:
Jwagal↲
78↲
3↲
Student detail is:
Name: Ramesh Roll: 17
Address: Jwagal, House no. – 78, state: 3

MKS
Arrays of Structure
An array having structure as its base type is known as array of structure. To create an array of
structure, first structure is declared and then array of structure is declared just like ordinary array.
For Example:
struct employee
{
int emp_id;
char name[20];
char dept[20];
float salary;
};

struct employee emp[10]; /* This is array of structure */


In this example, first structure employee is declared, then array of structure created using new type
i.e. struct employee. Using the above array of structure 10 set of employee records can be stored
and manipulated.
To access any structure, index is used. For example, to read the emp_id of first structure we use
scanf(“%d”, emp[0].emp_id); as we know in C array indexing starts from 0.
Similar array of structure can also be declared like:

Manish Kumar Shah(MKS) 220


220 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
struct employee
{
int emp_id;
char name[20];
char dept[20];
float salary;
} emp[10];

And like:
typedef struct
{
int emp_id;
char name[20];
char dept[20];
float salary;
}employee;

employee emp[10];

MKS
Which we have already seen in structure declaration section.

Programming Examples to Illustrate Concept of Array of Structure


1. Program to read records of three different students in structure having member name,
roll and marks, and displaying it.
Program Output
#include<stdio.h> Enter name, roll and marks of student:
#include<conio.h> Manjari↲
/* Declaration of structure */ 17↲
struct student 80.5↲
{ Enter name, roll and marks of student:
char name[30]; Monalisa↲
int roll; 18↲
float marks; 90↲
}; Enter name, roll and marks of student:
Manita↲
void main() 19↲
{ 78↲
/* Declaration of array of structure */ Inputted details are:
struct student s[3]; Name: Manjari
int i; Roll: 17
Manish Kumar Shah(MKS) 221
221 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
clrscr(); Marks: 80.50
for(i=0;i<3;i++)
{ Name: Monalisa
printf("Enter name, roll and marks of student:\n"); Roll: 18
scanf("%s%d%f",s[i].name, &s[i].roll, &s[i].marks); Marks: 90.00
}
printf("Inputted details are:\n"); Name: Manita
for(i=0;i<3;i++) Roll: 19
{ Marks: 78.00
printf("Name: %s\n",s[i].name);
printf("Roll: %d\n", s[i].roll);
printf("Marks: %0.2f\n\n", s[i].marks);
}
getch();
}

2. Program to read records of n different students in structure having member name, roll
and marks, and displaying the student detail obtaining highest marks.
Program Output

MKS
#include<stdio.h> Enter n:
#include<conio.h> 4↲
/* Declaration of structure */ Enter name, roll and marks of student:
struct student Ram↲
{ 10↲
char name[30]; 88↲
int roll; Enter name, roll and marks of student:
float marks; Shyam↲
}; 11↲
67↲
void main() Enter name, roll and marks of student:
{ Hari↲
/* Declaration of array of structure */ 12↲
struct student s[20], lg; 92↲
int i,n; Enter name, roll and marks of student:
clrscr(); Prakash↲
printf("Enter n:\n"); 13↲
scanf("%d",&n); 88.5↲
for(i=0;i<n;i++) Student obtaining highest marks is:
{ Name: Hari
printf("Enter name, roll and marks of student:\n"); Roll: 12
scanf("%s%d%f",s[i].name, &s[i].roll, &s[i].marks); Marks: 92.50
}
lg = s[0];
for(i=0;i<n;i++)
{
if(s[i].marks>[Link])

Manish Kumar Shah(MKS) 222


222 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
{
lg = s[i];
}
}
printf("Student obtaing highest marks is:\n");
printf("Name: %s\n", [Link]);
printf("Roll: %d\n", [Link]);
printf("Marks: %0.2f\n", [Link]);
getch();
}

3. Program to read records of n different students in structure having member name, roll
and marks, and displaying the student details which are sorted by marks in ascending
order.
Program Output
#include<stdio.h> Enter n:
#include<conio.h> 4↲
/* Declaration of structure */ Enter name, roll and marks of student:
struct student Ram↲

MKS
{ 10↲
char name[30]; 88↲
int roll; Enter name, roll and marks of student:
float marks; Shyam↲
}; 11↲
67↲
void main() Enter name, roll and marks of student:
{ Hari↲
/* Declaration of array of structure */ 12↲
struct student s[20], temp; 92↲
int i,j,n; Enter name, roll and marks of student:
clrscr(); Prakash↲
printf("Enter n:\n"); 13↲
scanf("%d",&n); 88.5↲
for(i=0;i<n;i++) Sorted records are:
{ Name: Shyam
printf("Enter name, roll and marks of student:\n"); Roll: 11
scanf("%s%d%f",s[i].name, &s[i].roll, &s[i].marks); Marks: 67.00
}
for(i=0;i<n-1;i++) Name: Ram
{ Roll: 10
for(j=i+1;j<n;j++) Marks: 88.00
{
if(s[i].marks>s[j].marks) Name: Prakash
{ Roll: 13
temp = s[i]; Marks: 88.50
s[i] = s[j];

Manish Kumar Shah(MKS) 223


223 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
s[j] = temp; Name: Hari
} Roll: 12
} Marks: 92.00
}
printf("Sorted records are:\n");
for(i=0;i<n;i++)
{
printf("Name: %s\n", s[i].name);
printf("Roll: %d\n", s[i].roll);
printf("Marks: %0.2f\n\n", s[i].marks);
}
getch();
}

4. Program to read records of n different students in structure having member name, roll
and marks, and displaying the student details which are sorted by name in alphabetic
order.

Just change

MKS
if(s[i].marks>s[j].marks)

to

if(strcmp(s[i].name,s[j].name)>0)

in the above program and include string.h in the program header file section ☺
5. WAP to read name, salary and age of 10 different employees as the three members of a
structure named ‘employee’. Display the name, salary and corresponding age of the
employees sorted on the basis of age in descending order.
Program Output
#include<stdio.h> Enter n:
#include<conio.h> 4↲
/* Declaration of structure */ Enter name, salary and age of employee:
typedef struct Ram↲
{ 10000↲
char name[30]; 58↲
int salary; Enter name, roll and marks of student:
int age; Shyam↲
}employee;
11000↲
67↲
void main()
Enter name, roll and marks of student:
{
/* Declaration of array of structure */ Hari↲
employee e[20], temp; 12000↲
int i,j,n; 37↲

Manish Kumar Shah(MKS) 224


224 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
clrscr(); Enter name, roll and marks of student:
printf("Enter n:\n"); Prakash↲
scanf("%d",&n); 13000↲
for(i=0;i<n;i++) 48↲
{ Sorted records are:
printf("Enter name, salary and age of employee:\n"); Name: Shyam
scanf("%s%d%d",e[i].name, &e[i].salary, &e[i].age); Salary: 11000
} Age: 67
for(i=0;i<n-1;i++)
{
Name: Ram
for(j=i+1;j<n;j++)
Salary: 10000
{
if(e[i].age<e[j].age) Age: 58
{
temp = e[i]; Name: Prakash
e[i] = e[j]; Salary: 13000
e[j] = temp; Age: 48
}
} Name: Hari
} Salary: 12000
printf("Sorted records are:\n"); Age: 37
for(i=0;i<n;i++)

MKS
{
printf("Name: %s\n", e[i].name);
printf("Salary: %d\n", e[i].salary);
printf("Age: %d\n\n", e[i].age);
}
getch();
}

Arrays within Structure


In C programming, we can have structure member of type array. To access each element from an
array within structure, we write structure variable followed by dot (.) and then array name along
with index.
Program to illustrate array within structure:
Program Output

Manish Kumar Shah(MKS) 225


225 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> Enter name and roll number of
#include<conio.h> students:
Neelima
struct student 171
{
char name[20]; Enter marks obtained in five
int roll; different subject
float marks[5]; /* This is array within structure */ Enter marks:
}; 78
Enter marks:
void main() 87
{ Enter marks:
struct student s; 92
int i; Enter marks:
float sum=0, p; 89
clrscr(); Enter marks:
printf("Enter name and roll number of students:\n"); 96
scanf("%s%d",[Link],&[Link]);
printf("\nEnter marks obtained in five different subject\n"); Student records and percentage
is:
for(i=0;i<5;i++) Name: Neelima

MKS
{ Roll Number: 171
printf("Enter marks:\n"); Percentage obtained is: 88.40
scanf("%f",&[Link][i]);
sum = sum + [Link][i];
}

p = sum/5;
printf(“Student records and percentage is:\n”);
printf("Name : %s\n", [Link]);
printf("Roll Number : %d\n", [Link]);
printf("Percentage obtained is: %f", p);
getch();
}

Structure and User Defined Function


Structure can be manipulated using user defined function just like any other normal user defined
functions. Just like any other normal variable, structure variable can be passed as function
arguments and can be returned from functions.

Programs to illustrate structure and user defined functions:


1. Program to add two distances in feet-inch system using structure and user defined
functions.

Manish Kumar Shah(MKS) 226


226 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Program Output
#include<stdio.h> Enter feet and inch of first
#include<conio.h> distance:
/* Structure Declaration */ 5
typedef struct 9
{ Enter feet and inch of second
int feet; distance:
int inch; 6
}distance; 11
/* Function Prototype */ Result is 12 feet and 8 inch
distance sum(distance x, distance y);

void main()
{
distance d1, d2, res;
clrscr();
printf("Enter feet and inch of first distance:\n");
scanf("%d%d", &[Link], &[Link]);
printf("Enter feet and inch of second distance:\n");
scanf("%d%d", &[Link], &[Link]);
res = sum(d1,d2);

MKS
printf("Result is %d feet and %d inch", [Link], [Link]);
getch();
}

distance sum(distance x, distance y)


{
distance s;
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
if([Link]>=12)
{
[Link]++;
[Link] = [Link]-12;
}
return(s);
}

2. Program to read start and stop time in hh:mm:ss and calculating difference between
them using structure and user defined function. (Assume inputs are in correct format).

Program Output

Manish Kumar Shah(MKS) 227


227 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
#include<stdio.h> Enter hh, mm and ss for start:
#include<conio.h> 1↲
/* Declartion of structure */ 50↲
typedef struct 55↲
{ Enter hh, mm and ss for stop:
int hh; 4↲
int mm; 12↲
int ss; 45↲
}time; Difference is: 2:21:50
/* Function prototype */
time diff_fun(time start, time stop);
void main()
{
time start, stop, res;
clrscr();
printf("Enter hh, mm and ss for start:\n");
scanf("%d%d%d", &[Link], &[Link], &[Link]);
printf("Enter hh, mm and ss for stop:\n");
scanf("%d%d%d", &[Link], &[Link], &[Link]);
res = diff_fun(start, stop);
printf("Result is: %d:%d:%d", [Link], [Link], [Link]);

MKS
getch();
}
time diff_fun(time start, time stop)
{
time diff;
if([Link]<[Link])
{
[Link] += 60;
[Link] -= 1;
}
if([Link]<[Link])
{
[Link] += 60;
[Link] -= 1;
}
[Link] = [Link] - [Link];
[Link] = [Link] - [Link];
[Link] = [Link] - [Link];
return(diff);
}

3. WAP to read name and age of 10 different students as the two members of a structure
named ‘student’. Display the name and corresponding age of the students sorted in
alphabetical order using user defined function.

Manish Kumar Shah(MKS) 228


228 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
/* Structure Declaration */
typedef struct
{
char name[30];
int age;
}student;
/* Function Prototype */
void sortname(student s[10]);
void main()
{
student s[10];
int i;
clrscr();
for(i=0;i<10;i++)
{
printf("Name and age of student:\n");
scanf("%s%d",s[i].name, &s[i].age);

MKS
}
sortname(s); /* Function Call */
printf("Sorted result is:\n");
for(i=0;i<10;i++)
{
printf("Name=%s\t Age=%d\n", s[i].name, s[i].age);
}
getch();
}
void sortname(student s[10])
{
student temp;
int i,j;
for(i=0;i<9;i++)
{
for(j=i+1;j<10;j++)
{
if(strcmp(s[i].name,s[j].name)>0)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
}

Manish Kumar Shah(MKS) 229


229 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

Data Files
Concept of Data Files
We frequently use files for storing information which can be processed by our programs. Such
files are called data files. A file is bunch of bytes stored on some storage device. Most of the
application program processes large volume of data which is permanently stored in data files. In
order to store information permanently and retrieve, we need to use data files.
So far we have used the technique of data communication between the console unit and program.
Some of the problems which may occur using this technique are:
1. A lot of time is taken for data entry.
2. Entire data would be re-entered if a mistake is made in input data.
3. If the same data is to be processed later on, it would be entered afresh i.e. for every run,
we require the same data entry.
Now we are going to describe the storage and retrieval of data from the files which overcomes the
problem stated above.

MKS
File Pointer
As we know, we can have many files on our disk. While dealing with files, in our program, we
need to specify which files we wish to use. In c programming, we use a new data type called file
pointer to communicate with files.
Every file we open has its own file pointer variable. When we wish to read from a file or write to
a file, we need to specify the file pointer variable. We can declare these file pointer variables as
follows.
General syntax to declare file pointer variables

FILE *file_pointer1, *file_pointer2, *file_pointer3, ......., *file_pointerN ;

For Example:
a. FILE *fptr;
Here fptr is file pointers and using fptr we can communicate with files.
b. FILE *source, *destination;
Here source, destination are two file pointers.
Opening and Closing File
1. Opening Data File
Manish Kumar Shah(MKS) 230
230 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
A data file must be opened before it can be processed. Since file can be used in different
ways i.e. for reading or writing to or both. In C programming, the mode of file utilization
is specified while opening the data file and library function fopen() defined in stdio.h is
used to open a file.

Syntax for fopen() is:

file_pointer_name = fopen("filename", "mode") ;

Here, filename represents the name of file that we wish to use and mode specifies the
purpose of opening the file i.e. reading, writing, appending, etc.

Different file modes and their meaning:


a. Text File

Mode Purpose
r Open text file for reading only. The file must already exist.

MKS
w Open text file for writing only. If the file specified already exist, its contents
will be destroyed. If it does not exist it will be created.
a Open text file for appending (i.e. adding data to the end of existing file). If
it does not exist it will be created.
r+ Open text file for both reading and writing. The file must already exist.
w+ Open text file for both reading and writing. If the file exists, its content will
be overwritten. If it does not exist it will be created.
a+ Open text file for both reading and appending. If file does not exist it will
be created.

b. Binary File

Mode Purpose
rb Open binary file for reading only. The file must already exist.
wb Open binary file for writing only. If the file specified already exist,
its contents will be destroyed. If it does not exist it will be created.
ab Open binary file for appending (i.e. adding data to the end of existing
file). If it does not exist it will be created.
rb+ or r+b Open binary file for both reading and writing. The file must already
exist.
wb+ or w+b Open binary file for both reading and writing. If the file exists, its
content will be overwritten. If it does not exist it will be created.
ab+ or a+b Open binary file for both reading and appending. If file does not exist
it will be created.

Manish Kumar Shah(MKS) 231


231 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
fopen() function returns a pointer to the beginning of the file if it is successfully opened
otherwise it returns NULL value which is defined in stdio.h.

c. Text File vs. Binary File

S.N. Text File Binary File


1. In text file, text, character, numbers
In binary file data is stored in binary
are stored one character per byte i.e.
format and each data would occupy
32667 occupies 5 bytes even thoughsame number of bytes on disks as it
it occupies 2 bytes in memory. occupies in memory.
2. In text file, newline character isIn binary file, conversion of newline
converted to carriage-return/linefeed
to carriage-return/linefeed does not
before being written to the disk. take place.
3. Text files are used to store data more
Binary files are used to store data
user friendly. more compactly.
4. In text file, special character whose
In binary file no such character is
ASCII value is 26 inserted after last
present. Files keep track of the end of
character to mark the end of [Link] from the number of character
present.

MKS
5. Content written in text files are Content written in binary files are
human readable. not human readable and look like
encrypted content.

2. Closing Data File


When the processing (reading,writing or both) is over in a file, it must be closed. The
library function fclose() defined in stdio.h is used for this purpose.

The general syntax of fclose() is:

fclose(file_pointer_name);

Input/Output Operations on File


1. Character I/O Operations on Files
Character input output functions are used to read a character or to write a character to a
file.
Commonly used character input output functions are:
a. fgetc()
fgetc() function reads a character from a file and returns EOF if end file is reached.

The general syntax of fgetc() is:


Manish Kumar Shah(MKS) 232
232 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming

character_variable = fgetc(file_pointer_variable);

b. fputc()
fputc() function is used to write a character to a file.

The general syntax of fputc() is:

fputc(character_or_character_variable, file_pointer_variable);

c. getc()
Same as fgetc(), getc() is also used to read a character from a file and returns EOF if
end of file is reached. fgetc() is function while getc() is macro.

The general syntax of getc() is

character_variable = getc(file_pointer_variable);

d. putc()

MKS
Same as fputc(), putc() is also used to write a character to file. fputc() is function while
putc() is macro.

The general syntax of putc() is:

putc(character_or_character_variable, file_pointer_variable);

2. String I/O Operations on Files


When we need to process only string data type, the string input output functions fgets() and
fputs() can be utilized for this purpose. String input output functions are used to read string
or to write a string to a file.
Commonly used character input output functions are:
a. fgets()
Function fgets() is used to read string from a file. General syntax is:

fgets(string_variable, intger_value, file_pointer);

b. fputs()
Manish Kumar Shah(MKS) 233
233 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Function fputs() is used to write string to a file. General syntax is:

fputs(string or string_variable, file_pointer);

3. Formatted I/O Operations with Files


In C programming files can be created to store formatted data and it can be read using
formatted input output functions.
Commonly used formatted input output functions are:
a. fprintf()
Function fprintf() is formatted output functions which is used to write some integer,
float, double, char, or string to a file.
Its syntax is:

fprintf(file_pointer, “format_string”, list_of_variables)

b. fscanf()
Function fscanf() is formatted input function which is used to read some integer, float,

MKS
double, char, or string from a file.
Its syntax is:

fscanf(file_pointer, “format_string”, list_of_address_of_variables);

4. Record I/O Operation in Files


Record I/O writes numeric values to files in binary format. Using record input output
functions, structures, array of structures can be read or write from or to file.
Function fread() and fwrite() are used to read or write record from or to file.
a. fread()
fread() is used for record input function and its syntax is:

fread(address, size, number, file_pointer);

b. fwrite()
fwrite() is used for record output functions and its syntax is:

fwrite(address, size, number, file_pointer);

Error Handling in File Operations


File handling operations may fail due to anyone of the following reasons:
Manish Kumar Shah(MKS) 234
234 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
1. A file for reading may not be present on the disk.
2. Insufficient disk space for opening a file for writing.
3. Write protected disk does not allow storage of data on it.
4. Dealing with corrupt file.

To handle these error we need to check whether the intended data files has opened
successfully or not by comparing the
result of fopen() function with NULL character. Since fopen() function points to the
begining of the file if file is opened successfully otherwise it returns NULL.
Code for handling error during file opening
if ( file_pointer == NULL)
{
printf("Something is wrong");

MKS
exit(1);
}
Other useful functions for handling error during read/write operations are:
1. ferror()
This function reports any error during a read/write operation on a file.
Its prototype is:
int ferror(file_pointer_variable);
2. perror()
This function writes the error message specified by the compiler.
Its prototype is:
void perror(error_message);

Manish Kumar Shah(MKS) 235


235 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Syntax Related Question – Answering Tips
1. Functions
printf()
printf() is formatted output function which is used to display string to standard
output device. printf() is defined in stdio.h header file.

General syntax for printf is:


printf(“format string”, comma separated list of variables);

For example:- printf(“Hello world!”) will display Hello world! to output device.
and similarly,
if a=34 and b=56
printf(“value of a = %d and value of b= %d”,a,b) will display value of a 34 and value
of b=56

Program to illustrate printf():


#include<stdio.h>
#include<conio.h>
void main()

MKS
{
int a=45;
clrscr();
printf(“Welcome to C programming.\n”);
printf(“Value of a= %d”,a);
getch();
}
Output:
Welcome to C programming.
Value of a=45

2. Keyword

int

In c programming, keyword int is used to create integer data types. Size of int is 2
bytes and range is -32768 to 32767.

General syntax for int is:

int comma_separated_list_of_variables;

Manish Kumar Shah(MKS) 236


236 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
For example: int a; will create variable a of integer data type.
And int a,b,c; will create three variables a,b,c of integer data types.

Program to illustrate int:

#include<stdio.h>
#include<conio.h>

void main()
{
int a=45;
clrscr();
printf(“Value of a= %d”,a);
getch();
}

Advantage of Pointer

MKS
Pointer is very important and useful feature of C. Pointer is variable which holds a memory address
which is the memory location of some other variable in memory. As a pointer is variable its value
is stored in some other memory location.
Main benefits of using pointer in C are:
- Pointers provide direct access to memory.
- Pointers provide a way to return multiple value from user defined function without using
return keyword.
- Pointer reduces the storage space and complexity of program.
- Pointer reduces the execution time of program.
- Pointers provide alternate way to access array elements.
Declaration of Pointer Variable
A pointer variable can be declared using following syntax:

data_type * pointer_name;

Examples:
1. int *ptr;
Here ptr is pointer variable which can points to integer value.
2. float *fptr;
Here fptr is pointer which can points to float value.
Manish Kumar Shah(MKS) 237
237 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
Initialization of Pointer Variable or Referencing
Making pointer variable to point other variable by providing address of that variable is known as
pointer referencing or initialization of pointer.
Examples:
1. int a=5;
int *ptr;
ptr = &a; Here pointer ptr got address of variable a so pointer ptr is now pointing to
variable a.
2. float val=5.5;
float *p;
p = &val; Here pointer p got address of variable val so pointer p is now pointing to
variable val.
Dereferencing of Pointer
After referencing, * pointer_name gives value of the variable pointed by pointer variable and
this is known as pointer dereferencing.

MKS
Examples:
1. int a=5;
int *ptr;
ptr = &a;
printf(“a = %d”, *ptr); This prints a = 5 which is accessed through pointer.
2. float val=5.5;
float *p;
p = &val;
printf(“val = %f”, *p); This prints val = 5.5 which is accessed through pointer.

Program to illustrate concept of pointer:


Program Output
#include<stdio.h> Value of a = 50
#include<conio.h> Value of val = 50.5
void main()
{
int a=50, *p;
float val = 50.5, *f
p = &a;
f = &val;
printf(“Value of a = %d\n”, *p);
printf(“Value of val = %d\n”, *f)
getch();

Manish Kumar Shah(MKS) 238


238 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
}

Comparison of Array and Pointer


Array Pointer
Array is collection of homogenous element Pointer is special type of variable which is
i.e. of similar data types. used to store the address of another ordinary
variable.
Array uses index/subscript for accessing array After referencing, i.e after initialization of
elements. pointer, pointer uses dereferencing or value-at
(*) operator to access values.
Name of the array is equivalent to address of We need to declare pointer variable to point
first element of that array. So name of array another variable using:
points to the first element of array and acts data_type *name_of_pointer_variable;
like pointer variable. Due to this, array is also
considered as indirect pointer.

MKS
General syntax for declaring array is: General syntax for declaring pointer is:
data_type name_of_array[size_of_array]; data_type *name_of_pointer variable;
For example: For example:
int a[30]; float b[4][4]; int *ptr; float *fptr; char *cptr;
Example: Example:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>

void main() void main()


{ {
int a[3] = {11,22,33}; int a=56, *p, **pp;
int i; p=&a;
clrscr(); pp=&p;
for(i=0;i<3;i++) clrscr();
{ printf("%d\t%d",*p,**p);
printf("%d\t",a[i]); getch();
} }
getch();
}

Output of the program is: 11 22 33 Output of the program is: 56 56

Comparison of Array and Structure


S.N. Array Structure

Manish Kumar Shah(MKS) 239


239 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
1. Array is collection of homogenous Structure is collection of heterogeneous
elements i.e. of similar data types. elements i.e. of different data types.
2. Array uses index or subscript for accessing Structure uses dot (.) operator for accessing
array elements. structure elements.
3. Accessing array elements takes less time. Accessing structure elements takes more
time.
4. Array can be declared as: Structure can be declared as:
int a[100]; struct book
{
int pages;
float price;
};

Call by Value Vs Call by Reference


S.N. Call by Value Call by Reference
1. In call by value method function is called In call by reference method function is
with actual value of the variable. called with addresses of variable.

MKS
2. Duplicate copy of original value is passed Original values are referenced from user
are passed to user defined function. defined function.
3. Changes made from user defined function Changes made from user defined function
does not affect original values. affects original values.
4. Using call by value method only one value Using call by reference method multiple
can be returned from function using return values can be returned from function
keyword. without using return keyword.
5. Example: Example:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void swap(int a, int b); void swap(int *p, int *q);
void main() void main()
{ {
int a=10, b=20; int a=10, b=20;
printf(“Before swap: a=%d and b=%d\n”,a,b); printf(“Before swap: a=%d and b=%d\n”,a,b);
swap(a,b); /* Call by Value */ swap(&a, &b); /* Call by Refernce */
printf(“After swap: a=%d and b=%d\n”,a,b); printf(“After swap: a=%d and b=%d\n”,a,b);
getch(); getch();
} }
void swap(int a, int b) void swap(int *p, int *q)
{ {
int temp; int temp;
temp = a; temp = *p;
a = b; *p = *q;
b = temp; *q = temp;
} }
Output: Output:
Before swap: a = 10 and b = 20 Before swap: a = 10 and b = 20

Manish Kumar Shah(MKS) 240


240 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/
Computer Programming
After swap: a = 10 and b = 20 After swap: a = 20 and b = 10

MKS

Manish Kumar Shah(MKS) 241


241 | Compiled by Ramesh Bhandari ([Link])
For More Examples: Visit [Link]/c-programming-examples/

You might also like