Introduction To C Programming Course Materail
Introduction To C Programming Course Materail
COURSE MATERIAL
Introduction to C Programming(BESCK104E)
I SEMESTER, 2022-23
Prepared by
Rajani D
Geetha Shishu Shikshana Sangha(R)
GSSS INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Affiliated to VTU, Belagavi ,Approved by AICTE, New Delhi & Govt. of Karnataka)
K R S Road, Metagalli, Mysuru-570016.
Accredited with Grade ‘A’ by NAAC
VISION
MISSION
M1: Equip students with continuous learning process to acquire Hardware, Software and
Computing knowledge to face new challenges.
M2: Inculcate the core Computer Science and Engineering components with discipline
among the students by providing the state-of-the-art learner centric environment.
M3: To impart essential knowledge through quality and value based education to mould them
as a complete Computer Science Engineer with ethical values, leadership roles by possessing
good communication skills and ability to work effectively as a team member.
PEO3: To provide Computer Science and Engineering graduates to support nation’s self-
employment growth with women entrepreneurial skills.
PEO4: To equip Graduates with minimum research blend for further career
challenges international
PROGRAM OUTCOMES (POs)
Teaching-LearningProcess(GeneralInstructions)
ThesearesampleStrategies,whichteacherscanusetoacceleratetheattainmentofthevariouscourseoutcomes.
1. Lecturer method (L) need not to be only traditional lecture method, but alternative effective
teaching methods could be adopted to attain the outcomes.
2. Use of Video/Animation to explain functioning of various concepts.
3. Encourage collaborative (Group Learning)Learning in the class.
4. Ask atleast three HOT(Higher order Thinking) questions in the class,which promotes critical
thinking.
5. Adopt Problem Based Learning (PBL),which fosters students’ Analytical skills, develop design
thinking skills such as the ability to design, evaluate, generalize, and analyze information rather than
simply recall it.
6. Introduce Topics in manifold representations.
7. Show the different ways to solve the same problem and encourage the students to come up with
their own creative ways to solve them.
8. Discuss how every concept can be applied to the real world-and when that's possible, it helps to
improve the students' understanding.
9. Use https://pythontutor.com/visualize.html#mode=edit in order to visualize the operations of C Programs
Module-1 (6 Hours of Pedagogy)
Introduction to C: Introduction to computers, input and output devices, designing efficient programs.
Introduction to C, Structure of C program, Files used in a C program, Compilers, Compiling and executing C
programs, variables, constants, Input/output statements in C,
Textbook: Chapter 1.1-1.9, 2.1-2.2, 8.1 – 8.6, 9.1-9.14
Teaching-Learning Process Chalk and talk method/Power Point Presentation
Decision control and Looping statements: Introduction to decision control, Conditional branching statements,
iterative statements, nested loops, break and continue statements, goto statement.
Textbook: Chapter 9.15-9.16, 10.1-10.6
Teaching-Learning Process Chalk and talk method/Power Point Presentation
Module-3 (6 Hours of
Pedagogy)
Functions: Introduction using functions, Function definition, function declaration, function call, return
statement,passing parameters to functions, scope of variables, storage classes, recursive functions.
Arrays: Declaration of arrays, accessing the elements of an array, storing values in arrays, Operations
on arrays,Passing arrays to functions,
Textbook: Chapter 11.1-11.13, 12.1-12.6
Reference Books:
1. E. Balaguruswamy, Programming in ANSI C, 7th Edition, Tata McGraw-Hill.
2. Brian W. Kernighan and Dennis M. Ritchie, The ‘C’ Programming Language, Prentice Hall of India.
Module 1: Introduction to C
Computer: A computer in simple terms can be defined as an electronic device that is designed to
accept data, perform the required mathematical and logical operations at high speed and output
the result.
Characteristics of computer:
1. Speed:
2. Accuracy:
A computer is a very fast, reliable and robust electronic device. It always gives accurate results,
provided the correct data and set of instructions are input to it. Hence in the event of an error,
only the user who has fed the incorrect data/program needs be held responsible. If the input is
wrong, then the output will also be erroneous, In computer terminology, this is known as
garbage-in garbage-out(GIGO).
3. Automation:
Computers are automatable devices that can perform a task without any user intervention. The
user just needs to assign the task to the computer, after which it automatically controls different
devices attached to it and executes the program instruction.
4. Diligence:
Unlike humans, a computer never gets tired of a repetitive task. It can continually work for hours
without creating errors.
5. Versatile:
Versatility is the quality of being flexible .Today, computers are used in our daily life in different
fields. For example they are used as personal computers (PCs)for home use, for business-
oriented tasks ,weather forecasting, space exploration,teaching,railways,banking,medicine, and
so on, indicating that computers can perform different tasks simultaneously.
6. Memory:
similar to humans, computers also have memory .Just the way we cannot store everything in our
memory and need secondary media, such as a notebook to record certain important things,
computers also have internal or primary memory(storage space) a s well as external or secondary
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
memory. While the internal memory of computers is very expensive and limited in size the
secondary storage is cheaper and of bigger capacity.
7. No IQ:
Although the trend today is to make computers intelligent by including artificial intelligence (AI)
in them, they still do not have any decision making abilities of their own. That is, their IQ level is
zero. They need guidance to perform various tasks.
8. Economical:
Using computers also reduce man power requirements and leads to an elegant and efficient way
of performing various tasks. Hence, computers save time, energy, and money. When compared
to other systems, computers can do more work in lesser time.
This generation computer is used thousands of vacuum tubes for circuitry for CPU
(Central processing unit)
Memory requirement were met by magnetic drums.
Took lot of space consumed enormous amount of power and generated lot of heat and
also was very expensive.
These computers used machine language.
Some computers of this generation were: ENIAC, EDVAC, UNIVAC etc..
Program input was provided by punch cards and outputs were produced on paper.
Transistors were used that were cheaper, consumed less power, more compact in size,
more reliable and faster.
Magnetic cores were used as the primary memory and magnetic tape and magnetic disks
as secondary storage devices.
These computers used assembly language (programmer could specify words and symbols
as instructions instead of 0’s and 1’s).
Some computers of this generation were: IBM 1620, IBM7094.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
A single IC has many transistors, resistors and capacitors along with the associated
circuitry.
This development made computers smaller in size, reliable and efficient.
In this generation remote processing, times sharing multi-programming operating system
were used.
High level language (FORTRAN, COBOL, PASCAL, BASIC, ALGOL) were used during this
generation.
Keyboard and monitor were used to interact with user.
Memory capacity increased substantially by the use of hard disks for secondary memory.
Some computers of this generation were: IBM360 series, Honeywell-6000 series, and
personal data processor.
Used very large scale integrated (VLSI) circuits having about 5000 transistors and other
circuit elements with their associated circuits on a single chip.
The microprocessor launched the fourth generation of computer, with thousands of
integrated circuits built onto a single silicon chip.
Computers became more powerful, compact, reliable and affordable.
As a result, it gave rise to personal computer revolution, laptops and smart phones
offering gigabytes of memory compared to few megabytes.
In this generation, time sharing, real time networks, distributed operating system were
used the high level languages like C,C++,DBASE etc..Were used in this generation
Fourth generation computers also saw the development of graphical user interface, the
mouse, and handled devices.
With ULS (ultra large scale integration) technology, microprocessor chips having ten
million electronic components were manufactured.
This generation is based on parallel processing hardware and AI.
AI is an emerging branch in computer science which interprets the means and method of
making computers think like human beings.
All the high-level languages like C and C++,java ,.Net etc..are used in this generation .
Neural networks and experts systems have to be developed.
Classification of computer:
Computers are broadly classified into 4 types based on speed, amount of data that they can hold
and price.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
1. Super computer:
The super computer is the fastest, most powerful and most expensive computer.
Supercomputers were first developed in the 1980’s to process large amounts of data and
to solve complex scientific problems.
A single supercomputer can support thousands of users at the same time.
Computers are mainly used for weather forcasting, nuclear energy research, aircraft
design, automotive design, online banking, controlling industrial units, etc.
1. Dumb terminal:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Dumb terminals consist of only a monitor and a keyboard (or mouse).They do not have their own
CPU, memory and use the mainframe systems CPU and storage devices.
2. Intelligent terminals:
Intelligent terminals have their own processor and thus can perform some processing
operations..They do not have their own storage space.
3. Mini computer:
4. Micro computers:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Displaying data
Controlling and coordinating all operations inside a computer.
Input:
This is the process of entering data instructions into the computer system.
The data and instructions can be entered by using different input devices such as
keyboard, mouse, scanner, trackball, etc...
Note that the computers understand binary language, which consist of only two symbols
(0 and 1), so it is the responsibility of the input devices to convert the input data into
binary codes.
Storage:
Storage is the process of saving data and instructions permanently in the computer so that they
can be used for processing.
1. Primary storage:
Primary storage also known as the main memory is the storage area that is directly
accessible by the CPU at very high speed.
Drawback of main memory is that it is volatile in nature that is as soon as the
computer is switched off, the information stored gets erased.
RAM and ROM are the examples of primary storage
RAM:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
ROM:
It stands for read only memory the data stored in these devices are non-volatile i.e. once
the data stored in the memory cannot be modified or deleted.
The memory form which will only read but cannot write.
The information is stored permanently.
There are 3 types
1. PROM (programmable ROM) :Data cannot be altered
2. EPROM(Erasable Programmable ROM): Possible to erase the information
3. EEPROM (electrically Erasable ROM): non-volatile memory used in computers,
usually integrated in microcontroller
1. Secondary storage:
Also known as auxiliary memory this is just the opposite of primary memory.
It basically overcomes all the drawbacks of the primary storage area.
It is cheaper, non-volatile and used to permanently store data and programs of those jobs
that are not being currently executed by the CPU.
Processing:
The process of performing operations on the data as per the instructions specified by the
user(programs) is called processing.
Data and instructions are taken from the primary memory and transferred to the
arithmetic and logical unit, which performs all sorts of calculations.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
The intermediate results of processing may be stored in the main memory as they be
required again.
When processing completes the final result is then transferred to the main memory
.Hence the data may move from main memory to the ALU multiple times before the
processing is over.
Output:
Output is the processing of giving the result of data processing to the outside world.
The results are given through output devices such as monitor, printer etc...
The output devices therefore convert the results available in binary codes into a human-
readable language before displaying it to the user.
Control:
The control unit is the central nervous system of the entire computer system. It manages and
controls all the components of the computer system.
CPU
Memory
unit/storage unit
ALU (arithmetic
and logical unit
An input device is used to fees data and instructions into the computer. In the absence of an input
device, a computer would have only been a display device.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Input devices
Track pad
Joystick
OCR
OMR
MICR
Keyboard:
The keyboard is the main input device for computers. Computer keyboards look very
similar to the keyboards of typewriters with some additional keys.
Most keyboards have between 80 and 110 keys.
The layout of a keyboard is known as QWERTY for its first six letters.
Types of keys:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Pointing devices:
Pointing input devices enable the users to easily control the movement of the pointer to
select items on a display screen to select commands menu, to draw graph, etc...
Some examples of pointing devices include mouse, track ball, light pen joystick and
touch pad
Mouse:
The mouse is an input device that was invented by Douglas Engelbart in 1963.
It is the key input device used in a graphical user interface
It can be used to handle the pointer easily on the screen to perform various functions such
as opening a program or file.
The mouse has two buttons and a scroll wheel. It can be held in the hand and easily
moved without lifting, along a hard flat surface to move the cursor to the desired
location-up, down, left, right.
Once the mouse is placed at appropriate postion,the user may perform the following
operation:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
o Point: Placing the mouse pointer over the word or the object on the screen by
moving the mouse on the desk is termed as pointing.
o Click: pressing either the left or the right button of the mouse is known asclicking.
o Drag: Pointing to a desired location while pressing the left button.
The most popular Mouse types are:
1. Mechanical mouse:
This type of mouse has a rubber or metal ball at its bottom and an electronic circuit
containing sensors.
When the mouse is moved over a flat surface, the sensor detects the direction of
movement of the ball.
The electronic circuit translates the movement into signals and feed it as input to the
computer.
2. Optical mouse:
3. Cordless mouse:
A cordless or wireless mouse is not connected to the computer. The movement of the
mouse is detected using radio waves or infrared light.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Track ball:
A trackball is a pointing device that is used to control the position of the cursor on the
screen. It is usually used in notebook computers, where it is placed on the keyboard.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Touchpad:
A touchpad (track pad) is a small, flat, rectangular stationary pointing device with a
sensitive surface of 1.5-2 square inches.
The user has to slide his or her fingertips across the surface of the pad to point to a
specific object on the screen.
The surface translates the motion and position of the users fingers to relative position on
the screen.
There are also button around the edge of the pad that work like mouse buttons.
Touch pad are widely used in laptops and are in built on the laptop keyboard.
Handheld device:
Joystick:
A joystick is a cursor control device widely used in computer games and computer aided design
(CAD)/computer aided manufacturing (CAM) applications.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Stylus:
A stylus is a pen-shaped input device used to enter information or write on the touch
screen of a handheld device.
It is a small stick that can also be used to draw lines on a surface as input into a device
choose an option from a menu, move the cursor to another location on the screen.
Touch screen:
A touch screen is a display screen that can identify the occurrence and position of a touch
inside the display region.
The user can touch the screen either by using a finger or a stylus.
The touch screen facilitates the users to interact with what is displayed on the screen in a
straightforward manner, rather than in an indirect way by using a mouse or a touchpad.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Optical devices:
Optical devices also known as data-scanning devices use light as a source of input for
detecting or recognizing different objects such as characters, marks, codes and images.
The optical device converts these objects into digital data and sends it to the computer for
further processing
Barcode reader:
A barcode reader is a handheld input device that ais used to capture and read information
stored in a barcode
It consists of a scanner a decoder and a cable used to connect the reader to a computer.
The function of the barcode reader is to capture and translate the barcode into numerical
and/or alphabets.
It is connected to computer for further processing of the captured information.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Image scanner:
A scanner is a device that captures images, printed text and handwriting from different sources
such as photographic prints, posters and magazines and converts them into digital images for
editing and displaying on computer.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Optical character recognition is the process of converting printed materials into text or word
processing files that can be easily edited and stored.
Optical mark recognition is the process of electrically extracting data from marked fields
such as checkboxes and fill in fields on printed forms.
The optical mark reader is fed with an OMR sheet that has pen or pencil marks is pre-
defined positions to indicate each selected response marks and space and stores the
interpreted data in a computer for storage analysis and reporting
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Magnetic ink character reader is used tto verify the legitimacy of paper documents
especially bank checks.
It consists of magnetic ink printed characters that can be recognized by high speed
magnetic recognition devices.
Audio devices:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Video input devices are used to capture video from the outside world into the computer.
Digital camera and webcam are the popular examples of video input device.
A digital camera is a handheld and easily portable device used to capture images or
videos.
The digital cameras digitalize images or video and store them on a memory card.
Web cameras too capture videos that can be transferred via the internet in real-time.
Web cameras are widely used for video conferencing
Digital camera
Web came
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Output devices:
Output devices
Monitor: The monitor is an integral part of computer which displays both text and
graphics. The performance is measured in terms of image quality, resolution, energy
consumption.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Printer: Printer is an output device that prints any data, report, document, picture, diagram
etc. Printers are classified into:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
1. Dot-Matrix Printer: The print head of the dot-matrix printer has either 9 or 24
pins. When the pins fire against the ribbon, an impression is created on the paper.
The speed is 300 cps and doesn’t produce high quality output. It can produce
multiple copies.
3. Line Printer: For heavy printing, the line printer is used. It uses a print chain
containing the characters. Hammers strike the paper to print and it rotates at the
speed of 1200 lpm. It is also noisy and is of low-quality.
Non-Impact Printers: They are fast, quiet and of high resolution. The most
commonly used non- impact printers are laser and ink-jet printers. The thermal printer is
not discussed here because it uses heat to print on high-sensitive paper.
1. Laser Printer: It works like a photocopier and uses toner i.e. black magnetic
powder. The image is created in the form of dots and passed from drums on to the
paper. It has built-in RAM which acts as buffer and RAM to store fonts. The resolution
varies from 300 dpi to 1200 dpi and the speed is about 20 ppm.
2. Ink-jet Printer: These are affordable printers. It sprays tiny drops of ink at high
pressure as it moves along the paper. The separate cartridges are available for
different colors. The resolution is about 300 dpi, can print1 to 6 pages/min.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Printer:
Printers
Plotters: The plotter can make drawings. It uses one or more automated pens. The
commands are taken from special file called vector graphic files. Depending on type of
plotter either paper or pen moves. It can handle large paper sizes and it is used for
creative drawings like buildings and machines. They are slow and expensive.
Speakers: The speaker is an output device which produces the voice or sound waves.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Projector: The projector is the by-pass device for the monitor where it produces larger
images or pictures
Applications of computers:
Internet:
The internet is a network of networks that connects computers all over the world.
It gives users access to an enormous amount of information, much more than available in
any library.
Government:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Music:
All computers today have musical instrument digital interface facility, which links
musical instruments to a PC, thereby enabling the computers to generate a variety of
sounds.
Movies:
Computers are used to create sets, special effects, animations, cartoons, imaginary characters,
videos and commercials.
Computers are used to prepare tickets, monitor the trains or airplanes route and guide the plane
to a safe landing.
In business and industry, computers are used and mainly for data processing, which includes
tasks such as word processing, analyzing data entering records, pay roll processing, personnel
record keeping and inventory management.
Hospitals:
Hospitals use computers to records every information about patients from the time of their
admission till their exit.
Weather forecasting:
When computers are fed with mathematical equations along with data about air pressure,
temperature, humidity, and other values, the solution of these equations given an accurate
prediction of the weather of a particular area.
Online banking:
Introduction to C programming:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
C is a powerful language that provides fast program execution. Its power and fast
program execution come from its ability to access low commands similar to assembly
language but with high level syntax.
History of C language:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Features of C language:
Simple robust:
C is a general purpose, structured programming language. It has the simplicity of a high level
language as well as the power of low level language. This aspect of c makes it suitable for
writing both application programs and system programs. Hence it is an excellent, efficient and
general purpose language for most of the application such as mathematical, scientific, business
and system software applications.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
C languages consist of 32 English words known as keywords. The power c lies in a rich set of
built in library functions and variety of operation.
Modularity:
C programs are modular in nature it supports compartmentalization of code and data. This
capability makes it very easy for c-programs to share sections of code. We can divide c programs
to several modules that will combine in a single module to build the final program.
Extensibility:
The c language is extensible since it allows the users to add their own library function to the
library function .section of code or modules can be stored in libraries for re-use them in future.
Portability:
C program written on one computer or operating system can be compiled and run on another
computer or operating system with little or no modification.
The compilation and execution of c programs are faster than modern programming languages.
This is due to its variety of data type and powerful operators.
Bit manipulation:
It provides wide variety of bitwise operators to manage data at bit level. We can perform
different operations at bit level
Documentation Section: It consists of a set of comment line giving the name of the
program, theauthor and other details. Compiler ignores these comments. Comment is a
short description of the problem to be solved which is written at beginning of each
program. There are two formats:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Syntax: //
b) Block comments /*Multi line comment*/: It is used when comments as several line.
Link Section: It provides instruction to the compiler to link functions from system
library.
Every c program is made of one or more pre-processor commands.
#include<stdio.h>
#include<conio.h>
#include<math.h>:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Every ‘C’ program has one main ( ) function and it contains two parts:
Sub-program Section: It contains all the user defined functions that are called by main( )
function.
Documentation section
Link section
Definition section
Global declaration section
main( ) Section
{
Declaration part
Executable part
}
Sub program section
Function 1
Function 2
-
-
Function n
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Example:
The c program is written using vi editor or text editor .Most language compilers have their
built-in editors. The program or source code should be written in the syntax provided by that
language. In c a source code file has extensions.
Linker assembles the entire libraries which are necessary for the program but existing
somewhere else. The system uses object code as input and translates it to executable code.
4. Executing programs(file.exe) :
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Executable file is ready to run file. Loader loads the executable file into the main/primary
memory and run program.
program using
Compilers:
A compiler is a program that translate the instruction of high level language (source code)
into machine language (object language)
A compiler is a program or set of programs that converts source code written in a high
level language to low level language (assembly language or machine language)
A programming language can have many compilers. For example, GCC,turbo C,Quick C
etc.. are different compilers for C programming language.
Need of computer:
A computer understands only binary language and executes instructions coded in binary
language. It cannot execute a single instruction given in any other form. Therefore we
must provide instructions to the computer in binary language.
Means we must write computer programs entirely in binary language and it is not
possible to write the program in binary language.’
So there was a need of a translator that translates the compiler instructions given in
English language to binary language.
Compiler interpreter
Compiler takes entire program as input Interpreter takes single instructions as input
Compiler generates object code Interpreter is not generates object code.
No source code is required in executable file Source code is required in executable file
Programming language like C,C++,C# uses Programming language like python ,ruby uses
compilers interpreters.
Compiler translates entire program at a time Interpreter translates program line by line
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Letter: A-Z,a-z
Digits: All decimal digit 0-9.
Special characters: . ; : , $ # ^&-+=
Whitespace: enter space, horizontal tab.
C tokens:
Tokens: token are the smallest unit of a program which are made up of one or more characters.
1. keywords:
Keywords are meant for some special purpose called as reserved words.
User cannot change the meaning of keywords.
Example:
Identifiers:
Identifiers are the names given to the elements of the program such as variable name ,
name or a function name.
An identifier is a word consisting of sequence of one or more letters or digits or a special
symbol called as _(underscore)
Rules:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Constants:
Constants are the data values that cannot be change during the execution of a program.
Operators:
Special symbol:
Special symbols have some special meaning in the c programming language for the compiler and
it is used to perform some special function\task in c.
Data types:
Data types: Data type defines the types of data that is stored in a variable.
There are 3 types:
i. Primary/ Built-in/ Fundamental data type int , float, double, char, void
ii. Derived data type array, structure
iii. User defines data type enum , type def
Primary/ Built-in/ Fundamental data type: These are the built in data types
available in C. There are5 types. Namely:
1. Integer (int)
2. Floating point (float)
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
3. Character (char)
4. Double precision floating point (double)
5. Void (void)
1. Integer type:
It is used to store whole numbers.
The keyword int is used to declare variable of integer type.
Int type takes 2B or 4B of storage depending on machine size.
The classes of integer are:
Unsigne Signe
d d
Data type Keyword Size Data type Keyword Size
Short Integer short int 1B Signed short integer signed short int 1B
Integer int 2B Signed integer signed int 2B
Long Integer long int 4B Long integer long int 4B
3. Double:
It is used to store double precision floating point numbers.
The keyword double is used to declare variable of floating point data type.
Double type takes 8B of storage.
Double precision is related to accuracy of data.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
4. Char:
It is used to store character type of data.
The keyword char is used to declare variable of character type.
Char type takes 1B of storage.
5. Void:
It is a special data type that has no value.
It doesn’t have size.
It is used for returning the result of function that returns nothing.
Variable A variable is a name given to memory location whose value changes during
execution.
Types of variables:
1. Numeric variable: numeric variable can be used to store either integer values or floating
point values.
2. Character variable:
Character variable can include any letter from the alphabet or from the ASCII chart and
number from 0-9 that are given within single quotes.
Declaration:
Where,
datatype Any built in data type
variable_list Identifiers that specifies variable name.
Example: int a;
Where,
int is the built in data type
a is variable of type int
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
1. Name should only consist of alphabets (both upper and lower case ),digits and underscore
sign.
2. First characters should be alphabet or underscore.
3. Name should not be a keyword.
4. Since C is a case sensitive the upper case and lower case considered differently for
example code ,Code<CODE etc..Are different identifiers.
5. As C defined up to 32 significant characters can be used and will be considered
significant by most compilers. If more than 32 are used they will be ignored by the
compiler.
6. No white space is used.
Initialization:
Syntax: datatype variable_name = value;
Where,
datatype Any built in data type
variable_name Identifier that specifies variable name.
value The data which will be stored in variable name.
Identifiers Variables
All identifiers are not variables All variables are identifiers
Identifiers may not have any All variables have memory.
memory unless it is a variable
Mentioning the type of an Type of the variable must be
identifier it not needed unless it is defined.
a variable
Constants:
Constants or a literal refers to fixed values that do not change during the execution of a
program.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Constants are treated just like regular variables except that their values cannot be
modified after their definition.
C supports several types of constants as shown
Numeric constants:
Numeric constants consist of numeric digits they may or may not have decimal point.
The rules for defining numeric constants are as follows:
1. Numeric constant should have at least one digit.
2. No comma or space is allowed within the numeric constant.
3. Numeric constant can either be positive or negative but default sign is always positive.
4. The value of a constant cannot exceed specified minimum and maximum bounds.
There are two types of numeric constants namely, integer constant floating point constant.
1. Integer constants:
Integer constants are whole numbers without any fractional part or decimal point. It must have at
least one digit and may contain either + or – sign. A number with no sign is assumed to be
positive.
There are 3 types of integer constants:
1. Decimal integer constants (base 10):
The interpretation of a floating point constant with an exponent is essentially the same as
scientific notation, except that the base 10 is replaced by the letter E or e.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
2. Character constants:
A character constant contains one single character enclosed within single quotes (‘’)
Example:
‘a’, ’Z’,’\n’
3. String constants:
String constant are sequence of character enclosed within double quotes (‘””).
Example:
“hello”,”1234”,”abc”,”\n”
Declaring constants:
1. To declare a constant precede the normal variable declaration with const keyword and
assign it a value.
Syntax: const data type constant value
Example: const float Pi=3.142
2. Another way is to use the preprocessor command define.
Syntax: #define const value
Example:
#define PI 3.142
Constants
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Files used in C
Source file:
The source code file contains the source code of the program.
The file extension of any C source code file is ‘.c’. This file contains C source code that
define the main function and may be other functions. The main () function is the starting
point of execution when you successfully compile and run the program.
Header file:
When working with large projects, it is often desirable to separate out certain sub routines
from the main () of the program.
There also may be a case that the same subroutine has to be used in different programs. In
the latter case one option is to copy the code of the desired subroutine from one program
to another. However copying the code is often tedious as well as error-prone and makes
maintainability more difficult.
Example:
Object file:
Object files are generated by the compiler as a result of processing the source code file. They
contain compact binary code of the function definition. Linker uses this object file to produce an
executable file (.exe file) by combining the object files together. Object file have a ‘.o’
extension.
We use the scanf() function for getting the formatted inputs or standard inputs so that the printf ()
function can provide the program with numerous options of conversion.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
We use this function for displaying a single or multiple values in the form of output for the user
end at the console.
Syntax:
Example:
#include <stdio.h>
int main()
{
int i;
float f;
char c;
printf("You entered:\n");
printf("i = %d, f = %f, c = %c\n", i, f, c);
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
The code in c program is executed sequentially from the first line of the program to its
last line, i.e., the second statement is executed after the first, the third statement is
executed after the second and so on..
C support two types of decision control statements that can alter the flow of sequence of
instructions. These include conditional and unconditional branching.
Selection /branching
statements
Conditional Unconditional
type type
Conditional statements:
The conditional branching statements help to jump from one part of the program to
another depending on whether a particular condition is satisfied or not.
1. if statement
3. if-else ladder
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
4. Nested if
5. Switch
1. if statement:
The if statement is the simplest form of decision control statements that is frequently used in
decision making.
Syntax:
Test false
if ( test Expression) expression
{
Statement1;
}
true
Statement2;
Statement block 1
Statement X
The if structure may include one statement or n statements enclosed within curly
brackets. First the test expression is evaluated.
If the test expression is true, the statement of if block (statement 1 to n)are executed,
otherwise these statements will be skipped and the execution will jump to statement.
The statement in an if construct is any valid c language statement and the test expression
is any valid C language expression that may include logical operators. Note that there is
no semicolon after the test expression .This is because the condition and statement should
be placed together as a single statement.
Example:
#include <stdio.h>
int main () {
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
int a = 10;
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
return 0;
}
Output:
2. if-else statement:
The if-else statement is an extension of simple if statement.
The test expression is evaluated, if the result is true, the statement followed by the
expression is executed else if the expression is false, the statement is skipped by the
compiler.
Syntax:
Test
expression
if (test Expression)
{
Statement1; true-block
}
else
{
Statement2; true-block Statement block 1 Statement block 1
}
Statement X;
Statement block X
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
If the Expression is true (or non-zero) then Statement1 will be executed; otherwise if
it is false (or zero),then Statement2 will be executed.
In this case either true block or false block will be executed, but not both.
Example:
#include <stdio.h>
int main () {
return 0;
}
Output:
3. Nested if .. else statement: When a series of decisions are involved, we have to use more than
oneif..else statement in nested form as shown below in the general syntax.
Syntax:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
if (Expression1)
{
if(Expression2)
{
Statement1;
}
else
{
Statement2;
}
}
else if(Expression3)
{
Statement3;
}
else
{
Statement4;
}
If Expression1 is true, check for Expression2, if it is also true then Statement1 isexecuted.
Once we start nesting if ..else statements, we may encounter a classic problem known as
dangling else.
C solution to this problem is a simple rule “always pair an else to most recent
unpaired if in the currentblock”.
Example:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
#include <stdio.h>
int main()
int age;
scanf("%d",&age);
if ( age < 18 )
else
else
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
return 0;
4. if –else ladder:
There is another way of putting ifs together when multipath decisions are involved. A multi path
decision is a chain of ifs in which the statement associated with eachelse is an if.
syntax:
if (Expression1)
{
Statement1;
}
else if(Expression2)
{
Statement2;
}
else if(Expression3)
{
Statement3;
}
else
{
Statement 4;
}
Next Statement ;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
The conditions are evaluated from the top (of the ladder), downwards. As soon as true
condition is found, the statement associated with it is executed and control transferred to
the Next statement skipping the rest of the ladder.
When all conditions are false then the final else containing the default Statement4 will be
executed.
It is not necessary that every if statement should have an else block as C supports simple if
statements. After the first test expression or the first if branch, the programmer can have as
many else-if branches as he wants depending on the expressions that have to be tested.
Example:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
#include<stdio.h>
void main( )
{
int a=20, b=5,c=3;
if((a>b) && (a>c))
printf(“A is greater\n”);
else if((b>a) && (b>c))
printf(“B is greater\n”);
Output:
A is greater
switch(choice)
{
case label1: block1;
break;
case label2: block2;
break;
case label3: block-3;
break;
default: default-block;
break;
}
Here switch, case, break and default are built-in C language words.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
If the choice matches to label1 then block1 will be executed else if it evaluates to label2
then block2will be executed and so on.
If choice does not matches with any case labels, then default block will be executed.
Each of these case labels should be unique within the switch statement. block1,
block2, block3,are statement lists and may contain zero or more statements.
There is no need to put braces around these blocks. Note that case labels end with colon
(:).
Break statement at the end of each block signals end of a particular case and
causes an exit fromswitch statement.
The default is an optional case when present, it will execute if the value of the choice
does not matchwith any of the case labels
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Example:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
} printf(“Result=%d\n”,res);
}
In this program if ch=1 case ‘1’ gets executed and if ch=2, case ‘2’ gets executed and so on.
Iterative statements:
Iterative statements are used to repeate the execution of a list of statements,depending on the
value of an integer expression. C language supports 3 types of iterative statements also know as
“looping statements”.They are
1. While
2. Do-while loop
3. For loop
The while loop provides a mechanism to repeate one or more statements while a
particular condition is true.
In while loop the condition is tested before any of the statements in the statement block is
executed.If the condition is true , only the the statements will be executed otherwise if the
condition is false,the control will jump to statement Y ,which is the immediate statement
outside the while loop block.
From the flow chart diagram ,it is clear that we nee dto constantly update the condition of
the while loop.’
Note that if the condition is never update and the condition never becomes false then the
computer will run into an infinite loop which is never desirable.
A while loop is also referred to as a top-checking loop since the contol condition is
placed as the first line of the code.If the control condition evaluates to false ,then the
statements enclosed in the loop are never executed.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Statement X
Syntax:
Statementx;
while (condition)
{ Update the conditio
statement-block; condition n
}
Statement Y;
Statement block false true
Statement Y
Example:
#include <stdio.h>
int main () {
return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
value of a: 18
value of a: 19
do-while: It is a post-test loop (also called exit controlled loop) it has two keywords do and
while. The General syntax:
Statement X
do
{
statement-block;
}while(condition);
Statement Y
Statement X
Statement block
Update the
condition
expression
true
condition
false
Statement Y
The do-while loop is similar to the while loop. The only difference is that in do-while
loop, the test condition is tested at the end of the loop. Now that the test condition is
tested at the end, this clearly means that the body of the loop gets executed at least once.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Note that the test condition is enclosed in parentheses and followed by a semicolon. The
statement blocks are enclosed within curly brackets. The curly bracket is optional if there
is only one statement in the body of the do-while loop.
The major disadvantage of using a do-while loop is that it always executes at least once,
even if the user enters some invalid data, the loop will execute. One complete execution
of the loop takes place before the first comparison is actually done.
Example:
#include <stdio.h>
int main () {
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
for loop:
Similar to the while and do-while loops, the for loop provides a mechanism to repeat a
task until a particular condition is true.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
For loop is usually known as determinate or definite loop because the programmer knows
exactly how many times the loop will repeat.
The number of times the loop has to be executed can be determined mathematically by
checking the logic of the loop.
When a for loop is used, the loop variable is initialized only once. With every iteration of
the loop, the value of the loop variable is updated and the condition is checked. If the
condition is true, the statement block of the loop is executed, else the statements
comprising the statement block of the for loop are skipped and the control jumps to the
immediate statement following the for loop body.
In the syntax of for loop, initialization of the loop variable allows the programmer to give
it a value. Second, the condition specifies that while the condition expression is TRUE
the loop should continue to repeat itself. Every iteration of the loop must make the
condition near to approachable. So, with every iteration the loop variable must be
updated.
Syntax:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
false
Controlling
condition for
true
Statement block
Statement Y
Example:
#include <stdio.h>
int main () {
int a;
return 0;
}
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Nested loop:
Loop that can be placed inside other loops. Although this feature will work with any loop
such as while, do-while and for but it is most commonly used with the for loop, because
it this is easiest to control.
A for loop can be used to control the number of times that a particular set of statements
will be executed. Another outer loop could be used to control the number of times that a
whole loop is repeated.
Syntax:
The syntax for a nested for loop statement in C is as follows −
for ( init; condition; increment ) {
The syntax for a nested while loop statement in C programming language is as follows −
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
while(condition)
{ while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows −
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
NOTE: A final note on loop nesting is that you can put any type of loop inside any other type of
loop
Example:
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf(“%d”, &a[i][j])
}
}
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Jumping statements:
Break and continue: break and continue are unconditional control construct.
1. Break
In switch statement if the break statement is missing then every case from the matched case label till
the end of the switch, including the default is executed.
Syntax Example
#include<stdio.h>
while(condition) void main( )
{ {
Statements; int i;
if(condition) for(i=1; i<=5; i++)
{
break;
if(i==3)
Statements; break;
} printf(“%d”, i)
OR }
for(){ statem }
ents; if
(condition) OUTPUT 12
break;
statements;
}
OR
do{
if (condition)
break;
}while(condition);
2. Continue
Similar to the break statement the continue statement can only appear in the body of a
loop. When the compiler encounters a continue statement then the rest of the statements
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
in the loop are skipped and the control is unconditionally transferred to the loop-
continuation portion of the nearest enclosing loop.
Syntax Flowchart
#include<stdio.h>
while(condition) void main( )
{ {
Statements; int i;
if(condition) for(i=1; i<=5; i++)
continue; {
Statements; if(i==3)
} continue;
OR printf(“%d”, i)
for(){ statem }
ents; if }
(condition)
continue; OUTPUT 1 2 4 5
statements;
}
OR
do{
if (condition)
continue;
}while(condition);
GOTO statement:
The goto statement is used to transfer control to a specified label. However the label must
reside in the same function and can appear only before one statement in the same
function.
Here, label is an identifier that specifies the place where the branch is to be made. Label
can be any valid variable name that is followed by a colon (:). The label is placed
immediately before the statement where the control has to be transferred.
The label can be placed anywhere in the program either before or after the goto
statement. Whenever the goto statement is encountered the control is immediately
transferred to the statements following the label. Therefore goto statement breaks the
normal sequential execution of the program.
If the label is placed after the goto statement , then it is called a forward jump and in case
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Syntax Example
goto void main( )
{
label; int a=5,
b=7;
statement; goto end;
a=a+1;
statement; b=b+1;
end: printf(“a=%d b=%d”, a,b);
label: }
OUTPUT: 5,7
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
CBESCK104E
Module 3: Functions
Every C program should consist of one or more functions. Among these functions main ( )
function iscompulsory. All programs start execution from main ( ) function.
Functions: Functions are independent program modules that are designed to carry out a
particular task.
A large program can be divided into manageable pieces called modules where each module does
a specific task. Thus, the functions often called modules are self-contained small programs that
carry out some specific, well defined tasks. Functions act like building blocks using which any
desired activity can be performed by combining one or more function.
main ()
{ func1 ()
------------------- {
------------------- Statement block;
func1 (); }
return 0;
}
From the figure we see that main () calls the function named func1().Therefore , main 0 is
Known as the calling function and func1() is known as the called function.
The moment the compiler encounters a function call, instead of executing the next
statement in the calling function, the control jumps to the statements that are a part of the
called function. After the called function is executed, the control is returned back to the
calling program.
It is not only the main () function that can call other function. A function can call any
other function. One function calling another and this function in turn calling some other
function.
GSSSIETW,MYSURU
There are two types:
1. Built-in (Library) functions
2. User defined functions
1. Built-in functions: These are C language functions already available with C compliers
and can beused by any programmers.
Ex: printf( ),scanf( )
2. User-defined functions: These are written by programmers for their own purpose and are
not readilyavailable.
Advantages of function:
The existing function can be re-used as building blocks to create new programs. This results in
reduced program size .These functions can be used any number of time.
Programs can be written easily and we can keep track of what each function is doing.
A large program is divided into smaller sub programs so that each sub program performs a
specific task. This approach makes the program development more manageable.
Easier debugging:
Using modular appoarch, localizing, locating and isolating a faulty function is much easier.
Function sharing:
#include<stdio.h>
void add()
int a,b,sum;
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“%d”,sum);
return;
void main()
add();
return;
After the declaration of every function there should be a semicolon. if the semicolon is
missing ,the compiler will generate an error message.
The function declaration is gobal.Therefore the declared function can be called from Any
point in the program.
A function called be declared within the body of another function.
A function having void as its return type cannot return any value.
A function having void as its parameter list cannot accept any value. So the function
declared as
void print(void); or void print();
if the function declaration does not specify any return type, then by default, the function
returns an integer value. Therefore when a function is declared as
Then the function sum() accepts two integer values from the calling function and in turn
returns n integer value to the caller.
Some compiler makes it compulsory to declare the function before its usage while other
compilers make it optional. However, it is good to always declares make function before
its usage as it allows error checking on the arguments in the function call.
NOTE: the variable names used in the function prototype and the variable names used in
function definition can be different. But the number of parameters type of parameters and the
order of parameters must be same.
Function definition:
The program module that is written to achieve a specific task is called function definition.
Each function definition consists of two parts. Namely:
Function header
Function body
Syntax:
}
Note: The first line function_type function_name(parameter list) is known as the function
header and thestatements within opening and closing braces is known as the function body.
i. Function Header: It consists of three parts: Function type, function name and
list of paraemeters.The semicolon is not present at the end of header.
Function type:
The function type specifies the type of value that the function is expected to
return to the callingfunction.
If the return type or function type is not specified, then it is assumed as int.
If function is not returning anything, then it is void.
Function name: The function name is any valid C identifier and must follow same rules
as of othervariable.
List of Parameters: The parameter list declares the variables that will receive the data
sent by the callingprogram which serves as input and known as Formal Parameter List.
ii. Function Body: The function body contains the declarations and statements
necessary forperforming the required task. The body is enclosed in braces, contains
three parts:
The number and order of arguments in the function header must be same as that given in the
function declaration statement.
The function header is same as that of the function declaration. The only difference between the
two is that list of variables is not followed by semicolon. The list of variables in the function
header is known as the formal parameters list. The parameter list may have zero or more
parameters of any data type. The function body contains instructions to perform the desired
computation in a function.
Function call:
The function call statement invokes the function. When a function is invoked the compiler jumps
to the called function to execute the statements that are a part of that function.
Syntax:
Example:
#include<stdio.h>
int main()
int num1,num2,total=0;
scanf(“%d”,&num1);
scanf(“%d”,&num2);
printf(“\n total=%d”,total);
{ //FUNCTION BODY
int result;
result=a+b;
return result;
Output:
Enter the first number: 20
Enter the second number: 10
Formal parameter: The variables defined in the function header of function definition are
called formal parameters. All the variables should be separately declared and each declaration
must be separated by commas.
Actual parameter: the variables that are used when a function is invoked are called actual
parameters. Using the actual parameters the data can be transferred to the function. The
corresponding formal parameters in the function definition receive them. The actual parameters
and formal parameters must match in number and type of data.
Example:
#include<stdio.h>
return a+b;
void main()
int m,n,res;
scanf(“%d %d”,&m,&n);
printf(“%d %d %d”,m,n,res);
return;
}
Actual parameters are used in calling function Formal parameters are used in the function
when a function is invoked. header of a called function.
Example: Example:
Actual parameters can be constants, variables Formal parameters should be only variables.
or expressions. Expressions and constants.
Example: Example:
Actual parameter sends values to the formal Formal parameters receive values from the
parameters. actual parameters.
Example: Example:
Pass by value:
In pass by value the values of actual parameters are copied into formal parameters i.e formal
parameters contain only the copy of actual parameters. So, even if the values of the formal
parameters changes in the called function, the values of the actual parameters are not changed.
Advantage:
Disadvantage:
It does not allow information to be transferred back to calling function via arguments.
Thus, pass by value is restricted to one-way transfer of information from calling function
to called function.
Example:
#include<stdio.h>
void swap( int m,int n)
{
int temp;
m=n;
n=temp;
}
void main()
{
int a,b;
a=10,b=20;
swap(a,b);
printf(“”a=%d and b=%d\n”,a,b);
}
Output:
a=10,b=20
NOTE: In pass by value any change done on formal parameters will not have any effect on
actual parameters.
Pass by reference:
In pass by reference when a function is called the address of actual parameters are sent. In the
called function, the formal parameters should be declared as pointers with the same type as the
actual parameters. The addresses of actual parameters are copied into formal parameters. Using
these addresses the values of the actual parameters can be changed. This way of changing the
actual parameters indirectly using the address of actual parameters is called pass reference.
Example:
#include<stdio.h>
void swap( int *m,int* n)
{
int temp;
temp=*m;
*m=*n;
*n=temp;
}
void main()
{
int a,b;
a=10,b=20;
swap(&a,&b);
printf(“”a=%d and b=%d\n”,a,b);
}
Output:
a=20,b=10
Storage classes:
The storage class of a variable defines the scope and lifetime of variables and/or
functions declared within a C program.
The storage class of a function or a variable determines the part of memory where storage
space will be allocated for that variable or function.
It specifies how long the storage allocation will continue to exist for that function or
variable.
Syntax of storage class:
Storage class
The various storage classes in C language are classified as:
1. Automatic(local variable):
Local variables are the variables which are defined within a function. These variables are
also called automatic variables. All variables must be defined before the first executable
in the function. Whenever control enters into the function memory is allocated for the
local variables and whenever control goes out of the function memory will de-allocated.
That is the reason the local variables cannot be accessed by any other function. The local
variables have the following feature:
These variables cannot be accessed by any function and are alive and active within the
function.
The scope of these variables is limited only to the function in which they are
declared and cannot be accessed outside the function.
No other function can use a local variable and change its value.
The auto is the default storage class for all local variables.
Example:
#include <stdio.h>
void func1()
{
int a=10;
printf(“\n a =%d”,a);//auto integer local variable
}
void func2()
{
int a=20;
print(“\n a =%d”,a);//auto integer local to func2()
}
void main()
{
int a=30; //auto integer local to main()
func1();
func2();
printf(“\n a =%d”,a);
}
2. Static:
Static the default storage class for global variables. The variable that are declared using
the keyword static are called static variable. The static variable can be declared outside
the function or within the function. They have the characteristic of both local and global
variable. The declaration of static variable should begin with the keyword static.
3. Register :
When a variable is declared using register as the storage class. It is stored in a
CPU register instead of RAM .since the variable is stored in RAM, the maximum
size of the variable is equal to the register size.
One drawback of using a register variable is that they cannot be operated using
the unary’&’ operator because it does not have a memory location associated with
it.
Example:
#include<stdio.h>
int exp(int a,int b);
main()
{
int a= 3,b=5,res;
res=exp(a,b);
printf(“\n%d to the power of %d=%d”,a,b,res);
getch();
return 0;
}
int exp(int a,int b)
{
Register int res=1;
int i;
for(i=1;i<b;i++)
res=res*b;
return res;
}
Out put:
3 to the power of 5=243
4. Extern :
The extern storage class is used to give reference of a global variable that is visible to all
the program files. Such global variables are declared like any other variable in one of the
program file. When there are multiple files in a program and you need to use a particular
function or variable in a file apart from which it is declared then use the keyword extern.
Example:
int x;
Void print(void);
int main()
{
x=10;
printf(“\n x in FILE1=%d”,x);
print();
return 0;
}
#include<stdio.h>
extern int x;
void print()
{
Printf(“\ x in FILE2=%d”,x);
}
main()
{
Statements;
}
Output:
X in FILE1=10
X in FILE 2=10
Comparision of storage classes:
Categories of function:
Based on parameters and return value the functions are categorized as
1. Function with no parameters and no return value
This category is also called “void function with no parameters”. In this category, there is
no data transfer between the calling function and called function.so, calling function
cannot send values and called function cannot receive the data.
Example :
2. Function with no parameters and return values:
In this category there is no data transfer from the calling function to the called function.
But, there is data transfer from called function to the calling function. When the function
returns a value, the calling function receives one value from the called function.
Example :
4. Functions with parameters and return values:
In this category there is data transfer between the calling function and called function.
When parameters are passed, the called function can receive values from the calling
function. When the function returns a value the calling function can receive a value from
the called function.
Example :
Return statement:
The return statement is used to terminate the execution of a function and returns
control to the calling function. When this statement is encountered the program
execution resumes in the calling function at the point immediately following the
function call.
A return statement may or may not return a value to the calling function.
Example:
#include<stdio.h>
#include<conio.h>
int check-relation(int a,int b);
main()
{
int a=3,b=5,res;
res=check_relation(a,b);
if(res==0)
printf(“\n EQUAL””);
if(res==1)
printf(“\n a is greater than b”);
if(res==-1)
printf(“\n a is less than b”);
getch();
return 0;
}
int check_relation (int a, int b)
{
if(a==b)
return 0;
if(a>b)
return 1;
else if (a<b)
return -1;
}
Output:
a is less than b
Scope of variables:
The accessibility and visibility of the variables at different point in the program.
A variable or a constant in c has four types of scope: block, function, file and program scope.
Block scope:
The statement block is a group of statements enclosed within opening and closing curly
brackets({}).If a variable is declared within a statement block then ,as soon as the control
exits that block, the variable will cease to exit. Such a variable also known as a local
variable is said to have a block scope.
Example:
#include <stdio.h>
int main()
{
int x=10;
int i=0;
printf(“\n the value of x outside the while loop is %d”,x);
while(i<3)
{
int x=i;
printf(“\n the value of x inside the while loop is %d
”,x);
i++;
}
printf(“\n the value of x outside the while loop is %d ”,x);
return 0;
}
Output:
the value of x outside the while loop is 10
the value of x inside the while loop is 0
the value of x inside the while loop is 1
the value of x inside the while loop is 2
the value of x outside the while loop is 10
Function scope:
Function scope indicates that a variable is active and visible from the beginning to the
end of a function.
In C only the goto label has function scope. In other words function scope is applicable
only with goto label names. This means that the programmer cannot have the same label
name inside a function.
Example:
int main()
{
return 0;
In this example, the label loop is visible from the beginning to the end of the main()
function. There should not be more than one label having the same name within the main
() function.
Example:
#include<stdio.h>
int x=10;
void print();
int main()
{
printf(“\n the value of x in main()=%d”,x);
int x=2;
printf(“\n the value of local variable x in main()=%d”,x);
print();
return 0;
}
void print()
{
printf(“\n the value of x in print()=%d”,x);
}
Output:
The value of x in main()=10
The value of local variable x in main()=2
The value of x in print()=10
File scope:
Global variable is accessible until the end of the file , the variable is said to have file
scope.To allow a variable to have file scope, declare that variable with the static
keyword before specifying its data type.
A global static variable can be used anywhere from the file in which it is declared but it is
not accessible by any other files.
Example:
Static int x =10;
Recursive functions:
A recursive function is defined as a function that calls itself to solve a smaller version of
its task until a final call is made which does not require a call to itself. Every recursive
solution has two major cases they are:
Base case: The problem is simple enough to be solved directly without making any
further calls to the same function.
Recursive case: The problem at hand is divided into simpler sub parts. Second the
function calls itself but with subparts of the problem obtained in the first step. Third the
result is obtained by combining the solution of simpler sub-parts.
Recursion is defining large and complex problem s in terms of a smaller and more easily
solvable problem. In recursive function, a complex problem is defined in terms of simpler
problems and the simplest problem is given explicitly.
#include<stdio.h>
main()
{
int num;
printf(“\n enter the number:”);
scanf(“%d”,&num);
printf(“result=%d”,fact(num));
}
int fact(int n)
{
if(n==0) or (n==1)
return 1;
else
return n*fact(n-1);
}
Base case is when n=1 or n=0 because if n=1 or n=0 the result will be 1
Recursive case of the factorial function will call itself but with a smaller value of n,this
case can be given as
n*fact(n-1)
Types of recursion:
Recursion is a technique that breaks a problem into one or more sub-problems that are similar to
the original problem.
Any recursive function can be categorized based on the following:
Whether the function calls itself directly or indirectly(direct or indirect recursion)
Whether any operation is pending at each recursive call(tail-recursion or not)
The structure of the calling pattern(linear or tree recursion)
1. Direct recursion:
Example:
int Func(int n)
{
if(n==0)
return n;
return(Func(n-1));
}
Here the function Func() calls itself for all positive values of n, so it is said to be a directly
recursive function.
2. Indirect Recursion:
A function is said to be indirectly recursive if it contains a call to another function which
ultimately calls it.
Example:
int Func1(int n)
{
if(n==0)
return n;
return Func2(n);
}
int Func2(int x)
{
return Func1(x-1);
}
3. Tail recursion:
int Fact(int n)
{
if(n==1)
return 1;
return (n*fact(n-1));
}
Module 4: ARRAYS
Types of Array:
1. Single dimensional array: the array with one set of square [] are single dimensional
arrays.
Example: int a[10];
2. Two dimensional array: The array with two sets of square brackets [][] are called 2-
dimensional array.
Example: int b[10][10];
3. Multi dimensional array: array with two or more dimensions are called multi-
dimensional arrays.
Example: int c[3][4][6];
Declaration of arrays:
An array must be declared before being used. Declaring an array means specifying three things:
Data Type: What kind of value it stores. For example: int, char, float, double.
Array Name: To identify the array.
Size: The maximum number of values that the array can hold.
Syntax:
Here type can be int, float, double or char any other valid data type. The number within
brackets indicates the size of the array, i.e the maximum number of elements that can be
stored in the array.
The size of array is constant and must have a value at compilation time.
Example:
int marks[10];
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
The integer expression enclosed within brackets must end with semicolon.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
For accessing an individual element of the array, the array subscripts must be used.
We can access the first element of array as a[0].
a 10 20 30 40 50
0 1 2 3 4
We calculate the address of any element in the array using the following simple formula:
Consider array a memory at location 1000.If array elements ar integer type(int),the size
of one element of int (2 bytes).
Assuming the size of an int is 4,the address of the element at index 3 is
Element address=1000+2*3=1006
Example program:
The first elements of array marks[5] can accessed by writing marks[0].Now to process all the
elements of the array, we will use a loop.
int i, marks[10];
for (i=0;i<10;i++)
marks [i]=-1;
Output:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Problem1:
Problem 2:
Solution:
To store values in array, there are three ways: first to initialize the array element, second to input
a value for every individual element, third to assign value to the elements.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
1 .Initialization of array:
Elements of the array can also be initialized at the time of declaration as in the case of
every other variable.
When an array is initialized ,we need to provide a value for every element in the array
.Array are initialized by writing:
Syntax:
The values are written with curly brackets and every value is separated by a comma.
This statement is absolutely legal. Here the compiler will allocate enough space for all
initialized elements. If the number of value provided is less than the number of elements
in the array, the un-assigned elements are filled with zeros.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
2. Assigning values:
The third way to assign values to individual elements of the array is by using the assignment
operator. Any value that evaluates to an appropriate data type as that of the array can be assigned
to the individual array element. A simple assignment statement can be written as,
Marks[3]=100;
Here , 100 is assigned to the fourth element of the array which is specified as marks[3].
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Length of the array is given by the number of elements stored in it.the general formula to
calculate the length of the array is,
Where upper bound is the index of the last element and lower bound is the index of the first
element in the array.
Solution:
1 Traversal
2. Deletion
3. Insertion
4. Search
5. Sorting
6. Merging
1. Traversal:
Traversing the array element means accessing each and every element of the array for a specific
purpose. We have already seen this while reading about accessing array elements.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
If A is an array of homogenous data elements, then traversing the data elements can include
printing very element, counting the total number of elements, or performing any process on these
elements. Since an array is a linear data structure, traversing its elements is very simple and
straightforward.
Insertion:
Inserting an element in the array means adding a new data element in an already existing array. If
the element has to be inserted at the end o the existing array, then the task of insertion is quite
simple. We just have to add 1 to the upper bound and assign the value. Here we assume that the
memory space allocated for the array is still available.
Example:
The array is declared to store marks of all the students in the aclass.now suppose that there are 54
students and a new student comes and is asked to given the same test. The marks of this new
student would be stored in marks [55].assuming that the student secured 68 marks.we will assign
the value as,
marks [55]=68;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Solution:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Deletion:
Deleting an element from the array means removing a data element from an already existing
array. If the element has to be deleted from the end of the existing array, then the task of deletion
is quite simple. We just have to subtract 1 from the upper bound.
Example:
int marks[];
The array is declared to store marks of all the students in the calss.Now suppose there are
54 students and the student with roll number 54 leaves the course. The marks of this
student was therefore stored in marks [54].We just have to decrement the upper bound.
Subtracting 1 from the upper bound will indicate that there are 53 valid data in the array.
If we have to delete the element from the middle of the array, then this task is not
trival.We just had to move as much as half of the elements from its position in order to
occupy the space of the deleted element.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Merging:
Merging two array in a third array mean first copying the contents of the first array of the
first array into the third array and then coping the contents of the second array into the third
array . Hence, the merge array contains the contents of first array followed by second array
Example:
Searching means to find whether a particular value is present in the array or not. If the
value is present in the array then searching is said to be successful and the searching
process given the location of that value in the array. Otherwise, if the value is not
present in the array, the searching process displays the appropriate message and in
this case searching is said to be unsuccessful.
There are two popular methods for searching the array elements. One is linear search
and second is binary search.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Linear search:
Linear search also known as sequential search is a very simple, method used for
searching n array for a particular value. It works by comparing every elements of the
array one by one in sequence until a match is found.
Linear search is mostly used to search an unordered list of elements
Example: if an array A[]is declared and initialized as, and VAL=7,then searching means to
find out whether the value ‘7’ is present in the array or not .If yes ,then the search is
successful and it returns the position of occurrence of VAL .
int A[]={10,8,2,7,3,4,9,1,6,5};
Solution:
Example:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Binary search:
The linear search algorithm is very slow. If we have an array with 1 million entries,
then to search a value from that array, we would need to make 1 million comparisons
in the worst case. However if the array is sorted, we have a better and efficient
alternative, known as binary search.
Binary search algorithm is a searching algorithm that works efficiently with the sorted
list. The algorithm finds out the position of a particular element in the array.
Example:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Two-dimensional arrays:
A 2D array is specified using two subscripts where one subscript denotes row and other
denotes column consider the 2D array as an array of 1D array.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Similar to one dimensional arrays, two –dimensional arrays must be declared before being
used.
The declaration statement tells the compiler the name of the array, the data type of each
element in the array and the size of each dimension.
Syntax:
Example:
int marks[3][5]
here two dimensional array called marks is declared that has m93) rows and n95) columns.
The first element of the array is denoted by marks[0][0],the second element as marks[0][1],
and so on. Here marks [0][0] stores the marks obtained by the first student in the first subject,
marks[1][0] stores the marks obtained by the second.
Syntax:
Example:
int marks[2][3]={90,87,78,68,62,71};
int marks[2][3]={{90,87,78},{68,62,71}};
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
The given 2-D array has two rows and 3 columns. Here, the elements in the first row
are initialized first and then the elements of the second row are initialized.then,
marks[0][0]=90
marks[0][1]=87
marks[0][2]=78
marks[1][0]=68
marks[1][1]=62
marks[1][2]=71
In the case of 1D array, if the array is completely initialized to, we may omit the size
of the array. The same concept can be applied to a 2D array, except that the only the
size of the first dimension can be omitted. Then ,
int marks[][3]={{90,87,78},{68,62,73}};
In order to initialize the entire 2D array to zero ,simply specify the first value as zero ,
int marks[2][3]={0};
If some values are missing in the initialize then it is automatically set to zero.
int marks[2][3]={{50,60,70}};
In case of 1D array we used a single for loop to vary the index I in every pass, so that all the
elements could be scanned. Similarly, since 2D array contains two subscripts, we will use
two for loops to scan the elements. The first for loop will loop for each row in the 2D array
and the second for loop will scan individual columns for every row in the array.
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf(“%d”,a[i][j]);
Transpose:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Sum:
Two matrices that are compatible with each other can be added together by storing
the result in the third matrix.
Two matrices are said to be compatible when they have the same number of rows and
columns.
Elements of the matrices can be added by writing : Ci,j=Ai,j+Bi,j
Difference:
Two matrices that are compatible with each other can be subtracted thereby storing the result
in the third matrix .Two matrices are said to be compatible when they have the same number
of rows and columns. Elements of the matrices can be subtracted by writing: Ci,j= Ai,j-Bi,j.
Product:
Two matrices can be multiplied with each other if the number of columns in the first matrix
is equal to the number of rows in the second matrix. Therefore, m x n matrix A can be
multiplied with a p x q matrix if n=q.
One-dimensional
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
The individual elements of an array can be passed to a function either by passing their addresses
or their data values.
The individual elements can be passed in the same manner as we pass value of any other datatype.
The condition is just that the data type of the array element must match the type of the function
parameter.
Example:
main()
int arr[5]=[1,2,3,4,5};
func(arr[3]);
Printf(“%d”,num);
In this example, only one element of the array is passed to the called function. This is done by
using the index expression. i.e arr[3].
Passing Address:
We can pass the address of an individual array element by preceding the address operator (&) to
the element’s indexed reference. Therefore, to pass the address of the fourth element of the array
to the called function we will write & arr [3].
In the called function value of the array element must be accessed using the indirection (*)
operator.
Example:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
main()
int arr[5]=[1,2,3,4,5};
func(&arr[3]);
Printf(“%d”,num);
When we need to pass an entire array to a function, we can simply pass the name of the array
main()
int arr[5]=[1,2,3,4,5};
func(arr);
int i ;
for(i=0;i<5;i++)
Printf(“%d”,arr[i]);
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
There are 3 ways of passing parts of the two dimensional array to a function.
First, we can pass individual elements of the array. This is exactly same as passing the
elements of a 1 D array.
Second, we can pass a single row of the 2D array. This is equivalent to passing the entire
1 D array to function.
Third, we can pass the entire 2D array to the function.
Passing a Row:
A row of a 2D array can be passed by indexing the array name with the row number. When we
send a single row of a two-dimensional array, then the called function receives one-dimensional
array.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
main ()
int arr[5]={{1,2,3},{4,5,6}};
func(arr);
int i ;
for(i=0;i<5;i++)
Printf(“%d”,arr[i]*10);
To pass a 2D array to a function, we can use the array name as the actual parameter.
The parameter in the called function must indicate that the array has two dimensions.
A multidimensional array in simple terms is an array of arrays. Like we have one index in a 1 D
array , two indices in a 2D array, in the same way we have n indices in an n-dimensional array or
multidimensional array..
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Declaration of a string:
Initialization of a string:
Example:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
3. Char str[5]=”HELLO”;
Reading strings:
Char str[100];
Then str can be read from the user by using three ways:
Scanf(“%s”,str);
The main drawback with this function is that it terminates as soon as it finds a blank space.
Example: if the user enters “Hello world”, then str will contain only “Hello”. This is because the
moment a blank space is encountered, the string is terminated by the scanf() function.
Syntax: gets(str);
gets() is a simple function that overcomes the drawbacks of scanf().The gets() function takes the
starting address of the string which will hold the input .
Example:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Writing strings:
Printf(“%s”,str);
The next method of writing a string is by using the puts function.The string can be displayed by
writing
Puts(str);
Puts() is a simple function that overcomes the drawbacks of printf ().the puts() function writes a
line of output on the screen. It terminates the line with a newline character (‘\n’).it returns an
EOF(end of file)(-1)if an error occurs and returns a positive number on success.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Example program:
String taxonomy:
In c we can stor ea string either in fixed length format or in variable length format.
string
Fixed Variable
length length
Length Delimited
controlled
When storing a string in a fixed length format, you need to specify an appropriate size for the
string variable. If the size is too small, then you will not be able to store all the elements in the
string. On the other hand, if the string size is large, then unnecessarily memory space will be
wasted.
Example: Declare string variable to store the name of a student. If student has a long name of
say 20 characters, then the string can be expanded to accommodate 20 characters, on the other
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
hand, a student name has only 5 characters, then the string variable can be contracted to store
only 5 characters.
In length controlled string you need to specify the number of characters in the string. This count
is used by string manipulation function to determine the actual length of the string variable.
Delimited string:
In this format the string is ended with a delimiter. The delimiter is then used to identify the end
of the string.
For example in English language every sentence is ended with a full-stop, similarly in C we can
use any character such as comma, semicolon, colon, dash, null character etc. as the delimiter of a
string.However,the null character is the most commonly used string delimiter in the C language.
String operations:
1. Length:
The number of characters in the string constitutes the length of the string.
Example: Length (“C programming is fun”)
Output: return 20
Example program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str[100],i=0,length;
Clrscr();
Printf(“\n enter the string:”);
gets(str);
while(str[i]!=’\0’)
i++;
length=I;
printf(“\\n the length of the string is:%d”,length);
getch();
}
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
We have already seen that in memory the ASCII codes are stored instead of the
real value. The ASCII code for A-Z varies from 65 to 91 and ASCII code for a-z
ranges from 97-123.
If we have to convert a lower case character to upper case then we just need to
subs tract 32 from the ASCII value of the character.
Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str[100],upper_str[100];
int i=0,j=0;
printf(“\n enter the string:”);
gets(str);
while(str[i]!=”\0”)
{
if(str[i]>=”a” && str[i]<=”z”)
upper_str[j]=str[i]-32;
else
upper_str[i]=str[i];
i++;
j++;
Upper_str[j]=”\0”;
Puts(upper_str);
return 0;
Output:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
The ASCII code for A-Z varies from 65 to 91 and the ASCII code for a-z ranges from 97-
123.
If we have to convert an upper case character into lower case, then we just need to add 32
to its ASCII value.
Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str[100],upper_str[100];
int i=0,j=0;
printf(“\n enter the string:”);
gets(str);
while(str[i]!=”\0”)
{
if(str[i]>=”a” && str[i]<=”z”)
lower_str[j]=str[i]-32;
else
lower_str[i]=str[i];
i++;
j++;
lower_str[j]=”\0”;
Puts(lower_str);
return 0;
Output:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
If s1 and s2 are two strings, then concatenation operation produces a string which contains
characters of s1 followed by the characters of s2.
Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str1[100],str2[100],str3[100];
int i=0,j=0;
printf(“\n enter the first string :”);
gets(str1);
printf(“\n enter the second string:”);
gets(str2);
while(str1[i]!=’\0’)
{
Str3[j]=str1[i];
i++;
j++;
}
i=0;
while(str2[i] !=’\0’)
{
Str3[j]=str2[i];
i++;
j++;
Str3[j]=’\0’;
Puts(str3);
getch();
return 0;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Output:
Appending strings:
Appending one string to another involves copying the contents of the source string at the
end of the destination string.
Example: if s1 and s2 are two strings, then appending s1 to s2 means we have to add the
contents of s1 to s2.
Here s1 is the source string and s2 is the destination string. The appending operation
would leave the source string s1 unchanged and the destination string s2=s2+s1.
Example program:
#include <stdio.h>
#include<conio.h>
main()
Char Dest_str[100],source_str[50];
int i=0,j=0;
Dest_str[i]=source_str[j];
i++;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
j++;
Dest_str[i]=’\0’;
Puts(Dest_str);
getch();
return 0;
Output:
If s1 and s2 are two strings then comparing two strings will give either of these results:
1. S1 and S2 are equal
2 . S1> S2,when in dictionary order s1 will come after s2.
3 S1<S2 ,when in dictionary order s1 precedes s2.
Example program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
Char str1[50],str2[50];
int i=0,len1=0,len2=0,same=0;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
gets(str1);
gets(str2);
len1=strlen(str1);
len2=strlen(str2);
if(len1==len2)
While(i=len1)
if(str1[i]==str2[i])
i++;
else
break;
if(i==len1)
Same=1;
if(len1!=len2)
if (same==0)
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
if(str1[i]>str2[i])
else if(str1[i]<str2[i]))
getch();
return 0;
Output:
Reversing a string:
If s1=“Hello”, then reverse of s1=”olleH”.To reverse a string we just need to swap the first
character with the last. Second character with the second last character and so on.
Note:
There is a library function strrev (s1) that reverses all the characters in the string except
the null character. It is defined in string.h.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Char str[100],reverse_str[100],temp;
int i=0,j=0;
gets(str);
j=strlen(str)-1;
while(i<j)
temp=str[j];
str[j]=str[i];
str[i]=temp;
i++;
j--;
Puts(str);
getch();
return 0;
Output:
In order to extract a substring from the main string we need to copy the content of the string
starting from the first position to the nth position where n is the number of characters to be
extracted.
Example:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
In order to extract a substring from the right side of the main string we need to first calculate the
position.
Example:
To extract a substring from a given string requires information about three things.The main
string the position of the first character of the substring in the given string and maximum number
of characters/length of the substring.
Example:
Insertion:
The insertion operation insert a string S, in the main text T, at the Kth position.The
general syntax of this operation is : INSERT(text,position,string).
Example: INSERT(“xyzxyz”,3,”AAA”)=”xyzAAAxyz”.
Program:
#include<stdio.>
#include<conio.h>
main()
{
Char text[100], str[20], ins_text[100];
int i=0,j=0,k=0,pos;
Printf(“\n enter the main text:”);
gets (text);
printf(“\n enter the string to be inserted:”);
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
gets(str);
printf(“\n enter the position at which the string has to be inserted:””);
scanf(“%d”,&pos);
ehile(text[i]!=’\0’)
{
if(i==pos)
{
While(str[k]!=’\0’)
{
ins_text[j]=str[k];
j++;
k++;
}
}
else
{
ins_text[j]=text[i];
j++;
}
i++;
}
ins_text[j]=’\0’;
printf(“\n the new string is:”);
puts(ins_text);
getch();
return 0;
}
Output:
Indexing:
Index operation returns the position in the string where the string pattern first occurs.
Example:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Deletion:
Example:
DELETE(“ABCDXXXABCD”,5,3)=”ABCDABCD”
Program:
#include<stdio.h>
#include<conio.h>
main()
Char text[200],str[20],new_text[200];
int i=0,j=0,found=0,k,n=0,copy_loop=0;
gets(text);
fflush(stdin);
gets(str);
fflush9stdin);
while(text[i]!=’\0’)
j=0,found=0,k=i;
k++;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
j++;
if(str[j]==’\0’)
copy_loop=k;
new_text[n]=text[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]=’\0’;
printf(“\n the new string is :”);
puts(new_text);
getch();
return 0;
Output:
Relpacement:
Replacement operation is used to replace the pattern p1 by another pattern t2 . This is done by
writing,REPLACE(text,pattern1,pattern2)
Example:
(“AAABBBCCC”,”BBB”,”X”)=AAAXCCC
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
The strcat() function appends the string pointed by str2 to the end of the string pointed to by str1.
Example:
#include<stdio.h>
#include<string.h>
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
int main()
Char str1[50]=””Programming”;
Strcat(str1,str2);
return 0;
Output:
Str1:Programming in c
2. strncat() function:
Syntax:
char *strncat(char *str1,const char *str2,size_t n);
This appends the string pointed to by str2 to the end of the string pointed to by str1 upto n
characters long.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str1[50]=”programming”;
Strncat(str1,str2,2);
Printf(“\n str1:%s”,str1);
return 0;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Output:
Str1:programming in
3. Strchr() function:
Syntax:
This function searches for the first occurrence of the character c in the string pointed to by the
argument str. The function returns a pointer pointing to the first matching character, or null if no
match was found.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char *pos;
Pos=strchr(str,’n’);
if(pos)
else
return 0;
Output:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
4. Strrchr()function:
Syntax:
The strchr() function searches for the first occurrence of the character c beginning at the rear end
and working towards the front in the string pointed to by the argument str.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char *pos;
if(pos)
else
return 0;
Output:
5. strcmp() function:
Syntax:
the strcmp compares the string pointed to by str1 to the string pointed to by str2.The function
return zero if the strings are equal.Otherwise,it returns a value less than zero or greater than zero
if str1 is less than or greater than str2 .
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str1[10]=”HELLO”;
Char str2[10]=”HEY”;
if(strcmp(str1,str2)==0)
else
return 0;
Output:
6. Strcpy() function:
Syntax:
This function copies the string pointed to by str2 to str1 including the null character of str2.it
returns the argument str1.
Example:
Example:
#include<stdio.h>
#include<string.h>
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
int main()
Char str1[10]=”HELLO”;
Char str2[10]=”HEY”;
strncpy(str1,str2,2)
printf(“\nstr1:%s”,str1);
return 0;
Output:
HE
7. strlen() function:
Syntax:
This function calculates the length of the string str upto but not including the null character, i.e
the function returns the number of characters in the string.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str[]=”HELLO”;
return 0;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Output:
Length of str is :5
8. strstr() function:
Syntax:
The function is used to find the first occurrence of string str2 in the string str1. It returns a
pointer to the first occurrence of str2 in str1.If no match is found then null pointer is returned.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str2[]=”DAY”;
Char *ptr;
Ptr=strstr(str1,str2));
if(ptr)
else
return 0;
Output:
Substring found
Array of string:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Char name[20][30];
Here the first index will specify how many strings are needed and the second index specifies the
length of every individual string.So here we allocate space for 20 names where each name can be
a maximum of 30 characters long.
Syntax:
Char name[5][10]={“Ram”,”Mohan”,”Shyam”,”Hari”,”Gopal”};
Name[0] R A M \0
M O H A N \0
Name[1]
S H Y A M \0
Name[2]
H A R I \0
Name[3]
G O P A L \0
Name[4]
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
POINTERS:
Pointer declaration:
Syntax:
Here data type is the data type of the value that the pointer will point to.
Example:
float *pch;
char *pfnum;
Example:
#include<stdio.h>
int main()
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
return 0;
Output:
#include<stdio.h>
Int main()
int num,*pnum;
Pnum=#
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Scanf(“%d”,&num);
return 0;
Output:
POINTER FLEXIBILITY:
We can make the same pointer to point to different data variables in different statements.
p = &x;
p = &y;
p = &z;
We can also use different pointers to point to the same data variable.
Ex: p1 = &x;
P2 = &x;
C P3 = &x
The data type of the pointer variable and the variable whose address it will store must
both be of the same type.
int x=10;
float y=2.0;
int *px;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
int *py;
Px=&y; //invalid
Py=&x; //invalid
Initialization:
Example:
int a=10;
int *p;
p=&a;
memory representation: a
10
p 1000(memory address of a)
1000
2000(memory address of p)
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Example:
int a=5;
int *p;
p=&a;
we access a value by *p
Example program:
#include<stdio.h>
Void main()
printf(“a=%d\n”,a); // 10
printf(“&a=%d\n”,&a); //1000
printf(“p=%d\n”,p); //1000
printf(“*p=%d\n”,*p); //10
printf(“&p=%d\n”,&p); //2000
1000(memory address
1000
2000(memorynaddress of p)
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Types of pointers:
Typed pointer:
Pointer which has been declared with specific type of data type.
syntax:
Example:
int *p;
float *p;
double *p;
A generic pointer is a pointer variable that has void as its data type.
The void pointer or the generic pointer is a special type of pointer that can be used to
point to variables of any data type.
Syntax:
Void * variable;
Example:
Void *ptr;
The void pointer will not point to any data and thus,cannot be dereferenced.You need to type cast
a void pointer to another kind of pointer before using it.
Example:
#include<stdio.h>
int main()
int x=10;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Char ch=’A’;
Void *gp;
gp=&x;
gp=&ch;
return 0;
Null pointer:
Null pointer which is a special pointer value that does not point anywhere. This means that a
NULL pointer does not point to any valid memory address.
To declare a null pointer you may use the predefined constant NULL,which is defined in several
standard header files including <stdio.h>,<stdlib.h> and <string.h>.
Syntax:
you can always check whether a given pointer variable stores address of some variable or
contains a NULL by writing,
if(ptr==NULL)
Statement block;
You may also initialize a pointer as a null pointer by using a constant 0 as follows:
int ptr;
ptr=0;
Call by value method of passing parameters to a function. Using call by value method, it
is impossible to modify the actual parameters in call when you pass them to a function.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
The incoming arguments to a function are treated as local variable in the function and
those local variables get a copy of the values passed from their caller.
The calling function sends the address of the variables and the called function must declare those
incoming arguments as pointers.
In order to modify the variables sent by the caller,the called function must dereference the
pointers that were passed to it.thus passing pointers to a function avoids the overhead of copying
data from one function to another.
To pass pointers for passing arguments to a function the programmer must do the following:
3. Pass the address as the actual argument when the function is called..
#include<stdio.h>
Void min()
int a,b;
printf(“enter 2 numbers\n”);
scanf(“%d%d”,&a,&b);
swap(&a,&b);
int hold;
temp=*px;
*px=*py;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
*py=temp;
Advantages of pointers:
Pointers provide a way to return more than one value to the functions
Pointers can be used to pass information back and forth between the calling function and
called function.
Pointers helps us to build complex data structures like linked list, stack, queues, trees,
graphs etc.
Disadvantages of pointers:
If pointers are updated with incorrect values, it might lead to memory corruption.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Structure
Structure is basically a user-defined data type that can store related information together.
The major difference between structure and an array is that, an array contains related
information of the same data type.
Structure declaration:
A structure is declared using the keyword struct followed by a structure name .all the variable of
the structure is declared within the structure.
Syntax 1:
……..
};
Example:
Struct student
int r_no;
char name[20];
char course[20];
float fees;
};
Now ,structure has become user defined data type .exach var-name declared within a structure is
called a member of the structure.
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Syntax 2:
Struct student
int r_no;
char name[20];
char course[20];
float fees;
}stud1,stud2;
In declaration ,we declare two variable stud1 and stud2 of the structure student.So,if you want
Tto declare more than one variable of the structure,then separate the variable using comma.
R_no
name
course
fees
Example1: Declare a structure to store information about the points in the coordinate
system
Solution:
Struct point
int x;
int y;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Solution:
Struct customer
int cust_id;
char name[20];
char address[20];
int DOB;
Typedef Declaration:
The typedef (derived from type definition) keyword enables the programmer to create a new type
name for an existing data type. By using typedef, no new data is created; rather an alternate name
is given to a known data type.
Syntax:
Example:
Then INTEGER is the new name of data type int. To declare variables using the new data type
name, precede the variable name, precede the variable name with the data type
name.Therefore,to define an integer variable, we may now write
INTEGER num=5;
Initialization of structure:
Initializing a structure means assigning some constants to the members of the structure. When
the user does not explicitly initialize the structure, then C automatically does that.For int and
float members, the values are initialized to zero and char and string members are initialized to
the ‘\0’ by default.
Syntax:
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Struct struct_name
Data_type member_name1;
Data_type member_name2;
Data_type member_name3;
……………….
}struct_var={constant1,constant2,constant3,….};
OR
Struct struct_name
…….
};
Example:
Struct student
int rollno;
char name[20];
char course[20];
float fees;
}stud1={01,”Rahul”,”BCA”,45000};
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
OR
Struct student
int rollno;
char name[20];
char course[20];
float fees;
Syntax:
Struct_var.member_name;
The dot operator is used to select a particular member of the structure.To assign value to the
individual data members of the structure variable stud1.
Stud1.rollno=01;
Stud1.name=”Rahul”;
Stud1.course=”BCA”;
Stud1.fees=45000;
To input values for data members of the structure variable stud1 we can write,
Scanf(“%d”,&stud1.rollno);
Scanf(“%s”,&stud1.name);
Printf(“%s”,stud1.course);
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
Printf(“%f”,stud1.fees);
Example:
Two structure Variables stud1 and stud2 of type struct student is given as:
Nested structures:
Structure can be placed within another structure, i.e., a structure may contain another structure as
its member. A structure that contains another structure as its member is called a nested structure.
Passing individual
members
Passing structures to
functions Passing the address of the
structure
To pass any individual member of the structure to a function, we must use the direct
selection operator to refer to the individual members for the actual parameters.
The called program does not know if the two variables are ordinary variables or structure
members.
Example:
#include<stdio.h>
Typedef struct
{
int x;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
int y;
}POINT;
void display(int,int);
main()
{
POINT p1={2,3};
display (p1.x,p1.y);
return 0;
}
void display(int a,int b)
{
printf(“the coordinates of the point are”%d%d”,a,b);
}
Output:
Just like any other variable, we can pass an entire structure as a function argument. when a
structure is passed as an argument, it is passed using the call by value method, i.e., a copy of
each member of the structure is made.
The general syntax for passing structure to a function and returning a structure can be given as,
Example:
#include<stdio.h>
typedef struct
int x;
int y;
}POINT;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
void display(POINT);
main()
POINT p1={2,3};
display (p1);
return 0;
void display(POINT p)
Output:
Passing large structures to function using the call by value method is very inefficient.Thereferore
it is preferred to pass structures through pointers
Syntax:
Struct struct_name
…………
}*ptr;
GSSSIETW,MYSURU
Introduction to C Programming BESCK104E
OR
To assign the address of stud to the pointer using the address operator(&) as we would do in case
of any other pointer. So to assign the address, we will write.
ptr_stud=&stud;
(*ptr_stud).roll_no;
Since parenthesis have a higher precedence than *, writing this statement would work well.
C introduces a new operator to do the same task. This operator is known as the pointing to
operator ().
ptr_stud roll_no=01;
GSSSIETW,MYSURU