You are on page 1of 161

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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Accredited Branches by NBA, New Delhi (Validity:
01.07.2017 – 30.06.2020 & 01.07.2020 – 30.06.2023)

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

Department of Computer Science and Engineering


Accredited Branches by NBA, New Delhi
(Validity: 01.07.2017 – 30.06.2020 & 01.07.2020 – 30.06.2023)

VISION

Knowledge dissemination with development of future leaders in Information Technology


having a research blend.

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.

 M4: Provide a platform to collaborate with successful people from entrepreneurial


and research domains to learn and accomplish.

PROGRAMME EDUCATIONAL OBJECTIVE (PEOS)


 PEO1: To produce graduates satisfying Computer Science Engineering challenges.

 PEO2: To meet dynamic requirements of IT industries professionally and ethically


along with social responsibilities.

 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)

 PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
 PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
 PO3: Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
 PO4: Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
 PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
 PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
 PO7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
 PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
 PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
 PO10: Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
 PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
 PO12: Life-long learning: Recognize the need for and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
Course Title Introduction to C Programming
Course Code: BESCK104E CIE Marks 50
Integrated SEE Marks 50
Course Type (Theory/Practical /Integrated ) Total Marks 100
Teaching Hours/Week (L:T:P: S) 2:0:2:0 Exam Hours 03
Total Hours of Pedagogy 40 hours Credits 03
CourseObjectives:

CLO 1. Elucidate the basic architecture and functionalities of a Computer


CLO 2. Apply programming constructs of C language to solve the real-world problems
CLO 3.Explore user-defined data structures like arrays, structures and pointers in implementing solutions to
problems
CLO 4. Design and Develop Solutions to problems using modular programming constructs such as
functions and procedures

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

Module-2 (6 Hours of Pedagogy)

Operators in C, Type conversion and typecasting.

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

Teaching-Learning Process Chalk and talk method/Power PointP resentation


Module-4 (6 Hours of
Pedagogy)

Two dimensional arrays, operations on two-dimensional arrays, two-dimensional arrays to functions,


multidimensionalarrays.
Applications of arrays and introduction to strings:Applications of arrays, case study with sorting techinques.
Introduction to strings: Reading strings, writing strings, summary of functions used to read and write
characters.Suppressing input using a Scanset.
Textbook: Chapter 12.7-12.12
Teaching-Learning Process Chalk and talk method/Power Point Presentation
Module-5 (6 Hours of
Pedagogy)
Strings: String taxonomy, operations on strings, Miscellaneous string and character functions, arrays of strings.
Pointers: Understanding the Computers Memory,Introduction to Pointers, Declaring Pointer Variables
Structures: Introduction to structures

Textbook: Chapter 13.1-13.6, 14.1-14.3,15.1


Teaching-LearningProcess Chalk and talk method/Power Point Presentation
CourseOutcomes(CourseSkillSet)
At the end of the course the student will be able to:
CO1. Elucidate the basic architecture and functionalities of a computer and also
recognizethe hardware parts.
CO 2. Apply programming constructs of C language to solve the real world
problemCO 3.Explore user-defined data structures like arrays in implementing
solutions to problems like searching and sorting
CO 4.Explore user-defined data structures like structures, unions and pointers in
implementing solutions
CO5.Design and Develop Solutions to problems using modular programming
constructsusing functions
Suggested Learning Resources:
Textbooks
1. Computer fundamentals and programming in c, “Reema Thareja”, Oxford University, Second edition, 2017.

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.

Web links and Video Lectures (e-Resources):


1. elearning.vtu.ac.in/econtent/courses/video/BS/15PCD23.html
2. https://nptel.ac.in/courses/106/105/106105171/ MOOC courses can be adopted for more clarity in
understanding the topics and verities of problem solving methods.

Activity Based Learning (Suggested Activities in Class)/ Practical Based learning



Quizzes

Assignments

Seminar
Introduction to C Programming BESCK104E

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:

 Computers can perform millions of operations per second.


 The speed of computers is usually given in nanoseconds and 1 picoseconds (1
nanoseconds=1*10^-9 and 1 Pico seconds=1*10^-12 seconds)

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.

Computer generations [10M]:

Generation in computer terminology is change in technology a computer is being used. There is


five generation of computers.

First generation of computer (1940-1956): vacuum tubes:

 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.

Second generation of computer (1956-1963) Transistor:

 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.

Third generation computer (1964-1971) Integrated circuits:

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.

Fourth generation computer (1971-1980) Microprocessor:

 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.

Fifth generation computer(1980-till date)Artificial intelligence:

 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.

2. Main frame computers:

 Mainframe is very large in size and is an expensive computer capable of supporting


hundreds or thousands of users simultaneously.
 The processor speed is measured in MIPS (million instructions per seconds).
 Used for online transactions.
 Capability to handle large amount of data makes mainframe suitable for use in
government, banks and financial institutions.
 There are basically two types of terminals that can be used with mainframe systems are:

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:

 It is multi-user computer system, capable of supporting hundreds of users simultaneously.


 Minicomputers are smaller, cheaper and slower than mainframes. They are called
minicomputers because they were the smallest computer of their times. Also know as
midrange computers, the capabilities of minicomputers fall between mainframe and PCs.
 The first minicomputer was introduced by digital equipment corporation (DEC) in the
mid 1960.
 The minicomputers are used in small organization or a department of a large one.

4. Micro computers:

 Microcomputers commonly known as PCs are very small and cheap.


 The microcomputer or PC is introduced by Apple and endorsed by IBM. This is a single-
user machine powered by a single-chip microprocessor.
 They are very powerful machines havinggigabytes of memory.
 They are both used in standalone mode and in a network.
 A microcomputer takes the form of desktop, notebook (laptop) or a notebook (smaller
laptop). PCs today are powered by 3 types of OS – windows (7, 8 or 10), Mac OS X
(Apple) and Linux.
 They are used for engineering and scientific applications and for software development.
 PCs can be classified into the following categories.
o Desktop
o Laptops
o Workstations

Basic organization of computer:

