Computer Programming Basics Explained
Computer Programming Basics Explained
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.
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:
Control Unit
MKS
Input Unit Output Unit
Memory Unit
Main Memory
Secondary Storage
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
MKS Users
Application Software
System Software
Hardware
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
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.
e) Web Browsers
These are used for accessing world wide web (www). Example includes Google Chrome,
Firefox, Microsoft Edge etc.
MKS
3. System software can exist as a lone Application software needs system
entity. software for its existence.
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.
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.
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.
High Level
MKS
Language Program
(Source Code)
Compiler
or
Interpreter
A high level language can be further categorized into object oriented and procedural
programming language.
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.
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.
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.
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.
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.
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
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
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
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
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:
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
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
MKS
Figure: History of 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.
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.
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.
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”.
MKS
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
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.
MKS
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.
(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).
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.
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.
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)
- 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.
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;
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.
MKS
Invalid: 25 (does not start with 0), 0387 (8 is not an octal digit),
04.32 (Decimal point is not allowed)
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.
For example:
1. const int a = 10;
2. const float pi = 3.141592;
3. const char op = ‘+’;
2. Syntax for creating variables is: General syntax for creating constant is:
data_type variable_name = value; const data_type constant_name = fixed_value;
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
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:
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:
MKS
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 (-)
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);
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.
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
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)
False True
Condition?
False_Expression True_Expression
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
MKS
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.
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.
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.
}
MKS
The putch() function is used for printing character to a screen at current cursor location. It
is defined in header file conio.h.
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 ↲
MKS
puts(“Hello,”); Note: ↲ indicates enter is
puts(name); pressed.
puts(“Have a good day.”);
getch(); /* Holding output */
}
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.
}
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 */
}
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
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
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)
MKS
}
MKS
}
getch();
}
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:
Condition1?
False
False
True Condition2?
Statement1
True
Statement2 ConditionN?
False
True
StatementN
Default_Statement
MKS
To next statement
(If Any)
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();
}
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↲
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?
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:
}
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;
}
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)
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();
}
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.
}
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:
False True
Condition?
False_Expression True_Expression
To next statement
(If Any)
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);
}
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.
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:
control_variable_initialization
False
condition?
control_variable_update
Program
#include<stdio.h>
MKS
Example1: Program to print “Programming is fun.” 10 times.
Output
Program Output
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();
}
for(i=1;i<=n; i++)
{
sum = sum + i;
}
printf("Sum is %d\n", sum);
getch();
}
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();
}
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
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.
while (condition)
{
statement(s);
control_variable_update;
}
control_variable_initialization
False
condition?
MKS
statements
control_variable_update
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();
}
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
}
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);
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:
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();
}
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
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
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();
}
MKS
}
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();
}
MKS
{
break;
}
printf("i=%d\tj=%d\n",i,j);
}
}
getch();
}
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
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
MKS
if(ch=='y')
{
goto up;
}
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
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
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
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);
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();
}
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();
}
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();
}
void main()
{
int num, sum=0, rem, numcopy;
clrscr();
printf("Enter three digit number:\n");
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();
}
#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();
}
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();
}
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.
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.
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.
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:
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:
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 statement;
}
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);
}
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:
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:
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.
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;
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>
void main()
{
float num1=12.34, num2=34.67, result;
clrscr();
result = my_sum(num1, num2); /* Function Call */
printf("Sum is : %f.",result);
getch();
}
Program 2:
/*
Program: Displaying some message using user defined function
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/
#include<stdio.h>
#include<conio.h>
MKS
void main()
{
clrscr();
message(); /* Function Call */
getch();
}
Program 3:
/*
Program: Factorial of a number using user defined function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/
#include<stdio.h>
#include<conio.h>
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;
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).
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
#include<stdio.h>
#include<conio.h>
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();
}
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.
#include<stdio.h>
#include<conio.h>
MKS
int main()
{
int num;
clrscr();
printf("Enter any integer number: ");
scanf("%d", &num);
prime_check(num); /* Function Definition */
getch();
return(0);
}
Run2
Enter any integer number: -8↲
-8 IS NOT PRIME.
No Arguments
MKS
Calling Function Called Function
Returned Value
#include<stdio.h>
#include<conio.h>
int main()
{
int s;
clrscr();
s = sum_of_digit(); /* Function Call */
printf("Sum of digit is %d.", s);
getch();
return(0);
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
#include<stdio.h>
#include<conio.h>
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();
}
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>
void main()
{
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.
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
1x1
1
MKS
/*
Program: a^x using recursive function.
Author: Ramesh Bhandari
Date: Jan 22, 2018
*/
#include<stdio.h>
#include<conio.h>
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();
}
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 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);
}
Output
How many terms? 5↲
1 1 2 3 5
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();
}
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.
#include<stdio.h>
#include<conio.h>
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
#include<stdio.h>
#include<conio.h>
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.
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.
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
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.
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 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
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 };
Index → 0 1 2 3 4 5 6 7
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
#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();
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.
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]);
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;
}
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();
}
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
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];
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
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;
}
}
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
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();
}
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.
/* 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
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 */
/* 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];
}
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);
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.
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 */
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);
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 */
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);
}
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.
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");
MKS
{
a[i] = a[i-1];
}
a[pos-1] = num;
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");
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]);
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.
/* 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];
}
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;
}
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);
}
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();
}
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]);
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();
}
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;
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]);
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);
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++)
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");
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");
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]);
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];
}
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>
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();
}
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();
}
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>
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();
}
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");
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 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();
}
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.");
}
}
#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++)
{
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++)
MKS
}
getch();
}
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:
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.
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);
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”
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.
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();
}
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();
}
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);
}
MKS
printf("Coped string is: %s”, str2);
getch();
}
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';
}
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++;
MKS
printf("Given strings are different.");
}
}
getch();
}
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);
}
}
}
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);
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';
}
strlwr( string);
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')
{
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;
}
}
}
strupr( string);
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();
}
MKS
{
str[i] = str[i]+32;
}
}
}
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();
}
MKS
}
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');
}
MKS
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:
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:
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;
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:
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:
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:
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
MKS
printf("Enter real and imaginary part for second:\n");
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]);
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();
}
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();
Output:
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;
};
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.
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])
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];
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↲
MKS
{
printf("Name: %s\n", e[i].name);
printf("Salary: %d\n", e[i].salary);
printf("Age: %d\n\n", e[i].age);
}
getch();
}
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();
}
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();
}
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
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.
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;
}
}
}
}
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
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.
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.
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.
MKS
5. Content written in text files are Content written in binary files are
human readable. not human readable and look like
encrypted content.
fclose(file_pointer_name);
character_variable = fgetc(file_pointer_variable);
b. fputc()
fputc() function is used to write a character to a file.
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.
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.
putc(character_or_character_variable, file_pointer_variable);
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:
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:
b. fwrite()
fwrite() is used for record output functions and its syntax is:
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);
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
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.
int comma_separated_list_of_variables;
#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.
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>
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
MKS