Computing Fundamentals and C
Programming
Dr. Sabitha Banu
19-06-2023 Computing Fundamentals and C Programming 1
History of Computers
• people used sticks, stones, and bones as counting tools
• Human mind improved with time more computing devices were developed like
Abacus, Napier’s Bones, etc to perform mathematical calculations
19-06-2023 Computing Fundamentals and C Programming 2
19-06-2023 Computing Fundamentals and C Programming 3
Abacus – Calculator
• A counting device
• Beads are moved to perform
arithmetic functions
• Still used by traders and clerks
in Asia, Africa, …
2700-2300BC
19-06-2023 Computing Fundamentals and C Programming 4
Slide Ruler
• An early analogue computer used primarily for
multiplication and division.
• Invented by William Oughtred
• Slide rulers were taken to the moon in the 1960s
1620
19-06-2023 Computing Fundamentals and C Programming 5
Pascaline
• Blaise Pascal created the first mechanical calculator
• Performed addition and subtraction
• Was too expensive for the time, hence it didn’t
become a commercial device.
• https://www.youtube.com/watch?v=3h71HAJWnVU
1642
19-06-2023 Computing Fundamentals and C Programming 6
Tables
• Mathematical tables were created by people called
’computers’.
• They were large charts showing the results of calculations, e.g.
multiplication, division, and trigonometry
• However, these were known to be error prone,
• Thus the need for more accurate math drove innovation.
19-06-2023 Computing Fundamentals and C Programming 7
Charles Babbage
• Noticed errors in mathematical tables (1820)
• Created the difference engine to compute this
math more accurately
• Used tons of grant money as well as his own
• Only built a small part, as he also had to
construct the tools to build it
• The difference engine wasn’t finished, and he
went on to design the Analytical engine.
19-06-2023 Computing Fundamentals and C Programming 8
Difference Engine
• The first mechanical computer
• Created by Charles Babbage a
“father of computing”
• Compiled mathematical tables
• add, subtract, polynomial
functions
1821
19-06-2023 Computing Fundamentals and C Programming 9
Ada Lovelace
• She wrote the first algorithm that
would have been executed by
the Analytical Engine
• She is considered the worlds first
programmer
19-06-2023 Computing Fundamentals and C Programming 10
What are Punch Cards?
• Stiff paper that holds commands
• Commands and data are indicated by holes/no holes
• Early computers used these as input commands
19-06-2023 Computing Fundamentals and C Programming 11
Herman Hollerith
• During the Industrial revolution the population 30%
each decade.
• They were still tabulating census data by hand.
• In 1887 they still had not completed tallying the 1880
census data
• Herman Hollerith an MIT prof introduced punch cards
and a machine to read them to tally this information.
• Took only 6 weeks to tally the 1890 census
• He continued to improve the machine, and created
the company IBM
• A computer is an electronic machine that collects information, stores it,
processes it according to user instructions, and then returns the result.
• A computer is a programmable electronic device that performs arithmetic and
logical operations automatically using a set of instructions provided by the
user
19-06-2023 Computing Fundamentals and C Programming 12
Generations of Computers
S.No Generation & Description
1
First Generation
The period of first generation: 1946-1959. Vacuum tube based.
2 Second Generation
The period of second generation: 1959-1965. Transistor based.
3 Third Generation
The period of third generation: 1965-1971. Integrated Circuit based.
4 Fourth Generation
The period of fourth generation: 1971-1980. VLSI microprocessor based.
5 Fifth Generation
The period of fifth generation: 1980-onwards. ULSI microprocessor based.
19-06-2023 Computing Fundamentals and C Programming 13
19-06-2023 Computing Fundamentals and C Programming 14
1st Generation Computers
• 1951 – 1959
• Based on Vacuum tubes
• Vacuum tubes: Control electric current using the vacuum, and
• Can be used to start/stop, or change the flow based on the current
• produce a lot of heat and the installations used to fuse frequently.
• Expensive to replace if it does not work
• Batch processing operating system was used.
• Punch cards, paper tape, and magnetic tape was used as input and
output devices.
• The computers in this generation used machine code as the
programming language.
• The main features of the first generation are
Vacuum tube technology
 Unreliable
 Supported machine language only
 Very costly
 Generated a lot of heat
 Slow input and output devices
 Huge size
 Need of AC
 Non-portable
 Consumed a lot of electricity
Eg of First Generation computers are ENIAC ,EDVAC,UNIVAC,IBM-701,IBM-650
19-06-2023 Computing Fundamentals and C Programming 15
19-06-2023 Computing Fundamentals and C Programming 16
Second Generation Computers
• Based on Transistors
• 1959-1965
• Stored instructions in memory
• magnetic cores were used as the primary memory and magnetic tape and
magnetic disks as secondary storage devices.
• assembly language and high-level programming languages like FORTRAN,
COBOL were used.
• The computers used batch processing and multiprogramming operating
system.
• The main features of second generation are
Use of transistors
 Reliable in comparison to first generation computers
 Smaller size as compared to first generation computers
 Generated less heat as compared to first generation computers
 Consumed less electricity as compared to first generation computers
 Faster than first generation computers
 Still very costly
 AC required
 Supported machine and assembly languages
• Eg of Second generation Computers are IBM 1620,IBM 7094,CDC 1604,CDC
3600,
UNIVAC 1108
19-06-2023 Computing Fundamentals and C Programming 17
19-06-2023 Computing Fundamentals and C Programming 18
Third Generation Computers
• Modern computers
• 1965-1971
• Used Integrated Circuits(IC) invented by Jack Kilby
• A single IC has many transistors, resistors, and capacitors along with the
associated circuitry.
• made computers smaller in size, reliable, and efficient.
• remote processing, time-sharing, multiprogramming operating system
were used.
• High-level languages (FORTRAN- II TO IV, COBOL, PASCAL PL/1, BASIC,
ALGOL-68 etc.)
• The main features of third generation are
IC used
 More reliable in comparison to previous two generations
 Smaller size,Faster
 Generated less heat
 Lesser maintenance
 Costly
 AC required
 Consumed lesser electricity
 Supported high-level language
Eg of third generation computers are IBM-360 series,Honeywell-6000 series,PDP (Personal
Data Processor),IBM-370/168,TDC-316
19-06-2023 Computing Fundamentals and C Programming 19
19-06-2023 Computing Fundamentals and C Programming 20
Fourth Generation Computers
• VLSI(very large scale integration) Microprocessor
• Development of the personal computer
• 1971 – 1981
• Addition of GUI’s, the mouse, and handheld devices
• VLSI circuits having about 5000 transistors and other circuit elements with their
associated circuits on a single chip made it possible to have microcomputers of
fourth generation.
• Created by Intel corp.
• Becomes the Central Processing Unit (CPU)
• Allow computers to be smaller, more powerful, faster, and cheaper
• Time sharing, real time networks, distributed operating system were used.
• High-level languages like C, C++, DBASE etc.
• The main features of fourth generation are
VLSI technology used
Very cheap
Portable and reliable
Use of PCs
Very small size
 Pipeline processing
No AC required
Concept of internet was introduced
 Great developments in the fields of networks ,Computers became easily available
Eg of Fourth generation computers are DEC 10,STAR 1000,PDP 11,CRAY-1(Super
Computer),CRAY-X-MP(Super Computer)
19-06-2023 Computing Fundamentals and C Programming 21
19-06-2023 Computing Fundamentals and C Programming 22
Fifth Generation Computers
• 1990 – Present
• VLSI technology became ULSI (Ultra Large Scale Integration) technology
• Parallel Processing software and Enhancement of Artificial Intelligence
• Nanotechnology
• Natural Language Processing
• high-level languages like C and C++, Java, .Net etc.
• The main features of fifth generation are
ULSI technology
Development of true artificial intelligence
Development of Natural language processing
Advancement in Parallel Processing
Advancement in Superconductor technology
More user-friendly interfaces with multimedia features
Availability of very powerful and compact computers at cheaper rates
Eg of Fifth generation computers are Desktop,Laptop,NoteBook,UltraBook,
ChromeBook
https://www.youtube.com/watch?v=G19ldX05Gb4
https://www.youtube.com/watch?v=z3KnlfATUek
https://www.youtube.com/watch?v=ta7Fh-ZcfyM
19-06-2023 Computing Fundamentals and C Programming 23
Classification of Computers
Sr.No. Type Specifications
1 PC (Personal
Computer) or
Micro-
Computers
It is a single user computer system having a moderately
powerful microprocessor. It is termed as a computer that
is equipped microprocessor as its CPU
2 Workstation It is also a single user computer system, similar to the
personal computer, however, has a more powerful microprocessor.
3 Mini-Computer It is a multi-user computer system, capable of supporting
hundreds of users simultaneously
4 Main Frame It is a multi-user computer system, capable of supporting
hundreds of users simultaneously. Software technology is
different from minicomputer
5 Super-Computer It is an extremely fast computer, which can execute hundreds of millions of instructions
per second.
19-06-2023 Computing Fundamentals and C Programming 24
Personal Computer (PC)
• small, relatively inexpensive computer designed for an individual user.
• microprocessor technology that enables manufacturers to put an entire
CPU on one chip.
• word processing, accounting, desktop publishing, and
for running spreadsheet and database management
Applications,playing games and surfing the Internet.
• single-user systems, these systems are normally linked together to form a
network.
19-06-2023 Computing Fundamentals and C Programming 25
Workstation
• Applications which require a moderate amount of computing power and
relatively high-quality graphics capabilities.
• Eg. (CAD/CAM),desktop publishing, software development
• high-resolution graphics screen, a large amount of RAM, inbuilt network
support, and a graphical user interface
• mass storage device such as a disk drive ,and diskless workstation also
available
• UNIX and Windows NT OS
• Stand alone systems
19-06-2023 Computing Fundamentals and C Programming 26
Minicomputer - It is a midsize multi-processing system capable of supporting up
to 250 users simultaneously.
19-06-2023 Computing Fundamentals and C Programming 27
Mainframe - The mainframe is very large in size and is an expensive computer
capable of supporting hundreds or even thousands of users simultaneously.
Mainframe executes many programs concurrently and supports much
simultaneous execution of programs.
19-06-2023 Computing Fundamentals and C Programming 28
Supercomputer –
• Fastest computers
• Expensive and specialized applications are used
• Eg. weather forecasting, scientific simulations, (animated)graphics, fluid
dynamic calculations, nuclear energy research, electronic design, and analysis
of geological data
19-06-2023 Computing Fundamentals and C Programming 29
Anatomy of Computer
• A Computer is divided in to two components
• Hardware -tangible parts of the computer
• Software-intangible set of instructions that control the hardware and make it perform
specific tasks. Without software, a computer is effectively useless.
19-06-2023 Computing Fundamentals and C Programming 30
Hardware
• physical components of a computer that includes all mechanical,electrical,
electronic and magnetic parts attached to it
• Some of the major Hardware components are
Input and output devices
Central processing unit (CPU)
Memory unit and storage devices
Interface unit
19-06-2023 Computing Fundamentals and C Programming 31
19-06-2023 Computing Fundamentals and C Programming 32
19-06-2023 Computing Fundamentals and C Programming 33
Process of a Computer
19-06-2023 Computing Fundamentals and C Programming 34
Input devices
• The data and instructions are typed, submitted, or transmitted to a computer
through input devices.
• Input devices are electronic or electro-mechanical equipment that provide a
means of communicating with the computer system
for feeding input data and instructions.
• Some of the input devices are
Keyboard
Mouse
scanner
19-06-2023 Computing Fundamentals and C Programming 35
Output Devices
• Output devices mirror the input data, or show the output results of the
operations on the input data or print the data.
• Some of the output devices are
Monitor
printer
19-06-2023 Computing Fundamentals and C Programming 36
Central Processing unit
• Brain of the computer
• Most of the processing takes place in CPU.
• During processing, it locates and executes the program instructions.
• It also fetches data from memory and input/output devices and sends data
back
• CPU is also called as microprocessor
• IC with many metal pins which helps
in processing the data.
19-06-2023 Computing Fundamentals and C Programming 37
• The components of CPU are
19-06-2023 Computing Fundamentals and C Programming 38
Control Unit-
• Coordinates the processing by controlling the transfer of
data and instructions between main memory and the
registers in the CPU.
• It also coordinates the execution of the arithmetic logic
unit (ALU) to perform operations on data stored in
particular registers.
Arithmetic logic unit (ALU) –
• It is the part of the CPU that performs arithmetic
operations, such as addition and subtraction as well as
logical operations, such as comparing two numbers to see
if they are the equal or greater or less
RAM-
Computer memory refers to storage area where data is
stored. It is of two types −
 Primary Memory
 Secondary Memory
Memory Unit-
• storage area is needed in a computer to store instructions and data, either temporarily or
permanently, so that subsequent retrieval of the instructions and data can be possible on
demand.
• uses registers exclusively to store and manipulate data and instructions during the
processing
Primary memory/Cache-main memory of computer present in motherboard.
Secondary Memory/Auxiliary memory
• Sometimes when data to be processed is large, it cannot fit in primary memory as it is
limited, in such cases, we use supplement memory or secondary memory.
• Secondary memory helps to store information permanently and is non-volatile.
• access time is high,can store high amount of data
for longer Period of time
• Examples of secondary storage memory are compact
disk, floppy disk, pen drive, external hard drive, etc.
19-06-2023 Computing Fundamentals and C Programming 39
Primary Memory-
• data and programs are stored while the program is being executed along with the
data.
• Also known as main memory and accessed directly by the processor.
• Unit memory of fixed length and each of which is identified by a sequence number
known as a memory address.
• It is called cache memory
• It is a type of high speed memory that allows the processor to access data more
rapidly than from memory located elsewhere on the system.
• It stores or caches some of the contents of the main memory that is currently
in use by the processor. It takes a fraction of the time, compared to main memory,
to access cache memory.
• The management of data stored in the cache memory ensures that for 20 per cent
of the total time, during which the cache is searched, the data needed is found to
be stored in cache.
• As a result the performance of the computer improves in terms of speed of
processing
19-06-2023 Computing Fundamentals and C Programming 40
Primary memory/Cache memory
RAM
• Temporary memory
• Volatile
• In which, information stored is lost
once computer is turned off.
• Instructions written in this memory can
be modified; hence it is also known as
programmable memory
• Available in small storage capacity
• Processing speed is high
• Expensive
• Types of RAM
Static memory
Dynamic Memory
ROM
• Permanent memory
• Non-Volatile
• In which information stored is available
even if computer is turned off.
• Instructions stored in this memory can
only be read and cannot be modified.
• Available in high storage capacity
• Processing speed is low
• Non expensive
• Types of ROM are
PROM (Programmable Read Only Memory),
EPROM (Erasable PROM),
 EEPROM (Electrically Erasable PROM) and
flash memory.
19-06-2023 Computing Fundamentals and C Programming 41
Interface unit-
• Interconnects the CPU with memory and also with the various input/output (I/O) devices.
It is a set of parallel wires or lines which connects all the internal computer components
to the CPU and main memory.
• Depending on the type of data transmitted, a bus can be classified into the
following three types:
 Data bus The bus used to carry actual data.
 Address bus memory or Input/output device Addresses travel via the address bus.
 Control bus This bus carries control information between the CPU and other devices within the
computer
19-06-2023 Computing Fundamentals and C Programming 42
19-06-2023 Computing Fundamentals and C Programming 43
Types of Software
• PC software is basically sort of program that permits clients to play out specific
assignments or really use them to work their PC.
• It basically indicates all peripherals in whole PC system – precisely what to do
and how to carry out responsibility.
• set of computer programs, which provide desired functions and performance,
the data which the programs use, data structures that facilitate the programs to
efficiently manipulate data and documents that describe the operation and use
of the programs.
• Installation involves copying several files to computer memory or requires a
series of steps and configurations
• Software is generally categorized as System software and Application software
or utility software.
19-06-2023 Computing Fundamentals and C Programming 44
System Software-
• System software is designed to facilitate and coordinate the use of the computer by
making hardware operational.
• It interacts with the computer system at low level.
• Examples of such software include language translator, operating system, loader,
linker, etc.
• The most important system software is the operating system which is a set of
programs designed to control the input and output operations of the computer,
provide communication interface to the user, and manage the resources of the
computer system, such as memory, processor, input/output devices etc. and
schedule their operations with minimum manual intervention.
• System software is used in printers, monitors, graphics cards, sound cards, network
cards, modems, storage devices, mouse, scanners, etc.
• Modern operating system recognizes almost all connected hardware devices and
immediately begins the installation process which is called a plug and- play device.
19-06-2023 Computing Fundamentals and C Programming 45
Application Software
• Application software is designed to perform specific usages of the users
• Some of the examples of Application software are
 Microsoft Word
 Microsoft Excel
 Microsoft Power Point
 Microsoft Access
 Page Maker
Coral Draw
 Photoshop,
 Tally
 AutoCAD
 Acrobat
 WinAmp
 Micro Media Flash,
 Xing MP3 Player
19-06-2023 Computing Fundamentals and C Programming 46
Application
software
Custom
Software
Pre written
Software
Operating System
• Operating System (OS) is an interface between a computer user and computer
hardware.
• An operating system is a software which performs all the basic tasks like
file management,
memory management,
process management,
 handling input and output, and