A computer is an electronic device that basically performs five major operations:

 Accepting data or instruction


 Storing data
 Processing data

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.

A computer has two types of storage areas:

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:

 It stands for random access memory.


 It is a temporary memory that means it is used to store information that is used
immediately.
 Once the computer is turned off the data will be deleted. With the help of RAM
computers can perform multiple tasks like loading applications, browsing the web tasks
like loading applications, browsing the web, editing a spreadsheet etc…
 There are 2 types:

1.S-RAM (static RAM): Volatile, stores until system is on

2.DRAM(Dynamic RAM): Store binary bits in the form of electrical charges.

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.

Difference between primary and secondary storage devices:

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

Control unit Output unit


Input unit

ALU (arithmetic
and logical unit

Input and output devices:

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

Keyboard Pointing devices Handheld devices Optical devices Audio/video devices

Mouse Stylus Barcode


reader

Track ball Touch


Scanner

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:

 The optical mouse is more advanced than the mechanical mouse.


 It contain ball inside. The movement of the mouse is detected using laser technology,
by using optical sensors.

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.

Fig: Trackball used in mouse

Fig: Trackball on 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.

Optical character recognition:

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.

The steps involved in OCR include:

1. Scanning the text character by character


2. Analyzing the scanned image to translate the character images into character codes.

Optical mark reader:

 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:

 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.

Audiovisual input devices:

Audio devices:

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

 Audio devices are used to either capture or create sound


 They enable computers to accept music, speech or sound effects for recording and /or
editing.
 Microphones and CD players are examples of two widely used audio input devices.
 A microphone feeds audio input to the compter.however the audio input must be
converted into digital data before being stored in the computer.

Video input devices:

 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

Soft copy devices Hard copy devices

Monitor Projector Speaker Printer Plotter

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.

CRT (Cathode Ray Tube) Monitors:


 Cathode ray tube is a specialized vacuum tube in which images are produced when
an electron beam strikes a phosphorescent surface.
 The smaller the pixel, the better image clarity or resolution.
 A finite number of characters can be displayed on screen at once.
 Most screens are capable of displaying 80 characters of data horizontally and 25
lines vertically.
 It is large in size and it consumes very high power.
 They usually have resolution of 640*840 pixels. They are large, heavy, energy
efficient and produce lot of heat.

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

LCD (Liquid Crystal Display) Monitors:


 Flat panel display is a thin screen display found on all portable computers and is the
new standard for desktop computers.
 Unlike monitors, flat panel displays use liquid-crystal display(LCD) or light-
emitting diode(LED)technology to make them much lighter and thinner compared
to a traditional monitor.
 The image is formed by applying voltage on crystals.
 The backlight is provided by fluorescent light. They consume less power, generate
less heat and have increased life span.

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

 Impact Printers: It produces the hardcopy of output. The impact


printers are old, noisy.But, still dot-matrix printer is in usage.

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.

2. Daisy-wheel Printer: It employs a wheel with separate characters distributed along


its outer edge. The wheels can be changed to obtain different set of fonts.

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

Impact printer Non impact printer

Dot matrix Daisy wheel Line Inkjet Laser Thermal

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

 Computes are used in government organization to keep records on legislative, internal


revenue service records etc..

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.

Travel and tourism:

Computers are used to prepare tickets, monitor the trains or airplanes route and guide the plane
to a safe landing.

Business and industry:

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:

Industry and engineering:

Introduction to C programming:

 C is a general purpose, structured programming language. It bridges the gap between


machine language and conventional high level languages. This flexibility allows c
language to be used for system programming as well as for applications 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:

 The c programming language was developed by Dennis Ritchie at AT&T bell


laboratories in the early 1970s.He was also known as father of c language.
 Like many other modern language C is derived from ALGOL.ALGOL was not accepted
widely in the United States but it was widely used in Europe.
 In 1967 Martin Richard developed a language called BCPL.
 BCPL was basically a type-less language which facilitated the user with direct access of
memory.
 1970 ken Thompson developed a language called B. B was used to develop the first
version of UNIX
 C was developed by Dennis Ritchie in 1972 that took concept from ALGOL, BCPL and
B.
 In addition to the concepts of these languages, c also supports the concept of data types.
 C was documented and popularized in the book the c programming language by Brain W
Kernighan and Dennis Ritchie in 1978.This book was so popular that the language came
to be known as “k & RC”.
 In 1983 the American national standards institute started working on defining the
standard for C. In December 1989 and came to be known as ANSI C.
 In 1990 the international standard organization adopted the ANSI standard. This version
of C came to be known as C89.
 In 1995 some minor changes were made to C89 the new modified version was known as
C95.
 In 1990 C++ and java became popular programming languages among the users so the
standardization committee of C felt that a few features of C++/java if added to C would
enhance its usefulness. So in 1999 when some significant changes were made to C95, the
modified version came to be known as C99.

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.

Small in size and power full:

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.

Efficient and fast:

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.

Efficient Use of pointers:

C supports efficient use of pointer. Pointers have direct access to memory.

Bit manipulation:

It provides wide variety of bitwise operators to manage data at bit level. We can perform
different operations at bit level

STRUCTURE OF ‘C’ PROGRAM

 C program consists of different sections. The structure of C program is as shown below.

 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:

a) Line comments //Single line comment: it uses two slashes(//)

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Syntax: //

Example:// The program takes the 2 values

b) Block comments /*Multi line comment*/: It is used when comments as several line.

Syntax: (opening token symbol)/* */(closing token symbol)

