INTRODUCTION
TO
PROGRAMMING
Using
Name: _____________________
Roll Number: ______________
Section: I – CSM –A _
By {, 𝓣. 𝓤𝓭𝓪𝔂 彡★★彡}
For exclusive use of I CSM –A
(2025 Admitted batch)
Follow me on /tMC Uday
SYLLABUS
UNIT I
Introduction to Programming and Problem Solving 2
History of Computers, Basic organization of a computer: ALU, input-output
units, memory, program counter, Introduction to Programming Languages,
Basics of a Computer Program- Algorithms, flowcharts (Using Dia Tool),
pseudo code. Introduction to Compilation and Execution, Primitive Data
Types, Variables, and Constants, Basic Input and Output, Operations, Type
Conversion, and Casting.
Problem solving techniques: Algorithmic approach, characteristics of
algorithm, Problem solving strategies: Top-down approach, Bottom-up
approach, Time and space complexities of algorithms
UNIT 2
Control Structures
Simple sequential programs Conditional Statements (if, if-else, switch), Loops
(for, while, do while) Break and Continue
UNIT 3
Arrays and Strings
Arrays indexing, memory model, programs with array of integers, two
dimensional arrays, Introduction to Strings.
UNIT 4
Pointers & User Defined Data types
Pointers, dereferencing and address operators, pointer and address
arithmetic, array manipulation using pointers, User-defined data types-
Structures and Unions.
UNIT 5
Functions & File Handling
Introduction to Functions, Function Declaration and Definition, Function call
Return Types and Arguments, modifying parameters inside functions using
pointers, arrays as parameters. Scope and Lifetime of Variables, Basics of File
Handling
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
UNIT 1
Introduction to Programming and Problem Solving
Topic Topic Title Page
No. No.
3
1.1 History of Computers 4
1.2 Basic Organization of a Computer 8
1.3 Introduction to Programming Languages 10
1.4 Basics of Computer Program 15
1.5 Compilation & Execution 22
1.6 Primitive Data Types 23
1.7 Variables & Constants 25
1.8 Basic Input & Output Operations 28
1.9 Type Conversion & Casting 32
1.10 Problem Solving Techniques 34
1.11 Problem Solving Strategies 35
1.12 Time & Space Complexities 37
Key Board symbols:
Symbol Name Symbol Name Symbol Name
! Exclamation mark + Plus , Comma
@ At symbol [ Left square bracket < Less than
# Hash / Number sign ] Right square bracket > Greater than
$ Dollar { Left curly brace . Period / Dot
% Percent } Right curly brace ? Question mark
^ Caret \ Backslash / Forward slash
& Ampersand ` ` ~ Tilde
* Asterisk ; Semicolon ` Backtick
( Left parenthesis : Colon , Comma
) Right parenthesis ' Single quote < Less than
- Hyphen / Minus " Double quote > Greater than
_ Underscore + Plus . Period / Dot
= Equal sign [ Left square bracket
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.1. History of Computer
What is a Computer?
A computer is an electronic machine that
collects information, stores it, processes it
according to user instructions, and then returns
the result. 4
A computer is a programmable electronic
device that performs arithmetic and logical
operations automatically using a set of
instructions provided by the user.
1.1.1. Early computing devices/
Evolution of a Computer:
People used sticks, stones, and bones as counting tools before computers
were invented. Let us look at a few of the early-age computing
devices used by mankind.
o In order to simplify the process of counting, people in Asia
Minor built a counting device called abacus. This device
allowed users to do calculations using a system of sliding
beads arranged on a rack.
o With the passage of time, many computing devices such as Napier
bones and slide rule were invented.
o In 1642, a French mathematician, Blaise Pascal
invented the first functional automatic calculator.
This brass rectangular box, also called a Pascaline,
used eight movable dios to adds sums eight figures
long.
o In 1694, german mathematician Gottfried wilhem von Leibniz extended
pascal’s design to perform multiplication, division and to find square
root. This machine is known as Stepped Reckoner.
o The real beginnings of computers as we
know them today, however, lay with an
English mathematics professor, Charles
Babbage.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
In 1822, he proposed a machine to perform differential equations,
called a Difference Engine.
o In 1946, John Eclcert and John Mauchy of developed ENIAC
(electronic numerical integrator and calculator)
o Thus computer used electronic vacuum tubes to make internal
parts of the computer
5
o Eckert and mauchy also proposed the development of EDVAC
(electronic discrete variable automatic computer.
o It was the first electronic computer to use the stored program
concept introduced by John von Neumann.
o In 1949, at the Cambridge university, Maurice wilkes developed EDSAC
(electronic delay storage automatic calculator)
o This machine used mercury delay lines for memory and vacuum
tubes for logic.
o The Eckert – mauchy corporation manufactured UNIVAC ( universal
automatic computer) in 1951 and its implementation marked the real
beginning of the computer era.
1.1.2. Computer Generations :
1st Generation: Vacuum Tube (1940 – 1956)
o First generation computer were vacuum tubes/thermionic
value based machines these computers used vacuum
tubes for circuitry and magnetic drums for memory.
o Input was based on punched cards and paper tape and
output was in the form of printouts.
o Example: ENIAC, EDVAC AND UNIVAC.
o Characteristics of 1st Generation of a computer:
These computers were based on vacuum tube
technology.
These were the fastest computing devices of their time.
These computers were very large, and required a lot of
space for installation.
These were non-portable and very slow equipments.
2nd Generation: Transistors (1959 – 1965)
o A transistor is made up of semiconductor material like
germanium and silicon. It usually had three leads and
performed electrical functions such as voltage,
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
current or power amplification with low power requirement.
o Computers became smaller, faster, cheaper, energy-efficient
and more reliable than their predecssors.
o Magnetic cores- were used as primary memory and magnetic
disks as secondary storage devices.
o Example: PDP – 8 , IBM 1401 and IBM 7090
o Characteristics of 2nd Generation of a computer: 6
These machines were based on transistor technology
. These were smaller as compared to the first generation
computers.
These were more portable and generated less amount of
heat.
3rd Generation: Integrated Circuits (1965 – 1971)
o The development of the integrated circuit was the trait of the third
generation computer.
o Also called an ic, an integrated circuit consists of a
single chip with many components such as
transistors and resistors fabricated on it.
o Integrated circuit replaced several individually
wired transistors. This development made
Computers smaller in size, reliable and efficient.
o Instead of punched cards and printouts, users interacted with third
generation computers through keyboards and monitors and interfaced
with operating system.
o example : NCR 395 and B6500
o Characteristics of 3rd generation computer:
These computers were based on integrated circuit (ic)
technology.
They were able to reduce computational time from micro
seconds to nano seconds.
Extensive use of high – level language became possible
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
4th Generation: Microprocessors (1971 – 1980)
o The technology of this generation was still based on the integrated
circuit, these have been made readily available to use because of the
development of the microprocessor.
o The fourth generation computers led to an era of
large scale integration (LSI) and very large 7
scale integration (vlsi) technology. LSI
technology allowed thousands of transistors to
be constructed on one small slice of silicon
material whereas vlsi squeezed hundreds of
thousands of components
o ULTRA – large scale integration (ULSI) increased that number into
millions the fourth generation computer became more powerful
compact, reliable and affordable.
o example: apple ii, attair 8800 and CRAY-1
o Characteristics of 4 th generation computer:
Fourth generation computers are microprocessor based systems
These computers are very small
Interconnection of computers leads to better communication
and resource sharing.
5th Generation: AI and ULSI (1980 – till date)
o These computers have been utilized since 1980 and
continue to be used now. This is the present and the
future of the computer world
o The defining aspect of this generation is artificial
intelligence. The use of parallel processing and
superconductors are making this a reality and provide a lot of scope
for the future
o Fifth-generation computers use ULSI (Ultra Large Scale
Integration) technology. These are the most recent and
sophisticated computers. C, C++, Java,.Net, and more
programming languages are used
o Example: IBM, Pentium, Desktop, Laptop, Notebook,
Ultra book, and so on.
o Characteristics of 5 th Generation :
They used ULSI and AI Technology
It uses advanced computing technologies
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.2. Basic organization of a computer: ALU, input-output units,
memory, program counter
According to Von Neumann, The basic organization of computer diagram
has the following units Control Unit, Arithmetic and Logic Unit (ALU), Memory
Unit, Registers and Inputs/Outputs.
Von Neumann architecture is based 8
on the stored-program computer
concept, where instruction data and
program data are stored in the same
memory. This design is
still used in most computers
produced today.
Central Processing Unit (CPU)
The Central Processing Unit (CPU) is the electronic circuit responsible for
executing the instructions of a computer program.
It is sometimes referred to as the microprocessor or processor.
The CPU contains the ALU, CU and a variety of registers.
Registers
Registers are high speed storage areas in the CPU. All data must be stored in
a register before it can be processed.
Memory Address Holds the memory location of data that needs to
MAR
Register be accessed
Holds data that is being transferred to or
MDR Memory Data Register
from memory
Where intermediate arithmetic and logic results are
AC Accumulator
stored
Contains the address of the next instruction to be
PC Program Counter
executed
Current Instruction
CIR Contains the current instruction during processing
Register
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Arithmetic and Logic Unit (ALU)
The ALU allows arithmetic (add, subtract etc) and logic (AND, OR, NOT etc)
operations to be carried out.
Control Unit (CU)
9
The control unit controls the operation of the computer’s ALU, memory and
input/output devices, telling them how to respond to the program instructions
it has just read and interpreted from the memory unit.
The control unit also provides the timing and control signals required by other
computer components.
Buses
Buses are the means by which data is transmitted from one part of a
computer to another, connecting all major internal components to the CPU
and memory.
A standard CPU system bus is comprised of a control bus, data
bus and address bus.
Carries the addresses of data between the processor and
Address Bus
memory
Carries data between the processor, the memory unit and the
Data Bus
input/output devices
Carries control signals/commands from the CPU (and status signals
Control Bus from other devices) in order to control and coordinate all the
activities within the computer
Memory Unit
The memory unit consists of RAM, sometimes referred to as primary or main
memory. Unlike a hard drive (secondary memory), this memory is fast and
also directly accessible by the CPU.
RAM is split into partitions. Each partition consists of an address and its
contents (both in binary form).
The address will uniquely identify every location in the memory.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Loading data from permanent memory (hard drive), into the faster and
directly accessible temporary memory (RAM), allows the CPU to operate
much quicker.
Input/output Devices
Program or data is read into main memory from the input device or
10
secondary storage under the control of CPU input instruction. Output
devices are used to output information from a computer. If some results
are evaluated by the computer and it is stored in the computer, then with
the help of output devices, we can present them to the user.
1.3. Introduction to Programming Languages
Program:
The set of instructions are called a program. For Example, Programmers
create programs by writing code that instructs the computer what to do and
execute it on special software designed for it such as turbo C for executing
‘C’ Programs.
Programming:
We can say that the process of writing a program is called Programming.
A programming language is a set of rules that provides a way of telling a
computer what operations to perform
“A programming language is a notational system for describing computation
in a machine – readable and human – readable form “
English is a natural language. It has words, symbols and grammatical rules
Similarly a programming language also has words, symbols and rules of
grammar. The grammatical rules are called SYNTAX.
First programming language is developed in 1950s. Since then thousands of
languages have been developed because different programming
languages are designed for different types of programs.
Why many programming languages?
Different programming languages are designed for different types of
applications
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Levels of programming languages:
High level:
High-level language is a computer language which can be understood by
the users. The high-level language is very similar to human languages and has
a set of grammar rules that are used to make instructions more easily.
11
Middle level:
instructions are created using symbols such as letters, digits and special
characters Assembly language is an example of middle-level language. In
assembly language, we use predefined words called mnemonics.
Low level:
Low-Level language is the only language which can be understood by the
computer. Low-level language is also known as Machine Language. The
machine language contains only two symbols 1 & 0.
Examples:
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
The principle paradigms:
Programming paradigms are different ways or styles in which a given
program or programming language can be organized.
Imperative programming ( Ex: C, Forton , Basic )
Procedure oriented programming ( Ex: C, Pacal ) 12
Object oriented programming (Ex: Java, Python)
Logical programming( Ex: Prolog )
Traditional Programming languages:
FORTRAN:
FORmula TRANslation
Developed by IBM in mid 1950s
Designed for scientific and mathematical applications
COBOL:
COmmon Business Oriented Language
Developed in 1959
Used to develop business applications
BASIC:
Beginners All Purpose Symbolic Instruction Code
Developed at Dartmouth college in mid 1960s
Written by students to interact with terminals
C Programming language:
C is a general purpose, simple and procedural programming language. It
was initially developed by Dennis Ritchie in the year 1972 at AT & T Bell labs.
It was mainly developed as a system programming language to write an
operating system. UNIX is written in C
C was first designed by Dennis Ritchie for use with
UNIX on DEC PDP-11 computers. The language
evolved from Martin Richard's BCPL, and one of its
earlier forms was the B language; first book on C
was “The C Programming Language “by Brian
Kernighan and Dennis Ritchie, published in 1978.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
In 1983, the American National Standards Institute (ANSI) established a
committee to standardize the definition of C. The resulting standard is
known as ANSI C, and it is the recognized standard for the language,
grammar, and a core set of libraries
There is also an ISO (International Standards Organization) standard that is
very similar to the ANSI standard. 13
It appears that there will be yet another ANSI C standard officially dated
1999 or in the early 2000 years; it is currently known as "C9X."
Features of C:
C is the widely used language. It provides many features that are given
below.
1. Simple
2. Machine
Independent or Simple Portable
Structured
Portable
3. structured
programming Memory
language
Rich Library Fast speed
manaement
4. Rich Library
5. Memory Management
Pointers Recursion Extensible
6. Fast Speed
7. Pointers
8. Recursion
9. Extensible
1. Simple:
C is a simple language in the sense that it provides a structured
approach (to break the problem into parts), the rich set of library
functions, data types, etc.
2. Machine Independent or Portable
Unlike assembly language, c programs can be executed on different
machines with some machine specific changes
3. structured programming language
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
C is a structured programming language in the sense that we can
break the program into parts using functions. So, it is easy to
understand and modify. Functions also provide code reusability.
4. Rich Library
C provides a lot of inbuilt functions that make the development fast. 14
5. Memory Management
It supports the feature of dynamic memory allocation. In C language,
we can free the allocated memory at any time by calling
the free() function.
6. Fast Speed
The compilation and execution time of C language is fast
7. Pointers
C provides the feature of pointers. We can directly interact with the
memory by using the pointers
8. Recursion
In C, we can call the function within the function. It provides code
reusability for every function
9. Extensible
C language is extensible because it can easily adopt new features.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.4. Basics of Computer Program- Algorithms, Flowcharts (Using
Dia Tool), pseudo code.
A typical programming task can be divided into 2 phases
Problem solving phase:
Produce an ordered sequence of steps that describe solution of problem. 15
This sequence of steps is called algorithm.
Implementation phase:
Implement the program in some programming language
1.4.1. Steps in Problem solving phase (Algorithm and pseudo code)
o First produce a general algorithm (one can use pseudo code)
o Refine the algorithm successively to get step by step detailed algorithm
that is very close to a computer language.
o Pseudo code is an artificial and informal language that helps
programmers develop algorithms.
o Pseudo code is very similar to everyday English.
Example 1:
Write an algorithm to determine a student to indicate whether he is passing
or failing using average of four marks. i.e., if he is failed to get average less
than 50 then he is failed
Pseudo code:
Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”
Algorithm:
step 1 : Start
step 2 : Take 4 integer inputs for the different 4 subject like math, english,
physics, chemistry.
step 3 :Then calculate
average = ( math + english + physics + chemistry ) / 4
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
step 4 : if the value of average is below 50 , it will print fail otherwise it shows
pass
step 5 : END
Algorithm Pseudo code
It is a step-by-step It is an easy way of writing
16
description of the solution. algorithms for users to understand.
It is always a real algorithm These are fake codes.
and not fake codes.
They are a sequence of They are representations of
solutions to a problem. algorithms.
It is a systematically written These are simpler ways of writing
code. codes
1.4.2. Flow chart:
Now we can also transform the algorithm to a flowchart.
A flowchart is a graphical representation of the algorithm (again, a sequence
of instructions that reach an end). Different symbols are used to draw each
type of flowchart.
Symbols used in flow chart:
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
17
Example 2:
Find algorithm and flow chart of Sum of Two Numbers Entered
Algorithm:
Step 1: Start
Step 2: Read the Integers n1,n2
Step 4: Perform the addition by using the formula: sum=n1+n2.
Step 5: Print the Integer sum
Step 6: Stop
Flow chart:
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.4.3 Dia tool to draw Flow chart in computer:
Step 1. Select Flow Chart in the diagram tools window
Select the flow chart in diagram tools window as shown below.
18
Fig. Select Flow Chart Menu Item from Dia
This will show the flow charting tools in the window.
1. Process
2. Input / Output
3. Decision
4. Connector
5. Display
6. Start / stop
7. and so on..
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Step 2. Select and draw using tools
Select the flow chart tool and start drawing. In the following example, I
started with the ‘Start’ flow-chart component.
19
Fig: “Start” Flow Chart Component in the Dia Program
In the following example, I quickly drew 5 flow chart components — Start, Get
Input, Process, Display Output, and Stop. At this stage, these flow chart
components are not aligned properly.
Fig: All Flow Chart Components in Dia Unaligned
Step 3. Align and Spread out the components
At this stage the flowchart may not look neat, as
the components are neither aligned nor spread-
out properly.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Before aligning and spreading-out the components, select all the flow-chart
components on the screen using the mouse as shown below.
Fig: Select all Dia Flow Chart Components Using Mouse
Align all the components to center
Click on Object Menu -> Align -> Center to center all the selected 20
components.
Spread Out all the components to center
When you draw the flow chart, each component will have a different
distance from the other component. To make all the spaces equivalent use
the spread out option.
Click on Object Menu -> Align -> Spread Out Vertically.
Fig: Dia Flow Chart after Spread Out Vertically
Step 4. Connect Flow Chart Components Using Arrows
Select the arrow from general tools window, and then connect the
components one by one. You can also change the arrow type, and the
thickness in the tools window.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
21
Fig: Dia Flow Chart with the Arrows
Step 5. Export the Flow Chart as an Image
Finally you can export the flow chart to an image file using the export option.
Click on File Menu -> Export -> Select the file type as png, or as what ever you
wanted -> Click export after specifying the file name.
Fig: Final Flow Chart Image Export from Dia
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.5. Introduction to Compilation and Execution
Generally coding is done in high level language or middle level language
(assembly language). For the computer to understand these languages, they
must be translated into machine level language.
The translation process is carried out by a compiler/interpreter (for high level
language) or an assembler (for assembly language program). 22
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
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.
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 file is passed through a
compiler which first translates high level
language into object code (A machine code
not ready to be executed).
A linker then links the object code with pre-
compiled library functions, thus creating an
executable program.
This executable program is then loaded into
the memory for execution. General
compilation process is shown in Figure:
Steps to Execute C program in Turbo C
compiler:
Enter the program in C editor
Save the program (File Save) or F2. Also use
the extension “.c “ to save the program
o Ex: Sample.c
Compile the program (compilecompile) or
Alt+F9
Run the program (RunRun) or Ctrl+F9 to see output
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.6. Primitive Data Types in C:
In C, each variable has a specific data type, where a data type tells us
the size, range and the type of a value that can be stored in a variable.
In C, there are about seven primitive data types. These data types are : short,
int, long, char, float, double primitive data types are categorized into these
parts 23
integer data types, such as short, int, long.
floating-point data types, such as float, double, long double
character data type, such as char.
Primitive data type’s size, range and format Specifier are given table below:
Format
Data Type Size (bytes) Range
Specifier
short int %hd
1 byte -128 to 127
unsigned short
%hu
int 1 bytes 0 to 255
int %d
2 bytes -32768 to 32767
unsigned int %u
2 bytes 0 to 65535
long int -2147483648 to %ld
4 bytes
2147483647
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
unsigned long
%lu
int 4 bytes 0 to 4294967295
signed char %c
1 byte -128 to 127
unsigned char %c
1 byte 0 to 255
24
float %f
4 bytes -3.4e38 to +3.4e38
double %lf
8 bytes -1.7e308 to 1.7e308
long double %Lf
10 bytes -1.7e4932 to +1.7e4932
Note : The sizes given are compiler dependent , sizes given in the figure are
for 16- bit Compiler
"Primitive data types" may refer to the standard data types built into a
programming language (built-in types – already defined data types by
programming language developer).
Example code Output
#include<stdio.h> int value is 10
#include<conio.h> float value is 88.88
int main() char value is a
{
int a=10;
float b=88.88;
char c=’a’;
clrscr();
printf(“int value is %d\n”,a);
printf(“float value is %f\n”,b);
printf(“char value is %c”,c);
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Data types which are not primitive are referred to as derived or non primitive
data types.
Non primitive data types in C:
These are the data types derived from primitive data types only.
Examples include Arrays, strings, Function, Pointers etc.,
25
User defined Data types in C:
Here one data type can store data of different data types under the same
variable name.
Examples include structure, union etc.,
1.7. Variables and Constants
1.7.1. Variables:
Variables are used to allocate memory and variables may take different
values during program execution
Syntax:
Datatype variable;
Example:
int a;
double b;
char c;
We can also provide values to variables directly using = operator
Called initialization
int a=100;
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
float b=88.88;
char c=’a’;
Rules for defining a variable:
o variable cannot be a keyword
Ex: int a; ✔ int float; ✘ 26
o It can have sequence of letters and digits and must begin with a
alphabet only or _ symbol are allowed
Ex: int a1; ✔int 2n; ✘
o White spaces are not allowed.
Ex: int sum; ✔ int s um; ✘
o variables are case sensitive
i.e., upper case and lower case alphabets treated as
different.
Note : Same rules applied for naming user defined functions also
Types of variables in C:
local: variables have scope with in a function
global: variables have scope more than one function
auto: default variable
static: to retain values between different function calls
external: have scope within entire program,
register: variables stored in register memory for faster access
(Note: in detailed explanation about types of variables will be discussed in
functions concept)
1.7.2. Constants:
As the name suggests, a constant in C is a variable that cannot be modified
once it is declared in the program.
We cannot make any change in the value of the constant variables after
they are defined.
Defining a constant in C:
There are 2 ways to define a constant
1. using const keyword
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
2. using #define preprocessor
1) Using const keyword:
The const keyword is used to define constant in C programming.
Ex : const float PI=3.14;
Now, the value of PI variable can't be changed. 27
Example code Output
#include<stdio.h> PI=3.14
#include<conio.h>
int main()
{
const float PI=3.14;
clrscr();
printf(“PI=%f”,PI);
getch();
return 0;
}
2) Using #define pre processor:
The #define preprocessor is also used to define constant. This is also called
macro substitution
Example code Output
#include<stdio.h> PI=3.14
#include<conio.h>
#define PI 3.14
int main()
{
clrscr();
printf(“PI=%f”,PI);
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.8. Basic Input and Output, Operations:
C provides a collection of library functions such
as getchar, putchar, scanf, printf, gets and puts. These functions enable the
transfer of data between the C program and standard input/output devices.
The standard input-output devices or the associated files or text streams, are
referred as – 28
stdin - standard input file, normally connected to the keyboard
stdout - standard output file, normally connected to the
screen/console
stderr - standard error display device file, normally connected to the
screen/console
In order to be able to use the above mentioned input-output functions in
your C program, you must begin each C program with a pre-processor
directive to include these standard library functions.
This can be done with a line entry - #include <stdio.h>
This input and output functions categorized into 2 types:
Formatted – printf() , scanf()
Un formatted – getchar(), putchar() , gets(), puts()
1.8.1. Formatted output statement: printf()
printf() acts as a formatted output statement in C programming language
it is used to output data on standard output device
This can be done in 2 ways,
On 1st way used to show message,
Syntax 1:
printf(“message”);
whatever you write in between that double quotes (“”) will be printed on
console
Example code Output
#include<stdio.h> Hello world
#include<conio.h>
int main()
{
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
clrscr();
printf(“Hello world”);
getch();
return 0;
}
29
On 2nd way used to access a value in a variable,
Syntax 2:
Printf(“<optional message> <format specifier>”, variable);
Here it will print value in variable in place of format specifier in console
We can print values of multiple variables also
Example Output
#include<stdio.h> value in a is 100
#include<conio.h>
int main()
{
int a=100;
clrscr();
printf(“value in a is %d”,a);
getch();
return 0;
}
-
1.8.2. Formatted input statement: scanf()
scanf() acts as formatted input statement in C programming language.
It is used to read value from console and store it in the specified location i.e.,
variable
Syntax:
scanf(“formatspecifier”,&variable);
format specifier can be %d for int, %f for float etc., already discussed in data
types concept
&variable tells address of variable.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Example Output
#include<stdio.h> Enter a value:100
value in a is 100
#include<conio.h>
int main()
{
30
int a;
clrscr();
printf(“Enter a value:”);
scanf(“%d”,&a);
printf(“value in a is %d”,a);
getch();
return 0;
}
1.8.3. Unformatted input and output statements:
getchar() : used to read a single character only but not to read int ,float etc.,
Syntax: char_variable = getchar();
putchar(): used to access a single character not to for int ,float etc.,
Syntax: putchar(ch);
gets(); used to read a string
Syntax: gets(string name);
puts(): used to access a string
Syntax: puts(string);
Example on getchar() and putchar()
Example Output
#include<stdio.h> Enter a character : a
Given character: a
#include<conio.h>
int main()
{
char ch;
clrscr();
printf(“Enter a character:”);
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
ch=getchar();
printf(“Given character:”);
putchar(ch);
getch();
return 0;
31
}
1.8.4. Escape Sequences:
Character combinations consisting of a backslash (\) followed by a letter or
by a combination of digits are called "escape sequences." are listed below
Escape Sequence Meaning
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
Example Output
#include<stdio.h> Helloworld
Hellworld
#include<conio.h>
world
int main() Hello
world
{
Hello’world’
clrscr(); Hello”world”
printf(“Hello\a world”);
printf(“Hello\bworld”);
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
printf(“Hello\rworld”);
printf(“Hello\nworld”);
printf(“Hello\’world\’”);
printf(“Hello\”world\””);
getch();
32
return 0;
}
1.9. Type Conversion, and Casting.
In programming languages sometimes expressions contains different data
types then they must be converted to the single data type of destination
data type.
For example, the multiplication of an integer data value with the float data
value and storing the result into a float variable. In this case, the integer value
must be converted to float value
In a C programming language, the data conversion is performed in two
different methods as follows...
a. Type Conversion
b. Type Casting
1.9.1. Type Conversion:
It is also called widening conversion. Here destination type is larger than
source type.
For example
int a=20;
float b=a; // then b= 20.000
Here int variable a takes 2 bytes where float variable b takes 4 bytes so
destination type is larger than source type.
1.9.2. Type casting:
It is also called a narrowing conversion.
Here the destination data type must be
smaller than the source data type.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Syntax:
Destination_datatype = (target_datatype) variable;
For Example,
float c=9.6; 33
int d= (int ) c; // b=9
here float variable c takes 4 bytes where as int variable d takes 2 bytes
so destination type is smaller than source type
Example code Output
#include<stdio.h> 20.000
9
#include<conio.h>
int main()
{
int a,d;
float b,c;
clrscr();
a=20;
b=a;
c=9.6;
d=(int)c;
printf(“%f\n”,b);
printf(“%d”,d);
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.10. Problem solving techniques: Algorithmic approach,
Characteristics of algorithm
As we discussed earlier in topic 1.4, writing algorithm is initial step in problem
solving Let us see definition of algorithm 1st
Algorithm:
34
Algorithm is step by step process of a given problem to solve it which defines
a set of instructions to be executed in a certain order to get the desired
output. An algorithm can be implemented in more than one programming
language.
Characteristics of an Algorithm
. An algorithm should have the following characteristics −
Unambiguous − Algorithm should be clear and unambiguous. Each of
its steps (or phases), and their inputs/outputs should be clear and must
lead to only one meaning.
Input − An algorithm should have 0 or more well-defined inputs.
Output − An algorithm should have 1 or more well-defined outputs, and
should match the desired output.
Finiteness − Algorithms must terminate after a finite number of steps.
Feasibility − Should be feasible with the available resources.
Independent − An algorithm should have step-by-step directions, which
should be independent of any programming code.
From the data structure point of view, following are some important
categories of algorithms −
Search − Algorithm to search an item in a data structure.
Sort − Algorithm to sort items in a certain order.
Insert − Algorithm to insert item in a data structure.
Update − Algorithm to update an existing item in a data structure.
Delete − Algorithm to delete an existing item from a data structure.
Example Algorithm for Addition of 2 numbers:
Step 1: Start
Step 2: Read the Integers n1,n2
Step 4: Perform the addition by using the formula: sum=n1+n2.
Step 5: Print the Integer sum
Step 6: Stop
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.11. Problem solving strategies: Top-down approach, Bottom-up
approach:
In the top-down approach, a bigger module/problem is divided into smaller
modules.
In the bottom-up approach, the smaller problems are solved and then they
are integrated to find the solution of a bigger problem. 35
1.11.1. Top-down approach:
Top-Down Approach is an approach to design algorithms in which a bigger
problem is broken down into smaller parts.
Thus, it uses the decomposition approach. This approach is generally used by
structured programming languages such as C, COBOL, FORTRAN
The drawback of using the top-down approach is that it may have
redundancy since every part of the code is developed separately.
Also, there is less interaction and communication between the modules in
this approach.
The implementation of algorithm using top-down approach depends on the
programming language and platform.
1.11.2. Bottom-up approach:
Bottom-Up Approach is one in which the smaller problems are solved, and
then these solved problems are integrated to find the solution to a bigger
problem. Therefore, it uses composition approach.
It is generally used with object oriented programming paradigm such
as C++, Java, and Python.
It requires a significant amount of communication among different modules.
Data encapsulation and data hiding is also implemented in this approach.
The bottom-up approach is generally used in testing modules.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.11.3. Difference between Top – down and Bottom – up approaches:
The following table highlights all the major differences between top-down
approach and bottom-up approach 36
S.No. Top-Down Approach Bottom-Up Approach
1. In this approach, the problem is In this approach, the smaller
broken down into smaller parts. problems are solved.
2. It is generally used by structured It is generally used with object
programming languages such as oriented programming paradigm
C, COBOL, FORTRAN, etc. such as C++, Java, Python, etc.
3. It is generally used with It is generally used in testing
documentation of module and modules.
debugging code.
4. It does not require It requires relatively more
communication between communication between
modules. modules.
5. It contains redundant information. It does not contain redundant
information.
6. Decomposition approach is used Composition approach is used
here. here.
7. The implementation depends on Data encapsulation and data
the programming language and hiding is implemented in this
platform. approach.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1.12. Time and space complexities of algorithms
The Complexity of an Algorithm
The algorithm's performance can be measured in two ways:
37
Time Complexity
The amount of time required to complete an algorithm's execution is
called time complexity.
The big O notation is used to represent an algorithm's time complexity.
The time complexity is calculated primarily by counting the number of
steps required to complete the execution. Let us look at an example of
time complexity.
mul = 1;
// Suppose you have to calculate the multiplication of n
numbers.
for i=1 to n
mul = mul *1;
// when the loop ends, then mul holds the multiplication
of the n numbers
return mul;
The time complexity of the loop statement in the preceding code is at least
n, and as the value of n escalates, so does the time complexity. While the
code's complexity, i.e., returns mul, will be constant because its value is not
dependent on the importance of n and will provide the result in a single step.
The worst-time complexity is generally considered because it is the maximum
time required for any given input size.
Space Complexity
he amount of space an algorithm requires to solve a problem and
produce an output is called its space complexity.
Space complexity, like time complexity, is expressed in big O notation.
The space is required for an algorithm for the following reasons:
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
1. To store program instructions.
2. To store track of constant values.
3. To store track of variable values.
4. To store track of function calls, jumping statements, and so on.
38
Space Complexity = Auxiliary Space + Input Size
Additional important Questions
1. Write an Algorithm and flow chart for calculate simple interest?
2. Write algorithm and flow chart for Determining the Largest
Number Among All the Entered Integers
3. Write algorithm and flow chart for Work Out All the Roots of a
Quadratic Equation ax² +bx +c=0
4. Write a C program to illustrate sizeof in data types?
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
UNIT 3
3. Arrays and Strings
3.1. Arrays indexing,
77
3.2. Memory model,
3.3. Programs with array of integers,
3.4. Two dimensional arrays,
3.5. Introduction to Strings.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
3. Arrays
Introduction to arrays: So far we have used only single variable name for
storing one data item. If we need to store multiple copies of the same data
then it is very difficult for the user.
To overcome the difficulty a new data structure is used called arrays.
78
Definition:
An array is a linear and homogeneous data structure
An array permits homogeneous data. It means that similar types of
elements are stored contiguously in the memory under one variable
name.
An array can be declared of any standard or custom data type.
It is static structure
Example of an Array:
Suppose we have to store the roll numbers of the 100 students the we
have to declare 100 variables named as roll1, roll2, roll3, …….roll100
which is very difficult job.
Concept of C programming arrays is introduced in C which gives the
capability to store the100 roll numbers in the contiguous memory which
has 100 blocks and which can be accessed by single variable name.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same
data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable
(index).
Pictorial representation of C Programming Arrays: (One Dimensional)
The above array is declared as int a[5];
a[0]=4; a[1]=5; a[2] =33; a[3] =13; a[4]=1;
In the above figure 4,5,33,13,1 are actual data items.
0, 1,2,3,4 are index variables.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Types of Arrays:
One Dimensional Array
Two Dimensional Arrays
Multidimensional Arrays
79
Types of Array
• One dimesional
• Two Dimesional
• Multi Dimesional
One dimensional Array:
A list of items can be given one variable name using only one subscript is
called single subscripted variable or one dimensional array.
Syntax: (to declare an array)
Data_type array_variable [SIZE];
Ex: int arr[5]; this array contains 5 elements namely
arr[0],arr[1],arr[2],arr[3],arr[4].
Program Output
// program to accept 5 numbers and display Enter 5 numbers:
//same 2
#include<stdio.h> 4
#include<conio.h> 8
int main() 12
{ 16
int arr[5],i; Given 5 numbers:
printf(“Enter 5 numbers:\n”); arr[0]=2
for(i=0;i<5;i++) // Assigning values arr[1]=4
{ arr[2]=8
scanf(“%d”, &arr[i]); arr[3]=12
} arr[4]=15
printf(“Given 5 numbers:\n”);
for(i=0;i<5;i++) // Accessing values
{
printf(“arr[%d]=%d\n”,i, arr[i]);
}
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Syntax: (to initialize an array)
data_type array_variable [SIZE] = { list of values };
Ex: int a[10] = { 1,2,3,4,5,6,7,78,9,10};
Program Output
// program to initilize 10 numbers and display same Given 10 numbers:
80
#include<stdio.h> 1
#include<conio.h> 2
int main() 3
{ 4
int arr[10] = { 1,2,3,4,5,6,7,8,9,10},i; // initilizing values 5
printf(“Given 10 numbers:\n”); 6
for(i=0;i<10;i++) // Accessing values 7
{ 8
printf(“%d\n”, arr[i]); 9
} 10
getch();
return 0;
}
Two Dimensional Arrays:
A list of items can be given one variable name using 2 subscripts namely rows
and columns called two sub scripted variable or two dimensional arrays.
Syntax : (2D array declaration)
Data_type array_variable[rows][columns];
Ex: int a[3][3];
This array contains 3*3 (rows*columns) = 9 elements, namely
a[0][0],a[0][1],a[0][2],a[1][0],a[1][1],a[1][2],a[2][0],a[2][1],a[2][2]
Syntax: (2D array initialization)
Data_type array_variable[rows][columns] = { list of values};
Ex: int a[3][3]= {{1,2,3},{4,5,6},{7,8,9}};
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program
// C Program to read 2D array and display same Enter values of 3*4 Matrix:
#include<stdio.h> 1
#include<conio.h> 2
int main() 3
{ 4
int a[3][4], i , j; 1 81
clrscr(); 2
printf(“Enter values of 3*4 Matrix:\n”); 3
for(i=0;i<3;i++) 4
{ 1
for(j=0;j<4;j++) 2
{ 3
scanf(“%d”,&a[i][j]); 4
}
} Given Matrix
printf(“Given Matrix\n”); 1234
for(i=0;i<3;i++) 1234
{ 1234
for(j=0;j<4;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
getch();
return 0;
}
Program
// C Program to initilize 2D array and display
same
#include<stdio.h> Given Matrix
#include<conio.h> 1234
int main() 1234
{ 1234
int a[3][4]={{1,2,3,4},{1,2,3,4},{1,2,3,4}}, i , j;
clrscr();
printf(“Given Matrix\n”);
for(i=0;i<3;i++)
{
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
for(j=0;j<4;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
getch(); 82
return 0;
}
Multi Dimensional Arrays:
A list of items can be given one variable name but more than 2 subscripts is
called multi dimensional array. We call it as N – Dimensional array
Syntax: data_type array_variable[size1][size2]....[sizeN];
Example: int arr[3][3][4]; // contains 3*3*4 = 36 elements
3.1. Array Indexing:
When we declare a variable storage is allocated to it,
For example, int a=100;
Storage is allocated to variable a and 100 is assigned to that location, along
with that each variable having its address location as well, which is system
dependent (i.e., probably different values from one computer to another)
As we know that Array is continuous memory location. So that the address of
each array variable’s address is continuous also
For Example, int x[6] = {10,20,30,50,40,80}; each int takes 2 bytes then
suppose address of x[0] is 3020 then next x[1] is 3022 and so on..
Similarly, index value for 10 is 0, 20 is 1 and so on .. two dimensional array’s
indexing also shown figure here
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
// Assigning and accessing array using its //index arr[0]=10
number arr[4]=40
#include<stdio.h> arr2[0][1]=20;
#include<conio.h>
int main()
{ 83
int arr[6];
int arr2[2][2];
clrscr();
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 50;
arr[4] = 40;
arr[5] = 80;
arr2[0][0]=10;
arr2[0][1]=20;
arr2[1][0]=30;
arr2[1][1]=40;
// Accessing 0,4 index array variables
printf(“arr[0]=%d\n”,arr[0]);
printf(“arr[4]=%d\n”,arr[4]);
// accessing 0th row 1st column of 2d array
printf(“arr[0][1]=%d\n”,arr[0][1]);
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
3.1.2. Why Array index starts from ‘0’:
Programming languages are designed in such a way that the array name is
always points to the first element of an array.
If we declare x[6] = {10, 20, 30, 50,40,80}, then x will point the first element of
the array. i.e. x holds the address of x[0].
So, in order to access the first element, we should use index 0.
84
x[0] which is equal to *(x) ==> *(3020) ==> value stored at 3020 is 10.
Array indexing will be calculated using the base address (first element's
address).
x+i = base address + i * sizeof(data type).
In our case, data type is int. base address is 3020
So, x+1 = 3020 + 1 * 2 => 3022
x+2 = 3020 + 2 * 2=> 3024 and so on.
If we use array index from 1, we will miss the first element always.
Because, x+1 will point the second element in the array. x[1] is as same as
*(x+1). *(3022) = 20.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
3.2. Memory models:
When you run a C program, your computer divides its memory into different
parts.
Each part stores a different kind of information — like your code, variables,
and function calls.
85
This organization of memory is called Memory Layout.
1. Text Segment (Code Segment)
This part stores the actual code that you write in your program.
For example, your functions like main() or printf() are kept here.
It is a read-only area, meaning the program can’t change it while running.
This helps keep the program safe and prevents errors.
2. Initialized Data Segment
This part stores global and static variables that already have a value when
the program starts.
For example, int a = 5; will be stored here.
The value is already set before the program runs.
This part of memory is created when the program starts and stays there until
the program ends.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
3. Uninitialized Data Segment (BSS Segment)
This part stores global and static variables that are declared but not given
any value.
For example, int count; is stored here.
The computer automatically sets their value to zero.
This part also stays in memory until the program ends.
86
4. Heap
The heap is used for dynamic memory allocation — memory that is created
while the program is running.
We use functions like malloc() or calloc() to ask for memory and free() to give
it back.
The heap grows upward as more memory is used.
If we don’t free the memory, it causes a memory leak, which wastes memory.
5. Stack
The stack stores local variables, function calls, and parameters.
Every time a function is called, a small block (called a stack frame) is added
to the stack.
When the function ends, that block is removed.
The stack grows downward, and it is managed automatically by the system.
If a program calls too many functions again and again (recursion), it can
cause a stack overflow.
Program Output
#include <stdio.h> Enter number of
#include <conio.h> elements: 3
#include <stdlib.h> // for malloc() and free() Enter 3 integers:
int main() 1
{ 2
int *ptr;
3
int n, i;
clrscr(); You entered:
printf("Enter number of elements: "); 123
scanf("%d", &n);
// allocate memory for n integers
ptr = (int *) malloc(n * sizeof(int));
if (ptr == NULL)
{
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
printf("Memory not allocated!\n");
return 0;
}
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++)
{ 87
scanf("%d", &ptr[i]);
}
printf("You entered:\n");
for (i = 0; i < n; i++)
{
printf("%d ", ptr[i]);
}
// free allocated memory
free(ptr);
getch();
return 0;
}
3.3. Programs with array of integers:
Program Output
// printing sum of elements of array Enter size of array: 5
#include<stdio.h> Enter 5 elements:
#include<conio.h> 2
#define MAX 100 7
int main() 8
{ 9
int arr[MAX], i, n, sum = 0; 5
clrscr(); sum = 31
printf(“Enter size of array:”);
scanf(“%d”,&n);
printf(“Enter %d elements:\n”,n);
for(i=0;i<n+i++)
{
scanf(“%d”,&arr[i]);
sum = sum +arr[i];
}
printf (“ \nsum =%d”,sum);
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
// printing biggest & smallest element in an biggest = 89
//array smallest = 1
#include<stdio.h>
#include<conio.h>
88
int main()
{
int arr[10] = { 12,45,1,56,78,67,43,65,89,5};
int i , big, small ;
clrscr();
big = arr[0];
small = arr[0];
for(i=1;i<10;i++)
{
if(arr[i]>big)
{
big=arr[i];
}
if(arr[i]<small)
{
small=arr[i];
}
printf (“ biggest=%d”,big);
printf (“ \nsmallest=%d”,small);
getch();
return 0;
}
Example: Bubble sort
Sorting is the process of arranging the data in some logical order.
Bubble sort is an algorithm to sort various linear data structure like an array.
The logical order can be ascending and descending in the case of numeric
values
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
89
Program Output
// Bubble sort using C Sorted list using Bubble sort
#include<stdio.h> are:
#include<conio.h> 2 4 6 24 28
int main()
{
int arr[5] = { 28, 6, 4, 2, 24};
int i ,j,temp ;
clrscr();
for(i=0;i<4;i++)
{
for(j=0;j<5-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j]= arr[j+1];
arr[j+1]= temp;
}
}
}
printf(“Sorted list using Bubble sort are:\n”);
for(i=0;i<5;i++)
{
printf(“%d\t”,arr[i]);
}
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Example: Linear search
Linear Search is defined as a sequential search algorithm that starts at one
end and goes through each element of a list until the desired element is
found
90
Program Output
// Linear Search Enter the
#include <stdio.h> number to
int main() search:34
{
int array[7] = {15,38,56,34,76,89,94}; 34 is present at
int search, c; location 3
clrscr();
printf("Enter the number to search:");
scanf("%d", &search);
for (c = 0; c < 7; c++)
{
if (array[c] == search) {
printf("%d is present at location %d.\n", search, c);
break;
}
}
if (c == 7)
printf("%d is not present in array.\n", search);
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
// C Program on Addition of 2 Enter values of 3*3 Matrix 1:
matrices – 2D 1
#include<stdio.h> 2
#include<conio.h> 3
int main() 4
{ 5 91
int a[3][3],b[3][3],c[3][3], i , j; 6
clrscr(); 7
printf(“Enter values of 3*3 Matrix 8
1:\n”); 9
for(i=0;i<3;i++) Enter values of 3*3 Matrix 2:
{ 1
for(j=0;j<3;j++) 2
{ 3
scanf(“%d”,&a[i][j]); 4
} 5
} 6
printf(“Enter values of 3*3 Matrix 7
2:\n”); 8
for(i=0;i<3;i++) 9
{
for(j=0;j<3;j++) Matrix 1 + Matrix 2:
{ 2 4 6
scanf(“%d”,&b[i][j]); 8 10 12
} 14 16 18
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j ] = a[i][j]+b[i][j];
}
}
printf(“Matrix 1 + Matrix 2:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
getch();
return 0;
}
Program Output
// C Program on Addition of 2 matrices using // 2
92
Dimensional array initilization
#include<stdio.h> Matrix 1 + Matrix 2:
#include<conio.h> 2 4 6
int main() 8 10 12
{ 14 16 18
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}},
int b[3][3]= {{1,2,3},{4,5,6},{7,8,9}},
int c[3][3], i , j;
clrscr();
(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j ] = a[i][j]+b[i][j];
}
}
printf(“Matrix 1 + Matrix 2:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
// Matrix multiplication Matrix 1 * Matrix 2:
6 12 18
#include<stdio.h>
6 12 18
#include<conio.h> 6 12 18
int main()
{ 93
int a[3][3]={{1,2,3},{1,2,3},{1,2,3}};
int b[3][3]={{1,2,3},{1,2,3},{1,2,3}};
int c[3][3],i,j,k;
clrscr();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
{ // multiply i'th row with j'th column
C[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf ("Matrix 1 * Matrix 2:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
//Transpose matrix Original matrix:
123
#include<stdio.h>
456
#include<conio.h> 789
int main() Transpose matrix:
{ 147
94
258
int a[3][3]={{1,2,3},{1,2,3},{1,2,3}}; 369
int i , j;
clrscr();
printf(“Original matrix:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“%\n”);
}
printf(“Transpose matrix:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,a[j][i]);
}
printf(“%\n”);
}
getch();
return 0;
}
3.4. Two dimensional arrays,
Already discussed in types of arrays topic Page no. 80, 81, 82
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
3.5. Introduction to Strings (char array)
A Collection of characters is usually referred as A
String it contains characters terminated by a null
character (‘\0’) and characters are enclosed
with in double quotes (“ ”)
3.5.1. Initialization of a String: Examples are,
95
char word [] ={ ‘H’,’e’,’l’,’l’,’o’,’\0’}; Or
char word [] =”Hello”;
When you assign a character array by listings it must be terminated with a null
character (\0) and unlike integer array, you need not specify any index value
to access a String.
And you need format specifier %s to access it.
Valid and Invalid Operations when Initializing a String:
char greet [] =”Hello”; ✔ // accepts when no index size is mentioned
char greet [45]=”Hello “; ✔ // accepts when index size is greater
char greet [3]=”Hello “; ✖ // not accepts when index size is less
char greet = “Hello “; ✖ // not accepts when index is not mentioned
char *greet =”Hello”; ✔ // accepts pointer assignment
Program Output
// string example 1 Hello
#include<stdio.h>
#include<conio.h>
int main()
{
char word[6]={'H','e','l','l','o','\0'};
clrscr();
printf("Given string=%s",greet);
getch();
return 0;
}
// string example 2 Hello
#include<stdio.h>
#include<conio.h>
int main()
{
char word[6]="Hello";
clrscr();
printf("Given string=%s",greet);
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
3.5.2. Declaration of a String:
When you read a string using scanf() function with format specifier %s there a
problem has been a raised
For example if you enter a string “ hello world “ its reads up to the word hello
only and leaves remaining characters. i.e., whenever 1st white space
encountered.
96
Solution 1: by using %[^\n] format specifier in scanf()
Solution 2: by using gets() function
gets() and puts() in strings:
gets(): gets() is used to read a string from key board
syntax: gets(string);
puts(): puts() is used to access a string.
Program Output
// string example 1 Enter a string: Hello world
#include<stdio.h> Given string: Hello world
#include<conio.h>
int main()
{
char word[20];
clrscr();
printf(“Enter a string:”);
scanf(“%[^\n]”,&word);
printf("Given string:%s",word);
getch();
return 0;
}
// string example 2 Enter a string: Hello world
#include<stdio.h> Given string: Hello world
#include<conio.h>
int main()
{
char word[20];
clrscr();
printf(“Enter a string:”);
gets(word);
printf("Given string:”);
puts(word);
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
3.5.3. String Handling functions:
There are some pre defined functions to handle strings. Called string handling
functions.
We need to use header file #include<string.h>
strcat():
To concatenate (join) 2 strings syntax: strcat(string1,string2); 97
Program Output
// strcat example before: str1=Hello str2=SITE
#include <stdio.h> after: str1=HelloSITE str2=SITE
#include <string.h>
int main()
{
char str1[20]= “Hello”;
char str2[20]= “SITE”;
printf(“before: str1=%s str2=%s\n”,str1,st2);
strcat(str1,str2);
printf(“after: str1=%s str2=%s\n”,str1,st2);
getch();
return 0;
}
strcpy():
to copy the one string over another syntax: strcpy(string1,string2);
Program Output
// strcat example before: str1=Hello str2=SITE
#include <stdio.h> after: str1=SITE str2=SITE
#include <string.h>
int main()
{
char str1[20]= “Hello”;
char str2[20]= “SITE”;
printf(“before: str1=%s str2=%s\n”,str1,st2);
strcpy(str1,str2);
printf(“after: str1=%s str2=%s\n”,str1,st2);
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
strcmp():
Used to compare two strings syntax: strcmp(string1,string2);
Program Output
// strcmp example Equal
#include <stdio.h>
#include <string.h>
int main() 98
{
char str1[20]= “Hello”;
char str2[20]= “Hello”;
if(strcmp(str1,str2)==0)
{
printf(“Equal”);
}
else
{
printf(“Not equal”);
}
getch();
return 0;
}
strrev():
used to reverse a given string syntax: strrev(string);
Program Output
// strrev example olleH
#include <stdio.h>
#include <string.h>
int main()
{
char str[20]= “Hello”;
printf(“%s”,strrev(str));
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
strlwr() & strupr() :
strlwr() makes complete string in lower case where as strupr() makes it upper
case syntax: strlwr(string) & strupr(string)
Program Output
// strlwr,strupr example hello
#include <stdio.h> HELLO
#include <string.h> 99
int main()
{
char str[20]= “Hello”;
printf(“%s”,strlwr(str));
printf(“%s”,strupr(str));
getch();
return 0;
}
strlen()
It results length of given string Syntax: strlen(string);
Program Output
// strlen example 5
#include <stdio.h>
#include <string.h>
int main()
{
char str[20]= “Hello”;
printf(“%d”,strlen(str));
getch();
return 0;
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Also more functions like strchr(),strstr() and many works under
#include<string.h>
Example: Palindrome in Strings
Ex: wow if you consider above number from left side it results wow from right
side also same such a property is called palindrome property of strings
100
Program Output
// palindrome string example Enter a string: wow
#include <stdio.h> Palindrome String
#include <string.h>
int main()
{
char str[50],t[50];
clrscr();
printf("Enter a string:");
gets(s);
strcpy(t,s);
strrev(t);
if(strcmp(t,s)==0)
{
printf("Palindrome String.");
}
else
{
printf("Not a palindrome");
}
getch();
return 0;
}
Additional Questions:
1. C program to eliminate duplicate elements in an array
2. C program to reverse a string using and without using built in function
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
UNIT 4
Pointers & User Defined Data types
4.1. Pointers,
101
4.2. Address operator and dereferencing pointer,
4.3. Pointer and address arithmetic,
4.4. Array manipulation using pointers,
4.5. User-defined data types: Structures and Unions.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
4.1. Pointers:
Pointer variable is a variable used to store the address of the other
variable.
Address of the variable
102
A pointer is a variable with a difference. It contains, not a simple value, but
the address of another variable
A pointer is a reference to another variable (memory location) in a program.
Advantages:
– Used to change variables inside a function (call by reference
parameters)
– Used to remember a particular member of a group (such as an
array)
– Used in dynamic memory allocation (especially of arrays)
– Used in building complex data structures (linked lists, stacks,
queues, trees, etc.).
4.2. Address operator(&) and Dereferencing pointer (*):
operator & used for accessing address of a variable
operator * is used for declare a pointer variable and also used
for dereferencing a pointer variable
4.2.1. Address operator &:
Address operator is used for Memory access of a pointer Or Accessing
address of a variable
A program evaluates a variable by accessing its memory location i.e.,
addresses and retrieving the value stored there. Because this process is
hidden in our programs.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Before the advent of 3GL languages, programmers had to explicitly specify
memory locations for data. Today, the same job is done by the compiler
When we declare a variable storage is allocated to it
For example, int a=100;
Storage is allocated to variable a and 100 is assigned to that location, along
103
with that each variable having its address location as well, which is system
dependent (i.e., probably different values from one computer to another)
The address of the variable can be accessed by using ampersand &
operator.
Program Output
#include<stdio.h> 10 is stored at 65524
#include<conio.h> 3.20000 is stored at 65520
int main() a is stored at 65519
{
int a=10;
float b=3.2;
char c=’a’;
NOTE:
clrscr();
printf("%d is stored at %u\n",a,&a); Address values
printf("%f is stored at %u\n",b,&b); in output are
system
printf("%c is stored at %u\n",c,&c);
dependent
getch();
return 0;
}
4.2.2. Declaring a pointer:
The pointer in c language can be declared using * (asterisk symbol). It is also
known as indirection pointer used to dereference a pointer.
Syntax:
data_type * pointer_variable;
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
data_type is C’s variable types and indicates the type of the variable
that the pointer points to.
The asterisk (*: the same asterisk used for multiplication) which is
indirection operator, declares a pointer.
Example:
int *p; // p is pointer variable of int data type
104
float *q; // q is pointer variable of float data type
float *ptr, var;.
/*ptr is a pointer to type float and var is an ordinary float variable */
4.2.2. Initializing a pointer :
Pointer initialization is the process where we assign some initial value to the
pointer variable.
We generally use the ( & ) ampersand operator to get the memory address
of a variable and then store it in the pointer variable.
Syntax:
pointer_variable = &variable;
Example:
int var = 50;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step.
int *ptr = &var;
BIG NOTE: Without initialization pointer variable must not be used. if
we use also memory issues might occur.
Pointer variable must point same data type only.
int a=10;
int *ptr=&a; // valid ✔
float x=2.67;
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
int *ptr=&x; // invalid. ✖
4.2.4. Dereferencing a pointer
4.2.5. )
Once we have a pointer that points to a specific memory location, we can 105
access or modify the value stored at that location by dereferencing the
pointer.
To dereference a pointer, we use the asterisk * symbol again, but this time in
front of the pointer variable itself.
Program Output
#include<stdio.h> 10 is stored at 65524
#include<conio.h> 10 is stored at 65524
int main() 10 is stored at 65524
{ 10 is stored at 65522
65524 stored at 65520
int x=10,y;
now x=20
int *ptr;
ptr=&x;
y=*ptr;
clrscr();
printf("%d is stored at %u\n",x,&x);
printf("%d is stored at %u\n",*ptr,ptr);
printf("%d is stored at %u\n",*&x,&x);
printf("%d is stored at %u\n",y,&y);
printf("%u is stored at %u\n",ptr,&ptr);
x=20;
printf("now x=%d",x); NOTE:
getch();
Address values
return 0; in output are
} system
dependent
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
4.2.6. Pointer to pointer:
A pointer can also point to another pointer variable. This is known as a
"pointer to a pointer".
106
We declare a pointer
to a pointer by using
two asterisks **. for
example:
int a=10;
int *ptr = &a;
int **dptr = &ptr;
4.3. Pointer and address arithmetic:
A pointer in c is an address, which is a numeric value. Therefore, you can
perform arithmetic operations on a pointer just as you can on a numeric
value.
Pointer arithmetic involves manipulating memory address using pointers
The following arithmetic operators that can be used on pointers arithmetic:
Increment ++,
Decrement --,
Addition +
Subtraction –
Also we can use for Relational operators (==, !+
,>,<,>=,<=)
Adding or subtracting two addresses is not possible, because there is no idea
what it would point to
Also remaining operations like multiplication, division etc, are not possible
4.3.1. Pointer arithmetic increment (++):
If we increment (++) pointer by 1, it will point to next immediate memory
location.
But this is different from general increment; value of pointer will be size of
pointer data type to which pointer is pointing.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Rule: new address = current address + i * sizeof (datatype)
As per rule given, if we increment by 1, then i =1,
Example:
int a ;
107
int *p;
p = &a;
p++;
NOTE: Incremented value is given for 16 – Bit system
4.3.2. Pointer arithmetic decrement (--):
If we decrement ( -- ) pointer by 1, it will point to previous memory location.
But this is different from general decrement; value of pointer will be size of
pointer data type to which pointer is pointing
Rule: new address = current address – i* sizeof (datatype)
As per rule given, if we decrement by 1, then i =1,
Example:
int b;
int *q;
q = &b;
q -- ;
NOTE: Decremented value is given for 16 – Bit system
4.3.3.Pointer arithmetic Addition (+):
We can add a value to the pointer variable, the rule is given below
Rule : new address = current address + offset * sizeof (datatype)
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Here, pointer is added with an offset value which is multiplied by the size of
the data type.
Example:
float c;
float *r; 108
r = &c;
r = r+2;
NOTE: Addition
value is given for 16 – Bit system
4.3.4. Pointer arithmetic Subtraction (-):
We can subtract a value to the pointer variable, the rule is given below
Rule : new address = current address - offset * sizeof (datatype)
Here, pointer is subtracted with an offset value which is multiplied by the size
of the data type.
-Example:
float d;
float *s;
s = &d;
s = s-2;
NOTE: Subtraction value is given for 16 – Bit system
Program Output
// pointer arithmetic example Before
#include<stdio.h> p=65000
#include<conio.h> q=66000
int main() r=67000
{ s=68000
int a,b;
After
float c,d;
p=65002
int *p = &a; q=65998
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
int *q = &b; r=67008
float *r = &c; s=67992
float *s = &d;
clrscr();
printf("Before\n p = %u\nq= %u\nr= %u\ns= %u\n",p,q,r,s); NOTE:
p++;
Address values
109
q--; in output are
r = r+2; system
s = s-2; dependent
printf("After\n p = %u\nq= %u\nr= %u\ns= %u\n",p,q,r,s);
getch();
return 0;
}
4.4. Array manipulation using pointers:
Array is a collection of similar data items into single unit of continuous memory
location. Whereas, pointer is used to store address of another variable
We know pointer arithmetic is used to add or subtract memory location to
current address.
Pointer array means pointer variable holds the address of first element of
array, For example
int p[5]= { 8,9,10,11,12};
int *ptr = p; ( or int *ptr = &p[0])
As per rule of pointer arithmetic,
ptr+1 is same as &p[1]
ptr+2 is same as &p[2]
ptr+3 is same as &p[3]
ptr+4 is same as &p[4]
As per rule of pointer dereferencing,
*ptr is 8
*(ptr+1) is 9
*(ptr+2) is 10
*(ptr+3) is 11
*(ptr+4) is 12
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
#include<stdio.h> &p[0]= 65516 p[0] = 8
#include<conio.h> &p[1]= 65518 p[1] = 9
int main() &p[2]= 65520 p[2] = 10
{ &p[3]= 65522 p[3] = 11
110
int p[5]={8,9,10,11,12}, i; &p[4]= 65524 p[4] = 12
int *ptr = &p;
clrscr(); NOTE:
for(i=0;i<5;i++) Address values
{ in output are
printf("p[%d]=%u\tp[%d]=%d\n",i,ptr+i,i,*(ptr+i)); system
} dependent
getch();
return 0;
}
We can modify array element using pointer also
For example,
*(ptr+3) = 16
Then resultant array will be
Program Output
#include<stdio.h> &p[0]= 65516 p[0] = 8
#include<conio.h> &p[1]= 65518 p[1] = 9
int main() &p[2]= 65520 p[2] = 10
{ &p[3]= 65522 p[3] = 16
int p[5]={8,9,10,11,12}, i; &p[4]= 65524 p[4] = 12
int *ptr = &p;
clrscr();
*(ptr+3)=16; NOTE:
for(i=0;i<5;i++)
Address values
{
in output are
printf("p[%d]=%u\tp[%d]=%d\n",i,ptr+i,i,*(ptr+i)); system
} dependent
getch();
return 0;
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
}
4.5. User-defined data types: Structures and Unions
When you want to access different types of variables this cannot be done
using arrays. But this can be done by using structure and union.
4.5.1. Structure:
111
Declaring a structure variable:
To declare a structure we must use a keyword called struct
The struct statement defines a new data type. With more than one member
The structure variable can be defined in 2 ways,
Example:
1. Declaring structure variables separately
struct student
syntax:
{
struct tag
{ int id;
datatype1 member1;
char name[30];
datatype2 member2;
: float marks;
:
datatypen membern; };
}; struct student ram,syam;
struct tag variable1, variable2………variable n;
Note: Semi colon(;) after structure declaration is mandatory.
2. Declaring structure variables with the structure
syntax: Example:
struct tag struct student
{
datatype1 member1; {
datatype2 member2; int id;
:
: char name[30];
datatypen membern;
float marks;
} variable1, variable2………variable n;
}ram,syam;
Initializing a structure variable:
When we declare a structure variable memory is allocated to each variable
with all member values
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
For example:
struct student
int id;
char name[30];
112
float marks;
};
struct student ram,syam;
memory is allocated to variable ram and variable syam like this
After initializing
struct student ram ={1001,”rama rao”,88.88};
struct student syam = {2002,”syam sundar”,99.99};
Accessing a structure variable:
Structure variable can be accessed by using .dot between structure variable
and member name
Example : printf(“%d”,ram.id); // returns 1001
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program
#include<stdio.h>
#include<conio.h>
struct student
{
int id;
char name[30];
float marks; 113
};
int main()
{
struct student ram={1001,"rama rao",88.88};
struct student syam={2002,"syam sundar",99.99};
clrscr();
printf("RAM details\nID:%d\tNAME:%s\tMARKS:%f\n",ram.id,ram.name,ram.marks);
printf("SYAM
details\nID:%d\tNAME:%s\tMARKS:%f\n",syam.id,syam.name,syam.marks);
getch();
return 0;
}
Output:
RAM details
ID:1001 NAME: rama rao MARKS:88.88
SYAM details
ID:2002 NAME: syam sundar MARKS:99.99
Instead of initializing we can also read values like this,
printf(“enter id of student ram:”);
scanf(“%d”,&ram.id);
printf(“enter full name of student ram:”);
gets(ram.name);
printf(“enter marks of student ram:”);
scanf(“%f”,&ram.marks);
printf(“enter id of student syam:”);
scanf(“%d”,&syam.id);
printf(“enter full name of student syam:”);
gets(syam.name);
printf(“enter marks of student syam:”);
scanf(“%f”,&syam.marks);
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
4.5.2. Union:
Union in C language is similar to structure but the major difference is in
storage.
We can understand the complete concept by using sizeof keyword.
In structure each member stores total of members placed in the structure will
be consumed 114
In union highest value member is applicable to all variables
sizeof in structure:
lets consider an example struct abc contain members int a which consumes
2 bytes , float b consumes 4 bytes and char c consumes 1 byte total of 7
bytes.
sizeof in union:
union keyword is used to save memory.
Here it consumes highest member memory
value.
sizeof in struct Program sizeof in union program
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
struct abc union abc
{ {
int a; int a;
float b; float b;
char c; char c;
}; };
void main() void main()
{ {
clrscr(); clrscr();
printf("takes %d bytes",sizeof(struct printf("takes %d bytes",sizeof(union
abc)); abc));
getch(); getch();
} }
Output: Output
takes 7 bytes takes 4 bytes
NOTE: Values given for 16 – Bit system
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
115
Point of Structure Union
Difference
Memory Allocates memory for all Allocates memory
Allocation its members. only for the largest
member.
Total Size Sum of sizes of all Size of the largest
members. member.
Data Storage Can store values for all Can store value for
members simultaneously. only one member at
a time.
Use Case When you want to group When you want to
different data types and save memory and
access all of them at only need one data
once. type at a time.
Example struct example { union example {
int a; int a;
float b; float b;
}; };
Accessing All members can be Only the last stored
Members accessed at any time. member can be
accessed.
Modification Modifying a member Modifying one
Impact doesn’t affect other member may
members.
4.5.3. typedef in C:
In C, the typedef keyword is used to create a new name (alias) for am
existing data type.
Syntax:
typedef existing_type new_type;
Example: typedef int uday;
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
#include<stdio.h> 30
#include<conio.h>
int main()
{
typedef int uday; 116
uday a=10,b=20;
clrscr();
printf(“%d”,a+b);
getch();
return 0;
}
4.5.4. enum in C:
enum( enumeration ) is a user defined datatype that consists of integer
values given names by user
Syntax:
enum enumname { value1,value2….,value n};
Example:
Program Output
#include<stdio.h> 3
#include<conio.h>
enum week { sun,mon,tue,wed,thu,fri,sat };
int main()
{
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
clrscr();
printf(“%d”,wed);
getch();
return 0;
}
Additional Questions: 117
1. Explain about following?
NULL Pointer
Wild Pointer
Dangling pointer
void pointer
2. What is nested structure explain with a program?
3. Explain use of Bit fields in structure explain?
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
UNIT 5
5.0. Introduction to Functions
116
5.1. Function Declaration and Definition,
5.2. Function call Return Types and Arguments,
5.3. Modifying parameters inside functions using pointers,
5.4. Arrays as parameters.
5.5. Scope and Lifetime of Variables,
5.6. Basics of File Handling
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
5.0. Introduction to Functions
Def: “Group of statements that are together to perform a task is called
function.”
Every C program has at least one function called main () function and most
117
of the trivial programs can define additional functions.
In C, we can divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed
by {}.
A function can be called multiple times to provide reusability.
Advantages:
1. Code reusability :
By creating a function one time we can re use it many times
2. Code optimization:
We don’t need to write much code
3. Code Easier :
We can track a large C program easily when it is divided into
multiple functions.
4. Division of labour:
Several programmers can divide the workload in large projects
by working on different functions for program
Types of functions:
Standard library functions or Pre Defined functions or Built in functions.
User defined functions.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Standard library functions or Pre Defined functions or Built in functions:
Already defined programs by C programming developer are called
predefined functions. And they are supplied as part of compiler for universal
requirements.
And we need to place a prototype / header file to use it.
118
#include<ctype. h>
Used for character Handling functions like
isalpha(): to know given is alphabet or not.
toupper(): to convert given character to upper case.
tolower (): to convert to lower case. etc.,
Program Output
//program to check whether you Enter a character: a
entered a character or not Yes u entered a character
#include<stdio.h>
#include<conio.h>
#include<ctype.h> Enter a character: 20
main() Not a character
{
char ch;
clrscr();
printf("Enter a character:");
ch=getchar();
if(isalpha(ch))
{
printf("Yes u entered a character");
}
else
{
printf("Not a character");
}
getch();
return 0;
}
#include<math .h>
Used to Handle Mathematical functions.
sqrt(): used to find square root of a given number
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
pow (n1,n2): used to find n1n2
sin(): used to find sin values
sinh(): used for hyperbolic sin values . etc.,
Program Output
#include<stdio.h> 8
119
#include<conio.h>
#include<math.h>
int main()
{
int a=2,b=3,c;
clrscr();
c=pow(a,b);
printf ("%d",c);
getch();
return 0;
}
#include<string.h>
Used for string handing functions
Ex: strcat(), strcpy(), strcmp(), strrev(), strupr(), strlwr() etc.,
#include<stdio.h>
Used for standard input and output library functions
Ex: printf(), scanf(), getchar(), putchar(), gets(), puts(), fprintf() etc.,
And many more like #include<dos.h>, #include<time.h>,
#include<complex.h> etc., are used
Under each and every header file or prototype some predefined functions
are placed by C language developer for universal requirements
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Structure of a C Program
Documentation section
The documentation section consists of a set of comment lines giving
the name of the program, the 120
author and other details, which the
programmer would like to use later.
Ex: // Addtion of 2 numbers by Uday
Link section
The link section provides instructions
to the compiler to link functions from
the system library
Ex: #include <stdio.h>
Definition section
The definition section defines all
symbolic constants such using the
Ex: #define PI 3.14
Global declaration section
There are some variables that are
used in more than one function.
Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also
declares all the user-defined functions.
main () function section
Every C program must have one main function section. This section contains
two parts; declaration part and executable part
Declaration part
The declaration part declares all the variables used in the executable part.
Executable part
There is at least one statement in the executable part. These two parts must
appear between the opening and closing braces.
Subprogram section
If the program is a multi-function program then the subprogram section
contains all the user-defined functions that are called in the main () function.
User-defined functions are generally placed immediately after the main ()
function, although they may appear in any order.
All section, except the main () function section may be absent when they are
not required.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
User - Defined functions:
C allows programmers to write their own functions, also known as user-
defined functions.
User-defined function has three main components: 121
Function declarations or function prototype
Function definition and
Function call.
Need for user defined functions:
As we discussed earlier every C program has at least one
function. Called main () function. Which is starting of program
When we write entire program in main () function. It leads to no.
of problems the task of debugging, testing , and maintenance
becomes difficult
If the program is divided into functional parts the task of
debugging, testing and maintenance becomes easier.
5.1. Function Declaration and Definition
To use a user-defined function, we first have to understand the different
parts of its syntax.
Function Declaration
Function Definition
Function Call
Function Declaration:
This is also called function prototype declaration. Which specifies
the function’s name, function parameters, and return type. The function
prototype does not contain the body of the function. It is basically used to
inform the compiler about the existence of the user-defined function which
can be used in the later part of the program.
Syntax
return_type function_name (type1 arg1, type2 arg2, ... typeN argN);
Example: int sum (int,int);
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Function Definition:
Once the function has been called, the function definition contains the
actual statements that will be executed. All the statements of the function
definition are enclosed within { } braces.
Syntax:
return_type function_name (type1 arg1, type2 arg2 .... typeN argN)
{ 122
// function body (return value if there)
}
Example:
int sum(int x,int y)
{
return x+y;
}
Function call:
In order to transfer control to a user-defined function, we need to call
it. Functions are called using their names followed by parenthesis ( )
their arguments are passed inside the brackets.
Syntax
function_name(arg1, arg2, ... argN);
Example: sum(a,b);
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
#include<stdio.h> Enter 1st no: 10
#include<conio.h> Enter 2nd no:20
int sum(int,int); // function declaration Total = 30
int main()
{
int a,b,c; 123
clrscr();
printf(“Enter 1st no:”);
scanf(“%d”,&a);
printf(“Enter 2nd no:”);
scanf(“%d”,&b);
c=sum(a,b); // function call
printf(“Total = %d”,c);
getch();
return 0;
}
int sum(int x, int y) // function definition
{
return x+y;
}
void keyword in C:
In computer programming, when void is used as a function return type, it
indicates that the function does not return a value.
When void appears in a pointer declaration, it specifies that the pointer is
universal.
When used in a function's parameter list, void indicates that the function
takes no parameters.
For example if we write
int main() then there is need of write return 0;
If it is void main() then there is no need of return 0;
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
5.2. Function call Return Types and Arguments:
To understand function calls and return types in C, lets see the following
Types of user defined functions:
1. Function with both arguments and return values
2. Function with arguments but NO return values 124
3. Function with NO arguments and NO return values
4. Function with NO arguments but return values
Function with both arguments and return values
Here called function accepts arguments and return value back to the
calling function Thus, there is 2 way communication between called function
and calling function.
Program Output
#include<stdio.h> Enter radius:5.0
#include<conio.h> Area= 78.5000
float area(float);
int main()
{
float rad,a;
clrscr();
printf(“Enter radius:”);
scanf(“%f”,&rad);
a=area(rad);
printf(“Area= %f”,a);
getch();
return 0;
}
float area(float r)
{
return 3.14*r*r;
}
Function with arguments but NO return values:
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Here called function accepts arguments and does not return any
value back to calling function so there is 1 way communication between
called function and calling function.
125
Program Output
#include<stdio.h> Enter radius:5.0
#include<conio.h> Area= 78.5000
void area(float);
int main()
{
float rad;
clrscr();
printf(“Enter radius:”);
scanf(“%f”,&rad);
area(rad);
getch();
return 0;
}
void area(float r)
{
printf(“Area = %f”,3.14*r*r);
}
Function with NO arguments and NO return values
Here called function accepts No arguments and does not return any
value back to calling function so there is No communication between called
function and calling function.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
#include<stdio.h> Enter radius:5.0
#include<conio.h> Area= 78.5000
void area();
void main()
{
clrscr(); 126
area();
getch();
}
void area()
{
float rad;
printf(“Enter radius:”);
scanf(“%f”,&rad);
printf(“Area = %f”,3.14*rad*rad);
}
Function with NO arguments and return values
Here called function accepts no arguments but returning value back
to calling function.
Program Output
#include<stdio.h> Enter radius:5.0
#include<conio.h> Area= 78.5000
float area();
void main()
{
float a;
clrscr();
a=area();
printf(“Area = %f”,a);
getch();
}
float area()
{
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
float rad;
printf(“Enter radius:”);
scanf(“%f”,&rad);
return 3.14*rad*rad;
}
5.3. Modifying parameters inside functions using pointers:
127
To modify parameters inside a function we need to pass address of the
variable to the function. In order to understand this lets see the following
argument passing techniques or Parameter passing Techniques
1. Call by value or Pass by value
2. Call by reference or Pass by reference
Call by value: (or Pass by value)
Arguments are passed without pointer is called call by value.
When we call a function using call by value Xerox value of original
value is created any modification done in called function will not
modify the Original Value
Program Output
#include<stdio.h> x=1000
#include<conio.h> a=10
void cube(int);
void main()
{
int a=10;
clrscr();
cube(a);
printf(“ a =%d”,a);
getch();
return 0;
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
}
void cube(int x)
{
x=x*x*x;
printf(“x = %d\n”,x);
}
128
Call by reference: (or Pass by reference)
Arguments are pas sed with a pointer is called call by reference
also called call by address.
When we call a function using call by reference we are actually
passing the address of a variable. Any modification done in
passed value will affect the original value also
Program Output
#include<stdio.h> x=1000
#include<conio.h> a=1000
void cube(int*);
void main()
{
int a=10;
clrscr();
cube(&a);
printf(“ a =%d”,a);
getch();
return 0;
}
void cube(int *x)
{
(*x) = (*x)*(*x)*(*x);
printf(“x = %d\n”,*x);
}
5.4. Arrays as parameters.
If you want to pass a one-dimension array
as an argument in a function, you would have to declare a formal parameter
in one of following three ways and all three declaration methods produce
similar results
Similarly, you can pass multi-dimensional arrays as formal parameters.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Way-1
Formal parameters as a pointer −
void myFunction(int *param) {
.
. 129
}
Way-2
Formal parameters as a sized array −
void myFunction(int param[10]) {
.
. .
}
Way-3
Formal parameters as an unsized array −
void myFunction(int param[]) {
.
. .
}
Program Output
#include <stdio.h> Array Elements:
void printArray(int arr[],int size); 12
void main() 4
{ 5
int arr[8] = { 12, 4, 5, 3, 7, 8, 11, 45 }; 3
int size = sizeof(arr) / sizeof(arr[0]); 7
printArray(arr, size);
8
return 0;
11
}
// function to print array 45
void printArray(int arr[], int size)
{
printf("Array Elements: \n");
for (int i = 0; i < size; i++) {
printf("%d\n", arr[i]);
}
}
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
We can also copy 2 dimensional elements also , example is given
below
Program Output
// C program for transpose of 2D array using Tranpose of given is
//function 1 4 7
#include<stdio.h>
#include<conio.h> 2 5 8 130
void transpose(int c[3][3]);
void main() 3 6 9
{
int arr[3][3]={{1,2,3},{4,5,6},{7,8,9}};
clrscr();
transpose(arr);
getch();
}
void transpose(int c[3][3])
{
int i,j;
printf(“Tranpose of given is \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[j][i]);
}
printf("\n");
}
}
5.5. Scope and Lifetime of Variables:
Let us understand the concept of Scope and life time of a variable first
Life time: Life time of any variable is the time for which the particular variable
lives in memory during running of the program.
Scope: A variable may be in the memory but, may not be accessible to all
functions. The variable which provides access to some region is depends
upon its scope.
Scope of a variable is categorised into 3 types
Local Scope: Local variables have scope within the function only
Global Scope: Global variables have scope more than one function
Function Scope: variables passed as formal parameters have scope
within function.
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
include<stdio.h> Global variable is 100
int global = 100; // global variable declared
void main() Local variable is 10
{
Global inside func1 is
int local = 10; // local variable declared 100
printf("Global variable is %d",global); 131
printf("Local variable is %d",local);
func1();
}
void func1()
{
printf("Global inside func1 is %d",global);
// Would print the global variable successfully.
}
To determine scope, life time and visibility of a variable
Storage classes are used
5.5.1. Storage classes:
Storage classes in C are used to determine the lifetime, visibility, memory
location, and initial value of a variable. There are four types of storage classes
in C
Automatic storage classes (auto)
Static storage classes (static)
External storage classes (extern)
Register storage classes(register)
Automatic storage classes (auto):
By default every variable defined auto only
Keyword used: auto
Storage place: RAM
Default Value: Garbage vale
Scope: Local
Lifetime: within the function
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Output
// auto variable example 1
#include<stdio.h> 1
#include<conio.h> 1
void increment(); 1
void main()
{ 132
clrscr();
increment();
increment();
increment();
increment();
getch();
}
void increment()
{
auto int i=1; // or int i=1;
printf("%d\n",i);
i++;
}
i.e., it leaves the value of variable between different function calls
Static storage classes (static):
When we declare a variable with static keyword (ex: static int i; ) we call it as
static variable
Keyword used: static
Storage place: RAM
Default Value: ZERO
Scope: Local
Lifetime: Till the end of the main program, Retains value between
multiple functions call
Program Output
// static variable example 1
#include<stdio.h> 2
#include<conio.h> 3
void increment(); 4
void main()
{
clrscr();
increment();
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
increment();
increment();
increment();
getch();
}
void increment()
{ 133
static int i=1;
printf("%d\n",i);
i++;
}
External storage classes (extern):
Keyword used: extern
Storage place: RAM
Default Value: ZERO
Scope: Global
Lifetime: Till the end of the main program Maybe declared anywhere in
the program
Program Output
#include<stdio.h> Global variable=10
#include<conio.h> external variable =100
int x=10; // global variable
void main()
{
extern int y;
clrscr();
printf("Global variable=%d",x);
printf("\nexternal variable =%d",y);
getch();
}
int y=20;// external variable
Register storage classes (register)
Actually computer memory is arranged like
Register memory is closest memory to processor so it
gives faster access than normal variable
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Keyword used: register
Storage place: register memory
Default Value: Garbage value
Scope: local
Lifetime: Within the function. 134
Program Output
#include<stdio.h> 10
#include<conio.h>
void main()
{
register int a=10;
clrscr();
printf(“%d”,a);
getch();
}
5.6. Basics of File Handling:
Introduction to file
Until now we have been using the functions such as scanf ,printf, getchar,
putchar, gets, puts etc to read and write data on the variables, arrays and
strings for storing data inside the programs.
But this approach poses the following.
1. The data is lost when program terminated or variable goes out of scope.
2. Difficulty to use large volume of data.
We can overcome these problems by storing data on secondary devices
such as Hard Disk. The data is storage on the devices using the concept of
''file''.
A file is collection of related records, a record is composed of several fields
and field is a group of character
Types of Files:
Text files: A text file contains data in the form of ASCII characters and is
generally used to store a stream of characters. Example: MS Word
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
135
Binary files: A binary file contains data in binary form (i.e. 0’s and 1’s) instead
of ASCII characters.
C File Operations
C file operations refer to the different possible operations that we can
perform on a file in C such as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Writing to a file – fprintf() or fputs()
4. Reading from file – fscanf() or fgets()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()
File Pointer:
A file is collection of related records, a record is composed of several fields
and field is a group of character.
The most straightforward use of files is via a file pointer.
FILE *fp;
fp is a pointer to a file.
The type FILE, is not a basic type, instead it is defined in the header file stdio.h
,
this file must be included in your program.
Open a File in C:
For opening a file in C, the fopen() function is used with the filename or
file path along with the required access modes.
Syntax :
FILE* fopen(const char *file_name, const char *access_mode);
Where file name is name of the file when present in the same directory as
the source file. Otherwise, full path.. Access mode can be following:
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
136
Writing to a File:
The file write operations can be performed by the functions fprintf() and
fputs() with similarities to read operations.
Function Description
fprintf() Similar to printf(), this function use formatted string and varible
arguments list to print output to the file.
fputs() Prints the whole line in the file and a newline at the end.
fputc() Prints a single character into the file.
Read from a file:
The file read operation in C can be performed using functions fscanf() or
fgets() etc.,
Function Description
fscanf() Use formatted string and variable arguments list to take input from
a file.
fgets() Input the whole line from the file.
fgetc() Reads a single character from the file.
Closing a file:
The fclose() function is used to close the file. After successful file operations,
you must always close a file to remove it from the memory.
Syntax:
fclose(FILE_POINTER);
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering
Program Check BIN
folder in
turbo C
directory
#include <stdio.h> example.txt
#include<conio.h>
int main() { Hello,this 137
FILE *file = fopen("example.txt", "w");// Creating a file is Uday
if (file == NULL) {
printf("Error creating the file.\n");
return 1;
}
fprintf(file, "Hello, this is Uday."); // Writing to the file
fclose(file); // Closing the file (create a
file)
file = fopen("example.txt", "r");// Opening the file for reading
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
} Hello, this is
Uday
char buffer[100]; // Reading from the file (read from
fgets(buffer, sizeof(buffer), file); a file)
printf("File content: %s\n", buffer);
// Closing the file again
fclose(file);
return 0;
}
Additional Questions:
1. What is recursion Explain with an example?
2. Write a C program to find ACKERMANN function using recursion
3. Write a C program to find Fibonacci series using recursion
4. Write a C program to swap 2 numbers using call by value and call by
reference
5. Write a C program to copy contents of one file to another file
© 𝓣. 𝓤𝓭𝓪y , Assistant Professor , Sasi Institute of Technology and Engineering