controlling peripheral devices such as
disk drives and printers.
• Some popular Operating Systems include
Linux OS, Windows OS, VMS, OS/400, AIX,
z/OS, etc.
19-06-2023 Computing Fundamentals and C Programming 47
• Following are some of important functions of an operating System.
19-06-2023 Computing Fundamentals and C Programming 48
Operating
System
Memory
Management
Security
Controls I/O
devices
Job Scheduling
Error Detection
Processor
Management
Device
Management
File
Management
Categories of OS
• There are 6 different categories of OS
• Batch OS- oldest operating system, only one program is allowed to run at one time,
program cannot be modified during runtime, if error is encountered starting execute
from the scratch.eg MS-DOS
• Interactive OS-found after batch OS where only one program is processed at a time,
entering the data and program can be modified while program is running.
• Multi user OS-allows either one user or more than one use to use the computer system
at same time or different times.eg windows 2000 and LINUX
• Multi-tasking OS-allows more than one program to run at the same time
• Multi-threading OS-allows the running of different parts of the program at the same
time.
• Real-time OS-designed specially to handle real time applications or embedded
applications
• Multiprocessor OS-allows to use many CPU’s to process many processes at the same
time.
• Embedded OS-installed on electronic devices to perform some computational tasks.
19-06-2023 Computing Fundamentals and C Programming 49
19-06-2023 Computing Fundamentals and C Programming 50
MS-DOS Operating System
• Microsoft Disk Operating System
• Found by Microsoft Corporation for IBM computers in 1981
• It was stand alone in the earlier and now it is integrated with the all the
versions of windows.
• Command Line user Interface called MS DOS prompt
• Various commands are used to perform the operations in MS-DOS
• Categories of MS DOS commands are
• Environment command
• File Manipulation Command
• Utilities
19-06-2023 Computing Fundamentals and C Programming 51
19-06-2023 Computing Fundamentals and C Programming 52
• Environment Commands –provides some information on the OS
• File Manipulation command-manipulating files like copying or deleting a file.
19-06-2023 Computing Fundamentals and C Programming 53
Commands Used for
CLS Clear the content of the screen
VER Helps to view the Version of the MS-DOs
DATE Helps to view the current date
TIME Helps to view the current time and can edit the time
Commands Used for
COPY Copies one or more files from a location to another location
DEL deletes a file from the computer
TYPE View the contents of the files of a file
DIR Allows to view the files available in the directories
MS Windows OS
• The architecture of windows OS is comprised of 3 layers
User mode
Kernel Mode
Hardware
19-06-2023 Computing Fundamentals and C Programming 54
19-06-2023 Computing Fundamentals and C Programming 55
Networking Concepts
• Computer networks interconnects many computers and enable them to
communicate with each other and share their resources, data and
applications.
• A network is a combination of PC, or mixed of PC’s, mini and mainframes
spanning a particular geographical area.
• Computer networks are divided into
Based on geographical area
Based on how computer nodes are used.
19-06-2023 Computing Fundamentals and C Programming 56
Based
on
Geographical
area
LAN
WAN
MAN
Internet
Intranet
19-06-2023 Computing Fundamentals and C Programming 57
LAN-Local Area Network
WAN-Wide Area Network
MAN-Metropolitan Area Network
Internet-International Network
Based on how computer
nodes are used
CSN PPN VAN
19-06-2023 Computing Fundamentals and C Programming 58
CSN-Client to
Server Network
PPN-Peer to Peer
Network
VAN-Value Added
Network
Local Area Network(LAN)-
• Is a group of computers connected together.
• Computers that are connected within a small area like building or home etc.
• Using this networks users can communicate with
each other to share messages or information's.
• All the computers in LAN connected through
twisted pair or coaxial cables.
• Computers connected in LAN is limited
but communication rate is higher and faster.
19-06-2023 Computing Fundamentals and C Programming 59
19-06-2023 Computing Fundamentals and C Programming 60
Metropolitan Area Network(MAN)-
• Connection of computers that covers a large area or city.
• Size of MAN is between LAN and WAN covering the distance of 5km to 50km.
• Owned by general organizations
• Connects with the help of optical fibres, copper wires.
• Eg cable television network
• Router is a devices used to connect the LAN’s together.
• The router directs the information packets to the desired destination.
19-06-2023 Computing Fundamentals and C Programming 61
19-06-2023 Computing Fundamentals and C Programming 62
Wide Area Network(WAN)-
• Group of compuytres connected together tht covers with in a country or
continent.
• Two or more LAN’s are connected with the help of telephone lines,microwave
• Data is transmitted at a slow rate
19-06-2023 Computing Fundamentals and C Programming 63
19-06-2023 Computing Fundamentals and C Programming 64
Networking Topologies
• Arrangement of the computers through some physical medium such as cable
, coaxial cable etc.
• It refers to the shape of the network and the communication path between
various nodes in the network.
• Different type of topologies are
Hierarchical topology
Bus Topology
Star Topology
Ring Topology
Mesh Topology
Hybrid Topology
19-06-2023 Computing Fundamentals and C Programming 65
Hierarchical Topology
• Also called as Tree topology
19-06-2023 Computing Fundamentals and C Programming 66
Linear Bus Topology
• All the nodes are connected to the single
Backbone or bus with some medium such as
Cables.
19-06-2023 Computing Fundamentals and C Programming 67
Star Topology
• All the nodes are connected to a single device called hub
19-06-2023 Computing Fundamentals and C Programming 68
Ring Topology
• Here the nodes are connected with each other in a ring shape with the help
of twister air cable.
19-06-2023 Computing Fundamentals and C Programming 69
Mesh Topology-
• Every computer is connected to every other computer in point-point mode.
19-06-2023 Computing Fundamentals and C Programming 70
Hybrid Topology-
• Combination of multiple topologies used for constructing a large topology.
19-06-2023 Computing Fundamentals and C Programming 71
Network Protocols-
• Network protocols are set of rules and regulations used for communication
between two networks.
• Some of the Protocols are
• HTTP-Hyper Text Transfer Protocol
• SMTP-Simple Mail Transfer Protocol
• FTP-File Transfer Protocol
• TCP/IP-Transmission Control Protocol/Internet Protocol
• Telnet
• DNS-Domain Name Service
19-06-2023 Computing Fundamentals and C Programming 72
Programming Languages
• A programming language is a set of commands, instructions, and other syntax use
to create a software program.
• Languages that programmers use to write code are called "high-level languages."
• This code can be compiled into a "low-level language," which is recognized directly
by the computer hardware.
• High-level languages are designed to be easy to read and understand. Eg C++, Java,
Perl, and PHP.
• Low-level languages include assembly and machine languages.
• An assembler can be used to translate the assembly code into machine code. The
machine code, or machine language, contains a series of binary codes that are
understood directly by a computer's CPU.
• Machine language is not designed to be human readable.
19-06-2023 Computing Fundamentals and C Programming 73
Translator Programs
• converts code from one computer language into another
• Converts to high level language to low level language
• Different types of translators are
Compiler-converts high level programming language to low level programming
language and stores in memory
Interpreter- Compiler-converts high level programming language to low level
programming language
Assembler- translate assembly language(low-level) into machine language (lower
level),translates low level language to lower level language
19-06-2023 Computing Fundamentals and C Programming 74
• Difference between translator programs
19-06-2023 Computing Fundamentals and C Programming 75
Compiler Interpreter Assembler
• convert high-level programming
language to low-level
programming language
• converts the whole program in
one session and reports errors
detected after the conversion
• processor-dependent and
platform-dependent.
• Takes time for conversion
• used to convert high-level
programming language to low-
level programming language
• converts the program one line of
code at a time and reports errors
when detected
• Interpreter is faster than a
compiler as it immediately
executes the code upon reading
the code.
• a debugging tool for software
development as it can execute a
single line of code at a time
• Processor independent
• Portable than compiler
• Translate assembly language into
machine language
• Difficult to understand
• Low level language to lower
language level
Problem Solving Techniques
• Computer is used to solve the problem because it takes less time than
humans.
• Following are the steps to solve a problem
Analyze the problem
Divide the process in a series of elementary tasks
Formulate the algorithm to solve the problem
Express the algorithm in the form of program
Feed it in to computer
CPU interprets the given program, process the data and generates the result.
Send the generated result to the output unit
• Algorithms and Flowcharts are the two problem solving techniques.
19-06-2023 Computing Fundamentals and C Programming 76
Problem
Solving
Techniques
Algorithms
Topdown
approach
of
algorithms
Program
verification
Efficiency
of an
algorithm
flowcharts
19-06-2023 Computing Fundamentals and C Programming 77
Algorithm-
• Is a complete ,detailed, and precise step by step procedure to solve a
problem independently of the software or hardware of the computer.
• It instructs the computer what specific steps need to perform to solve a
problem.
19-06-2023 Computing Fundamentals and C Programming 78
Algorithm 1: Add two numbers entered by the user
• Step 1: Start
• Step 2: Declare variables num1, num2 and sum.
• Step 3: Read values num1 and num2.
• Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
• Step 5: Display sum
• Step 6: Stop
19-06-2023 Computing Fundamentals and C Programming 79
Algorithm 2: Find the largest number among three numbers
• Step 1: Start
• Step 2: Declare variables a,b and c.
• Step 3: Read variables a,b and c.
• Step 4: If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else If b > c
Display b is the largest number.
Else
Display c is the greatest number.
• Step 5: Stop
19-06-2023 Computing Fundamentals and C Programming 80
Top-down approach of algorithms-
• Also called as divide and conquer method.
• The problem is divided in to more sub problems and each of which
resembles the original problem.
• The solution of the sub problem is taken out independently and combined
together
• Eg Binary Search
19-06-2023 Computing Fundamentals and C Programming 81
Suppose we wish to search 38 in the array.
• Step 1: Find the middle element of the array.
• index(Middle) = index(low) + index(high – low)/2.
• Here, middle = 0 + (9-0)/2 = 4 i.e. the element at
the 4th index i.e. 25.
19-06-2023 Computing Fundamentals and C Programming 82
Step 2: Compare 38 with the middle element. 38 > 25 So, discard the first half.
Step 3: Select the send half of the array. For the second half, low = middle+1 as shown:
19-06-2023 Computing Fundamentals and C Programming 83
• Step 4: Find the middle element of this smaller array which comes out to 32.
Compare 38 with 32. 38 > 32 Thus, discard the first half of this array.
• Step 5: Select the remaining half of the array by doing low = middle+1 as
shown:
• Finally, we have found 38 and thus the algorithm will halt here.
19-06-2023 Computing Fundamentals and C Programming 84
Program Verification-
• Writing a program to perform a task and testing the program with different examples.
• If the program gives correct result then it is verified that program is correct.
Efficiency of an algorithm-
• How fast the program produces the correct result
• It depends upon the two factors
• Time Complexity-running time of the program
• Space Complexity-memory taken by the program
• Space Complexity defines the amount of memory required by the algorithm for the
execution and generation of the output.
• Time Complexity refers to the amount of computer time required by an algorithm for its
execution.
• It includes both compile and runtime.
19-06-2023 Computing Fundamentals and C Programming 85
Analysis of algorithm-
• Determines the amount of resources such as time and memory(space) required for the execution.
• Algorithm analysis provides theoretical estimates required by an algorithm to solve a problem.
Asymptotic Analysis
• Performance of the algorithm based on the input size
• Relation between the running time and the input size
• Time and Space factor
Worst, Average and Best Cases
• Divided into three different cases
 Best Case(Ω) − minimum time taken to execute the program.
 Average Case(θ) − average time taken to execute the program.
 Worst Case(O) − maximum time taken to execute the program.
Asymptotic Notations
• Asymptotic notations are mathematical tools to represent the time complexity of algorithms for asymptotic
analysis.
 Ο (Big O) Notation
 Ω (Omega)Notation
 θ (Theta) Notation