Example:/*the program takes the 2 values*/

 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>

 They come in the beginning of the program


 All preprocessor commands start with hash (#) symbol.
 The preprocessor command tells the compiler to include the standard input /outputlibrary.
 Stdio we need library file to print a message to a terminal.
 #include<stdio.h>tells the compiler that we will be using parts of the standard function
library.
 .hheader file
 <>tell the compiler the exact location of the header file.

#include<conio.h>

 Console input output header file.


 It consist of function clrscr(),getch().

#include<math.h>:

 Consist of mathematical functions like pow(),sqrt(),fabs() etc..

 Definition Section: It defines all symbolic constants.


 Global Declaration Section: variable type that is declared outside any function
and is accessible to all functions through the program.
 main( ) Section:
 It is the starting point of the program.

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

 Main is a user defined function.


 Void: void is data type, void has no values and no operations, which
is returned to operating system to indicate end of the program.
 The function main starts with open braces {and terminates with a
close braces}.

Every ‘C’ program has one main ( ) function and it contains two parts:

i. Declaration Part: Here, all the variables used are declared.


ii. Executable Part: Here, it contains at least one executable statement.

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:

//Addition of two numbers


#include<stdio.h>
void main( )
{
int a, b, sum;
printf(“Enter two numbers\n”);
scanf(“%d%d”, &a, &b);
sum = a + b;
printf(“The sum is %d”, sum);
}

Compiling and executing a C program:

The program development cycle has following four steps:

1. Writing the source code:

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.

2. Compiling the source code (compilation):


The second stage a compilation contains the steps preprocessing, compilation and
assembling code. In preprocessing source code is passed to preprocessor. Preprocessor
removes comments, expand macros and do expansion of the included files. The source
code is compiled using compiler. The compiler checks the syntax errors in the source
code. It produce an intermediate compiled output file .obj .
3. Linking the object code (linking):

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.

Writing a Editor source code Compiler object code Linker executable

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.

Difference between compiler and interpreter:

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

Character set: A character set include.

 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.

There are 5 different types of tokens as follows:

1. keywords:
 Keywords are meant for some special purpose called as reserved words.
 User cannot change the meaning of keywords.

Example:

Auto double int struct break do


Else Long switch goto sizeof if
Case enum register typedef default
Char extern return union volatile
const Float short unsigned while
continue for signed void static

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:

 The rules to write an identifier are as follows:


1. It must contain only alphabets (A to Z, a to z), numbers (0 to 9) and underscore ( _
).
2. It must start with alphabet or underscore but not numeric character.
3. It should not contain any special symbols apart from underscore.

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

4. It should not have any space.


5. Keywords cannot be used as identifiers.
6. Identifiers are case sensitive.
7. Maximum length of an identifier is 31 characters.
 Examples:
Valid Identifiers: integer, minimum, sum_total, row1, _cpps
Invalid Identifiers: float  It is a keyword.
I am  It has space
123_Abc  It is starting with number N1 + n2. It contains
special symbol (+)

Constants:

Constants are the data values that cannot be change during the execution of a program.

Operators:

It is a symbol that indicates the operation to be performed.

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.

Example: {,}, [,], &,*.

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

2. Floating point data type:


 It is used to store decimal numbers.
 The keyword float is used to declare variable of floating point data type.
 Float type takes 4B or 8B of storage depending on machine size.
 It can be expressed in fractional or exponential form.

Data type Keyword Size


Floating point Float 4B
Double Double 8B
Long double long double 10B

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:

Syntax: datatype variable_list;

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

Rules for declaring/naming variables:

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.

Example: int a = 5;Where,


int  data type
a  variable name
5 value

NOTE: Refer class notes for example program

Difference between variable and identifiers:

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):

 Decimal integer constant consists of a set of digits 0 to 9 preceded by an optional + or –


sign. If the constant contains two or more digits, the first digit must be something other
than 0.
Example: 0, 1, 743, 5233, 9999, 6000
2. Octal integer constants (base 8):

 Octal integer constant is always preceded with 0 and consists of 0 to 7 digits.


Example:
0,01,0743
3. Hexadecimal integer constants (base 16):
 Hexadecimal integer constant is always preceded by 0x or 0X. It consist of digits 0-9 and
letters A-F or a-f. Note that the letters although f represents the quantities 10 through 15
respectively.
Example:
Ox, 0x1, 0x7fff
4. Floating point constant or real constant:
 A floating point constant is a base 10 number that contains either a decimal point or an
exponent or both. It may also have either + or – sign preceding it.
Example: 0.05,-0. 09 , 33. 44

 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

 Thus the number 1.2X 10^-3 would be written as 1.2E-3 or 1.2e-3.

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

NOTE: Refer class notes for example program

Constants

Numeric constant Character constant String constant

Integer Floating point

Decimal Octal Hexadecimal

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Files used in C program:

Files used in C

Source file Header file Object file Executable file

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:

Stdio.h, stdlib.h, conio.h

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.

Input and output statements/Formatted I/O statements:

Input function: scanf():

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

Syntax for scanf()


scanf (format_specifier, &data_a, &data_b,……); // Here, & refers to the address operator
The purpose of the scanf() function is to read the characters that we get from the standard input,
convert them according to the string of format specification, and then store the available inputs in
the memory slots that the other arguments represent
Example:

scanf(“%d %c”, &info_a,&info_b);

Output statement: Printf():

We use this function for displaying a single or multiple values in the form of output for the user
end at the console.

Syntax:

printf (format_specifiers, variable, variable,...........);

Example:

printf(“%d %c”, info_a, info_b);

Program to illustrate input and output statements:

#include <stdio.h>

int main()
{
int i;
float f;
char c;

printf("Enter an integer and a float, then Y or N\n> ");


scanf("%d%f%c", &i, &f, &c);

printf("You entered:\n");
printf("i = %d, f = %f, c = %c\n", i, f, c);

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Module 2: Decision control and looping statements


Introduction to decision control:

 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

if If-else If-else Nested if Switch


ladder

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.

 The decision control statement includes:

1. if statement

2. if- else 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 () {

/* local variable definition */

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

int a = 10;

/* check the boolean condition using if statement */

if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}

printf("value of a is : %d\n", a);

return 0;
}

Output:

a is less than 20;


value of a is : 10

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.

 In both the cases, the control is transferred subsequently to the Statement X.

Example:

#include <stdio.h>

int main () {

/* local variable definition */


int a = 100;

/* check the boolean condition */


if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
} else {
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}

printf("value of a is : %d\n", a);

return 0;
}

Output:

a is not less than 20;


value of a is : 100

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.

 If Expression1 is true, check for Expression2, if it is false then Statement2 is executed.

 If Expression1 is false, then Statement3 is executed.

 Once we start nesting if ..else statements, we may encounter a classic problem known as
dangling else.

 This problem is created when no matching else for every if.

 C solution to this problem is a simple rule “always pair an else to most recent
unpaired if in the currentblock”.

 Solution to the dangling else problem, a compound statement.

 In compound statement, we simply enclose true actions in braces to make the


second if a compoundstatement.

Example:

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

#include <stdio.h>

int main()

int age;

printf("Please Enter Your Age Here:\n");

scanf("%d",&age);

if ( age < 18 )

printf("You are Minor.\n");

printf("Not Eligible to Work");

else

if (age >= 18 && age <= 60 )

printf("You are Eligible to Work \n");

printf("Please fill in your details and apply\n");

else

printf("You are too old to work as per the Government rules\n");

printf("Please Collect your pension! \n");

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

 This construct is known as the else if ladder.

 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”);

else if((c>a) && (c>b))


printf(“C is greater\n”);
else
printf(“all are equal”);
}

Output:

A is greater

Switch case statement:

 C language provides a multi-way decision statement so that complex else-if statements


can be easily replaced by it. C language’s multi-way decision statement is called
switch.
 General syntax of switch statement is as follows:

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.

 The choice is an integer expression or characters.

 The label1, label2, label3,….are constants or constant expression evaluate to integer


constants.

 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:

Label  Number Label  Character


#include<stdio.> #include<stdio.>
#include<stdlib.h #include<stdlib.h
>void main( ) >void main( )
{ {
int ch,a,b,res; int a,b,res;
float div; char ch;
printf(“Enter two numbers:\n”); float div;
scanf(“%d%d”,&a,&b); printf(“Enter two numbers:\n”);
printf(“1.Addition\n 2.Subtraction\n scanf(“%d%d”,&a,&b);
3.Multiplication\n 4.Division\n 5.Remainder\n”); printf(“a.Addition\n b.Subtraction\n
printf(“Enter your choice:\n”); c.Multiplication\n d.Division\n e.Remainder\n”);
scanf(“%d”,&ch); printf(“Enter your choice:\n”);
switch(ch) scanf(“%c”,&ch);
{ switch(ch)
case 1: res=a+b; {
break; case ‘a’: res=a+b;
case 2: res=a-b; break;
break; case ‘b’: res=a-b;
case 3: res=a*b; break;
break; case ‘c’: res=a*b;
case 4: break;
div=(float)a case ‘d’:
/b;break; div=(float)a/

case 5: res=a%b; b;break;


break; case ‘e’ : res=a%b;
default: printf(“Wrong choice!!\n”); break;
} default: printf(“Wrong choice!!\n”);
printf(“Result=%d\n”,res); }

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

While loop (pre-tested/entry controlled):

 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.’

 The while loop will execute as long as the condition is true

 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 () {

/* local variable definition */


int a = 10;

/* while loop execution */


while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}

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 () {

/* local variable definition */


int a = 10;

/* 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:

for (initialization; condition; increment/decrement/update);


{
Statement block;
}
Statement Y;

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Initialization of loop variable

false
Controlling
condition for

true

Statement block

Update the loop variable

Statement Y

Example:

#include <stdio.h>

int main () {

int a;

/* for loop execution */


for( a = 10; a < 20; a = a +
1 ){printf("value of
a: %d\n", 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

Difference between while and do-while loop:

While do… while


It is a pre test loop. It is a post test loop.
It is an entry controlled loop. It is an exit controlled loop.
The condition is at top. The condition is at bottom.
There is no semi colon at the end of while. The semi colon is compulsory at the end of while.
It is used when condition is important. It is used when process is important.
Here, the body of loop gets executed if and only if Here, the body of loop gets executed atleast once
condition is true. even if condition is false.
SYNTAX, FLOWCHART, EXAMPLE (Same as in SYNTAX, FLOWCHART, EXAMPLE (Same as in
explanation) explanation)

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 ) {

for ( init; condition; increment )


{statement(s);
}
statement(s);
}

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

 It terminates the execution of remaining iteration of loop.

 A break can appear in both switch and looping statements.

 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

 It terminates only the current iteration of the loop.

 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

it is located before the goto statement, it is said to be a backward jump.

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;
}

fig: The function main() calls func1()

 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.

main() func1() func2() func3()


{ { { {

func1(); func2(); func3(); ---------------


------------- ------------- ------------- return ;
return 0; return ; return ; }
} } }

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:

Reusability and reduction of code size:

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.

Readability of the program can be increased:

Programs can be written easily and we can keep track of what each function is doing.

Modular programming approach:

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:

A function can be shared by many programmers.

Example program: Program to add two numbers using user-defined function

#include<stdio.h>

void add()

int a,b,sum;

printf(“enter the values for a and b\n”);

scanf(“%d%d”,&a,&b);
sum=a+b;

printf(“%d”,sum);

return;

void main()

add();

return;

ELEMENTS OF USER-DEFINED FUNCTIONS


There are three elements that are related to functions:
i. Function definition
ii. Function call
iii. Function declaration/Function prototype
1. Function declaration: As we normally declare the variables before they are used the
functions also should be declared before they are used. This process of declaring the
function before they are used is called function prototype. The function prototype also
known as function declaration.
A function declaration consists of four parts:
 Function type/ return type
 Function name
 Parameter List
 Terminating semicolon

Syntax: return_type function_name(list of parameters);

Ex: int sum(int, int);

The following points should be kept in mind about function declaration:

 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

sum(int a, int b);

 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:

function_type function_name(list of parameters) Function header int add(int a,int b)


{
int sum;
sum=a+b;
{ Function body return sum;
local variable declaration; }
executable statement1;
executable statement2;
......
......
return statement;

}
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:

1. Local declarations that specify the variables needed by the function.


2. Function statements that perform the task of the function.
3. A return statement that returns the value evaluated by the function.

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:

function name(variable 1,variable2,…);

Example: add (a,b);


Points to remember while calling a function:
 Function name and the number and type of argument in the function call must be same as
that given in the function declaration and the header of the function definition.
 If by mistake the parameters passed to a function are more than what it is specified to
accept then the extra arguments will be discarded.
 If by mistake the parameters passed to a function are less than what it is specified to
accept then the unmatched argument will be initialized to some garbage value.
 Names of variables in function declaration function call and header of function definition
may vary.
 If the data type of the argument passed does not match with that specified in the function
declaration, then either the unmatched argument will be initialized to some garbage value
or compile time error will be generated.

Example:

#include<stdio.h>

int sum(int a,int b); //FUNCTION DECLARATION

int main()

int num1,num2,total=0;

printf(“\n eneter the first number:=”);

scanf(“%d”,&num1);

printf(“\n enter the second number :”);

scanf(“%d”,&num2);

total=sum(num1,num2); // FUNCTION CALL

printf(“\n total=%d”,total);

int sum(int a,int b) //FUNCTION HEADER

{ //FUNCTION BODY

int result;

result=a+b;
return result;

Output:
Enter the first number: 20
Enter the second number: 10

Actual and Formal parameter:

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>

int add ( int a,int b) /*Formal parameter*/

return a+b;

void main()

int m,n,res;

printf(enter two numbers”);

scanf(“%d %d”,&m,&n);

res=add (m,n); /*Actual parameters*/

printf(“%d %d %d”,m,n,res);

return;
}

Actual parameter Formal parameter

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:

C=add(a,b); int add(int m,int n)

Here a and b are actual parameters. {

Actual parameters can be constants, variables Formal parameters should be only variables.
or expressions. Expressions and constants.

Example: Example:

C= add(a+4,b); int add(int m,int n) //correct

int add(int m+n,int n) //wrong

int add(int m,10) //wrong

Actual parameter sends values to the formal Formal parameters receive values from the
parameters. actual parameters.

Example: Example:

C=add(4,5); int add(int m,int n)

Here,m will have the vaue 4 and n will have


the value 5.
Passing parameter a function:
There are two ways to pass parameters to the function:

1. Pass by value/call by value


2. Pass by reference/call by reference

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:

 Makes the functions more self-contained.


 Protect them against accidental changes (i.e., even if formal parameters are changed
actual parameters are not changed.

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

Difference between Pass by value and pass by reference:

Pass by value Pass by reference


When a function is called the values of variable When a function is called the address of
are passed variables are passed
The type of formal parameters should be same The type of formal parameters should be same
as type of actual parameters as type of actual parameters, but they have to
be declared as pointers.
Change of formal parameters in the function The actual parameters are changed since the
will not affect the actual parameters in the formal parameters indirectly manipulate the
calling function. actual parameters.
Execution is slower since all the values have to Execution is faster since only addresses are
be copied into formal parameters. copied.
Transfer of information is possible only in one Even though only one value can be returned
direction i.e from calling function to the called using return statement, though the parameters
function. we can send the values to actual
parameters.Here,two way communication is
possible.

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.

Example: static int a, b;


Static variable have a lifetime over the entire program,i.e .memory for the static variables
is allocated when the program begins ruuning and is freed when the program terminates.

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 for function with no parameter and return value:

3. Function with parameters and no return values:


This category also called “void functions with parameters”. In this category, there is data
transfer from the calling function to the called function using parameters. But there is no
data transfer from called function to the calling 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.

 The syntax of return statement can be given as:


return <expression>;
Here the expression is placed in between angular brackets because specifying an
expression is optional.
 The value of expression if present is returned to the calling function.
 A function that has void as its return type cannot return any 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()
{

loop; /* goto label has function scope*/

goto loop; /*the goto statement*/

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.

Program scope/Global scope:


 Global variables declared outside the function bodies have program scope.
 The availability of global variable stays for the entire program after its declaration.

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.

Example 1: Factorial of number:

#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)

Greatest common divisor:


#include<stdio.h>
int GCD(int,int);
int main()
{
printf(“enter the value of a ,b”);
scanf(“%d%d”,&a,&b);
printf(“Result=%d”,GCD(a,b));
}
int GCD(int a,int b)
{
if(a==0)
return b;
else if(b==0)
return a;
else
return GCD(b,a%b);
}

The Fibonacci series:


#include<stdio.h>
int fib(int);
void main()
{
Int I,n;
printf(“enter the value of n terms”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
Printf(“%d”,fib(n));
}
int fib(int n)
{
if(n==0)
return 0;
else if(n==1)
return1;
else
return fib(n-1)+fib(n-2);
}
Finding exponent:
#include<stdio.h>
int exp_rec(int,int);
main()
{
int num1,num2,res;
printf(“\n enter the two numbers:”);
scanf(“%d%d”,&num1,&num2);
res=exp_rec(num1,num2);
printf(“\n result=%d”,res);
return 0;
}
int exp_res(int x,int y)
{
if(y==0)
return 1;
else
return (x* exp_rec(x,y-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:

A function is said to be directly recursive if it explicitly calls itself.

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:

A recursive function is said to be tail recursive if no operations are pending to be performed


when the recursive function returns to its caller. When the called function returns the returned
value is immediately returned from the calling function.
Example for tail recursion:

int Fact(int n)
{
if(n==1)
return 1;
return (n*fact(n-1));
}

Example for non tail:

int Fact (n)


{
return Fact1(n,1);
}
int Fact1(int n,int res)
{
if (n==1)
return res;
return Fact1(n-1,n*res);
}
Converting Recursive function to Tail Recursive:
 A non tail recursive function can be converted into a tail-recursive function by using a
auxiliary parameter as we did in case of the factorial function.
 The auxiliary parameter is used to form the result .when we use such a parameter, the
pending operation is incorporated into the auxiliary parameter so that the recursive call
no longer has a pending operation.

Linear and Tree recursion:

 A recursive function is said to be linearly recursive when the pending operation


does not make another recursive call to the function.
 A recursive function is said to be tree recursive if the pending operation makes
another recursive call to the function.
Introduction to C Programming BESCK104E

Module 4: ARRAYS

DEFINITION: An array is a collection of similar (homogeneous) data elements .these data


elements have the same data type. The elements of the array are stored in consecutive memory
locations and are referenced by index (also known as subscripts).

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:

type array name [size];

 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

This statement declares a marks variable to be an array containing 10 elements.

What are the rules to be followed while declaring an array?

 The expression must be enclosed within brackets

Example 1: int marks[5]; //OK : it is enclosed within brackets.

Example 2: int marks[5]; /error:It is enclosed within parentheses

Example3: int marks[5]; //Error: it is enclosed within braces

 The expression can be an integer constant:

Example 1: int marks[5]; //ok

Example 2: int marks[5.5]; //Error:expression must be an integer

 The expression can be an integer expression without variables.

Example 1:int marks[3+2]; //ok

Example 2: int marks[3+a]; //Error:expression must have constants but a is a variable.

 The integer expression enclosed within brackets must end with semicolon.

Example 1: int a[5]; //ok

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Example2: int a[2+3]; //ok

Example 3: int a[0]; //Error

Example 4: int a[2-2]; //Error

Accessing elements of the Array:

 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].

Example: int a[5]={10,20,30,40,50};

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:

Address of data element= base address+(size of(element)*index)

 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.

// set each elements of the array to -1

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:

Storing values in array:

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:

Type array name [size]={list of variables};

The values are written with curly brackets and every value is separated by a comma.

Example: int marks []={908,97,90};

 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

The various ways of initializing arrays are:

1. Initializing all specified memory location:


Array can be initialized at the time of declaration when their initial values are known in
advanced .Array elements can be initialized with data items of type integer, character,
float etc...

2. Partial array initialization:

Partial array initialization is possible in C l;anguage.If the number of values to be


initialized is less than the size of the array, then the elements are initialized in the order
from 0Th location. The remaining location will be initialized to zero automatically.

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

Calculating the length of the array:

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,

Length=upper bound-lower bound +1

Where upper bound is the index of the last element and lower bound is the index of the first
element in the array.

Solution:

Operations that can be performed on array:

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.

The algorithm for array traversal is given by:

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.

The algorithm to insert a new element to the end of the array:

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:

Algorithm to insert an element in the middle of the array:

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.

Algorithm to delete an element from the end of the array.

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 array elements:

 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

Declaration of two-dimensional array:

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:

Data type array name [row size][column size];

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.

Row/column Column 0 Column 1 Column 2 Column 3 Column 4


Row 0 marks[0][0] marks[0][1] marks[0][2] marks[0][3] marks[0][4]
Row 1 marks[1][0] marks[1][1] marks[1][2] marks[1][3] marks[1][4]
Row 2 marks[2][0] marks[2][1] marks[2][2] marks[2][3] marks[2][4]
Fig : Two dimensional array

Initialization of Two-dimensional Array:

A 2D array initialized in the same way as a 1D array.

Syntax:

return type array name[row size][column size]={list of values};

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}};

Accessing the elements:

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]);

Operations on two dimensional arrays:

Transpose:

Transpose of a m x n matrix A is given as a n x m matrix B where , Bi,j=Ai,j

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.

Elements of matrices can be multiplied by writing:

Ci,j =∑Ai,kBj,k for k=1 to k<n

One dimensional array for inter-Function communication:

One-dimensional

Passing individual Passing an entire


elements array

Passing data Passing


values addresses

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Passing individual elements:

The individual elements of an array can be passed to a function either by passing their addresses
or their data values.

Passing 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]);

void func(int num)

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]);

void func(int * num)

Printf(“%d”,num);

Passing the entire array:

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);