19-06-2023 Computing Fundamentals and C Programming 86
Flowchart-
• Pictorial representation of the algorithm depicting the flow of the various
steps.
• Visualize the working of an algorithm
19-06-2023 Computing Fundamentals and C Programming 87
19-06-2023 Computing Fundamentals and C Programming 88
References
1. https://gacbe.ac.in/pdf/ematerial/18BIT13C-U1.pdf
2. https://www.tutorialspoint.com/computer_concepts/computer_concepts_c
omputer_memory.htm?key=Types+of+software
3. https://www.geeksforgeeks.org/
19-06-2023 Computing Fundamentals and C Programming 89
Overview of C
• C is one of the most popular language
• It is a structured ,high-level, machine
independent language.
• ALGOL was the first structured programming
language and it is the root of the programming
languages.
• BCPL –Basic Combined Programming Language
used for writing system software
• B was used in UNIX OS in Bell Laboratories.
• C was evolved from ALGOL,BCPL,B by
dennis Ritchie at the Bell laboratories in 1972.
19-06-2023 Computing Fundamentals and C Programming 90
• C uses concepts from the previous languages and concept of datatypes and
other powerful features were added.
• After the publication of book “The C Programming Language” written by Brian
Kerningham and Dennis Ritchie in 1978 it was called K&R C
• ANSI (American National Standards Institute )approved the standard of C so it
was called ANSI C and later approved by ISO (International Standard
Organization) so it was called ANSI/ISO C or C89.
• Later on in 1990 C++ and JAVA modelled on C and some features from C++ and
Java used in C called as C99.
19-06-2023 Computing Fundamentals and C Programming 91
Importance of C
• Robust Language
• Efficient and fast
• Built in functions and 32keywords
• Highly portable
• Structured Programming which makes debugging,testing and maintenance
easier.
• Ability to extend with functions supported by C library.
19-06-2023 Computing Fundamentals and C Programming 92
SAMPLE PROGRAM FOR PRINTING A MESSAGE
main()-execution of the program
begins or start of the program
every program should have 1 main().
if the program has more than one
main() .the compiler cannont understand
where to begin.
{-beginning of the function, }-closing of the function
Statements between { &} are called function body which contains set of instructions to
perform a task
19-06-2023 Computing Fundamentals and C Programming 93
Output
• printf statement is the only executable statement
• /* or// known as comment lines
whichare not executable statement to
Enhance the readability and
understandability.
• Comment lines are ignored by the
Compiler
• Comments can be inserted anywhere inside the program
• Printf is a predefined standard C function for printing output.
• Predefined-function that is already written and compiled linked with the program.
• It should be given with “ ******“
• Every statement should end with semicolon(;)
19-06-2023 Computing Fundamentals and C Programming 94
• If printf function is given like
• n-instructs the computer to go to the next new line
• n should be given wth string of characters without any space between  and
n followed by coma(,)
19-06-2023 Computing Fundamentals and C Programming 95
• In C program is written in lower case letters
• For eg PRINTF and printf is not
same
19-06-2023 Computing Fundamentals and C Programming 96
• main() is part of the every C Program
• Different forms of main() statement are
• Empty parantheses () means that the function has no
arguments.
• void() returns does not return any info to the OS
• int() returns integer value to the OS and if int is
specified last statement of the program must be
“return 0”
19-06-2023 Computing Fundamentals and C Programming 97
Number and amount-
variable names
Variables must be
declared before they
use to tell the compiler
int ,float-keywords
Values are assigned by
using assignment
operators
number=100
amount=30.75+75.35
%d –decimal integer
%5.2f-values of 5 places
with 2 values after
decimal point of float
datatype
19-06-2023 Computing Fundamentals and C Programming 98
• #define –pre-processor compiler directive not a statement
• It should not end with semicolon
• Symbolic constants are written in uppercase letters to distinguish between the
variable names.
• #define placed in the program in the beginning before the main().
• #define –defines values to a symbolic constant
• Wherever #define is encountered compiler substitutes the value with the
name automatically.
• For eg
19-06-2023 Computing Fundamentals and C Programming 99
• If 3 variable of same data type it can be given in one line separated by comma.
• For eg
• C supports four basic arithmetic operators
• + (addition)
• -(subtraction)
• *-(multiplication)
• /-(division)
19-06-2023 Computing Fundamentals and C Programming 100
float amount,value,inrate;
Uses of Subroutines
• Subroutines which is also called sub functions or sub program
• User-defined function : A funtion defined by the user
19-06-2023 Computing Fundamentals and C Programming 101
• Syntax of function declaration
return_type function_name( parameter list );
•
19-06-2023 Computing Fundamentals and C Programming 102
Use of MATH functions
• If a program contains standard mathematical functions like
• Sin
• Cos
• Tan
• Exp
• C makes use of MATH library function
• #include<math.h>
• The standard mathematical functions are defined and kept as a part.
• Tells the compiler to link the mathematical functions from the math library
with the program.
19-06-2023 Computing Fundamentals and C Programming 103
#include directive preprocessor
• C is comprised of user defined functions and library functions
• Library functions are stored in different header files.
• #include<filename.h> must be included in the program telling the compiler
about the files to be accessed in the program
19-06-2023 Computing Fundamentals and C Programming 104
Basic structure of the C program
19-06-2023 Computing Fundamentals and C Programming 105
Set of comment lines giving the name of the program etc // or/*
Links the library functions
Symbolic constants definition
Variable used in more than one functions are declared globally
Every c program must have main()
Contains declaration part and executable statements part
Contains { } tells the compiler program execution start and end
Every statement ends with semicolon(;)
Subprograms contains the user-defined functions
It can be called in the main() function
Programming Style
• C is a free form language
• C program statements should be written in lower case letters
• Upper case statements used to define symbolic constants.
• Indentation of braces is important to identify opening and closing line of program.
19-06-2023 Computing Fundamentals and C Programming 106
Executing a C program
• It has a series of steps
Creating the program
Compiling the program
Linking the program with the library functions
Executing the program
19-06-2023 Computing Fundamentals and C Programming 107
• A Programming language helps to process some kinds of data consisting of
numbers,characters,strings to provide a useful output called information.
• Data is processed by giving a set of instructions called program
• These instructions consists of words and symbols according to some rules
called syntax rules.
• Every program must follow the syntax rules
Character set
• The characters used in C are
Letters
Digits
Special characters
White spaces
19-06-2023 Computing Fundamentals and C Programming 108
19-06-2023 Computing Fundamentals and C Programming 109
Trigraph Characters
• Trigraph characters consists of 3 charcaters (2 question marks followed up by
another character)
19-06-2023 Computing Fundamentals and C Programming 110
C Tokens
• The smallest individual unit are known as C tokens
19-06-2023 Computing Fundamentals and C Programming 111
Keywords and Identifiers
• Every C word is classified into
• Keywords
• Identifiers
• These keywords have fixed meanings cannot be changed
19-06-2023 Computing Fundamentals and C Programming 112
Identifiers –
• Refers name of the variables,functions, and arrays
• User defined names
• Can use both upper case and lowercase letters
• _ is also permitted in identifiers
19-06-2023 Computing Fundamentals and C Programming 113
Constants
• Refers to fixed values that do not change during execution of the program
19-06-2023 Computing Fundamentals and C Programming 114
Integer Constants-refers to a sequence of digits.
• Decimal integer-0 to 9 ,+,-
• Octal integer-any digits from 0to 7 leading with 0.
• Hexadecimal integer-sequence of digits preceded by 0x or 0X ,A-F or a-f
19-06-2023 Computing Fundamentals and C Programming 115
No spaces, commas,any symbols
Real/Floating point Constants
• Numbers containing fractional parts
• Exponential or scientific notation is given as
Single Character Constant-
• Contains a single character enclosed in single quotes ‘ ‘ eg. ‘r’
• Print 97
19-06-2023 Computing Fundamentals and C Programming 116
String constants-
• Sequence of characters enclosed within “ “
• It may be letters,numbers,special characters,blank spaces
• ‘X’≠ “X”
Backslash character constants-
• C supports backslash characters(n) in some output functions.
19-06-2023 Computing Fundamentals and C Programming 117
19-06-2023 Computing Fundamentals and C Programming 118
Variables
• It refers to the data name to store some values
19-06-2023 Computing Fundamentals and C Programming 119
No white spaces, keywords,TOTAL ≠total
Data Types
• C is rich in its data type
• Three classes of data types are
• Primary or fundamental datatype
• Derived data type
• User defined data type
19-06-2023 Computing Fundamentals and C Programming 120
Integer
• Has 3 classes based on range and storage of numbers
Floating point/real data type
19-06-2023 Computing Fundamentals and C Programming 121
Void datatype-
• Has no values
• Does not return any value to the calling function
• Represent any data types
Character datatype-
• A single character can be defined using char datatype.
19-06-2023 Computing Fundamentals and C Programming 122
Declaration of variables
• Declaring a variable tells the compiler what the variable name is.
• What type of data the variable will hold.
• Declaration must be done before the program
• Declaration of variable can be done before or after the main()
19-06-2023 Computing Fundamentals and C Programming 123
Variable
declaration
Primary type
declaration
User defined
declaration
Primary type declaration-
• A variable can be used to store a value of any data type
• V1,v2,…vn –variable names
• Variables are separated by commas
• Declaration must end with semicolon(;)
19-06-2023 Computing Fundamentals and C Programming 124
19-06-2023 Computing Fundamentals and C Programming 125
User defined declaration-
• C supports a feature known as “type definition” that allows the user to define
an identifier that would represent an existing data type
• Later it can be used to declare variables
• Advantage of typedef is to create a meaning full data type name for increasing
the readability of the program.
19-06-2023 Computing Fundamentals and C Programming 126
Declaration of Storage class
• Storage class that provides information about their location and their visibility
• The storage class decides the portion of the program within which the variables
are recognized
19-06-2023 Computing Fundamentals and C Programming 127
• ‘m’-called as global or external variable
• Variable declared before the main() is called
global or external variable
• variables I,balance,sum are called local
variables which can be used only inside the
program
• Local variables are visible and meaningful
only inside the program or functions where it
is declared.
• Variable ‘i’ is declared in both functions does
not affect the value
• C has variety of storage class classifiers used to declare explicitly the scope
and lifetime of variables
• Scope and lifetime is considered only in the program which contains multi
functions and multi program files
19-06-2023 Computing Fundamentals and C Programming 128
Storage
class
auto register static extern
19-06-2023 Computing Fundamentals and C Programming 129
Assigning values to variables
Assignment statement(=)-
• Values can be assigned to a variable using the = operator
19-06-2023 Computing Fundamentals and C Programming 130
19-06-2023 Computing Fundamentals and C Programming 131
• The process of giving initial values to variables I called
initialization
• C permits initialization of values to more than one variables
in one statement using the assignment operator
• External and static variables are initialized to zero by
default
• Auto variables which does not contain values called as
garbage
Reading data from keyboard-
• Giving values to variables is to input data through keyboard
• “scanf()”
• Input statement
• “control string”-format of data being received
• “&variable1-address of the variable1
• If & is not given error occurs in scanf statement
• When compiler encounters scanf statement executions stops and waits till
the value of the number is typed in.
• Once the value is entered it the computer proceeds to the next statement
19-06-2023 Computing Fundamentals and C Programming 132
Defining symbolic constants
• It is also another way assigning values to constants
•
19-06-2023 Computing Fundamentals and C Programming 133
19-06-2023 Computing Fundamentals and C Programming 134
19-06-2023 Computing Fundamentals and C Programming 135
19-06-2023 Computing Fundamentals and C Programming 136
• Declaring variable as a constant
• Declaring variable as volatile
 a variable declared as volatile tell the complier explicitly that the value
may be change at any time by external sources(outside of the programs)
If the value should not modified then it can be declared as
19-06-2023 Computing Fundamentals and C Programming 137
Overflow and underflow of data-
• Overflow occurs when the value of variable is either too big or too small for
the data type to hold.
• The largest value that a variable can hold depends up on the machine
• Over flow error results in largest possible float point
• Underflow errors result in zero
•
19-06-2023 Computing Fundamentals and C Programming 138
Operators and Expressions
• An operator tells a computer to perform a mathematical or logical
manipulation
• Operators used to manipulate data and variables
• Operators form a part of mathematical or logical expressions
19-06-2023 Computing Fundamentals and C Programming 139
C operators
Arithmetic
operators
Relational
operators
Logical
operators
Assignment
operators
Increment
and
decrement
operators
Conditional
operators
Bitwise
operators
Special
operators
• An expression is a sequence of operators and operands that reduces to a
single value
• For eg =25(Value)
• The return type of the value can be of any type except ‘void’
Arithmetic Operators
• C provides all basic arithmetic operators
19-06-2023 Computing Fundamentals and C Programming 140
a,b are operands
Arithmetic
operators
Integer
arithmetic
Real
arithmetic
Mixed mode
arithmetic
19-06-2023 Computing Fundamentals and C Programming 141
Integer arithmetic
• When an operands both are integers with an arithmetic operator
Real arithmetic
• It contains operations of 2 real operands
• %(mode) cannot be used with real arithmetic
19-06-2023 Computing Fundamentals and C Programming 142
When modulo division the sign of the result
will have the sign of first operand
Mixed mode arithmetic
• When one of the operand is real and another is integer
• For eg
• When one of the operand is real type the result of the expression will be in
real type
19-06-2023 Computing Fundamentals and C Programming 143
Relational Operators
• Comparing 2 operands and depending on their relations decisions are made
• These comparisons and relations are made by using relational operators
• C supports 6 types of relational operators .result of the relational expression
will be either 0 or 1 /true or false
19-06-2023 Computing Fundamentals and C Programming 144
19-06-2023 Computing Fundamentals and C Programming 145
• Arithmetic operators have high priority than relational operators
• Relational operators are expressed in if and while loop
Relational Operator complements
Logical operators
• C follows three logical operators
• Logical operators && and || are used to test more than one one condition and
make decisions
• An expression combines two or more relational expressions are called logical
or compound relational expression
• For eg
19-06-2023 Computing Fundamentals and C Programming 146
• The result of an logical expression will be either true or false
19-06-2023 Computing Fundamentals and C Programming 147
Assignment operators
• Assigning the result of an expression to a variable by using “=“
• C supports a set of shorthand assignment operators
19-06-2023 Computing Fundamentals and C Programming 148
X=x+3
Advantages of shorthand operators
• It is easier to read and concise
• More efficient
• No need of repeating left hand side
19-06-2023 Computing Fundamentals and C Programming 149
Increment and decrement operators-
• C allows two operators for increment and decrement of variable
• The operator ++ adds 1 to the operand and -- decreases value by 1
• It is also called unary operator
19-06-2023 Computing Fundamentals and C Programming 150
Behaviour of m++ and ++m /m– and –m
19-06-2023 Computing Fundamentals and C Programming 151
19-06-2023 Computing Fundamentals and C Programming 152
Conditional operator-
• Ternary operator “?:” cosntructsthe conditional expression
• Exp1 is evaluated first if it is true exp2 is evaluated and becomes the value of
the expression
• If exp1 is false ,exp3 is evaluated and becomes the value of the expression
19-06-2023 Computing Fundamentals and C Programming 153
Bitwise operators
• Testing the data in bit wise, shifting left or right
• Float or double is not permitted
19-06-2023 Computing Fundamentals and C Programming 154
Special operators-
• C supports some special operators
• Comma operator(,)
• sizeof()
• Pointer operators(* and &)
• Member selection operator(. and ->)
• Comma operator(,)-links the related expression together
19-06-2023 Computing Fundamentals and C Programming 155
• sizeof()-returns the number of bytes that operand occupies,can be used to
know the length of arrays or structures when the size is not known to the
programmer,can also be used to allocate memory dynamically
19-06-2023 Computing Fundamentals and C Programming 156
Arithmetic expressions-
• Combinations of variables,constants and operators
• It does not have any operator for exponentiation
19-06-2023 Computing Fundamentals and C Programming 157
Evaluation of expression-
• Expressions are evaluated using the assignment operator
19-06-2023 Computing Fundamentals and C Programming 158
Precedence of arithmetic expressions-
• Arithmetic expressions are evaluated from left side given inside the
parentheses
• Using the rules of precedence of operators
• C have 2 distinct priority levels of arithmetic operators
• High priority -* / %
• Low priority- + -
• For eg
19-06-2023 Computing Fundamentals and C Programming 159
• High priority -* / %
• Low priority- + -
19-06-2023 Computing Fundamentals and C Programming 160
19-06-2023 Computing Fundamentals and C Programming 161
• If the expression has
parentheses values within the
parentheses will be evaluated
first
• If it contains more sets of
parentheses parentheses
value are evaluated first from
the left hand side and the
right most end in the last
19-06-2023 Computing Fundamentals and C Programming 162
Type Conversions in Expression
19-06-2023 Computing Fundamentals and C Programming 163
Type
Conversions
Implicit
Conversion
Explicit
Conversion
Implicit Conversion-
• Automatic Conversion of datatypes
• During conversion it follows some rules
• If the lower type is converted to higher type the result will be of higher
datatype
Explicit Conversion-
• Forced type conversion or manual type conversion different from automatic
conversion
• The process of local conversion is called implicit conversion/casting a value
19-06-2023 Computing Fundamentals and C Programming 164
int female_number;
int male_number;
• The expression can be a value or constant or an expression
19-06-2023 Computing Fundamentals and C Programming 165
Operator Precedence and Associativity-
• The precedence is used to determine how an expression involving more than
one operator is evaluated
• The operators ta the higher level of precedence are evaluated first
• The operators having the same precedence are evaluated from left to right or
from right to left called associativity
19-06-2023 Computing Fundamentals and C Programming 166
Math functions-
• The math functions supported by c compilers are used in real life problems
19-06-2023 Computing Fundamentals and C Programming 167
Managing input and output operations-
• Reading ,processing and writing of data are the essential functions of a
computer program
• Some functions use to take data and some functions to display data
• Two ways to providing data to the variables
• Assignment operator
• Scanf and printf function
• Scanf-to read data from the keyboard
• Printf-to display data on the screen
19-06-2023 Computing Fundamentals and C Programming 168
Reading a character-
• Reading a character from the standard input unit(keyboard)
• Writing a character to the standard output unit(screen)
• Reading a single character can be done by the function
• scanf() function can also be used to read the input
• When getchar() is encountered the computer waits till it receives input from
the user through the keyboard
19-06-2023 Computing Fundamentals and C Programming 169
19-06-2023 Computing Fundamentals and C Programming 170
19-06-2023 Computing Fundamentals and C Programming 171
19-06-2023 Computing Fundamentals and C Programming 172
19-06-2023 Computing Fundamentals and C Programming 173
• #include<stdio.h>
• #include<math.h>
• #include<ctype.h>
19-06-2023 Computing Fundamentals and C Programming 174
Unit -3
Decision Making ,Looping and Arrays
• Executing a segment of a program repeatedly by introducing a counter and
later testing it using the if statement
• For every decision making loops ,
• Initialize
• Test
• Increment
• Above steps to be followed to complete a loop
19-06-2023 Computing Fundamentals and C Programming 175
Calculating the sum of squares for all integers between 1 and 10 using if
statement
19-06-2023 Computing Fundamentals and C Programming 176
• Looping-sequence of statements are executed until some conditions for
termination of the loop are satisfied
• A Program loop contains
• Body of the loop
• Control statement
• Depending on the position of the control statement in the loop control
structure is classified into
• Entry controlled loop/pre-test loop
• Exit controlled loop/post-test loop
19-06-2023 Computing Fundamentals and C Programming 177
• Entry controlled/Pre-test loop
 The control conditions are tested before
the start of the loop execution.
If the conditions are not satisfied then the
body of the loop will not be executed
19-06-2023 Computing Fundamentals and C Programming 178
• Exit controlled/Post-test loop
The test is performed at the end of the body of the loop and therefore the body is
executed unconditionally for the first time
19-06-2023 Computing Fundamentals and C Programming 179
• Infinite loop-
The body of the loop is executed over and over again.
• The four steps of the looping process includes
1. Setting and initialization of the condition variable
2. Execution of the statements in the loop
3. Test for a specified value of the condition variable for execution of the loop
4. Incrementing or updating the condition variable
• c language has 3 constructs for performing loop operations
The while statement
The do statement
The for statement
19-06-2023 Computing Fundamentals and C Programming 180
While loop
• Simplest form of looping structure
• The basic structure of while loop is
• It is an entry controlled loop
• The test condition is evaluated first and if it is true the body of the loop is
executed until the test condition becomes false
• The control is transferred out of the loop once it becomes false
• The body of the loop must contains one or two statements and entred with
in { …. }
19-06-2023 Computing Fundamentals and C Programming 181
19-06-2023 Computing Fundamentals and C Programming 182
19-06-2023 Computing Fundamentals and C Programming 183
19-06-2023 Computing Fundamentals and C Programming 184
Do loop
• The structure of do loop is
•
19-06-2023 Computing Fundamentals and C Programming 185
For loop
• The general form of for loop structure is
19-06-2023 Computing Fundamentals and C Programming 186
19-06-2023 Computing Fundamentals and C Programming 187
19-06-2023 Computing Fundamentals and C Programming 188
Additional Features of for loop-
• Initialization, Testing control variables and increment or decrementing a
variable can have more than one variable
• For eg
19-06-2023 Computing Fundamentals and C Programming 189
• It is permissible to use expressions in the assignment statements of
initialization and increment sections
• Some sections in for loop can be omitted if necessary
• Only the variable is omitted but semicolon remains
19-06-2023 Computing Fundamentals and C Programming 190
• When a for loop does not have test condition it sets up a infinite loop
• It can be stopped by using
• break
• goto
• Null statement
19-06-2023 Computing Fundamentals and C Programming 191
Nesting of for loops-
• One for statement within another for statement
• The loops must be properly indented
• It can have 15 nesting loops and even more
19-06-2023 Computing Fundamentals and C Programming 192
19-06-2023 Computing Fundamentals and C Programming 193
Selecting a loop
19-06-2023 Computing Fundamentals and C Programming 194
JUMP statement in loop–
• C Permits a jump from one statement to another within a loop as well as a
jump out of a loop
I. JUMPING out of a loop
break –will exit only one single loop
Goto
19-06-2023 Computing Fundamentals and C Programming 195
19-06-2023 Computing Fundamentals and C Programming 196
19-06-2023 Computing Fundamentals and C Programming 197
II Structured Programming
• Approach to the design and development of the programs
• a Discipline making a program’s logic easy to understand by using only the
following 3 control structures
Sequence structure
Selection(branching) structure
Repetition (looping) structure
• Structured programming techniques helps to ensure the programs easy to
write ,read, debug, and maintain compared to those which are unstructured.
• C supports another similar statement called continue statement.
• Continue causes a loop to be continued with the next iteration after skipping
some statements in between
19-06-2023 Computing Fundamentals and C Programming 198
• Continue statement tells the compiler “skip the following statements and
continue with the next iteration
• The format of continue statement is
19-06-2023 Computing Fundamentals and C Programming 199
19-06-2023 Computing Fundamentals and C Programming 200
19-06-2023 Computing Fundamentals and C Programming 201
19-06-2023 Computing Fundamentals and C Programming 202
Avoiding goto statements –
• It makes the program logic complicated and renders the program
unreadable
• Many compilers generate a less efficient code
• If it is necessary it should be documented
19-06-2023 Computing Fundamentals and C Programming 203
Jumping out of the program-
• Break statement
• Goto statement
• exit()- library function which breaks the program and return to the os.
• Exit() takes an integer as an argument
• 0-normal termination
• Non zero-abnormal termination or due to an error
19-06-2023 Computing Fundamentals and C Programming 204
Arrays
• To handle bulk volume of data in terms of reading processing and printing
• Need of new and powerful data type that would facilitate efficient storing,
accessing and manipulation of data items
• C supports a derived data type arrays which can be used in these applications.
• Array is a fixed size sequenced collection of elements of the same data type.
simply like grouping of like-type data.
• For eg array can be used to represent a list of names or numbers
19-06-2023 Computing Fundamentals and C Programming 205
• It is classified as one of the data structures in C
• Data Structure -Structuring/organizing the Data in a computer so that it can
be used effectively .Other types are structures,queue,trees ,graphs and lists.
• Array can have a common name
• For eg salary for representing set of salaries for 100 employees
• Individual salary can be represented by index or subscript
19-06-2023 Computing Fundamentals and C Programming 206
• fixed-size sequenced collection of variables belonging to the same data types
and stored in contiguous memory.
• Set of pairs, index or value
• The array has adjacent memory locations to store values.
• convenient structure for representing data
• Two terms to understand the concept of array are Element and Index
Element − Each item stored in an array is called an element.
Index − Each location of an element in an array has a numerical index, which is used to
identify the element.
data_type array_name [array_size];
19-06-2023 Data Structures
• Index starts with 0.
• Array length is 10 which means it can store 10 elements.
• Each element can be accessed via its index(mapping). For example, we can fetch an
element at index 6 as 9.
• Arrays can be not only to represent a list of values but also a table of two or three or ore
dimensions
• Different types of arrays
• One dimensional or 1D array
• Two Dimensional or 2D array
• Three Dimensional or 3D array
19-06-2023 Data Structures
19-06-2023 Computing Fundamentals and C Programming 209
1D or one dimensional array-
• A list of items having one variable name with only one subscript
• Computer reserves 5 storage locations
• Int number[5]={35,40,20,57,19}
19-06-2023 Computing Fundamentals and C Programming 210
19-06-2023 Computing Fundamentals and C Programming 211
Char name[10]=“well done”;
When declaring a character arrays ,allocate one extra element space
for the null terminator
When a compiler reads a character arrays it terminates with the
additional null character(‘0’)
19-06-2023 Computing Fundamentals and C Programming 212
19-06-2023 Computing Fundamentals and C Programming 213
19-06-2023 Computing Fundamentals and C Programming 214
• Two different types of initialization of arrays
• Compile time initialization
• Run time initialization
Compile time Initialization
19-06-2023 Computing Fundamentals and C Programming 215
• Run time initialization
19-06-2023 Computing Fundamentals and C Programming 216
Two Dimensional Array-
• To store a table of values
• C allows us to store the table of values using 2D or two dimensional array
• Two dimensional array can be declared as
• C places each size its own set of brackets.
19-06-2023 Computing Fundamentals and C Programming 217
19-06-2023 Computing Fundamentals and C Programming 218
19-06-2023 Computing Fundamentals and C Programming 219
19-06-2023 Computing Fundamentals and C Programming 220
Initializing an 2D array –
1. 6.
2. 7.
3.
4.
5.
19-06-2023 Computing Fundamentals and C Programming 221
Memory Layout-
• The subscripts in the 2d arrays represents the rows and columns
• The elements of the array are stored contiguously in increasing memory
locations.
• Starts to store row wise ,starting from the first row and ending with the last
row, treating each row like a simple array.
19-06-2023 Computing Fundamentals and C Programming 222
A[3][3]={{10,20,30},{40,50,60},{70,80,90
}};
Multi-dimensional array-
• C allows arrays of 3 or more dimensions.the exact limit is decided by the
compiler
• There is no limit for dimensions but compiler permits only 7-10 dimensions.
19-06-2023 Computing Fundamentals and C Programming 223
19-06-2023 Computing Fundamentals and C Programming 224
Dynamic arrays-
• Arrays created at compile time by specifying the size of the array in the
program and cannot be modified at runtime.
• Memory allocations is of two types
Static memory allocation
Dynamic memory allocation
Static memory allocation –
• Process of allocating memory at compile time .
• Arrays that receive static memory allocation are called Dynamic arrays
• This approach will work for the known data requirements
19-06-2023 Computing Fundamentals and C Programming 225
Dynamic Memory allocation –
• Allocating memory at runtime
• It is called dynamic memory allocation
• Arrays created at run time is called dynamic arrays
• Dynamic arrays are created using pointer variables and memory management
functions.
• Memory management functions are
malloc
calloc
realloc
• These functions are included in <stdlib.h>
• Dynamic arrays are used in data sstructure concepts such as linked lists, stacks,
queues
19-06-2023 Computing Fundamentals and C Programming 226
• More about arrays -
19-06-2023 Computing Fundamentals and C Programming 227
Character Arrays and Strings-
19-06-2023 Computing Fundamentals and C Programming 228
Character Strings-
• A string is a group of characters treated as single data item
• For eg
•
• Some common operations performed on character string
19-06-2023 Computing Fundamentals and C Programming 229
Declaring and Initializing string variables-
• C does not support string as a datatype
• It allows to represent strings as character array
• String variable=array of characters
• When compiler assigns the character string to character array it automatically
supplies null character”0” at the end of the string
• So size of the character array should be maximum number of characters in the
string +1
• Character array can be initialized either using 2 forms
19-06-2023 Computing Fundamentals and C Programming 230
• Declaring the size much larger than the string size in the initializer
• For eg
•
19-06-2023 Computing Fundamentals and C Programming 231
• Purpose of using null character (“0”)-to determine the end of the string
data and null character serves as the “end of the string “ marker
Reading strings from terminal-
• Using scanf() function
• %s format specification to read a string of characters
• Scanf() terminates its input on the first white space it finds.
19-06-2023 Computing Fundamentals and C Programming 232
• To read the entire line
• To specify the field with
•
19-06-2023 Computing Fundamentals and C Programming 233
•
19-06-2023 Computing Fundamentals and C Programming 234
• Reading a line of text with white spaces ,special characters
• getchar() and gets()
• Available in <stdlib.h>
19-06-2023 Computing Fundamentals and C Programming 235
Writing strings to screen
• Using printf()
• Can specify the precision with which the array is displayed
• For
• Creates a width of 10 columns where the first four characters are to be
printed
• putchar() ,puts()
• putchar()-character handling function to output the values of character
variables.requires one parameter ,write characters to the screen.Same
function can used to be repeatedly output a string of charcaters stored in
the array using a loop.
19-06-2023 Computing Fundamentals and C Programming 236
• Printing string values ,has one parameter
19-06-2023 Computing Fundamentals and C Programming 237
Arithmetic operations on Characters –
• C allows us to manipulate characters the same way doing with the numbers
• Whenever a character constant or character variable is used in the
expression it is automatically converted to an integer value by the system
• For eg To write a character in its integer representation
• Prints 97 on the screen
• Can also perform arithmetic operations on the character constants and
variables
19-06-2023 Computing Fundamentals and C Programming 238
19-06-2023 Computing Fundamentals and C Programming 239
Relational operations-
• To test whether the ch is upper case letter
Converting a character to integer
19-06-2023 Computing Fundamentals and C Programming 240
Converting a string of digits into their integer values
• String conversion functions are stored in the header file <std.lib.h>
19-06-2023 Computing Fundamentals and C Programming 241
number=1988
• Putting strings together
• Comparison of strings
• String handling functions
• Table of strings
19-06-2023 Computing Fundamentals and C Programming 242
Putting strings together –
• Adding a string with other string
• Called as concatenation or appending or joining
• Assigning one string with the another string is not possible
19-06-2023 Computing Fundamentals and C Programming 243
Comparison of two strings –
• C does not permit to compare strings directly
• Strings has to be tested and compared character by character until a
mismatch is found or of the strings terminates into a null character
19-06-2023 Computing Fundamentals and C Programming 244
String handling functions-
• C supports many string handling functions to make easy string
manipulations
• Import <string.h>
• Some of the common functions are
19-06-2023 Computing Fundamentals and C Programming 245
Strcat()
• Joins two strings together
• String 2 is appended to string 1 by removing the null character of the string 1
and placing the string 2
• make sure that string 1 should be large
enough to hold the string 2
19-06-2023 Computing Fundamentals and C Programming 246
strcmp()-
• Compare the two strings identified by the arguments and ha a value 0
if they are equal
19-06-2023 Computing Fundamentals and C Programming 247
strcpy()-
• Copies the last string to the first string
•
Strlen()-
• Counts and returns the number of characters in a string
• N holds the length of the string and the counting ends at the first null
character
19-06-2023 Computing Fundamentals and C Programming 248
19-06-2023 Computing Fundamentals and C Programming 249
strncpy()-
• Copies only the left most n characters of the source string to the target string
variable
• It contains three parameter
• Since 5 characters does not include the null character it has to be explicitly
placed in 6th position
19-06-2023 Computing Fundamentals and C Programming 250
Strncmp()
• It contains 3 parameters
• It compares left most n characters of s1 and s2 and returns 0 if they are
equal or negative number if s1 is less than s2 otherwise positive
strncat()-
• Another concatenation function takes 3 paramters
19-06-2023 Computing Fundamentals and C Programming 251
Strstr()-
• Used to locate a substring in a string
• Strstr searches for the s2 in s1 and returns the position of the first occurrence
of the sub string
19-06-2023 Computing Fundamentals and C Programming 252
19-06-2023 Computing Fundamentals and C Programming 253
Table of strings-
• To prepare a list of character strings
• Eg list of names in the class ,list of employees in an organization ,list of places
in a state
• It is done by using 2D character array to store the entire list
19-06-2023 Computing Fundamentals and C Programming 254
19-06-2023 Computing Fundamentals and C Programming 255
Unit-4
User define functions ,Structures and Unions
19-06-2023 Computing Fundamentals and C Programming 256
Introduction
• One of the strength of C is C functions
• C functions can be classified into two categories
• Library functions eg printf,scanf,sqrt,cos,tan etc
• User defined functions eg main()
Need for the user defined function-
19-06-2023 Computing Fundamentals and C Programming 257
19-06-2023 Computing Fundamentals and C Programming 258
Multi function Program –
• A function is a self contained block of code that performs a particular task.
• It is called as black box that takes some data from the main program and
return as value
19-06-2023 Computing Fundamentals and C Programming 259
19-06-2023 Computing Fundamentals and C Programming 260
19-06-2023 Computing Fundamentals and C Programming 261
• Any function can call any function
• A function can call by itself
• “a called function” can call another function
• A function can be placed in any order
• It follows the concept of modular programming
• This is the main feature of user defined function
19-06-2023 Computing Fundamentals and C Programming 262
19-06-2023 Computing Fundamentals and C Programming 263
Modular Programming-
• Design and development of the software systems
• Organizing a large program into small, independent program segments
called modules
• Every modules have separate names and called as program units
• Finally it is integrated into one program
• It is basically called divide and conquer approach of problem solving
• Here each module refers to a function
• Some of the characteristics of the modular programming are
19-06-2023 Computing Fundamentals and C Programming 264
19-06-2023 Computing Fundamentals and C Programming 265
Elements of user defined functions-
• Function definition
• Function call
• Function declaration
Function definition
Independent program module specially written to implement the
requirement of the function .Function has to be called somewhere in the
program
Function Call-
The function or program that calls the function is referred as calling function
or function call
19-06-2023 Computing Fundamentals and C Programming 266
Function declaration/protoype –
The calling function should declare any function which can be used later in
the program
19-06-2023 Computing Fundamentals and C Programming 267
Definition of functions-
• A function definition should have
19-06-2023 Computing Fundamentals and C Programming 268
Function header
Function body
19-06-2023 Computing Fundamentals and C Programming 269
Function header –it contains three parts
No semicolon needed in function header
19-06-2023 Computing Fundamentals and C Programming 270
Function
header
Function
return type
Function
name
Function
parameter list
Function name and Type –
• Specifies the type of value that the function is expected to return to the
program calling the function
• Integer by default
• If function is not returning anything it should be void
List of parameters –
• The parameter list declares the variable that will receive the ddata sent by
the calling program
• They serve as an input data to the function to carry out the specific task
• They are also called formal parameters
19-06-2023 Computing Fundamentals and C Programming 271
• Declaration of variable combined is not allowed
19-06-2023 Computing Fundamentals and C Programming 272
Function Body –
• Contains the declarations and statements necessary for performing the
required task.
• It contains 3 parts
Local declarations that specify the variables needed by the function
Function statements that performs the task of the function
A return statement that returns the value evaluated by the function
19-06-2023 Computing Fundamentals and C Programming 273
19-06-2023 Computing Fundamentals and C Programming 274
Return values and their types –
• A function may or may not send back values to the calling function
• It is done through return statement
• A function can return only one value per function call
19-06-2023 Computing Fundamentals and C Programming 275
Does not return any value(acts as closing brace
of a function
Return some value and control is
passed back to the calling function
• A function may have one or more return statements based on the value
returned on certain conditions.
• All functions by default return value of int data type
• When a value is returned it is automatically cast to the function’s type
19-06-2023 Computing Fundamentals and C Programming 276
Function calls –
• A function can be called by using the name of the function followed by the list
of actual parameters /arguments enclosed in parenthesis
19-06-2023 Computing Fundamentals and C Programming 277
• Some of the ways to call a function are
•
19-06-2023 Computing Fundamentals and C Programming 278
Function Declaration/Prototype-
• All functions should be declared before they are invoked.
• It has 4parts
19-06-2023 Computing Fundamentals and C Programming 279
19-06-2023 Computing Fundamentals and C Programming 280
A function protoype/declaration can be placed in two places of the program
• Above all the functions (including main())-global protoype
• Inside a function definition-local prototype
 the place of declaration of a function defines a region in a program in
which the function may be used by other functions which is called scope of
the function .
Adds flexibility
Provides quick reference to the functions in the program
Enhances documentation
19-06-2023 Computing Fundamentals and C Programming 281
19-06-2023 Computing Fundamentals and C Programming 282
19-06-2023 Computing Fundamentals and C Programming 283
Formal parameters
actual parameters
Called function
Calling function/function
call
Category of Functions-
• A function depending on whether arguments are present or not and whether
a value is returned or not
• There are 5 different categories
19-06-2023 Computing Fundamentals and C Programming 284
Category 1 No arguments and No return values
• When a function does not have no arguments means it does not receive any
data from the calling function
• When it does not return a value the calling function does not receive any
data from the called function
• There is no data transfer between the calling function and the called function
19-06-2023 Computing Fundamentals and C Programming 285
19-06-2023 Computing Fundamentals and C Programming 286
19-06-2023 Computing Fundamentals and C Programming 287
Category 2 Arguments but no return values
• The main() function has no control over the way the functions receive input
data
• Making the calling function to read data from the terminal and pass it to the
called function.
• The nature of data communication between the calling function and the
called function with arguments and no return value
19-06-2023 Computing Fundamentals and C Programming 288
19-06-2023 Computing Fundamentals and C Programming 289
19-06-2023 Computing Fundamentals and C Programming 290
• Points to remember
Ensure the function should have matching arguments
If actual arguments are more than the formal arguments the extra actual arguments
are discarded
If actual argumets is less than formal arguments the unmatched formal arguments are
initilaized to some garbage values
Category 3 Arguments with return values -
• The function value receives data from the calling function through
arguments but does not send back any value
• Rather it displays the results of calculations at the terminal
19-06-2023 Computing Fundamentals and C Programming 291
19-06-2023 Computing Fundamentals and C Programming 292
19-06-2023 Computing Fundamentals and C Programming 293
Category 4 No arguments but returns a value –
• Functions that may not take any arguments but returns a value to the calling
function
• For eg getchar()
• The getchar() has no parameters but it returns an integer type that
represents a character
19-06-2023 Computing Fundamentals and C Programming 294
19-06-2023 Computing Fundamentals and C Programming 295
Category 5 Function that returns multiple values –
• Functions can return multiple values but not directly
• By using a method “call by address or call by reference” using pointers, arrays
and structures
• Address operator (&),indirection operator(*)
19-06-2023 Computing Fundamentals and C Programming 296
• X,y are input arguments and s,d are output arguments
• X and y actual values are passed during the function call and s,d
(where stored in memory)address of memory locations are passed
19-06-2023 Computing Fundamentals and C Programming 297
19-06-2023 Computing Fundamentals and C Programming 298
19-06-2023 Computing Fundamentals and C Programming 299
19-06-2023 Computing Fundamentals and C Programming 300
Nesting of Functions-
• C permits nesting of functions freely
19-06-2023 Computing Fundamentals and C Programming 301
19-06-2023 Computing Fundamentals and C Programming 302
19-06-2023 Computing Fundamentals and C Programming 303
19-06-2023 Computing Fundamentals and C Programming 304
19-06-2023 Computing Fundamentals and C Programming 305
Recursion-
• When a function calls by itself
• Execution is terminated abruptly
• Recursive functions can be effectively used to solve problems where solution is
expressed in terms of successively applying the same solution to the subset of the
problem
• Recursive function must have an if statement somewhere to force the function to
return without the recursive call being executed
• Otherwise function will never return
19-06-2023 Computing Fundamentals and C Programming 306
19-06-2023 Computing Fundamentals and C Programming 307
Passing arrays to functions –
• One dimensional arrays
• Two dimensional arrays
One dimensional arrays
• An array of values can be passed to a called function
• by listing the name of the array without any subscripts and the size of the
array as arguments
19-06-2023 Computing Fundamentals and C Programming 308
19-06-2023 Computing Fundamentals and C Programming 309
19-06-2023 Computing Fundamentals and C Programming 310
19-06-2023 Computing Fundamentals and C Programming 311
• Passing addresses of parameters to the function is referred to as pass by
address (or pointers)
19-06-2023 Computing Fundamentals and C Programming 312
• If a function changes the value of the elements of an array then these changes
will be made to the original array that passed to the function
• When an entire array is passed as an argument the contents of the array are
not copied into the formal parameter array instead addresses of array
elements are passed on to the function
• Changes in the array elements are reflected in the original array in the calling
function
19-06-2023 Computing Fundamentals and C Programming 313
Two dimensional array-
19-06-2023 Computing Fundamentals and C Programming 314
19-06-2023 Computing Fundamentals and C Programming 315
19-06-2023 Computing Fundamentals and C Programming 316
Passing strings to functions-
• Strings are considered as character arrays
• So the rules for passing strings to functions is same as passing arrays to
functions
19-06-2023 Computing Fundamentals and C Programming 317
19-06-2023 Computing Fundamentals and C Programming 318
19-06-2023 Computing Fundamentals and C Programming 319
19-06-2023 Computing Fundamentals and C Programming 320
Pass by Values Pass by Pointers
Values of actual parameters are copied
to variables in the parameter list of the
called function . The called function
Works on the copy and not on the
original values of the actual
parameters .original data cannot be
changed
Known as Pass by address .the
memory address of the variable rather
than the copies of values sent to the
called function .called function
directly works on the data in the
calling function and the changed
values are available in the calling
function
19-06-2023 Computing Fundamentals and C Programming 321
The data passed from one function to another is known as parameter
passing
The Scope ,Visibility and Life time of variables
• C has variety of storage class classifiers used to declare explicitly the scope
and lifetime of variables
• Scope and lifetime is considered only in the program which contains multi
functions and multi program files
19-06-2023 Computing Fundamentals and C Programming 322
Storage
class
auto register static extern
Automatic variables-
• Declared inside the function where it is used
• They are created when the function is called and destroyed when the
function is exited
• So it is private /local to the ffunction where they are declared
• It is also known as internal or local variables
• Values cannot be changed and can use the same variable in different
functions
19-06-2023 Computing Fundamentals and C Programming 323
External variables-
• Variables that are alive and active in the entire program
• Also known as global variables
• Global variables can be accessed by any function
• External variables are declared outside the function
19-06-2023 Computing Fundamentals and C Programming 324
• Global variables as parameters
19-06-2023 Computing Fundamentals and C Programming 325
Static variables-
• The value of the static variables persists the entire program
• It can be either internal or external depending on the place of declaration
• Internal static variables can be used to retain the values between the
function calls
Register variables –
19-06-2023 Computing Fundamentals and C Programming 326
19-06-2023 Computing Fundamentals and C Programming 327
Multifile programs-
• Multiple source files can share a variable provided it is declared as an
external variable appropriately
• Variables that are shared by two or more files are global variables so
declaring the variable in one file and then explicitly define them with extern
in other files
• The extern specifier tells the compiler that the following variabl has been
declared somewhere and no need to create storage space for them
• Multifile global variable should be declared without extern in the other two
files .
• The extern declaration is done in places where secondary references are
made
19-06-2023 Computing Fundamentals and C Programming 328
19-06-2023 Computing Fundamentals and C Programming 329
Structures and Unions
19-06-2023 Computing Fundamentals and C Programming 330
Introduction-
• Structure is a collection of data items of different data types using a single
name
• C supports a constructed data type known as structures for packing a data
items of different data types
• Structure is a convenient tool for handling group of logically related data
items
• Structure helps to organize the
data in a meaningful way
19-06-2023 Computing Fundamentals and C Programming 331
Defining a Structure-
• Structure and their variables should declared before using it
• The general syntax of structure definition is
• For example creating a database of
books information can be done by using
structures which holds the information
19-06-2023 Computing Fundamentals and C Programming 332
Structure elements or members
Structure tag(name of the structure)
19-06-2023 Computing Fundamentals and C Programming 333
Defining a structure has the following syntax
• Arrays VS Structures
19-06-2023 Computing Fundamentals and C Programming 334
Arrays Structures
a collection of related data elements of same data type Is a collection of elements of different datatypes
Derived data type Programmer defined datatype
rray uses subscripts or “[ ]” (square bracket) for element
access
Structure uses “.” (Dot operator) for element access
Built-in data type, declare and use it Design and declare a structure before the variables of that
type are declared and used
Array size is fixed and is basically the number of elements
multiplied by the size of an element.
Structure size is not fixed as each element of Structure can
be of different type and size.
Array declaration is done simply using [] and not any
keyword.
Structure declaration is done with the help of “struct”
keyword.
Array elements are stored in contiguous memory locations.
Structure elements may or may not be stored in a
contiguous memory location.
Array elements are accessed by their index number using
subscripts.
Structure elements are accessed by their names using dot
operator.
Declaring a structure variable-
• A structure declaration should have the following elements
• For eg
19-06-2023 Computing Fundamentals and C Programming 335
19-06-2023 Computing Fundamentals and C Programming 336
Accessing structure members-
• Accessing and assigning values to the members of the structure
• It should be linked to the structure variables to make a meaningful members
• For eg
• The link between a member and a variable is established by using a member
operator(.)
19-06-2023 Computing Fundamentals and C Programming 337
Accessing Structure members –
• Structure initialization
• Rules for initializing structures
Structure Initialization –
• Initialization of structure is done during compile time
• There is a one to one correspondence
Between the members and their
initializing values
19-06-2023 Computing Fundamentals and C Programming 338
19-06-2023 Computing Fundamentals and C Programming 339
19-06-2023 Computing Fundamentals and C Programming 340
Rules for initializing structures-
19-06-2023 Computing Fundamentals and C Programming 341
Copying and comparing the structure variables-
• Logical operations are not permitted in structures
19-06-2023 Computing Fundamentals and C Programming 342
Operations on Individual Members-
• Members of a structure variable is accessed by dot operator
• Arithmetic and relational operations can be done on members
• Three ways to access members of the structure variable :dot operator,
pointer ,selection notation
19-06-2023 Computing Fundamentals and C Programming 343
Array of structures-
• Each element of the array representing a structure variable
• Array of structures is stored inside the memory in the same way as a multi
dimensional array
19-06-2023 Computing Fundamentals and C Programming 344
Array within the structures-
• c permits to use the arrays as structure members
• 1D or 2D or multi dimensional arrays can be used of int or float
19-06-2023 Computing Fundamentals and C Programming 345
Structures within structures
• Nesting of structures
19-06-2023 Computing Fundamentals and C Programming 346
19-06-2023 Computing Fundamentals and C Programming 347
The salary structure contains a member named allowance which
itself as a structure with 3 members
The inner structure contains members dearness, house rent, city
Inner most member can be accessed by dot operator from
outermost to inner most
19-06-2023 Computing Fundamentals and C Programming 348
Structures and functions
19-06-2023 Computing Fundamentals and C Programming 349
19-06-2023 Computing Fundamentals and C Programming 350
19-06-2023 Computing Fundamentals and C Programming 351
19-06-2023 Computing Fundamentals and C Programming 352
Unions and structures
• Unions concept is borrowed from structures and follow the same syntax as
structures
• Difference between structures and unions vary in terms of storage
• Structures-each member has its own storage space location
• Union-all the members of a union share the same location. union may have
many members of different datatypes it can handle only one member at a
time.
19-06-2023 Computing Fundamentals and C Programming 353
Size of the structures-
• Array,structures and unions used to create variables for large sizes
• The size of the variables vary from machine to machine
• A unary operator sizeof() can be used to find the size of a structure or
variable
19-06-2023 Computing Fundamentals and C Programming 354
Bit fields-
• Bit field is a set of adjacent bits whose size can be from 1 to 16 bit length
• A word can be therefore divided into number of bit fields
• The name and size of the bit field are given in the structure
19-06-2023 Computing Fundamentals and C Programming 355
19-06-2023 Computing Fundamentals and C Programming 356
19-06-2023 Computing Fundamentals and C Programming 357
19-06-2023 Computing Fundamentals and C Programming 358
Unit-5
Pointers & File Management
19-06-2023 Computing Fundamentals and C Programming 359
Introduction-
• A pointer is a derived data type in c
• Pointers contains memory addresses as their values
• These memory addresses are the locations in the computer memory where
program instructions and data are stored
• Pointers can be used to access and manipulate data stored in the memory
• The number of benefits for programmers using pointers are
• Pointers are efficient in handling arrays and data tables
• Pointers can return multiple values from a function via function arguments
• Pointers permit references to functions and thereby facilitating passing of functions as
arguments to other functions
• The use of pointer arrays to character strings results in saving data storage space in memory
• Pointers allow C to support dynamic memory management
• Pointers reduce the length and complexity of the programs
• increase the execution speed and reduce the program execution time
19-06-2023 Computing Fundamentals and C Programming 360
Understanding pointers-
• The computers memory is the sequence collection of
storage cells
• Each cell knowns as byte has a number called
address associated with it
• The addressed are numbered consecutively starting
from zero ,the last address depends upon the
memory size
• when a variable is declared the system allocates
Space in the memory ,an appropriate location to hold
the value of the variable
19-06-2023 Computing Fundamentals and C Programming 361
• For eg int quality =175;
• Value 175 can be accessed by either using the
variable name quantity or the address 5000
• When a variable are assigned to the address
of the another variable it is called pointer
variable
• A pointer variable is nothing but a
variable that contains the address which is
the location of another variable in memory
19-06-2023 Computing Fundamentals and C Programming 362
Underlying concepts of pointers –
• Pointers are built on the three underlying concepts
• Memory addresses within a computer are referred as pointer constants
• The value of the variable stored there using the address operator(&) called
the pointer value .pointer value may change from one run of the program
• The variable contains the pointer value is called pointer variable
19-06-2023 Computing Fundamentals and C Programming 363
Accessing the address of the variable-
• Address of the variable can be determined by address operator &
• Address operator is used in scanf
• The operator & preceding a variable returns the address of the variable
associated with it
• For eg
• If x is an array then expression is
19-06-2023 Computing Fundamentals and C Programming 364
Declaring a pointer variable –
• Pointer variable should be declared as pointer variables
• The syntax is
• Type int refers to the data type of the variable being pointed to by p and not
the type of the value of the pointer
19-06-2023 Computing Fundamentals and C Programming 365
Pointer declaration style-
• Pointer variables are declared similarly as normal variable except for the
addition unary * operator
19-06-2023 Computing Fundamentals and C Programming 366
Initialization of Pointer Variable-
• The process of assigning the address of a variable to a pointer variable is
called initialization.
• Uninitialized pointers produce some errors
• It is important to initialize a pointer variable before using it
• Once a pointer variable has been declared ,assignment operator is used
initialize the variable
• Eg
19-06-2023 Computing Fundamentals and C Programming 367
• Pointer variables always point to the corresponding data type
• For eg
• Combining declaration of a data variable,pointer variable and initialization
of a pointer variable in one step
• Pointer variables can be set to NULL or 0
19-06-2023 Computing Fundamentals and C Programming 368
Pointer Flexibility-
• Pointers are flexible
• Same pointer variable can point to different data variables in different
statements
• Using different pointers to point the same data value
19-06-2023 Computing Fundamentals and C Programming 369
Accessing a variable through its pointer-
• The value of the variable can be accessed by using pointers with the help of
unary operator(*) also called as indirection operator or dereferencing
operator
• When the operator placed before the pointer variable in an expression (on
the right hand side of the equal sign) the pointer returns the value of the
variable of which the pointer value is the address
• value at address
• Returns the value of the pointer variable
19-06-2023 Computing Fundamentals and C Programming 370
19-06-2023 Computing Fundamentals and C Programming 371
19-06-2023 Computing Fundamentals and C Programming 372
Chain of pointers-
• Making pointer to point another pointer creating a chain of pointers
• Pointer variable P2 contains the address of the another pointer variable P1
Which points to the location that contains the desired value
• It is called multiple indirections
• A variable that is a pointer to a pointer must be declared using additional
indirection operator symbols in front of the name.
19-06-2023 Computing Fundamentals and C Programming 373
Pointer expressions-
• Pointer variables can be used in expressions
• Pointers must be declared and initialized properly
19-06-2023 Computing Fundamentals and C Programming 374
Pointer increments and Scale Factor-
• Pointers can be incremented by
19-06-2023 Computing Fundamentals and C Programming 375
Pointers and arrays-
• When
• When p is declared as integer pointer
19-06-2023 Computing Fundamentals and C Programming 376
19-06-2023 Computing Fundamentals and C Programming 377
Pointers and Character Strings-
19-06-2023 Computing Fundamentals and C Programming 378
19-06-2023 Computing Fundamentals and C Programming 379
Array of pointers-
• With the help of pointers we can handle table of strings
19-06-2023 Computing Fundamentals and C Programming 380
19-06-2023 Computing Fundamentals and C Programming 381
Pointers and Function arguments-
• When addresses are passed to a function,the parameters receiving the
addresses should be pointers .
• The process of calling a function using pointers to pass the addresses of
variables is known as call by reference
• The function which is called by “reference” can change the value of the
variable used in the call
19-06-2023 Computing Fundamentals and C Programming 382
19-06-2023 Computing Fundamentals and C Programming 383
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m = 10, n = 20;
printf("m = %dn", m);
printf("n = %dnn", n);
swap(&m, &n); //passing address of m and n to the swap function printf("After Swapping:nn");
printf("m = %dn", m);
printf("n = %d", n);
return 0;
} /* pointer 'a' and 'b' holds and points to the address of 'm' and 'n'*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
19-06-2023 Computing Fundamentals and C Programming 384
Functions returning pointers –
• Since pointers are data type in C ,we can force a function to return a
pointer to the calling function
19-06-2023 Computing Fundamentals and C Programming 385
19-06-2023 Computing Fundamentals and C Programming 386
Pointers to functions-
• It is possible to declare a pointer pointing to a function which can then be
used as an argument in another function. A pointer to a function is
declared as follows,
• int (*sum)();
• A function pointer can point to a specific function when it is assigned the
name of that function.
int sum(int, int);
int (*s)(int, int);
s = sum;
• Here s is a pointer to a function sum. Now sum can be called using function
pointer s along with providing the required argument values s (10, 20);
19-06-2023 Computing Fundamentals and C Programming 387
#include <stdio.h>
int sum(int x, int y)
{
return x+y;
}
int main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d", s);
return 0;
}
19-06-2023 Computing Fundamentals and C Programming 388
Compatibility and casting-
• Assigning of a pointer variable of one type to a pointer of another type is
not permissible
• It is called incompatibility of pointers
• Cannot use the assignment operator with the pointers of different types.
• Assigning in compatible pointers with the help of cast operator explicitly
• void pointer is a generic pointer that can represent any pointer
type. All pointer types can be assigned to a void pointer and a void pointer
can be assigned to any pointer without casting
19-06-2023 Computing Fundamentals and C Programming 389
Pointers and Structures-
• To use array of structure variables efficiently is used pointers of structure
type
19-06-2023 Computing Fundamentals and C Programming 390
19-06-2023 Computing Fundamentals and C Programming 391
File management in C-
19-06-2023 Computing Fundamentals and C Programming 392
Introduction-
• Scanf and printf used to read and write data
• These are console oriented I/O operations use the terminal (keyboard and
screen)
• It works for small data
• When the data is very large the major problems faced are it becomes
cumbersome and time consuming to handle data thru terminals and entire
data is lost when the computer is turned off /program is terminated
• In need of flexible approach where data can be stored on disks and read
whenever necessary without destroying the data
• This method employs the concept of FILES to store data
• A file is a place on the disk where a group of related data is stored
• C supports a number of functions that have the ability to perform basic file
operations which include
19-06-2023 Computing Fundamentals and C Programming 393
Naming a file
Opening a file
Reading data from a file
Writing data to a file
Closing a file
• There are two distinct ways to perform file operations in c
• Low level I/o which uses unix sytem calls
• High level I/O uses functions in C standard library
19-06-2023 Computing Fundamentals and C Programming 394
• C file handling functions are
19-06-2023 Computing Fundamentals and C Programming 395
Defining and Opening a file-
• To store a file in the secondary memory certain things about the file has to
be specified .they are
File name-string of characters gives a valid file name for OS.it contains primary name
and optional period with the extension
Data structure-defined as FILE in the library of standard I/O function.
all files should be declared before using it .FILE is a defined data type
Purpose – write data to /read data from the file
• the general syntax of declaring and opening a file
19-06-2023 Computing Fundamentals and C Programming 396
19-06-2023 Computing Fundamentals and C Programming 397
Additional modes of operations:
• r+ -Opens a text file for both reading and writing.
• w+ -Opens a text file for both reading and writing. It first truncates the file
to zero length if it exists, otherwise creates a file if it does not exist.
• a+ -Opens a text file for both reading and writing. It creates the file if it does
not exist. The reading will start from the beginning but writing can only be
appended.
19-06-2023 Computing Fundamentals and C Programming 398
Closing a File-
• A file must be closed as soon as all operations is completed
• This prevents from misuse of the file
• Only limited files can be open simultaneously at a time
• Closing unwanted files might help open required files
• Close a file and reopen he same file with different mode
19-06-2023 Computing Fundamentals and C Programming 399
• Once a file is closed ,its file pointer can be reused for another file
• All files are closed automatically when program terminates
• Closing a file as soon as the task is completed is considered as a good habit
Input/output operations on files-
• When a file is opened reading or writing is accomplished by standard I/O
routines that are listed
getc and putc functions:
Simplest file I/O functions are getc and putc
Same like getchar and putchar functions handle one character at a time
19-06-2023 Computing Fundamentals and C Programming 400
The file pointer moves by one character position for every operation of getc
and putc
getc will return EOF(end-of-file) marker when end of the file is reached
Reading should be terminated with EOF
19-06-2023 Computing Fundamentals and C Programming 401
fprintf and fscanf functions-
• Handle a group of mixed data simultaneously
• Identical to printf and scanf functions
• When end of the file is reached it returns EOF value
19-06-2023 Computing Fundamentals and C Programming 402
Error handling during I/O operations-
• If failed to check read and write errors program may behave abnormally
when an error occurs
• An unchecked error result in preature termination or incorrect output
19-06-2023 Computing Fundamentals and C Programming 403
• They have two status inquiry I/O library functions to detect I/O errors in
files
feof-used to test for an end of the file function
Ferror-returns the status of the file indicated
• if the file cannot be open for some reason then the function returns a
NULL pointer .it can be used to test whether the file has been opened or
not
19-06-2023 Computing Fundamentals and C Programming 404
Random access to files-
• Reading or writing only specific part of the file
• Can be done with the help of these I/O functions fseek(),ftell(),and rewind
• Fseek –used to move the file position to a desired location within a file
19-06-2023 Computing Fundamentals and C Programming 405
19-06-2023 Computing Fundamentals and C Programming 406
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
19-06-2023 Computing Fundamentals and C Programming 407
Command line arguments-
• It is a parameter supplied to a program when the program is invoked
• It may be a filename the program should process
• So far main() is used without arguments
• Main() can take two arguments argc and argv and information contained in
the command line is passed on to the program through these arguments
when main() is called up by the system
• argc – counts the no of arguments on the command line
• argv- argument vector that represents array of character pointers that
point to the command line arguments .Size of the array =argc
19-06-2023 Computing Fundamentals and C Programming 408
19-06-2023 Computing Fundamentals and C Programming 409

Computing Fundamentals and C.pptx

  • 1.
    Computing Fundamentals andC Programming Dr. Sabitha Banu 19-06-2023 Computing Fundamentals and C Programming 1
  • 2.
    History of Computers •people used sticks, stones, and bones as counting tools • Human mind improved with time more computing devices were developed like Abacus, Napier’s Bones, etc to perform mathematical calculations 19-06-2023 Computing Fundamentals and C Programming 2
  • 3.
    19-06-2023 Computing Fundamentalsand C Programming 3 Abacus – Calculator • A counting device • Beads are moved to perform arithmetic functions • Still used by traders and clerks in Asia, Africa, … 2700-2300BC
  • 4.
    19-06-2023 Computing Fundamentalsand C Programming 4 Slide Ruler • An early analogue computer used primarily for multiplication and division. • Invented by William Oughtred • Slide rulers were taken to the moon in the 1960s 1620
  • 5.
    19-06-2023 Computing Fundamentalsand C Programming 5 Pascaline • Blaise Pascal created the first mechanical calculator • Performed addition and subtraction • Was too expensive for the time, hence it didn’t become a commercial device. • https://www.youtube.com/watch?v=3h71HAJWnVU 1642
  • 6.
    19-06-2023 Computing Fundamentalsand C Programming 6 Tables • Mathematical tables were created by people called ’computers’. • They were large charts showing the results of calculations, e.g. multiplication, division, and trigonometry • However, these were known to be error prone, • Thus the need for more accurate math drove innovation.
  • 7.
    19-06-2023 Computing Fundamentalsand C Programming 7 Charles Babbage • Noticed errors in mathematical tables (1820) • Created the difference engine to compute this math more accurately • Used tons of grant money as well as his own • Only built a small part, as he also had to construct the tools to build it • The difference engine wasn’t finished, and he went on to design the Analytical engine.
  • 8.
    19-06-2023 Computing Fundamentalsand C Programming 8 Difference Engine • The first mechanical computer • Created by Charles Babbage a “father of computing” • Compiled mathematical tables • add, subtract, polynomial functions 1821
  • 9.
    19-06-2023 Computing Fundamentalsand C Programming 9 Ada Lovelace • She wrote the first algorithm that would have been executed by the Analytical Engine • She is considered the worlds first programmer
  • 10.
    19-06-2023 Computing Fundamentalsand C Programming 10 What are Punch Cards? • Stiff paper that holds commands • Commands and data are indicated by holes/no holes • Early computers used these as input commands
  • 11.
    19-06-2023 Computing Fundamentalsand C Programming 11 Herman Hollerith • During the Industrial revolution the population 30% each decade. • They were still tabulating census data by hand. • In 1887 they still had not completed tallying the 1880 census data • Herman Hollerith an MIT prof introduced punch cards and a machine to read them to tally this information. • Took only 6 weeks to tally the 1890 census • He continued to improve the machine, and created the company IBM
  • 12.
    • A computeris an electronic machine that collects information, stores it, processes it according to user instructions, and then returns the result. • A computer is a programmable electronic device that performs arithmetic and logical operations automatically using a set of instructions provided by the user 19-06-2023 Computing Fundamentals and C Programming 12
  • 13.
    Generations of Computers S.NoGeneration & Description 1 First Generation The period of first generation: 1946-1959. Vacuum tube based. 2 Second Generation The period of second generation: 1959-1965. Transistor based. 3 Third Generation The period of third generation: 1965-1971. Integrated Circuit based. 4 Fourth Generation The period of fourth generation: 1971-1980. VLSI microprocessor based. 5 Fifth Generation The period of fifth generation: 1980-onwards. ULSI microprocessor based. 19-06-2023 Computing Fundamentals and C Programming 13
  • 14.
    19-06-2023 Computing Fundamentalsand C Programming 14 1st Generation Computers • 1951 – 1959 • Based on Vacuum tubes • Vacuum tubes: Control electric current using the vacuum, and • Can be used to start/stop, or change the flow based on the current • produce a lot of heat and the installations used to fuse frequently. • Expensive to replace if it does not work • Batch processing operating system was used. • Punch cards, paper tape, and magnetic tape was used as input and output devices. • The computers in this generation used machine code as the programming language.
  • 15.
    • The mainfeatures of the first generation are Vacuum tube technology  Unreliable  Supported machine language only  Very costly  Generated a lot of heat  Slow input and output devices  Huge size  Need of AC  Non-portable  Consumed a lot of electricity Eg of First Generation computers are ENIAC ,EDVAC,UNIVAC,IBM-701,IBM-650 19-06-2023 Computing Fundamentals and C Programming 15
  • 16.
    19-06-2023 Computing Fundamentalsand C Programming 16 Second Generation Computers • Based on Transistors • 1959-1965 • Stored instructions in memory • magnetic cores were used as the primary memory and magnetic tape and magnetic disks as secondary storage devices. • assembly language and high-level programming languages like FORTRAN, COBOL were used. • The computers used batch processing and multiprogramming operating system.
  • 17.
    • The mainfeatures of second generation are Use of transistors  Reliable in comparison to first generation computers  Smaller size as compared to first generation computers  Generated less heat as compared to first generation computers  Consumed less electricity as compared to first generation computers  Faster than first generation computers  Still very costly  AC required  Supported machine and assembly languages • Eg of Second generation Computers are IBM 1620,IBM 7094,CDC 1604,CDC 3600, UNIVAC 1108 19-06-2023 Computing Fundamentals and C Programming 17
  • 18.
    19-06-2023 Computing Fundamentalsand C Programming 18 Third Generation Computers • Modern computers • 1965-1971 • Used Integrated Circuits(IC) invented by Jack Kilby • A single IC has many transistors, resistors, and capacitors along with the associated circuitry. • made computers smaller in size, reliable, and efficient. • remote processing, time-sharing, multiprogramming operating system were used. • High-level languages (FORTRAN- II TO IV, COBOL, PASCAL PL/1, BASIC, ALGOL-68 etc.)
  • 19.
    • The mainfeatures of third generation are IC used  More reliable in comparison to previous two generations  Smaller size,Faster  Generated less heat  Lesser maintenance  Costly  AC required  Consumed lesser electricity  Supported high-level language Eg of third generation computers are IBM-360 series,Honeywell-6000 series,PDP (Personal Data Processor),IBM-370/168,TDC-316 19-06-2023 Computing Fundamentals and C Programming 19
  • 20.
    19-06-2023 Computing Fundamentalsand C Programming 20 Fourth Generation Computers • VLSI(very large scale integration) Microprocessor • Development of the personal computer • 1971 – 1981 • Addition of GUI’s, the mouse, and handheld devices • VLSI circuits having about 5000 transistors and other circuit elements with their associated circuits on a single chip made it possible to have microcomputers of fourth generation. • Created by Intel corp. • Becomes the Central Processing Unit (CPU) • Allow computers to be smaller, more powerful, faster, and cheaper • Time sharing, real time networks, distributed operating system were used. • High-level languages like C, C++, DBASE etc.
  • 21.
    • The mainfeatures of fourth generation are VLSI technology used Very cheap Portable and reliable Use of PCs Very small size  Pipeline processing No AC required Concept of internet was introduced  Great developments in the fields of networks ,Computers became easily available Eg of Fourth generation computers are DEC 10,STAR 1000,PDP 11,CRAY-1(Super Computer),CRAY-X-MP(Super Computer) 19-06-2023 Computing Fundamentals and C Programming 21
  • 22.
    19-06-2023 Computing Fundamentalsand C Programming 22 Fifth Generation Computers • 1990 – Present • VLSI technology became ULSI (Ultra Large Scale Integration) technology • Parallel Processing software and Enhancement of Artificial Intelligence • Nanotechnology • Natural Language Processing • high-level languages like C and C++, Java, .Net etc.
  • 23.
    • The mainfeatures of fifth generation are ULSI technology Development of true artificial intelligence Development of Natural language processing Advancement in Parallel Processing Advancement in Superconductor technology More user-friendly interfaces with multimedia features Availability of very powerful and compact computers at cheaper rates Eg of Fifth generation computers are Desktop,Laptop,NoteBook,UltraBook, ChromeBook https://www.youtube.com/watch?v=G19ldX05Gb4 https://www.youtube.com/watch?v=z3KnlfATUek https://www.youtube.com/watch?v=ta7Fh-ZcfyM 19-06-2023 Computing Fundamentals and C Programming 23
  • 24.
    Classification of Computers Sr.No.Type Specifications 1 PC (Personal Computer) or Micro- Computers It is a single user computer system having a moderately powerful microprocessor. It is termed as a computer that is equipped microprocessor as its CPU 2 Workstation It is also a single user computer system, similar to the personal computer, however, has a more powerful microprocessor. 3 Mini-Computer It is a multi-user computer system, capable of supporting hundreds of users simultaneously 4 Main Frame It is a multi-user computer system, capable of supporting hundreds of users simultaneously. Software technology is different from minicomputer 5 Super-Computer It is an extremely fast computer, which can execute hundreds of millions of instructions per second. 19-06-2023 Computing Fundamentals and C Programming 24
  • 25.
    Personal Computer (PC) •small, relatively inexpensive computer designed for an individual user. • microprocessor technology that enables manufacturers to put an entire CPU on one chip. • word processing, accounting, desktop publishing, and for running spreadsheet and database management Applications,playing games and surfing the Internet. • single-user systems, these systems are normally linked together to form a network. 19-06-2023 Computing Fundamentals and C Programming 25
  • 26.
    Workstation • Applications whichrequire a moderate amount of computing power and relatively high-quality graphics capabilities. • Eg. (CAD/CAM),desktop publishing, software development • high-resolution graphics screen, a large amount of RAM, inbuilt network support, and a graphical user interface • mass storage device such as a disk drive ,and diskless workstation also available • UNIX and Windows NT OS • Stand alone systems 19-06-2023 Computing Fundamentals and C Programming 26
  • 27.
    Minicomputer - Itis a midsize multi-processing system capable of supporting up to 250 users simultaneously. 19-06-2023 Computing Fundamentals and C Programming 27
  • 28.
    Mainframe - Themainframe is very large in size and is an expensive computer capable of supporting hundreds or even thousands of users simultaneously. Mainframe executes many programs concurrently and supports much simultaneous execution of programs. 19-06-2023 Computing Fundamentals and C Programming 28
  • 29.
    Supercomputer – • Fastestcomputers • Expensive and specialized applications are used • Eg. weather forecasting, scientific simulations, (animated)graphics, fluid dynamic calculations, nuclear energy research, electronic design, and analysis of geological data 19-06-2023 Computing Fundamentals and C Programming 29
  • 30.
    Anatomy of Computer •A Computer is divided in to two components • Hardware -tangible parts of the computer • Software-intangible set of instructions that control the hardware and make it perform specific tasks. Without software, a computer is effectively useless. 19-06-2023 Computing Fundamentals and C Programming 30
  • 31.
    Hardware • physical componentsof a computer that includes all mechanical,electrical, electronic and magnetic parts attached to it • Some of the major Hardware components are Input and output devices Central processing unit (CPU) Memory unit and storage devices Interface unit 19-06-2023 Computing Fundamentals and C Programming 31
  • 32.
  • 33.
  • 34.
    Process of aComputer 19-06-2023 Computing Fundamentals and C Programming 34
  • 35.
    Input devices • Thedata and instructions are typed, submitted, or transmitted to a computer through input devices. • Input devices are electronic or electro-mechanical equipment that provide a means of communicating with the computer system for feeding input data and instructions. • Some of the input devices are Keyboard Mouse scanner 19-06-2023 Computing Fundamentals and C Programming 35
  • 36.
    Output Devices • Outputdevices mirror the input data, or show the output results of the operations on the input data or print the data. • Some of the output devices are Monitor printer 19-06-2023 Computing Fundamentals and C Programming 36
  • 37.
    Central Processing unit •Brain of the computer • Most of the processing takes place in CPU. • During processing, it locates and executes the program instructions. • It also fetches data from memory and input/output devices and sends data back • CPU is also called as microprocessor • IC with many metal pins which helps in processing the data. 19-06-2023 Computing Fundamentals and C Programming 37
  • 38.
    • The componentsof CPU are 19-06-2023 Computing Fundamentals and C Programming 38 Control Unit- • Coordinates the processing by controlling the transfer of data and instructions between main memory and the registers in the CPU. • It also coordinates the execution of the arithmetic logic unit (ALU) to perform operations on data stored in particular registers. Arithmetic logic unit (ALU) – • It is the part of the CPU that performs arithmetic operations, such as addition and subtraction as well as logical operations, such as comparing two numbers to see if they are the equal or greater or less RAM- Computer memory refers to storage area where data is stored. It is of two types −  Primary Memory  Secondary Memory
  • 39.
    Memory Unit- • storagearea is needed in a computer to store instructions and data, either temporarily or permanently, so that subsequent retrieval of the instructions and data can be possible on demand. • uses registers exclusively to store and manipulate data and instructions during the processing Primary memory/Cache-main memory of computer present in motherboard. Secondary Memory/Auxiliary memory • Sometimes when data to be processed is large, it cannot fit in primary memory as it is limited, in such cases, we use supplement memory or secondary memory. • Secondary memory helps to store information permanently and is non-volatile. • access time is high,can store high amount of data for longer Period of time • Examples of secondary storage memory are compact disk, floppy disk, pen drive, external hard drive, etc. 19-06-2023 Computing Fundamentals and C Programming 39
  • 40.
    Primary Memory- • dataand programs are stored while the program is being executed along with the data. • Also known as main memory and accessed directly by the processor. • Unit memory of fixed length and each of which is identified by a sequence number known as a memory address. • It is called cache memory • It is a type of high speed memory that allows the processor to access data more rapidly than from memory located elsewhere on the system. • It stores or caches some of the contents of the main memory that is currently in use by the processor. It takes a fraction of the time, compared to main memory, to access cache memory. • The management of data stored in the cache memory ensures that for 20 per cent of the total time, during which the cache is searched, the data needed is found to be stored in cache. • As a result the performance of the computer improves in terms of speed of processing 19-06-2023 Computing Fundamentals and C Programming 40
  • 41.
    Primary memory/Cache memory RAM •Temporary memory • Volatile • In which, information stored is lost once computer is turned off. • Instructions written in this memory can be modified; hence it is also known as programmable memory • Available in small storage capacity • Processing speed is high • Expensive • Types of RAM Static memory Dynamic Memory ROM • Permanent memory • Non-Volatile • In which information stored is available even if computer is turned off. • Instructions stored in this memory can only be read and cannot be modified. • Available in high storage capacity • Processing speed is low • Non expensive • Types of ROM are PROM (Programmable Read Only Memory), EPROM (Erasable PROM),  EEPROM (Electrically Erasable PROM) and flash memory. 19-06-2023 Computing Fundamentals and C Programming 41
  • 42.
    Interface unit- • Interconnectsthe CPU with memory and also with the various input/output (I/O) devices. It is a set of parallel wires or lines which connects all the internal computer components to the CPU and main memory. • Depending on the type of data transmitted, a bus can be classified into the following three types:  Data bus The bus used to carry actual data.  Address bus memory or Input/output device Addresses travel via the address bus.  Control bus This bus carries control information between the CPU and other devices within the computer 19-06-2023 Computing Fundamentals and C Programming 42
  • 43.
  • 44.
    Types of Software •PC software is basically sort of program that permits clients to play out specific assignments or really use them to work their PC. • It basically indicates all peripherals in whole PC system – precisely what to do and how to carry out responsibility. • set of computer programs, which provide desired functions and performance, the data which the programs use, data structures that facilitate the programs to efficiently manipulate data and documents that describe the operation and use of the programs. • Installation involves copying several files to computer memory or requires a series of steps and configurations • Software is generally categorized as System software and Application software or utility software. 19-06-2023 Computing Fundamentals and C Programming 44
  • 45.
    System Software- • Systemsoftware is designed to facilitate and coordinate the use of the computer by making hardware operational. • It interacts with the computer system at low level. • Examples of such software include language translator, operating system, loader, linker, etc. • The most important system software is the operating system which is a set of programs designed to control the input and output operations of the computer, provide communication interface to the user, and manage the resources of the computer system, such as memory, processor, input/output devices etc. and schedule their operations with minimum manual intervention. • System software is used in printers, monitors, graphics cards, sound cards, network cards, modems, storage devices, mouse, scanners, etc. • Modern operating system recognizes almost all connected hardware devices and immediately begins the installation process which is called a plug and- play device. 19-06-2023 Computing Fundamentals and C Programming 45
  • 46.
    Application Software • Applicationsoftware is designed to perform specific usages of the users • Some of the examples of Application software are  Microsoft Word  Microsoft Excel  Microsoft Power Point  Microsoft Access  Page Maker Coral Draw  Photoshop,  Tally  AutoCAD  Acrobat  WinAmp  Micro Media Flash,  Xing MP3 Player 19-06-2023 Computing Fundamentals and C Programming 46 Application software Custom Software Pre written Software
  • 47.
    Operating System • OperatingSystem (OS) is an interface between a computer user and computer hardware. • An operating system is a software which performs all the basic tasks like file management, memory management, process management,  handling input and output, and controlling peripheral devices such as disk drives and printers. • Some popular Operating Systems include Linux OS, Windows OS, VMS, OS/400, AIX, z/OS, etc. 19-06-2023 Computing Fundamentals and C Programming 47
  • 48.
    • Following aresome of important functions of an operating System. 19-06-2023 Computing Fundamentals and C Programming 48 Operating System Memory Management Security Controls I/O devices Job Scheduling Error Detection Processor Management Device Management File Management
  • 49.
    Categories of OS •There are 6 different categories of OS • Batch OS- oldest operating system, only one program is allowed to run at one time, program cannot be modified during runtime, if error is encountered starting execute from the scratch.eg MS-DOS • Interactive OS-found after batch OS where only one program is processed at a time, entering the data and program can be modified while program is running. • Multi user OS-allows either one user or more than one use to use the computer system at same time or different times.eg windows 2000 and LINUX • Multi-tasking OS-allows more than one program to run at the same time • Multi-threading OS-allows the running of different parts of the program at the same time. • Real-time OS-designed specially to handle real time applications or embedded applications • Multiprocessor OS-allows to use many CPU’s to process many processes at the same time. • Embedded OS-installed on electronic devices to perform some computational tasks. 19-06-2023 Computing Fundamentals and C Programming 49
  • 50.
  • 51.
    MS-DOS Operating System •Microsoft Disk Operating System • Found by Microsoft Corporation for IBM computers in 1981 • It was stand alone in the earlier and now it is integrated with the all the versions of windows. • Command Line user Interface called MS DOS prompt • Various commands are used to perform the operations in MS-DOS • Categories of MS DOS commands are • Environment command • File Manipulation Command • Utilities 19-06-2023 Computing Fundamentals and C Programming 51
  • 52.
  • 53.
    • Environment Commands–provides some information on the OS • File Manipulation command-manipulating files like copying or deleting a file. 19-06-2023 Computing Fundamentals and C Programming 53 Commands Used for CLS Clear the content of the screen VER Helps to view the Version of the MS-DOs DATE Helps to view the current date TIME Helps to view the current time and can edit the time Commands Used for COPY Copies one or more files from a location to another location DEL deletes a file from the computer TYPE View the contents of the files of a file DIR Allows to view the files available in the directories
  • 54.
    MS Windows OS •The architecture of windows OS is comprised of 3 layers User mode Kernel Mode Hardware 19-06-2023 Computing Fundamentals and C Programming 54
  • 55.
  • 56.
    Networking Concepts • Computernetworks interconnects many computers and enable them to communicate with each other and share their resources, data and applications. • A network is a combination of PC, or mixed of PC’s, mini and mainframes spanning a particular geographical area. • Computer networks are divided into Based on geographical area Based on how computer nodes are used. 19-06-2023 Computing Fundamentals and C Programming 56
  • 57.
    Based on Geographical area LAN WAN MAN Internet Intranet 19-06-2023 Computing Fundamentalsand C Programming 57 LAN-Local Area Network WAN-Wide Area Network MAN-Metropolitan Area Network Internet-International Network
  • 58.
    Based on howcomputer nodes are used CSN PPN VAN 19-06-2023 Computing Fundamentals and C Programming 58 CSN-Client to Server Network PPN-Peer to Peer Network VAN-Value Added Network
  • 59.
    Local Area Network(LAN)- •Is a group of computers connected together. • Computers that are connected within a small area like building or home etc. • Using this networks users can communicate with each other to share messages or information's. • All the computers in LAN connected through twisted pair or coaxial cables. • Computers connected in LAN is limited but communication rate is higher and faster. 19-06-2023 Computing Fundamentals and C Programming 59
  • 60.
  • 61.
    Metropolitan Area Network(MAN)- •Connection of computers that covers a large area or city. • Size of MAN is between LAN and WAN covering the distance of 5km to 50km. • Owned by general organizations • Connects with the help of optical fibres, copper wires. • Eg cable television network • Router is a devices used to connect the LAN’s together. • The router directs the information packets to the desired destination. 19-06-2023 Computing Fundamentals and C Programming 61
  • 62.
  • 63.
    Wide Area Network(WAN)- •Group of compuytres connected together tht covers with in a country or continent. • Two or more LAN’s are connected with the help of telephone lines,microwave • Data is transmitted at a slow rate 19-06-2023 Computing Fundamentals and C Programming 63
  • 64.
  • 65.
    Networking Topologies • Arrangementof the computers through some physical medium such as cable , coaxial cable etc. • It refers to the shape of the network and the communication path between various nodes in the network. • Different type of topologies are Hierarchical topology Bus Topology Star Topology Ring Topology Mesh Topology Hybrid Topology 19-06-2023 Computing Fundamentals and C Programming 65
  • 66.
    Hierarchical Topology • Alsocalled as Tree topology 19-06-2023 Computing Fundamentals and C Programming 66
  • 67.
    Linear Bus Topology •All the nodes are connected to the single Backbone or bus with some medium such as Cables. 19-06-2023 Computing Fundamentals and C Programming 67
  • 68.
    Star Topology • Allthe nodes are connected to a single device called hub 19-06-2023 Computing Fundamentals and C Programming 68
  • 69.
    Ring Topology • Herethe nodes are connected with each other in a ring shape with the help of twister air cable. 19-06-2023 Computing Fundamentals and C Programming 69
  • 70.
    Mesh Topology- • Everycomputer is connected to every other computer in point-point mode. 19-06-2023 Computing Fundamentals and C Programming 70
  • 71.
    Hybrid Topology- • Combinationof multiple topologies used for constructing a large topology. 19-06-2023 Computing Fundamentals and C Programming 71
  • 72.
    Network Protocols- • Networkprotocols are set of rules and regulations used for communication between two networks. • Some of the Protocols are • HTTP-Hyper Text Transfer Protocol • SMTP-Simple Mail Transfer Protocol • FTP-File Transfer Protocol • TCP/IP-Transmission Control Protocol/Internet Protocol • Telnet • DNS-Domain Name Service 19-06-2023 Computing Fundamentals and C Programming 72
  • 73.
    Programming Languages • Aprogramming language is a set of commands, instructions, and other syntax use to create a software program. • Languages that programmers use to write code are called "high-level languages." • This code can be compiled into a "low-level language," which is recognized directly by the computer hardware. • High-level languages are designed to be easy to read and understand. Eg C++, Java, Perl, and PHP. • Low-level languages include assembly and machine languages. • An assembler can be used to translate the assembly code into machine code. The machine code, or machine language, contains a series of binary codes that are understood directly by a computer's CPU. • Machine language is not designed to be human readable. 19-06-2023 Computing Fundamentals and C Programming 73
  • 74.
    Translator Programs • convertscode from one computer language into another • Converts to high level language to low level language • Different types of translators are Compiler-converts high level programming language to low level programming language and stores in memory Interpreter- Compiler-converts high level programming language to low level programming language Assembler- translate assembly language(low-level) into machine language (lower level),translates low level language to lower level language 19-06-2023 Computing Fundamentals and C Programming 74
  • 75.
    • Difference betweentranslator programs 19-06-2023 Computing Fundamentals and C Programming 75 Compiler Interpreter Assembler • convert high-level programming language to low-level programming language • converts the whole program in one session and reports errors detected after the conversion • processor-dependent and platform-dependent. • Takes time for conversion • used to convert high-level programming language to low- level programming language • converts the program one line of code at a time and reports errors when detected • Interpreter is faster than a compiler as it immediately executes the code upon reading the code. • a debugging tool for software development as it can execute a single line of code at a time • Processor independent • Portable than compiler • Translate assembly language into machine language • Difficult to understand • Low level language to lower language level
  • 76.
    Problem Solving Techniques •Computer is used to solve the problem because it takes less time than humans. • Following are the steps to solve a problem Analyze the problem Divide the process in a series of elementary tasks Formulate the algorithm to solve the problem Express the algorithm in the form of program Feed it in to computer CPU interprets the given program, process the data and generates the result. Send the generated result to the output unit • Algorithms and Flowcharts are the two problem solving techniques. 19-06-2023 Computing Fundamentals and C Programming 76
  • 77.
  • 78.
    Algorithm- • Is acomplete ,detailed, and precise step by step procedure to solve a problem independently of the software or hardware of the computer. • It instructs the computer what specific steps need to perform to solve a problem. 19-06-2023 Computing Fundamentals and C Programming 78
  • 79.
    Algorithm 1: Addtwo numbers entered by the user • Step 1: Start • Step 2: Declare variables num1, num2 and sum. • Step 3: Read values num1 and num2. • Step 4: Add num1 and num2 and assign the result to sum. sum←num1+num2 • Step 5: Display sum • Step 6: Stop 19-06-2023 Computing Fundamentals and C Programming 79
  • 80.
    Algorithm 2: Findthe largest number among three numbers • Step 1: Start • Step 2: Declare variables a,b and c. • Step 3: Read variables a,b and c. • Step 4: If a > b If a > c Display a is the largest number. Else Display c is the largest number. Else If b > c Display b is the largest number. Else Display c is the greatest number. • Step 5: Stop 19-06-2023 Computing Fundamentals and C Programming 80
  • 81.
    Top-down approach ofalgorithms- • Also called as divide and conquer method. • The problem is divided in to more sub problems and each of which resembles the original problem. • The solution of the sub problem is taken out independently and combined together • Eg Binary Search 19-06-2023 Computing Fundamentals and C Programming 81
  • 82.
    Suppose we wishto search 38 in the array. • Step 1: Find the middle element of the array. • index(Middle) = index(low) + index(high – low)/2. • Here, middle = 0 + (9-0)/2 = 4 i.e. the element at the 4th index i.e. 25. 19-06-2023 Computing Fundamentals and C Programming 82
  • 83.
    Step 2: Compare38 with the middle element. 38 > 25 So, discard the first half. Step 3: Select the send half of the array. For the second half, low = middle+1 as shown: 19-06-2023 Computing Fundamentals and C Programming 83
  • 84.
    • Step 4:Find the middle element of this smaller array which comes out to 32. Compare 38 with 32. 38 > 32 Thus, discard the first half of this array. • Step 5: Select the remaining half of the array by doing low = middle+1 as shown: • Finally, we have found 38 and thus the algorithm will halt here. 19-06-2023 Computing Fundamentals and C Programming 84
  • 85.
    Program Verification- • Writinga program to perform a task and testing the program with different examples. • If the program gives correct result then it is verified that program is correct. Efficiency of an algorithm- • How fast the program produces the correct result • It depends upon the two factors • Time Complexity-running time of the program • Space Complexity-memory taken by the program • Space Complexity defines the amount of memory required by the algorithm for the execution and generation of the output. • Time Complexity refers to the amount of computer time required by an algorithm for its execution. • It includes both compile and runtime. 19-06-2023 Computing Fundamentals and C Programming 85
  • 86.
    Analysis of algorithm- •Determines the amount of resources such as time and memory(space) required for the execution. • Algorithm analysis provides theoretical estimates required by an algorithm to solve a problem. Asymptotic Analysis • Performance of the algorithm based on the input size • Relation between the running time and the input size • Time and Space factor Worst, Average and Best Cases • Divided into three different cases  Best Case(Ω) − minimum time taken to execute the program.  Average Case(θ) − average time taken to execute the program.  Worst Case(O) − maximum time taken to execute the program. Asymptotic Notations • Asymptotic notations are mathematical tools to represent the time complexity of algorithms for asymptotic analysis.  Ο (Big O) Notation  Ω (Omega)Notation  θ (Theta) Notation 19-06-2023 Computing Fundamentals and C Programming 86
  • 87.
    Flowchart- • Pictorial representationof the algorithm depicting the flow of the various steps. • Visualize the working of an algorithm 19-06-2023 Computing Fundamentals and C Programming 87
  • 88.
  • 89.
  • 90.
    Overview of C •C is one of the most popular language • It is a structured ,high-level, machine independent language. • ALGOL was the first structured programming language and it is the root of the programming languages. • BCPL –Basic Combined Programming Language used for writing system software • B was used in UNIX OS in Bell Laboratories. • C was evolved from ALGOL,BCPL,B by dennis Ritchie at the Bell laboratories in 1972. 19-06-2023 Computing Fundamentals and C Programming 90
  • 91.
    • C usesconcepts from the previous languages and concept of datatypes and other powerful features were added. • After the publication of book “The C Programming Language” written by Brian Kerningham and Dennis Ritchie in 1978 it was called K&R C • ANSI (American National Standards Institute )approved the standard of C so it was called ANSI C and later approved by ISO (International Standard Organization) so it was called ANSI/ISO C or C89. • Later on in 1990 C++ and JAVA modelled on C and some features from C++ and Java used in C called as C99. 19-06-2023 Computing Fundamentals and C Programming 91
  • 92.
    Importance of C •Robust Language • Efficient and fast • Built in functions and 32keywords • Highly portable • Structured Programming which makes debugging,testing and maintenance easier. • Ability to extend with functions supported by C library. 19-06-2023 Computing Fundamentals and C Programming 92
  • 93.
    SAMPLE PROGRAM FORPRINTING A MESSAGE main()-execution of the program begins or start of the program every program should have 1 main(). if the program has more than one main() .the compiler cannont understand where to begin. {-beginning of the function, }-closing of the function Statements between { &} are called function body which contains set of instructions to perform a task 19-06-2023 Computing Fundamentals and C Programming 93 Output
  • 94.
    • printf statementis the only executable statement • /* or// known as comment lines whichare not executable statement to Enhance the readability and understandability. • Comment lines are ignored by the Compiler • Comments can be inserted anywhere inside the program • Printf is a predefined standard C function for printing output. • Predefined-function that is already written and compiled linked with the program. • It should be given with “ ******“ • Every statement should end with semicolon(;) 19-06-2023 Computing Fundamentals and C Programming 94
  • 95.
    • If printffunction is given like • n-instructs the computer to go to the next new line • n should be given wth string of characters without any space between and n followed by coma(,) 19-06-2023 Computing Fundamentals and C Programming 95
  • 96.
    • In Cprogram is written in lower case letters • For eg PRINTF and printf is not same 19-06-2023 Computing Fundamentals and C Programming 96 • main() is part of the every C Program • Different forms of main() statement are • Empty parantheses () means that the function has no arguments. • void() returns does not return any info to the OS • int() returns integer value to the OS and if int is specified last statement of the program must be “return 0”
  • 97.
    19-06-2023 Computing Fundamentalsand C Programming 97 Number and amount- variable names Variables must be declared before they use to tell the compiler int ,float-keywords Values are assigned by using assignment operators number=100 amount=30.75+75.35 %d –decimal integer %5.2f-values of 5 places with 2 values after decimal point of float datatype
  • 98.
  • 99.
    • #define –pre-processorcompiler directive not a statement • It should not end with semicolon • Symbolic constants are written in uppercase letters to distinguish between the variable names. • #define placed in the program in the beginning before the main(). • #define –defines values to a symbolic constant • Wherever #define is encountered compiler substitutes the value with the name automatically. • For eg 19-06-2023 Computing Fundamentals and C Programming 99
  • 100.
    • If 3variable of same data type it can be given in one line separated by comma. • For eg • C supports four basic arithmetic operators • + (addition) • -(subtraction) • *-(multiplication) • /-(division) 19-06-2023 Computing Fundamentals and C Programming 100 float amount,value,inrate;
  • 101.
    Uses of Subroutines •Subroutines which is also called sub functions or sub program • User-defined function : A funtion defined by the user 19-06-2023 Computing Fundamentals and C Programming 101
  • 102.
    • Syntax offunction declaration return_type function_name( parameter list ); • 19-06-2023 Computing Fundamentals and C Programming 102
  • 103.
    Use of MATHfunctions • If a program contains standard mathematical functions like • Sin • Cos • Tan • Exp • C makes use of MATH library function • #include<math.h> • The standard mathematical functions are defined and kept as a part. • Tells the compiler to link the mathematical functions from the math library with the program. 19-06-2023 Computing Fundamentals and C Programming 103
  • 104.
    #include directive preprocessor •C is comprised of user defined functions and library functions • Library functions are stored in different header files. • #include<filename.h> must be included in the program telling the compiler about the files to be accessed in the program 19-06-2023 Computing Fundamentals and C Programming 104
  • 105.
    Basic structure ofthe C program 19-06-2023 Computing Fundamentals and C Programming 105 Set of comment lines giving the name of the program etc // or/* Links the library functions Symbolic constants definition Variable used in more than one functions are declared globally Every c program must have main() Contains declaration part and executable statements part Contains { } tells the compiler program execution start and end Every statement ends with semicolon(;) Subprograms contains the user-defined functions It can be called in the main() function
  • 106.
    Programming Style • Cis a free form language • C program statements should be written in lower case letters • Upper case statements used to define symbolic constants. • Indentation of braces is important to identify opening and closing line of program. 19-06-2023 Computing Fundamentals and C Programming 106
  • 107.
    Executing a Cprogram • It has a series of steps Creating the program Compiling the program Linking the program with the library functions Executing the program 19-06-2023 Computing Fundamentals and C Programming 107
  • 108.
    • A Programminglanguage helps to process some kinds of data consisting of numbers,characters,strings to provide a useful output called information. • Data is processed by giving a set of instructions called program • These instructions consists of words and symbols according to some rules called syntax rules. • Every program must follow the syntax rules Character set • The characters used in C are Letters Digits Special characters White spaces 19-06-2023 Computing Fundamentals and C Programming 108
  • 109.
    19-06-2023 Computing Fundamentalsand C Programming 109
  • 110.
    Trigraph Characters • Trigraphcharacters consists of 3 charcaters (2 question marks followed up by another character) 19-06-2023 Computing Fundamentals and C Programming 110
  • 111.
    C Tokens • Thesmallest individual unit are known as C tokens 19-06-2023 Computing Fundamentals and C Programming 111
  • 112.
    Keywords and Identifiers •Every C word is classified into • Keywords • Identifiers • These keywords have fixed meanings cannot be changed 19-06-2023 Computing Fundamentals and C Programming 112
  • 113.
    Identifiers – • Refersname of the variables,functions, and arrays • User defined names • Can use both upper case and lowercase letters • _ is also permitted in identifiers 19-06-2023 Computing Fundamentals and C Programming 113
  • 114.
    Constants • Refers tofixed values that do not change during execution of the program 19-06-2023 Computing Fundamentals and C Programming 114
  • 115.
    Integer Constants-refers toa sequence of digits. • Decimal integer-0 to 9 ,+,- • Octal integer-any digits from 0to 7 leading with 0. • Hexadecimal integer-sequence of digits preceded by 0x or 0X ,A-F or a-f 19-06-2023 Computing Fundamentals and C Programming 115 No spaces, commas,any symbols
  • 116.
    Real/Floating point Constants •Numbers containing fractional parts • Exponential or scientific notation is given as Single Character Constant- • Contains a single character enclosed in single quotes ‘ ‘ eg. ‘r’ • Print 97 19-06-2023 Computing Fundamentals and C Programming 116
  • 117.
    String constants- • Sequenceof characters enclosed within “ “ • It may be letters,numbers,special characters,blank spaces • ‘X’≠ “X” Backslash character constants- • C supports backslash characters(n) in some output functions. 19-06-2023 Computing Fundamentals and C Programming 117
  • 118.
    19-06-2023 Computing Fundamentalsand C Programming 118
  • 119.
    Variables • It refersto the data name to store some values 19-06-2023 Computing Fundamentals and C Programming 119 No white spaces, keywords,TOTAL ≠total
  • 120.
    Data Types • Cis rich in its data type • Three classes of data types are • Primary or fundamental datatype • Derived data type • User defined data type 19-06-2023 Computing Fundamentals and C Programming 120
  • 121.
    Integer • Has 3classes based on range and storage of numbers Floating point/real data type 19-06-2023 Computing Fundamentals and C Programming 121
  • 122.
    Void datatype- • Hasno values • Does not return any value to the calling function • Represent any data types Character datatype- • A single character can be defined using char datatype. 19-06-2023 Computing Fundamentals and C Programming 122
  • 123.
    Declaration of variables •Declaring a variable tells the compiler what the variable name is. • What type of data the variable will hold. • Declaration must be done before the program • Declaration of variable can be done before or after the main() 19-06-2023 Computing Fundamentals and C Programming 123 Variable declaration Primary type declaration User defined declaration
  • 124.
    Primary type declaration- •A variable can be used to store a value of any data type • V1,v2,…vn –variable names • Variables are separated by commas • Declaration must end with semicolon(;) 19-06-2023 Computing Fundamentals and C Programming 124
  • 125.
    19-06-2023 Computing Fundamentalsand C Programming 125
  • 126.
    User defined declaration- •C supports a feature known as “type definition” that allows the user to define an identifier that would represent an existing data type • Later it can be used to declare variables • Advantage of typedef is to create a meaning full data type name for increasing the readability of the program. 19-06-2023 Computing Fundamentals and C Programming 126
  • 127.
    Declaration of Storageclass • Storage class that provides information about their location and their visibility • The storage class decides the portion of the program within which the variables are recognized 19-06-2023 Computing Fundamentals and C Programming 127 • ‘m’-called as global or external variable • Variable declared before the main() is called global or external variable • variables I,balance,sum are called local variables which can be used only inside the program • Local variables are visible and meaningful only inside the program or functions where it is declared. • Variable ‘i’ is declared in both functions does not affect the value
  • 128.
    • C hasvariety of storage class classifiers used to declare explicitly the scope and lifetime of variables • Scope and lifetime is considered only in the program which contains multi functions and multi program files 19-06-2023 Computing Fundamentals and C Programming 128 Storage class auto register static extern
  • 129.
    19-06-2023 Computing Fundamentalsand C Programming 129
  • 130.
    Assigning values tovariables Assignment statement(=)- • Values can be assigned to a variable using the = operator 19-06-2023 Computing Fundamentals and C Programming 130
  • 131.
    19-06-2023 Computing Fundamentalsand C Programming 131 • The process of giving initial values to variables I called initialization • C permits initialization of values to more than one variables in one statement using the assignment operator • External and static variables are initialized to zero by default • Auto variables which does not contain values called as garbage
  • 132.
    Reading data fromkeyboard- • Giving values to variables is to input data through keyboard • “scanf()” • Input statement • “control string”-format of data being received • “&variable1-address of the variable1 • If & is not given error occurs in scanf statement • When compiler encounters scanf statement executions stops and waits till the value of the number is typed in. • Once the value is entered it the computer proceeds to the next statement 19-06-2023 Computing Fundamentals and C Programming 132
  • 133.
    Defining symbolic constants •It is also another way assigning values to constants • 19-06-2023 Computing Fundamentals and C Programming 133
  • 134.
    19-06-2023 Computing Fundamentalsand C Programming 134
  • 135.
    19-06-2023 Computing Fundamentalsand C Programming 135
  • 136.
    19-06-2023 Computing Fundamentalsand C Programming 136
  • 137.
    • Declaring variableas a constant • Declaring variable as volatile  a variable declared as volatile tell the complier explicitly that the value may be change at any time by external sources(outside of the programs) If the value should not modified then it can be declared as 19-06-2023 Computing Fundamentals and C Programming 137
  • 138.
    Overflow and underflowof data- • Overflow occurs when the value of variable is either too big or too small for the data type to hold. • The largest value that a variable can hold depends up on the machine • Over flow error results in largest possible float point • Underflow errors result in zero • 19-06-2023 Computing Fundamentals and C Programming 138
  • 139.
    Operators and Expressions •An operator tells a computer to perform a mathematical or logical manipulation • Operators used to manipulate data and variables • Operators form a part of mathematical or logical expressions 19-06-2023 Computing Fundamentals and C Programming 139 C operators Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operators Bitwise operators Special operators
  • 140.
    • An expressionis a sequence of operators and operands that reduces to a single value • For eg =25(Value) • The return type of the value can be of any type except ‘void’ Arithmetic Operators • C provides all basic arithmetic operators 19-06-2023 Computing Fundamentals and C Programming 140 a,b are operands
  • 141.
  • 142.
    Integer arithmetic • Whenan operands both are integers with an arithmetic operator Real arithmetic • It contains operations of 2 real operands • %(mode) cannot be used with real arithmetic 19-06-2023 Computing Fundamentals and C Programming 142 When modulo division the sign of the result will have the sign of first operand
  • 143.
    Mixed mode arithmetic •When one of the operand is real and another is integer • For eg • When one of the operand is real type the result of the expression will be in real type 19-06-2023 Computing Fundamentals and C Programming 143
  • 144.
    Relational Operators • Comparing2 operands and depending on their relations decisions are made • These comparisons and relations are made by using relational operators • C supports 6 types of relational operators .result of the relational expression will be either 0 or 1 /true or false 19-06-2023 Computing Fundamentals and C Programming 144
  • 145.
    19-06-2023 Computing Fundamentalsand C Programming 145 • Arithmetic operators have high priority than relational operators • Relational operators are expressed in if and while loop Relational Operator complements
  • 146.
    Logical operators • Cfollows three logical operators • Logical operators && and || are used to test more than one one condition and make decisions • An expression combines two or more relational expressions are called logical or compound relational expression • For eg 19-06-2023 Computing Fundamentals and C Programming 146
  • 147.
    • The resultof an logical expression will be either true or false 19-06-2023 Computing Fundamentals and C Programming 147
  • 148.
    Assignment operators • Assigningthe result of an expression to a variable by using “=“ • C supports a set of shorthand assignment operators 19-06-2023 Computing Fundamentals and C Programming 148 X=x+3
  • 149.
    Advantages of shorthandoperators • It is easier to read and concise • More efficient • No need of repeating left hand side 19-06-2023 Computing Fundamentals and C Programming 149
  • 150.
    Increment and decrementoperators- • C allows two operators for increment and decrement of variable • The operator ++ adds 1 to the operand and -- decreases value by 1 • It is also called unary operator 19-06-2023 Computing Fundamentals and C Programming 150
  • 151.
    Behaviour of m++and ++m /m– and –m 19-06-2023 Computing Fundamentals and C Programming 151
  • 152.
    19-06-2023 Computing Fundamentalsand C Programming 152
  • 153.
    Conditional operator- • Ternaryoperator “?:” cosntructsthe conditional expression • Exp1 is evaluated first if it is true exp2 is evaluated and becomes the value of the expression • If exp1 is false ,exp3 is evaluated and becomes the value of the expression 19-06-2023 Computing Fundamentals and C Programming 153
  • 154.
    Bitwise operators • Testingthe data in bit wise, shifting left or right • Float or double is not permitted 19-06-2023 Computing Fundamentals and C Programming 154
  • 155.
    Special operators- • Csupports some special operators • Comma operator(,) • sizeof() • Pointer operators(* and &) • Member selection operator(. and ->) • Comma operator(,)-links the related expression together 19-06-2023 Computing Fundamentals and C Programming 155
  • 156.
    • sizeof()-returns thenumber of bytes that operand occupies,can be used to know the length of arrays or structures when the size is not known to the programmer,can also be used to allocate memory dynamically 19-06-2023 Computing Fundamentals and C Programming 156
  • 157.
    Arithmetic expressions- • Combinationsof variables,constants and operators • It does not have any operator for exponentiation 19-06-2023 Computing Fundamentals and C Programming 157
  • 158.
    Evaluation of expression- •Expressions are evaluated using the assignment operator 19-06-2023 Computing Fundamentals and C Programming 158
  • 159.
    Precedence of arithmeticexpressions- • Arithmetic expressions are evaluated from left side given inside the parentheses • Using the rules of precedence of operators • C have 2 distinct priority levels of arithmetic operators • High priority -* / % • Low priority- + - • For eg 19-06-2023 Computing Fundamentals and C Programming 159
  • 160.
    • High priority-* / % • Low priority- + - 19-06-2023 Computing Fundamentals and C Programming 160
  • 161.
    19-06-2023 Computing Fundamentalsand C Programming 161 • If the expression has parentheses values within the parentheses will be evaluated first • If it contains more sets of parentheses parentheses value are evaluated first from the left hand side and the right most end in the last
  • 162.
    19-06-2023 Computing Fundamentalsand C Programming 162
  • 163.
    Type Conversions inExpression 19-06-2023 Computing Fundamentals and C Programming 163 Type Conversions Implicit Conversion Explicit Conversion
  • 164.
    Implicit Conversion- • AutomaticConversion of datatypes • During conversion it follows some rules • If the lower type is converted to higher type the result will be of higher datatype Explicit Conversion- • Forced type conversion or manual type conversion different from automatic conversion • The process of local conversion is called implicit conversion/casting a value 19-06-2023 Computing Fundamentals and C Programming 164 int female_number; int male_number;
  • 165.
    • The expressioncan be a value or constant or an expression 19-06-2023 Computing Fundamentals and C Programming 165
  • 166.
    Operator Precedence andAssociativity- • The precedence is used to determine how an expression involving more than one operator is evaluated • The operators ta the higher level of precedence are evaluated first • The operators having the same precedence are evaluated from left to right or from right to left called associativity 19-06-2023 Computing Fundamentals and C Programming 166
  • 167.
    Math functions- • Themath functions supported by c compilers are used in real life problems 19-06-2023 Computing Fundamentals and C Programming 167
  • 168.
    Managing input andoutput operations- • Reading ,processing and writing of data are the essential functions of a computer program • Some functions use to take data and some functions to display data • Two ways to providing data to the variables • Assignment operator • Scanf and printf function • Scanf-to read data from the keyboard • Printf-to display data on the screen 19-06-2023 Computing Fundamentals and C Programming 168
  • 169.
    Reading a character- •Reading a character from the standard input unit(keyboard) • Writing a character to the standard output unit(screen) • Reading a single character can be done by the function • scanf() function can also be used to read the input • When getchar() is encountered the computer waits till it receives input from the user through the keyboard 19-06-2023 Computing Fundamentals and C Programming 169
  • 170.
    19-06-2023 Computing Fundamentalsand C Programming 170
  • 171.
    19-06-2023 Computing Fundamentalsand C Programming 171
  • 172.
    19-06-2023 Computing Fundamentalsand C Programming 172
  • 173.
    19-06-2023 Computing Fundamentalsand C Programming 173
  • 174.
    • #include<stdio.h> • #include<math.h> •#include<ctype.h> 19-06-2023 Computing Fundamentals and C Programming 174
  • 175.
    Unit -3 Decision Making,Looping and Arrays • Executing a segment of a program repeatedly by introducing a counter and later testing it using the if statement • For every decision making loops , • Initialize • Test • Increment • Above steps to be followed to complete a loop 19-06-2023 Computing Fundamentals and C Programming 175
  • 176.
    Calculating the sumof squares for all integers between 1 and 10 using if statement 19-06-2023 Computing Fundamentals and C Programming 176
  • 177.
    • Looping-sequence ofstatements are executed until some conditions for termination of the loop are satisfied • A Program loop contains • Body of the loop • Control statement • Depending on the position of the control statement in the loop control structure is classified into • Entry controlled loop/pre-test loop • Exit controlled loop/post-test loop 19-06-2023 Computing Fundamentals and C Programming 177
  • 178.
    • Entry controlled/Pre-testloop  The control conditions are tested before the start of the loop execution. If the conditions are not satisfied then the body of the loop will not be executed 19-06-2023 Computing Fundamentals and C Programming 178
  • 179.
    • Exit controlled/Post-testloop The test is performed at the end of the body of the loop and therefore the body is executed unconditionally for the first time 19-06-2023 Computing Fundamentals and C Programming 179
  • 180.
    • Infinite loop- Thebody of the loop is executed over and over again. • The four steps of the looping process includes 1. Setting and initialization of the condition variable 2. Execution of the statements in the loop 3. Test for a specified value of the condition variable for execution of the loop 4. Incrementing or updating the condition variable • c language has 3 constructs for performing loop operations The while statement The do statement The for statement 19-06-2023 Computing Fundamentals and C Programming 180
  • 181.
    While loop • Simplestform of looping structure • The basic structure of while loop is • It is an entry controlled loop • The test condition is evaluated first and if it is true the body of the loop is executed until the test condition becomes false • The control is transferred out of the loop once it becomes false • The body of the loop must contains one or two statements and entred with in { …. } 19-06-2023 Computing Fundamentals and C Programming 181
  • 182.
    19-06-2023 Computing Fundamentalsand C Programming 182
  • 183.
    19-06-2023 Computing Fundamentalsand C Programming 183
  • 184.
    19-06-2023 Computing Fundamentalsand C Programming 184
  • 185.
    Do loop • Thestructure of do loop is • 19-06-2023 Computing Fundamentals and C Programming 185
  • 186.
    For loop • Thegeneral form of for loop structure is 19-06-2023 Computing Fundamentals and C Programming 186
  • 187.
    19-06-2023 Computing Fundamentalsand C Programming 187
  • 188.
    19-06-2023 Computing Fundamentalsand C Programming 188
  • 189.
    Additional Features offor loop- • Initialization, Testing control variables and increment or decrementing a variable can have more than one variable • For eg 19-06-2023 Computing Fundamentals and C Programming 189
  • 190.
    • It ispermissible to use expressions in the assignment statements of initialization and increment sections • Some sections in for loop can be omitted if necessary • Only the variable is omitted but semicolon remains 19-06-2023 Computing Fundamentals and C Programming 190
  • 191.
    • When afor loop does not have test condition it sets up a infinite loop • It can be stopped by using • break • goto • Null statement 19-06-2023 Computing Fundamentals and C Programming 191
  • 192.
    Nesting of forloops- • One for statement within another for statement • The loops must be properly indented • It can have 15 nesting loops and even more 19-06-2023 Computing Fundamentals and C Programming 192
  • 193.
    19-06-2023 Computing Fundamentalsand C Programming 193
  • 194.
    Selecting a loop 19-06-2023Computing Fundamentals and C Programming 194
  • 195.
    JUMP statement inloop– • C Permits a jump from one statement to another within a loop as well as a jump out of a loop I. JUMPING out of a loop break –will exit only one single loop Goto 19-06-2023 Computing Fundamentals and C Programming 195
  • 196.
    19-06-2023 Computing Fundamentalsand C Programming 196
  • 197.
    19-06-2023 Computing Fundamentalsand C Programming 197
  • 198.
    II Structured Programming •Approach to the design and development of the programs • a Discipline making a program’s logic easy to understand by using only the following 3 control structures Sequence structure Selection(branching) structure Repetition (looping) structure • Structured programming techniques helps to ensure the programs easy to write ,read, debug, and maintain compared to those which are unstructured. • C supports another similar statement called continue statement. • Continue causes a loop to be continued with the next iteration after skipping some statements in between 19-06-2023 Computing Fundamentals and C Programming 198
  • 199.
    • Continue statementtells the compiler “skip the following statements and continue with the next iteration • The format of continue statement is 19-06-2023 Computing Fundamentals and C Programming 199
  • 200.
    19-06-2023 Computing Fundamentalsand C Programming 200
  • 201.
    19-06-2023 Computing Fundamentalsand C Programming 201
  • 202.
    19-06-2023 Computing Fundamentalsand C Programming 202
  • 203.
    Avoiding goto statements– • It makes the program logic complicated and renders the program unreadable • Many compilers generate a less efficient code • If it is necessary it should be documented 19-06-2023 Computing Fundamentals and C Programming 203
  • 204.
    Jumping out ofthe program- • Break statement • Goto statement • exit()- library function which breaks the program and return to the os. • Exit() takes an integer as an argument • 0-normal termination • Non zero-abnormal termination or due to an error 19-06-2023 Computing Fundamentals and C Programming 204
  • 205.
    Arrays • To handlebulk volume of data in terms of reading processing and printing • Need of new and powerful data type that would facilitate efficient storing, accessing and manipulation of data items • C supports a derived data type arrays which can be used in these applications. • Array is a fixed size sequenced collection of elements of the same data type. simply like grouping of like-type data. • For eg array can be used to represent a list of names or numbers 19-06-2023 Computing Fundamentals and C Programming 205
  • 206.
    • It isclassified as one of the data structures in C • Data Structure -Structuring/organizing the Data in a computer so that it can be used effectively .Other types are structures,queue,trees ,graphs and lists. • Array can have a common name • For eg salary for representing set of salaries for 100 employees • Individual salary can be represented by index or subscript 19-06-2023 Computing Fundamentals and C Programming 206
  • 207.
    • fixed-size sequencedcollection of variables belonging to the same data types and stored in contiguous memory. • Set of pairs, index or value • The array has adjacent memory locations to store values. • convenient structure for representing data • Two terms to understand the concept of array are Element and Index Element − Each item stored in an array is called an element. Index − Each location of an element in an array has a numerical index, which is used to identify the element. data_type array_name [array_size]; 19-06-2023 Data Structures
  • 208.
    • Index startswith 0. • Array length is 10 which means it can store 10 elements. • Each element can be accessed via its index(mapping). For example, we can fetch an element at index 6 as 9. • Arrays can be not only to represent a list of values but also a table of two or three or ore dimensions • Different types of arrays • One dimensional or 1D array • Two Dimensional or 2D array • Three Dimensional or 3D array 19-06-2023 Data Structures
  • 209.
    19-06-2023 Computing Fundamentalsand C Programming 209
  • 210.
    1D or onedimensional array- • A list of items having one variable name with only one subscript • Computer reserves 5 storage locations • Int number[5]={35,40,20,57,19} 19-06-2023 Computing Fundamentals and C Programming 210
  • 211.
    19-06-2023 Computing Fundamentalsand C Programming 211 Char name[10]=“well done”; When declaring a character arrays ,allocate one extra element space for the null terminator When a compiler reads a character arrays it terminates with the additional null character(‘0’)
  • 212.
    19-06-2023 Computing Fundamentalsand C Programming 212
  • 213.
    19-06-2023 Computing Fundamentalsand C Programming 213
  • 214.
    19-06-2023 Computing Fundamentalsand C Programming 214
  • 215.
    • Two differenttypes of initialization of arrays • Compile time initialization • Run time initialization Compile time Initialization 19-06-2023 Computing Fundamentals and C Programming 215
  • 216.
    • Run timeinitialization 19-06-2023 Computing Fundamentals and C Programming 216
  • 217.
    Two Dimensional Array- •To store a table of values • C allows us to store the table of values using 2D or two dimensional array • Two dimensional array can be declared as • C places each size its own set of brackets. 19-06-2023 Computing Fundamentals and C Programming 217
  • 218.
    19-06-2023 Computing Fundamentalsand C Programming 218
  • 219.
    19-06-2023 Computing Fundamentalsand C Programming 219
  • 220.
    19-06-2023 Computing Fundamentalsand C Programming 220
  • 221.
    Initializing an 2Darray – 1. 6. 2. 7. 3. 4. 5. 19-06-2023 Computing Fundamentals and C Programming 221
  • 222.
    Memory Layout- • Thesubscripts in the 2d arrays represents the rows and columns • The elements of the array are stored contiguously in increasing memory locations. • Starts to store row wise ,starting from the first row and ending with the last row, treating each row like a simple array. 19-06-2023 Computing Fundamentals and C Programming 222 A[3][3]={{10,20,30},{40,50,60},{70,80,90 }};
  • 223.
    Multi-dimensional array- • Callows arrays of 3 or more dimensions.the exact limit is decided by the compiler • There is no limit for dimensions but compiler permits only 7-10 dimensions. 19-06-2023 Computing Fundamentals and C Programming 223
  • 224.
    19-06-2023 Computing Fundamentalsand C Programming 224
  • 225.
    Dynamic arrays- • Arrayscreated at compile time by specifying the size of the array in the program and cannot be modified at runtime. • Memory allocations is of two types Static memory allocation Dynamic memory allocation Static memory allocation – • Process of allocating memory at compile time . • Arrays that receive static memory allocation are called Dynamic arrays • This approach will work for the known data requirements 19-06-2023 Computing Fundamentals and C Programming 225
  • 226.
    Dynamic Memory allocation– • Allocating memory at runtime • It is called dynamic memory allocation • Arrays created at run time is called dynamic arrays • Dynamic arrays are created using pointer variables and memory management functions. • Memory management functions are malloc calloc realloc • These functions are included in <stdlib.h> • Dynamic arrays are used in data sstructure concepts such as linked lists, stacks, queues 19-06-2023 Computing Fundamentals and C Programming 226
  • 227.
    • More aboutarrays - 19-06-2023 Computing Fundamentals and C Programming 227
  • 228.
    Character Arrays andStrings- 19-06-2023 Computing Fundamentals and C Programming 228
  • 229.
    Character Strings- • Astring is a group of characters treated as single data item • For eg • • Some common operations performed on character string 19-06-2023 Computing Fundamentals and C Programming 229
  • 230.
    Declaring and Initializingstring variables- • C does not support string as a datatype • It allows to represent strings as character array • String variable=array of characters • When compiler assigns the character string to character array it automatically supplies null character”0” at the end of the string • So size of the character array should be maximum number of characters in the string +1 • Character array can be initialized either using 2 forms 19-06-2023 Computing Fundamentals and C Programming 230
  • 231.
    • Declaring thesize much larger than the string size in the initializer • For eg • 19-06-2023 Computing Fundamentals and C Programming 231
  • 232.
    • Purpose ofusing null character (“0”)-to determine the end of the string data and null character serves as the “end of the string “ marker Reading strings from terminal- • Using scanf() function • %s format specification to read a string of characters • Scanf() terminates its input on the first white space it finds. 19-06-2023 Computing Fundamentals and C Programming 232
  • 233.
    • To readthe entire line • To specify the field with • 19-06-2023 Computing Fundamentals and C Programming 233
  • 234.
  • 235.
    • Reading aline of text with white spaces ,special characters • getchar() and gets() • Available in <stdlib.h> 19-06-2023 Computing Fundamentals and C Programming 235
  • 236.
    Writing strings toscreen • Using printf() • Can specify the precision with which the array is displayed • For • Creates a width of 10 columns where the first four characters are to be printed • putchar() ,puts() • putchar()-character handling function to output the values of character variables.requires one parameter ,write characters to the screen.Same function can used to be repeatedly output a string of charcaters stored in the array using a loop. 19-06-2023 Computing Fundamentals and C Programming 236
  • 237.
    • Printing stringvalues ,has one parameter 19-06-2023 Computing Fundamentals and C Programming 237
  • 238.
    Arithmetic operations onCharacters – • C allows us to manipulate characters the same way doing with the numbers • Whenever a character constant or character variable is used in the expression it is automatically converted to an integer value by the system • For eg To write a character in its integer representation • Prints 97 on the screen • Can also perform arithmetic operations on the character constants and variables 19-06-2023 Computing Fundamentals and C Programming 238
  • 239.
    19-06-2023 Computing Fundamentalsand C Programming 239
  • 240.
    Relational operations- • Totest whether the ch is upper case letter Converting a character to integer 19-06-2023 Computing Fundamentals and C Programming 240
  • 241.
    Converting a stringof digits into their integer values • String conversion functions are stored in the header file <std.lib.h> 19-06-2023 Computing Fundamentals and C Programming 241 number=1988
  • 242.
    • Putting stringstogether • Comparison of strings • String handling functions • Table of strings 19-06-2023 Computing Fundamentals and C Programming 242
  • 243.
    Putting strings together– • Adding a string with other string • Called as concatenation or appending or joining • Assigning one string with the another string is not possible 19-06-2023 Computing Fundamentals and C Programming 243
  • 244.
    Comparison of twostrings – • C does not permit to compare strings directly • Strings has to be tested and compared character by character until a mismatch is found or of the strings terminates into a null character 19-06-2023 Computing Fundamentals and C Programming 244
  • 245.
    String handling functions- •C supports many string handling functions to make easy string manipulations • Import <string.h> • Some of the common functions are 19-06-2023 Computing Fundamentals and C Programming 245
  • 246.
    Strcat() • Joins twostrings together • String 2 is appended to string 1 by removing the null character of the string 1 and placing the string 2 • make sure that string 1 should be large enough to hold the string 2 19-06-2023 Computing Fundamentals and C Programming 246
  • 247.
    strcmp()- • Compare thetwo strings identified by the arguments and ha a value 0 if they are equal 19-06-2023 Computing Fundamentals and C Programming 247
  • 248.
    strcpy()- • Copies thelast string to the first string • Strlen()- • Counts and returns the number of characters in a string • N holds the length of the string and the counting ends at the first null character 19-06-2023 Computing Fundamentals and C Programming 248
  • 249.
    19-06-2023 Computing Fundamentalsand C Programming 249
  • 250.
    strncpy()- • Copies onlythe left most n characters of the source string to the target string variable • It contains three parameter • Since 5 characters does not include the null character it has to be explicitly placed in 6th position 19-06-2023 Computing Fundamentals and C Programming 250
  • 251.
    Strncmp() • It contains3 parameters • It compares left most n characters of s1 and s2 and returns 0 if they are equal or negative number if s1 is less than s2 otherwise positive strncat()- • Another concatenation function takes 3 paramters 19-06-2023 Computing Fundamentals and C Programming 251
  • 252.
    Strstr()- • Used tolocate a substring in a string • Strstr searches for the s2 in s1 and returns the position of the first occurrence of the sub string 19-06-2023 Computing Fundamentals and C Programming 252
  • 253.
    19-06-2023 Computing Fundamentalsand C Programming 253
  • 254.
    Table of strings- •To prepare a list of character strings • Eg list of names in the class ,list of employees in an organization ,list of places in a state • It is done by using 2D character array to store the entire list 19-06-2023 Computing Fundamentals and C Programming 254
  • 255.
    19-06-2023 Computing Fundamentalsand C Programming 255
  • 256.
    Unit-4 User define functions,Structures and Unions 19-06-2023 Computing Fundamentals and C Programming 256
  • 257.
    Introduction • One ofthe strength of C is C functions • C functions can be classified into two categories • Library functions eg printf,scanf,sqrt,cos,tan etc • User defined functions eg main() Need for the user defined function- 19-06-2023 Computing Fundamentals and C Programming 257
  • 258.
    19-06-2023 Computing Fundamentalsand C Programming 258
  • 259.
    Multi function Program– • A function is a self contained block of code that performs a particular task. • It is called as black box that takes some data from the main program and return as value 19-06-2023 Computing Fundamentals and C Programming 259
  • 260.
    19-06-2023 Computing Fundamentalsand C Programming 260
  • 261.
    19-06-2023 Computing Fundamentalsand C Programming 261
  • 262.
    • Any functioncan call any function • A function can call by itself • “a called function” can call another function • A function can be placed in any order • It follows the concept of modular programming • This is the main feature of user defined function 19-06-2023 Computing Fundamentals and C Programming 262
  • 263.
    19-06-2023 Computing Fundamentalsand C Programming 263
  • 264.
    Modular Programming- • Designand development of the software systems • Organizing a large program into small, independent program segments called modules • Every modules have separate names and called as program units • Finally it is integrated into one program • It is basically called divide and conquer approach of problem solving • Here each module refers to a function • Some of the characteristics of the modular programming are 19-06-2023 Computing Fundamentals and C Programming 264
  • 265.
    19-06-2023 Computing Fundamentalsand C Programming 265
  • 266.
    Elements of userdefined functions- • Function definition • Function call • Function declaration Function definition Independent program module specially written to implement the requirement of the function .Function has to be called somewhere in the program Function Call- The function or program that calls the function is referred as calling function or function call 19-06-2023 Computing Fundamentals and C Programming 266
  • 267.
    Function declaration/protoype – Thecalling function should declare any function which can be used later in the program 19-06-2023 Computing Fundamentals and C Programming 267
  • 268.
    Definition of functions- •A function definition should have 19-06-2023 Computing Fundamentals and C Programming 268 Function header Function body
  • 269.
    19-06-2023 Computing Fundamentalsand C Programming 269
  • 270.
    Function header –itcontains three parts No semicolon needed in function header 19-06-2023 Computing Fundamentals and C Programming 270 Function header Function return type Function name Function parameter list
  • 271.
    Function name andType – • Specifies the type of value that the function is expected to return to the program calling the function • Integer by default • If function is not returning anything it should be void List of parameters – • The parameter list declares the variable that will receive the ddata sent by the calling program • They serve as an input data to the function to carry out the specific task • They are also called formal parameters 19-06-2023 Computing Fundamentals and C Programming 271
  • 272.
    • Declaration ofvariable combined is not allowed 19-06-2023 Computing Fundamentals and C Programming 272
  • 273.
    Function Body – •Contains the declarations and statements necessary for performing the required task. • It contains 3 parts Local declarations that specify the variables needed by the function Function statements that performs the task of the function A return statement that returns the value evaluated by the function 19-06-2023 Computing Fundamentals and C Programming 273
  • 274.
    19-06-2023 Computing Fundamentalsand C Programming 274
  • 275.
    Return values andtheir types – • A function may or may not send back values to the calling function • It is done through return statement • A function can return only one value per function call 19-06-2023 Computing Fundamentals and C Programming 275 Does not return any value(acts as closing brace of a function Return some value and control is passed back to the calling function
  • 276.
    • A functionmay have one or more return statements based on the value returned on certain conditions. • All functions by default return value of int data type • When a value is returned it is automatically cast to the function’s type 19-06-2023 Computing Fundamentals and C Programming 276
  • 277.
    Function calls – •A function can be called by using the name of the function followed by the list of actual parameters /arguments enclosed in parenthesis 19-06-2023 Computing Fundamentals and C Programming 277
  • 278.
    • Some ofthe ways to call a function are • 19-06-2023 Computing Fundamentals and C Programming 278
  • 279.
    Function Declaration/Prototype- • Allfunctions should be declared before they are invoked. • It has 4parts 19-06-2023 Computing Fundamentals and C Programming 279
  • 280.
    19-06-2023 Computing Fundamentalsand C Programming 280
  • 281.
    A function protoype/declarationcan be placed in two places of the program • Above all the functions (including main())-global protoype • Inside a function definition-local prototype  the place of declaration of a function defines a region in a program in which the function may be used by other functions which is called scope of the function . Adds flexibility Provides quick reference to the functions in the program Enhances documentation 19-06-2023 Computing Fundamentals and C Programming 281
  • 282.
    19-06-2023 Computing Fundamentalsand C Programming 282
  • 283.
    19-06-2023 Computing Fundamentalsand C Programming 283 Formal parameters actual parameters Called function Calling function/function call
  • 284.
    Category of Functions- •A function depending on whether arguments are present or not and whether a value is returned or not • There are 5 different categories 19-06-2023 Computing Fundamentals and C Programming 284
  • 285.
    Category 1 Noarguments and No return values • When a function does not have no arguments means it does not receive any data from the calling function • When it does not return a value the calling function does not receive any data from the called function • There is no data transfer between the calling function and the called function 19-06-2023 Computing Fundamentals and C Programming 285
  • 286.
    19-06-2023 Computing Fundamentalsand C Programming 286
  • 287.
    19-06-2023 Computing Fundamentalsand C Programming 287
  • 288.
    Category 2 Argumentsbut no return values • The main() function has no control over the way the functions receive input data • Making the calling function to read data from the terminal and pass it to the called function. • The nature of data communication between the calling function and the called function with arguments and no return value 19-06-2023 Computing Fundamentals and C Programming 288
  • 289.
    19-06-2023 Computing Fundamentalsand C Programming 289
  • 290.
    19-06-2023 Computing Fundamentalsand C Programming 290
  • 291.
    • Points toremember Ensure the function should have matching arguments If actual arguments are more than the formal arguments the extra actual arguments are discarded If actual argumets is less than formal arguments the unmatched formal arguments are initilaized to some garbage values Category 3 Arguments with return values - • The function value receives data from the calling function through arguments but does not send back any value • Rather it displays the results of calculations at the terminal 19-06-2023 Computing Fundamentals and C Programming 291
  • 292.
    19-06-2023 Computing Fundamentalsand C Programming 292
  • 293.
    19-06-2023 Computing Fundamentalsand C Programming 293
  • 294.
    Category 4 Noarguments but returns a value – • Functions that may not take any arguments but returns a value to the calling function • For eg getchar() • The getchar() has no parameters but it returns an integer type that represents a character 19-06-2023 Computing Fundamentals and C Programming 294
  • 295.
    19-06-2023 Computing Fundamentalsand C Programming 295
  • 296.
    Category 5 Functionthat returns multiple values – • Functions can return multiple values but not directly • By using a method “call by address or call by reference” using pointers, arrays and structures • Address operator (&),indirection operator(*) 19-06-2023 Computing Fundamentals and C Programming 296
  • 297.
    • X,y areinput arguments and s,d are output arguments • X and y actual values are passed during the function call and s,d (where stored in memory)address of memory locations are passed 19-06-2023 Computing Fundamentals and C Programming 297
  • 298.
    19-06-2023 Computing Fundamentalsand C Programming 298
  • 299.
    19-06-2023 Computing Fundamentalsand C Programming 299
  • 300.
    19-06-2023 Computing Fundamentalsand C Programming 300
  • 301.
    Nesting of Functions- •C permits nesting of functions freely 19-06-2023 Computing Fundamentals and C Programming 301
  • 302.
    19-06-2023 Computing Fundamentalsand C Programming 302
  • 303.
    19-06-2023 Computing Fundamentalsand C Programming 303
  • 304.
    19-06-2023 Computing Fundamentalsand C Programming 304
  • 305.
    19-06-2023 Computing Fundamentalsand C Programming 305
  • 306.
    Recursion- • When afunction calls by itself • Execution is terminated abruptly • Recursive functions can be effectively used to solve problems where solution is expressed in terms of successively applying the same solution to the subset of the problem • Recursive function must have an if statement somewhere to force the function to return without the recursive call being executed • Otherwise function will never return 19-06-2023 Computing Fundamentals and C Programming 306
  • 307.
    19-06-2023 Computing Fundamentalsand C Programming 307
  • 308.
    Passing arrays tofunctions – • One dimensional arrays • Two dimensional arrays One dimensional arrays • An array of values can be passed to a called function • by listing the name of the array without any subscripts and the size of the array as arguments 19-06-2023 Computing Fundamentals and C Programming 308
  • 309.
    19-06-2023 Computing Fundamentalsand C Programming 309
  • 310.
    19-06-2023 Computing Fundamentalsand C Programming 310
  • 311.
    19-06-2023 Computing Fundamentalsand C Programming 311
  • 312.
    • Passing addressesof parameters to the function is referred to as pass by address (or pointers) 19-06-2023 Computing Fundamentals and C Programming 312
  • 313.
    • If afunction changes the value of the elements of an array then these changes will be made to the original array that passed to the function • When an entire array is passed as an argument the contents of the array are not copied into the formal parameter array instead addresses of array elements are passed on to the function • Changes in the array elements are reflected in the original array in the calling function 19-06-2023 Computing Fundamentals and C Programming 313
  • 314.
    Two dimensional array- 19-06-2023Computing Fundamentals and C Programming 314
  • 315.
    19-06-2023 Computing Fundamentalsand C Programming 315
  • 316.
    19-06-2023 Computing Fundamentalsand C Programming 316
  • 317.
    Passing strings tofunctions- • Strings are considered as character arrays • So the rules for passing strings to functions is same as passing arrays to functions 19-06-2023 Computing Fundamentals and C Programming 317
  • 318.
    19-06-2023 Computing Fundamentalsand C Programming 318
  • 319.
    19-06-2023 Computing Fundamentalsand C Programming 319
  • 320.
    19-06-2023 Computing Fundamentalsand C Programming 320
  • 321.
    Pass by ValuesPass by Pointers Values of actual parameters are copied to variables in the parameter list of the called function . The called function Works on the copy and not on the original values of the actual parameters .original data cannot be changed Known as Pass by address .the memory address of the variable rather than the copies of values sent to the called function .called function directly works on the data in the calling function and the changed values are available in the calling function 19-06-2023 Computing Fundamentals and C Programming 321 The data passed from one function to another is known as parameter passing
  • 322.
    The Scope ,Visibilityand Life time of variables • C has variety of storage class classifiers used to declare explicitly the scope and lifetime of variables • Scope and lifetime is considered only in the program which contains multi functions and multi program files 19-06-2023 Computing Fundamentals and C Programming 322 Storage class auto register static extern
  • 323.
    Automatic variables- • Declaredinside the function where it is used • They are created when the function is called and destroyed when the function is exited • So it is private /local to the ffunction where they are declared • It is also known as internal or local variables • Values cannot be changed and can use the same variable in different functions 19-06-2023 Computing Fundamentals and C Programming 323
  • 324.
    External variables- • Variablesthat are alive and active in the entire program • Also known as global variables • Global variables can be accessed by any function • External variables are declared outside the function 19-06-2023 Computing Fundamentals and C Programming 324
  • 325.
    • Global variablesas parameters 19-06-2023 Computing Fundamentals and C Programming 325
  • 326.
    Static variables- • Thevalue of the static variables persists the entire program • It can be either internal or external depending on the place of declaration • Internal static variables can be used to retain the values between the function calls Register variables – 19-06-2023 Computing Fundamentals and C Programming 326
  • 327.
    19-06-2023 Computing Fundamentalsand C Programming 327
  • 328.
    Multifile programs- • Multiplesource files can share a variable provided it is declared as an external variable appropriately • Variables that are shared by two or more files are global variables so declaring the variable in one file and then explicitly define them with extern in other files • The extern specifier tells the compiler that the following variabl has been declared somewhere and no need to create storage space for them • Multifile global variable should be declared without extern in the other two files . • The extern declaration is done in places where secondary references are made 19-06-2023 Computing Fundamentals and C Programming 328
  • 329.
    19-06-2023 Computing Fundamentalsand C Programming 329
  • 330.
    Structures and Unions 19-06-2023Computing Fundamentals and C Programming 330
  • 331.
    Introduction- • Structure isa collection of data items of different data types using a single name • C supports a constructed data type known as structures for packing a data items of different data types • Structure is a convenient tool for handling group of logically related data items • Structure helps to organize the data in a meaningful way 19-06-2023 Computing Fundamentals and C Programming 331
  • 332.
    Defining a Structure- •Structure and their variables should declared before using it • The general syntax of structure definition is • For example creating a database of books information can be done by using structures which holds the information 19-06-2023 Computing Fundamentals and C Programming 332 Structure elements or members Structure tag(name of the structure)
  • 333.
    19-06-2023 Computing Fundamentalsand C Programming 333 Defining a structure has the following syntax
  • 334.
    • Arrays VSStructures 19-06-2023 Computing Fundamentals and C Programming 334 Arrays Structures a collection of related data elements of same data type Is a collection of elements of different datatypes Derived data type Programmer defined datatype rray uses subscripts or “[ ]” (square bracket) for element access Structure uses “.” (Dot operator) for element access Built-in data type, declare and use it Design and declare a structure before the variables of that type are declared and used Array size is fixed and is basically the number of elements multiplied by the size of an element. Structure size is not fixed as each element of Structure can be of different type and size. Array declaration is done simply using [] and not any keyword. Structure declaration is done with the help of “struct” keyword. Array elements are stored in contiguous memory locations. Structure elements may or may not be stored in a contiguous memory location. Array elements are accessed by their index number using subscripts. Structure elements are accessed by their names using dot operator.
  • 335.
    Declaring a structurevariable- • A structure declaration should have the following elements • For eg 19-06-2023 Computing Fundamentals and C Programming 335
  • 336.
    19-06-2023 Computing Fundamentalsand C Programming 336
  • 337.
    Accessing structure members- •Accessing and assigning values to the members of the structure • It should be linked to the structure variables to make a meaningful members • For eg • The link between a member and a variable is established by using a member operator(.) 19-06-2023 Computing Fundamentals and C Programming 337
  • 338.
    Accessing Structure members– • Structure initialization • Rules for initializing structures Structure Initialization – • Initialization of structure is done during compile time • There is a one to one correspondence Between the members and their initializing values 19-06-2023 Computing Fundamentals and C Programming 338
  • 339.
    19-06-2023 Computing Fundamentalsand C Programming 339
  • 340.
    19-06-2023 Computing Fundamentalsand C Programming 340
  • 341.
    Rules for initializingstructures- 19-06-2023 Computing Fundamentals and C Programming 341
  • 342.
    Copying and comparingthe structure variables- • Logical operations are not permitted in structures 19-06-2023 Computing Fundamentals and C Programming 342
  • 343.
    Operations on IndividualMembers- • Members of a structure variable is accessed by dot operator • Arithmetic and relational operations can be done on members • Three ways to access members of the structure variable :dot operator, pointer ,selection notation 19-06-2023 Computing Fundamentals and C Programming 343
  • 344.
    Array of structures- •Each element of the array representing a structure variable • Array of structures is stored inside the memory in the same way as a multi dimensional array 19-06-2023 Computing Fundamentals and C Programming 344
  • 345.
    Array within thestructures- • c permits to use the arrays as structure members • 1D or 2D or multi dimensional arrays can be used of int or float 19-06-2023 Computing Fundamentals and C Programming 345
  • 346.
    Structures within structures •Nesting of structures 19-06-2023 Computing Fundamentals and C Programming 346
  • 347.
    19-06-2023 Computing Fundamentalsand C Programming 347 The salary structure contains a member named allowance which itself as a structure with 3 members The inner structure contains members dearness, house rent, city Inner most member can be accessed by dot operator from outermost to inner most
  • 348.
    19-06-2023 Computing Fundamentalsand C Programming 348
  • 349.
    Structures and functions 19-06-2023Computing Fundamentals and C Programming 349
  • 350.
    19-06-2023 Computing Fundamentalsand C Programming 350
  • 351.
    19-06-2023 Computing Fundamentalsand C Programming 351
  • 352.
    19-06-2023 Computing Fundamentalsand C Programming 352
  • 353.
    Unions and structures •Unions concept is borrowed from structures and follow the same syntax as structures • Difference between structures and unions vary in terms of storage • Structures-each member has its own storage space location • Union-all the members of a union share the same location. union may have many members of different datatypes it can handle only one member at a time. 19-06-2023 Computing Fundamentals and C Programming 353
  • 354.
    Size of thestructures- • Array,structures and unions used to create variables for large sizes • The size of the variables vary from machine to machine • A unary operator sizeof() can be used to find the size of a structure or variable 19-06-2023 Computing Fundamentals and C Programming 354
  • 355.
    Bit fields- • Bitfield is a set of adjacent bits whose size can be from 1 to 16 bit length • A word can be therefore divided into number of bit fields • The name and size of the bit field are given in the structure 19-06-2023 Computing Fundamentals and C Programming 355
  • 356.
    19-06-2023 Computing Fundamentalsand C Programming 356
  • 357.
    19-06-2023 Computing Fundamentalsand C Programming 357
  • 358.
    19-06-2023 Computing Fundamentalsand C Programming 358
  • 359.
    Unit-5 Pointers & FileManagement 19-06-2023 Computing Fundamentals and C Programming 359
  • 360.
    Introduction- • A pointeris a derived data type in c • Pointers contains memory addresses as their values • These memory addresses are the locations in the computer memory where program instructions and data are stored • Pointers can be used to access and manipulate data stored in the memory • The number of benefits for programmers using pointers are • Pointers are efficient in handling arrays and data tables • Pointers can return multiple values from a function via function arguments • Pointers permit references to functions and thereby facilitating passing of functions as arguments to other functions • The use of pointer arrays to character strings results in saving data storage space in memory • Pointers allow C to support dynamic memory management • Pointers reduce the length and complexity of the programs • increase the execution speed and reduce the program execution time 19-06-2023 Computing Fundamentals and C Programming 360
  • 361.
    Understanding pointers- • Thecomputers memory is the sequence collection of storage cells • Each cell knowns as byte has a number called address associated with it • The addressed are numbered consecutively starting from zero ,the last address depends upon the memory size • when a variable is declared the system allocates Space in the memory ,an appropriate location to hold the value of the variable 19-06-2023 Computing Fundamentals and C Programming 361
  • 362.
    • For egint quality =175; • Value 175 can be accessed by either using the variable name quantity or the address 5000 • When a variable are assigned to the address of the another variable it is called pointer variable • A pointer variable is nothing but a variable that contains the address which is the location of another variable in memory 19-06-2023 Computing Fundamentals and C Programming 362
  • 363.
    Underlying concepts ofpointers – • Pointers are built on the three underlying concepts • Memory addresses within a computer are referred as pointer constants • The value of the variable stored there using the address operator(&) called the pointer value .pointer value may change from one run of the program • The variable contains the pointer value is called pointer variable 19-06-2023 Computing Fundamentals and C Programming 363
  • 364.
    Accessing the addressof the variable- • Address of the variable can be determined by address operator & • Address operator is used in scanf • The operator & preceding a variable returns the address of the variable associated with it • For eg • If x is an array then expression is 19-06-2023 Computing Fundamentals and C Programming 364
  • 365.
    Declaring a pointervariable – • Pointer variable should be declared as pointer variables • The syntax is • Type int refers to the data type of the variable being pointed to by p and not the type of the value of the pointer 19-06-2023 Computing Fundamentals and C Programming 365
  • 366.
    Pointer declaration style- •Pointer variables are declared similarly as normal variable except for the addition unary * operator 19-06-2023 Computing Fundamentals and C Programming 366
  • 367.
    Initialization of PointerVariable- • The process of assigning the address of a variable to a pointer variable is called initialization. • Uninitialized pointers produce some errors • It is important to initialize a pointer variable before using it • Once a pointer variable has been declared ,assignment operator is used initialize the variable • Eg 19-06-2023 Computing Fundamentals and C Programming 367
  • 368.
    • Pointer variablesalways point to the corresponding data type • For eg • Combining declaration of a data variable,pointer variable and initialization of a pointer variable in one step • Pointer variables can be set to NULL or 0 19-06-2023 Computing Fundamentals and C Programming 368
  • 369.
    Pointer Flexibility- • Pointersare flexible • Same pointer variable can point to different data variables in different statements • Using different pointers to point the same data value 19-06-2023 Computing Fundamentals and C Programming 369
  • 370.
    Accessing a variablethrough its pointer- • The value of the variable can be accessed by using pointers with the help of unary operator(*) also called as indirection operator or dereferencing operator • When the operator placed before the pointer variable in an expression (on the right hand side of the equal sign) the pointer returns the value of the variable of which the pointer value is the address • value at address • Returns the value of the pointer variable 19-06-2023 Computing Fundamentals and C Programming 370
  • 371.
    19-06-2023 Computing Fundamentalsand C Programming 371
  • 372.
    19-06-2023 Computing Fundamentalsand C Programming 372
  • 373.
    Chain of pointers- •Making pointer to point another pointer creating a chain of pointers • Pointer variable P2 contains the address of the another pointer variable P1 Which points to the location that contains the desired value • It is called multiple indirections • A variable that is a pointer to a pointer must be declared using additional indirection operator symbols in front of the name. 19-06-2023 Computing Fundamentals and C Programming 373
  • 374.
    Pointer expressions- • Pointervariables can be used in expressions • Pointers must be declared and initialized properly 19-06-2023 Computing Fundamentals and C Programming 374
  • 375.
    Pointer increments andScale Factor- • Pointers can be incremented by 19-06-2023 Computing Fundamentals and C Programming 375
  • 376.
    Pointers and arrays- •When • When p is declared as integer pointer 19-06-2023 Computing Fundamentals and C Programming 376
  • 377.
    19-06-2023 Computing Fundamentalsand C Programming 377
  • 378.
    Pointers and CharacterStrings- 19-06-2023 Computing Fundamentals and C Programming 378
  • 379.
    19-06-2023 Computing Fundamentalsand C Programming 379
  • 380.
    Array of pointers- •With the help of pointers we can handle table of strings 19-06-2023 Computing Fundamentals and C Programming 380
  • 381.
    19-06-2023 Computing Fundamentalsand C Programming 381
  • 382.
    Pointers and Functionarguments- • When addresses are passed to a function,the parameters receiving the addresses should be pointers . • The process of calling a function using pointers to pass the addresses of variables is known as call by reference • The function which is called by “reference” can change the value of the variable used in the call 19-06-2023 Computing Fundamentals and C Programming 382
  • 383.
    19-06-2023 Computing Fundamentalsand C Programming 383
  • 384.
    #include <stdio.h> void swap(int*a, int *b); int main() { int m = 10, n = 20; printf("m = %dn", m); printf("n = %dnn", n); swap(&m, &n); //passing address of m and n to the swap function printf("After Swapping:nn"); printf("m = %dn", m); printf("n = %d", n); return 0; } /* pointer 'a' and 'b' holds and points to the address of 'm' and 'n'*/ void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } 19-06-2023 Computing Fundamentals and C Programming 384
  • 385.
    Functions returning pointers– • Since pointers are data type in C ,we can force a function to return a pointer to the calling function 19-06-2023 Computing Fundamentals and C Programming 385
  • 386.
    19-06-2023 Computing Fundamentalsand C Programming 386
  • 387.
    Pointers to functions- •It is possible to declare a pointer pointing to a function which can then be used as an argument in another function. A pointer to a function is declared as follows, • int (*sum)(); • A function pointer can point to a specific function when it is assigned the name of that function. int sum(int, int); int (*s)(int, int); s = sum; • Here s is a pointer to a function sum. Now sum can be called using function pointer s along with providing the required argument values s (10, 20); 19-06-2023 Computing Fundamentals and C Programming 387
  • 388.
    #include <stdio.h> int sum(intx, int y) { return x+y; } int main( ) { int (*fp)(int, int); fp = sum; int s = fp(10, 15); printf("Sum is %d", s); return 0; } 19-06-2023 Computing Fundamentals and C Programming 388
  • 389.
    Compatibility and casting- •Assigning of a pointer variable of one type to a pointer of another type is not permissible • It is called incompatibility of pointers • Cannot use the assignment operator with the pointers of different types. • Assigning in compatible pointers with the help of cast operator explicitly • void pointer is a generic pointer that can represent any pointer type. All pointer types can be assigned to a void pointer and a void pointer can be assigned to any pointer without casting 19-06-2023 Computing Fundamentals and C Programming 389
  • 390.
    Pointers and Structures- •To use array of structure variables efficiently is used pointers of structure type 19-06-2023 Computing Fundamentals and C Programming 390
  • 391.
    19-06-2023 Computing Fundamentalsand C Programming 391
  • 392.
    File management inC- 19-06-2023 Computing Fundamentals and C Programming 392
  • 393.
    Introduction- • Scanf andprintf used to read and write data • These are console oriented I/O operations use the terminal (keyboard and screen) • It works for small data • When the data is very large the major problems faced are it becomes cumbersome and time consuming to handle data thru terminals and entire data is lost when the computer is turned off /program is terminated • In need of flexible approach where data can be stored on disks and read whenever necessary without destroying the data • This method employs the concept of FILES to store data • A file is a place on the disk where a group of related data is stored • C supports a number of functions that have the ability to perform basic file operations which include 19-06-2023 Computing Fundamentals and C Programming 393
  • 394.
    Naming a file Openinga file Reading data from a file Writing data to a file Closing a file • There are two distinct ways to perform file operations in c • Low level I/o which uses unix sytem calls • High level I/O uses functions in C standard library 19-06-2023 Computing Fundamentals and C Programming 394
  • 395.
    • C filehandling functions are 19-06-2023 Computing Fundamentals and C Programming 395
  • 396.
    Defining and Openinga file- • To store a file in the secondary memory certain things about the file has to be specified .they are File name-string of characters gives a valid file name for OS.it contains primary name and optional period with the extension Data structure-defined as FILE in the library of standard I/O function. all files should be declared before using it .FILE is a defined data type Purpose – write data to /read data from the file • the general syntax of declaring and opening a file 19-06-2023 Computing Fundamentals and C Programming 396
  • 397.
    19-06-2023 Computing Fundamentalsand C Programming 397
  • 398.
    Additional modes ofoperations: • r+ -Opens a text file for both reading and writing. • w+ -Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. • a+ -Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. 19-06-2023 Computing Fundamentals and C Programming 398
  • 399.
    Closing a File- •A file must be closed as soon as all operations is completed • This prevents from misuse of the file • Only limited files can be open simultaneously at a time • Closing unwanted files might help open required files • Close a file and reopen he same file with different mode 19-06-2023 Computing Fundamentals and C Programming 399
  • 400.
    • Once afile is closed ,its file pointer can be reused for another file • All files are closed automatically when program terminates • Closing a file as soon as the task is completed is considered as a good habit Input/output operations on files- • When a file is opened reading or writing is accomplished by standard I/O routines that are listed getc and putc functions: Simplest file I/O functions are getc and putc Same like getchar and putchar functions handle one character at a time 19-06-2023 Computing Fundamentals and C Programming 400
  • 401.
    The file pointermoves by one character position for every operation of getc and putc getc will return EOF(end-of-file) marker when end of the file is reached Reading should be terminated with EOF 19-06-2023 Computing Fundamentals and C Programming 401
  • 402.
    fprintf and fscanffunctions- • Handle a group of mixed data simultaneously • Identical to printf and scanf functions • When end of the file is reached it returns EOF value 19-06-2023 Computing Fundamentals and C Programming 402
  • 403.
    Error handling duringI/O operations- • If failed to check read and write errors program may behave abnormally when an error occurs • An unchecked error result in preature termination or incorrect output 19-06-2023 Computing Fundamentals and C Programming 403
  • 404.
    • They havetwo status inquiry I/O library functions to detect I/O errors in files feof-used to test for an end of the file function Ferror-returns the status of the file indicated • if the file cannot be open for some reason then the function returns a NULL pointer .it can be used to test whether the file has been opened or not 19-06-2023 Computing Fundamentals and C Programming 404
  • 405.
    Random access tofiles- • Reading or writing only specific part of the file • Can be done with the help of these I/O functions fseek(),ftell(),and rewind • Fseek –used to move the file position to a desired location within a file 19-06-2023 Computing Fundamentals and C Programming 405
  • 406.
    19-06-2023 Computing Fundamentalsand C Programming 406
  • 407.
    #include <stdio.h> #include <stdlib.h> intmain() { int num; FILE *fptr; fptr = fopen("C:program.txt","w"); if(fptr == NULL) { printf("Error!"); exit(1); } printf("Enter num: "); scanf("%d",&num); fprintf(fptr,"%d",num); fclose(fptr); return 0; } 19-06-2023 Computing Fundamentals and C Programming 407
  • 408.
    Command line arguments- •It is a parameter supplied to a program when the program is invoked • It may be a filename the program should process • So far main() is used without arguments • Main() can take two arguments argc and argv and information contained in the command line is passed on to the program through these arguments when main() is called up by the system • argc – counts the no of arguments on the command line • argv- argument vector that represents array of character pointers that point to the command line arguments .Size of the array =argc 19-06-2023 Computing Fundamentals and C Programming 408
  • 409.
    19-06-2023 Computing Fundamentalsand C Programming 409