void func(int arr[5] )

int i ;

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

Printf(“%d”,arr[i]);

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Two –dimensional array for inter-function communication:

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.

2D array for inter-


function communication

Passing individual Passing row Passing an entire


element 2D array

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);

void func(int arr[5] )

int i ;

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

Printf(“%d”,arr[i]*10);

Passing the entire array:

 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.

Multi Dimensional arrays:

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..

N dimensional array is specified using n indices. An n-dimensional m1x m2 .

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Module 4- Strings and pointers

 A group of characters together is called string.


 String is always enclosed within double quotes(“:”)
 String always ends with deli meter (NULL,’\0’).

Declaration of a string:

A string is declared like an array of character.

 Syntax: data type string name [size];


 Example: char str [10];

Initialization of a string:

Syntax: data type string name [size]=value;

Example:

1. Char str []={‘H’, ’e’, ’l’, ’l’, ’o’, ’\0’};


Here compiler will automatically calculate the size based on the number of elements
initialized.so,in this example 6 memory slots will be reserved to store the string variable.

2. Char str [10]=”HELLO”;


The compiler created a character array of size 10, stores the value “HELLO” in it, and
finally terminates the value with a null character. Rest of the elementin the array is
automatically initialized to NULL.

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

3. Char str[5]=”HELLO”;

Reading strings:

If we declare a string by writing

Char str[100];

Then str can be read from the user by using three ways:

1. Using scanf function.


2. Using gets () function.
3. Using getchar() ,getch() or getche() function repeatedly.

The string can be read using scanf() by writing

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.

The next method of reading a string is by using gets() 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:

The strings can be displayed on screen using three ways:

1. Using printf() function.


2. Using puts() function.
3. Using putchar() function repeatedly.

The string can be displayed using printf() by writing

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

Fixed length string:

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.

Variable length string:

The string can be expanded or contracted to accommodate the elements in it.

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.

Length –controlled string:

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

Converting characters of a string into upper case:

 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”;

Printf(“\n the string converted into upper case is:”);

Puts(upper_str);

return 0;

Output:

enter the string : hello


The string converted into lower case is : HELLO

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Converting characters of a string into lower case:

 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”;

Printf(“\n the string converted into lower case is:”);

Puts(lower_str);

return 0;

Output:

Enter the string :Hello


The string converted into lower case is :hello

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Concatenating two strings to form a new string:

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’;

Printf(“\n the concentrated string is:”);

Puts(str3);

getch();

return 0;

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Output:

Enter the first string : Hello

Enter the second string : How are you?

The concentrated string is : Hello,How are you?

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;

printf(“\n enter the source string:”);


gets(source_str);
printf(“\n enter the destination string:”);
gets(Dest_str);
while(Dest_str[i]!=’\0’)
i++;
while(source_str[j]!=’\0’)

Dest_str[i]=source_str[j];

i++;

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

j++;

Dest_str[i]=’\0’;

Printf(“\n After appending , the destination string is :”);

Puts(Dest_str);

getch();

return 0;

Output:

Enter the source string :How are you?

Enter the destination string:Hi,

After appending,the destination string is :Hi,How are you?

Comparing two strings:

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

printf(“\n enter the first string :”);

gets(str1);

printf(“\n enter the second string ”);

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;

Printf(“\n the two strings are equal”);

if(len1!=len2)

printf(“\n the two strings are not equal ”);

if (same==0)

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

if(str1[i]>str2[i])

printf(“\n string1 is greater than string2”);

else if(str1[i]<str2[i]))

printf(“\n string2 is greater than string1”);

getch();

return 0;

Output:

Enter the first string: Hello

Enter the second string: Hello

The two strings are equal

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;

printf(“\n enter the string”);

gets(str);

j=strlen(str)-1;

while(i<j)

temp=str[j];

str[j]=str[i];

str[i]=temp;

i++;

j--;

Printf(“\n the reversed string is :”);

Puts(str);

getch();

return 0;

Output:

Enter the string :Hi there

The reversed string is:ereht iH

Extracting a substring from the left of a string:

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

If s1=”Hello world”,then substr_left(s1,7)=Hello w

Extracting a substring from the right of a string:

In order to extract a substring from the right side of the main string we need to first calculate the
position.

Example:

If s1=”Hello world” ,then substr_right(s1,7)=”o world”

Extracting a substring from the Middle of a string:

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:

Str[]=”Welcome to the world of programming”;


Then, Substring(str,15,5)=world

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:

Enter the main text: How you?

Enter the string to be inserted: are

Enter the position at which the string has to be inserted: 6

The new string is: How are you?

Indexing:

Index operation returns the position in the string where the string pattern first occurs.

Example:

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

INDEX(“Welcome to the world of programming”,”world”)=15

Deletion:

The deletion operation deletes a substring from a given text.we write it as


DELETE(text,position,length).

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;

printf(“\n enter the main text:”);

gets(text);

fflush(stdin);

printf(“\n enter the string to be deleted:”);

gets(str);

fflush9stdin);

while(text[i]!=’\0’)

j=0,found=0,k=i;

while(text[k]==str[j] && str[j]!=’\0’)

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:

Enter the main text :Hello,how are you?

Enter the string to be deleted :,how are you?

The new string is:Hello

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

Miscellaneous string and character functions:

Function Usage Example


isalnum(int c) Checks whether character c is isalpha(‘A’);
an alphanumeric character
isalpha(int c) Checks whether character c is isalpha(‘z’);
an alphanumeric character
iscntrl(int c) Checks whether character c is Scanf(“%d”,&c);
a control character iscntrl(c);
isdigit(int c) Checks whether character c is isdigit(3);
a digit
isgraph() Checks whether character c is isgraph(‘!’);
a graphic or printing
character.The function
excludes the white space
character
isprint(int c) Checks whether character c is isprint(‘@’);
a printing character.the
function includes the white
space charcter
Islower(int c) Checks whether the character Islower(‘k’);
c is in lower case
Isupper(int c) Checks whether the character Isupper(‘K’);
c is in upper case
Ispunct(int c) Checks whether the character Isspace(‘’)
c is a white space character
Isxdigit(int c) Checks whether the character Isxdigi(‘F’);
c is a hexadecimal digit
tolower(int c) Converts the character c to tolower(‘K’)
lower case Returns k
toupper(int c) Converts the character c to Tolower(‘k’)
upper case returns K

String Manipulation functions:


1. Strcat() function:

Syntax: char*strcat(char *str1,const char*str2);

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”;

Char str2[]=”in c”;

Strcat(str1,str2);

Printf(“\n str1: %s”,str1);

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”;

Char str2[]=”in c”;

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:

Char*strchr (const char *str, int c);

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 str[50]=”programming in c”;

Char *pos;

Pos=strchr(str,’n’);

if(pos)

printf(“\n n is found in str at position %d”,pos);

else

printf(“”\n n is not present in the string”);

return 0;

Output:

n is found in str at position 9

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

4. Strrchr()function:

Syntax:

Char*strrchr(const char *str,int c);

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 str[50]=”programming in c”;

Char *pos;

if(pos)

printf(“\n the last position of n is :%d”,pos-str);

else

printf(“\n n is not present in the string”);

return 0;

Output:

The last position of n is:13

5. strcmp() function:

Syntax:

int strcmp(const char * str1,const char *str2);

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)

printf(“\n the two strings are identical”);

else

printf(“\n the two strings are not identical”);

return 0;

Output:

The two strings are not identical

6. Strcpy() function:

Syntax:

Char *strcpy(char *str1,const char *str2);

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:

Size_t strlen(const char *str);

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”;

Printf(“\n length of str is :”%d”,strlen(str));

return 0;

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Output:

Length of str is :5

8. strstr() function:

Syntax:

Char*strstr(const char * str1,const char *str2);

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 str1[]=”HAPPY BIRTHDAY TO YOU”;

Char str2[]=”DAY”;

Char *ptr;

Ptr=strstr(str1,str2));

if(ptr)

printf(“\n substring found”);

else

printf(“\n substring not found”);

return 0;

Output:

Substring found

Array of string:

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

 String is an array of characters.


 For example if we say, char name[]=”Mohan”, then name is a string(character array) that
has five characters.
 Now suppose that there are 20 students in a class and we need a string that stores names
of all the 20 students.Here we need a string of strings or an array of strings.Such an array
of strings would store 20 individual strings.An array of sring is declared as,

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:

Data type array name [row size] [column size];

Memory representation of an array of strings

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:

 A pointer is a variable that contains the address of a variable.


 Pointer is indicated by * symbol.
 *Is known as deferencing operator.

Pointer declaration and initialization:

Pointer declaration:

Declaration refers to the process of creating a pointer declaration of a pointer.

Syntax:

Data type * Ptr_ name;

Here data type is the data type of the value that the pointer will point to.

Example:

int * p; // p is a pointer to an integer

float *pch;

char *pfnum;

 Pointer variables can hold only address of other variables.


 The above three pointers are called dangling pointers because pointers are not specifically
pointing to any particular variable

Example:

#include<stdio.h>

int main()

Printf(“\n the size of short integer is :%d”,sizeof(short int));

Printf(“\n the size of unsigned integer is :%d”,sizeof(unsigned int));

Printf(“\n the size of signed integer is:%d”,sizeof(signed int));

Printf(“\n the size of integer is:%d“,sizeof(int));

Printf(“\n the size of long integer is :%d”,sizeof(long int));

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Printf(“\n the size of character is :%d”,sizeof(char));

Printf(“\n the size of unsigned character is :%d”,sizeof(unsigned char));

Printf(“\n the size of signjed character is :%d,size of(signed char));

Printf(“\n the size of floating point number is :%d”,sizeof(float));

Printf(“\n the size of double number is :%d”,sizeof(double));

return 0;

Output:

The size of short integer is: 2

The size of unsigned integer is: 2

The size of signed integer is: 2

The size of integer is: 2

The size of long integer is: 4

The size of character is: 1

The size of unsigned character is: 1

The size of signed character is: 1

The size of floating point number is: 4

The size of double number is: 8

#include<stdio.h>

Int main()

int num,*pnum;

Pnum=&num;

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Printf(“\n enter the number:”);

Scanf(“%d”,&num);

Printf(“\n the number that was entered is:%d”,*pnum);

Printf(“\n the address of number in memory is :%p,&num);

return 0;

Output:

Enter the number:10

The number that was entered is:10

The address of number in memory is:FFDC

POINTER FLEXIBILITY:

We can make the same pointer to point to different data variables in different statements.

Ex: int x, y, z, *p;

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:

Process of assigning an address to the pointer.

Example:

int a=10;

int *p;

p=&a;

memory representation: a

10

p 1000(memory address of a)

1000

2000(memory address of p)

Accessing variables through pointers:

 Accessing variable’s values via pointers uses unary * operator.


 This is called as indirection or de-referencing operator.

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Example:

int a=5;

int *p;

p=&a;

we access a value by *p

Example program:

Program to demonstrate pointers.

#include<stdio.h>

Void main()

int a=5 *p; //declaration of variable a and pointer variable p

p=&a; //initializing address of a to p

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:

data type *variable;

Example:

int *p;

float *p;

double *p;

Untyped pointer or generic pointer:

 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;

Printf(“\n generic pointer points to the integer value=%d”,*(int*)gp);

gp=&ch;

printf(“\n generic pointer now points to the character %c”,*(char*)gp);

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:

int *ptr =NULL;

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;

Passing arguments to functions using pointers:

 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:

1. Declare the function parameter as pointers.

2. Use the dereference pointers in the function body.

3. Pass the address as the actual argument when the function is called..

Example: Swapping of two numbers.

#include<stdio.h>

Void swap(int * n1,int *n2);

Void min()

int a,b;

printf(“enter 2 numbers\n”);

scanf(“%d%d”,&a,&b);

swap(&a,&b);

printf(“after swap a=%d\nb=%d”,a,b);

Void swap (int *px,int *py)

int hold;

temp=*px;

*px=*py;

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

*py=temp;

Advantages of pointers:

 Pointers provide direct access to memory

 Pointers provide a way to return more than one value to the functions

 Reduces the storage space and complexity of the program

 Reduces the execution time of the program

 Provides an alternate way to access array elements

 Pointers can be used to pass information back and forth between the calling function and
called function.

 A pointer allows us to perform dynamic memory allocation and deallocation.

 Pointers helps us to build complex data structures like linked list, stack, queues, trees,
graphs etc.

 A pointer allows us to resize the dynamically allocated memory block.

 Addresses of objects can be extracted using pointers

Disadvantages of pointers:

 Uninitialized pointers might cause segmentation fault.

 Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to


memory leak.

 Pointers are slower than normal variables.

 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:

Struct structure name

Data type var-name;

Data type var-name;

……..

};

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

fig: memory allocation for a structure variable

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

Example2: Declare a structure to store customer information .

Solution:

Struct customer

int cust_id;

char name[20];

char address[20];

long int phone_num;

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:

Typedef existing data type new data type;

Example:

Typedef int INTEGER;

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

Data_type ember _name1;

Data_type ember _name2;

Data_type ember _nam3;

…….

};

Struct struct_name struct_var={constant1,constant2,constant3,…..};

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;

Struct student stud1={01,”Rahul”,”BCA”,45000};

Accessing the members of a structure:

A structure member variable is generally accessed using a ‘.’(dot) operator.

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);

Similarly,to print the values of structure variable stud1,we may write,

Printf(“%s”,stud1.course);

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

Printf(“%f”,stud1.fees);

Copying and comparing structure:

Assign a structure to another structure of the same type.

Example:

Two structure Variables stud1 and stud2 of type struct student is given as:

Struct student stud1={01,”Rahul”.”BCA”,45000};

Then to assign one structure variable to another we will write stud2=stud1;

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.

Structures and functions:

A function may access the members of a structure in three ways as

Passing individual
members

Passing the entire structure

Passing structures to
functions Passing the address of the
structure

Passing individual members:

 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:

The coordinates of the point are : 2 3

Passing the entire structure:

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,

Struct struct_name func_name(struct struct_name struct_var);

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)

printf(“the coordinates of the point are”%d%d”,a,b);

Output:

The coordinates of the point are :2 3

Passing structures through pointers:

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

Data type member_name1;

Data type member_name2;

Data type member_name3;

…………

}*ptr;

GSSSIETW,MYSURU
Introduction to C Programming BESCK104E

OR

Struct struct_name *ptr;

For our student structure we can declare a pointer variable by writing.

Struct student *ptr_stud, stud;

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;

to access the members of the structure one way is to write.

(*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

You might also like