BSC Ist Year Programming in C
BSC Ist Year Programming in C
Bachelor Of Science
PROGRAMMING IN C
I-Year I-Sem Syllbus
4:credits Internal-20M+External-80M
_________________________________________________________________________
Unit –I
Computer Fundamentals: Introduction of Computers, Classification of Computers,
Anatomy of a Computer, Memory Hierarchy, Introduction to OS, Operational
Overview of a CPU.Program Fundamentals: Generation and Classification of
Programming Languages, Compiling, Interpreting, Loading, Linking of a Program,
Developing Program, SoftwareDevelopment.
Algorithms: Definitions, Different Ways of Stating Algorithms(Step-form, Pseudo-
code, Flowchart), Strategy for Designing Algorithms, Structured Programming
Concept.
Basics of C: Overview of C, Developing Programs in C, Parts of Simple C Program,
Structure of a C Program, Comments, Program Statements, C Tokens, Keywords,
Identifiers, Data Types, Variables, Constants, Operators and Expressions, Expression
Evaluation–precedence and associativity, Type Conversions.
Unit –II
Input-Output: Non-formatted and Formatted Input and Output Functions, Escape
Sequences,Control Statements: Selection Statements –if, if-else, nested if, nested if-
else, comma operator, conditional operator, switch; Iterative Statements–while, for,
do-while; Special Control Statement–goto, break, continue, return, exit.
Arrays and Strings:One-dimensional Arrays, Character Arrays, Functions from
ctype.h, string.h, Multidimensional Arrays.
Unit –III
Functions: Concept of Function, Using Functions, Call-by-Value VsCall-by-reference,
Passing Arrays to Functions, Score of Variables, Storage Classes, Inline Functions,
and Recursion.
Pointers: Introduction, Address of Operator (&),Pointer, Uses of Pointers, Arrays and
Pointers, Pointers and Strings, Pointers to Pointers, Array of Pointers, Pointer to
Array, Dynamic Memory Allocation.
Unit –IV
User-defined Data Types: Declaring a Structure (Union) and its members,
Initialization Structure (Union), Accessing members of a Structure (Union), Array of
Structures (Union),Structures versesUnions, Enumeration Types.
Files: Introduction, Using Files in C, Working with Text Files, Working with Binary
Files, Files of Records, Random Access to Files of Records, Other File Management
Functions
Hardware
Hardware is the physical components of a computer that includes all mechanical,
electrical, electronic and magnetic parts attached to it. Ex: CPU, Monitor, Keyboard,
Mouse, Printer, Speakers… etc.
*Business
A computer has high speed of calculation, diligence,
accuracy, reliability, or versatility which has made it
an integrated part in all business organizations.
Computer is used in business organizations for −
• Payroll calculations
• Budgeting
• Sales analysis
• Financial forecasting
• Managing employee database
• Maintenance of stocks, etc.
*Banking
Today, banking is almost totally dependent on computers.
Banks provide the following facilities −
• Online accounting facility, which includes checking current balance, making
deposits and overdrafts, checking interest charges, shares, and trustee records.
• ATM machines which are completely automated are making it even easier for
customers to deal with banks.
*Insurance
Insurance companies are keeping all records up-to-date with the help of computers.
Insurance companies,
VARIOUS DIGITALCOMPUTERASPERTHEPURPOSE
General Purpose digital computers: These computers aretheoretically used for any type
of applications. These computers canbe used in solving a business Problem and also
used to solve mathematical equation with same accuracy and consistency.Most of the
computers now are general purpose digital computers.
Special Purpose Computers: These digital computers are designed,made and used for
any specific job. These are usually used for those purposes which are critical and need
great accuracy and response like Satellitelaunching weather forecasting etc.
2. Minicomputers
Are medium sized computers on the basis of size
A centrally located server or CPU is connectedwith more than 50 terminals.
Examples: Prime 9755, Vax 36 etc.
Characteristics:
Medium size
SIVA SIVNI DEGREE COLLEGE 13 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
More than 50 terminals and large capacitystorage devices than microcomputers.
Used for general purpose.
Used in medium sized organizations and corporation for their database
administration.
3. Mainframe Computer
Are the largest types of computers
Are used in large organizationslike insurance companies, banks where people need
frequent access to the same data, which is usuallyorganized into one or more huge
databases.
Examples: IBM 1401, ICL 2950/10, IBM S/390 etc
Characteristics:
Very large in size.
Central processor, central administration
More than 100 terminals, large capacity storage devices used
Fastest and more expensive system.
Used by large agencies and government for large scale data processing.
4. SuperComputer
Are the most sophisticated and powerful computers. They are large in size
These systems are built to process t h e amount of data and the fastest
supercomputer canperform more than 1 trillion calculations per second.
Some super computers are Cray T90, Super Cray, Cyber 205 and Super SXI.
These can house thousands of processors
These speed and power make supercomputers ideal for handling large and highly
complexproblems that require extreme calculating power.
Used in weather forecasting, nuclear fusion, study of DNA structures.
Can cost tens of millions of dollars and consume enough electricity to power dozen of
homes.
They are often housed in protective rooms with special cooling systems, power
protection andother security features.
Because of their size and cost, super computers are relatively rare, used only
by largecorporations, universities and government agencies that can afford them.
COMPUTER – GENERATIONS
Generation in computer terminology is a change in technology a computer is/was
being used. Initially, the generation term was used to distinguish between varying
hardware technologies. Nowadays, generation includes both hardware and
software, which together make up an entire computer system.
There are five computer generations known till date.
1First Generation: The period of first generation: 1946-1959. Vacuum tube based.
2Second Generation: The period of second generation: 1959-1965. Transistor based.
3Third Generation: The period of third generation: 1965-1971.
Integrated Circuit based.
4Fourth Generation: The period of fourth generation: 1971-1980.
VLSI microprocessor based.
5Fifth Generation:The period of fifth generation: 1980-onwards. ULSI
microprocessor based.
First Generation
The period of first generation was from 1946-1959. The computers of first generation
used vacuum tubes as the basic components for memory and circuitry for CPU
(Central Processing Unit). These tubes, like electric bulbs, produced a lot of heat and
SIVA SIVNI DEGREE COLLEGE 14 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
the installations used to fuse frequently. Therefore, they were very expensive and
only large organizations were able to afford it.
In this generation, mainly 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
Some computers of this generation were −
ENIAC EDVAC UNIVAC IBM-701 IBM-650
Second Generation
The period of second generation was from 1959-1965. In this generation, transistors
were used that were cheaper, consumed less power, more compact in size, more
reliable and faster than the first generation machines made of vacuum tubes. In this
generation, magnetic cores were used as the primary memory and magnetic tape and
magnetic disks as secondary storage devices.
In this generation, 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
Some computers of this generation were −
IBM 1620 IBM 7094 CDC 1604 CDC 3600 UNIVAC 1108
Third Generation
The period of third generation was from 1965-1971. The computers of third
generation used Integrated Circuits (ICs) in place of transistors. A single IC has many
transistors, resistors, and capacitors along with the associated circuitry.
The IC was invented by Jack Kilby. This development made computers smaller in
size, reliable, and efficient. In this generation remote processing, time-sharing,
multiprogramming operating system were used.
High-level languages (FORTRAN-II TO IV, COBOL, PASCAL PL/1, BASIC,
ALGOL-68 etc.) were used during this generation.
The main features of third generation are −
IC used
AI includes −
Robotics
Neural Networks
Game Playing
SIVA SIVNI DEGREE COLLEGE 16 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Development of expert systems to make decisions in real-life situations
Natural language understanding and generation
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
Some computer types of this generation are −
Desktop Laptop NoteBook UltraBook ChromeBook
DRAW A SIMPLE MODEL OF A COMPUTER (BLOCK DIAGRAM OF THE
COMPUTER)
Input Unit :This unit contains devices with the help of which we enter data into the
computer. This unit creates a link between the user and the computer. The input
devices translate the information into a form understandable by the computer.
CPU (Central Processing Unit) : CPU is considered as the brain of the computer. CPU
performs all types of data processing operations. It stores data, intermediate results,
and instructions (program). It controls the operation of all parts of the computer.
CPU itself has the following three components –
ALU (Arithmetic Logic Unit) :
This unit consists of two subsections namely, Arithmetic Section and Logic Section
Arithmetic Section: Function of arithmetic section is to perform arithmetic operations
like addition, subtraction, multiplication, and division. All complex operations are
done by making repetitive use of the above operations.
Logic Section: Function of logic section is to perform logic operations such as
comparing, selecting, matching, and merging of data.
Memory Unit or Storage Unit: This unit can store instructions, data, and intermediate
results. This unit supplies information to other units of the computer when needed.
Memory is also known as internal storage unit or the main memory or the primary
storage or Random Access Memory (RAM).
Its size affects speed, power, and capability.
Primary memory and secondary memory are two types of memories in the computer.
Functions of the memory unit are −
SIVA SIVNI DEGREE COLLEGE 17 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
It stores all the data and the instructions required for processing.
It stores intermediate results of processing.
It stores the final results of processing before these results are released to an output
device.
All inputs and outputs are transmitted through the main memory.
Control Unit:
This unit controls the operations of all parts of the computer but does not carry out
any actual data processing operations.
Functions of this unit are −
It is responsible for controlling the transfer of data and instructions among other units
of a computer.
It manages and coordinates all the units of the computer.
It obtains the instructions from the memory, interprets them, and directs the
operation of the computer.
It communicates with Input / Output devices for transfer of data or results from
storage.
It does not process or store data.
Output Unit :The output unit consists of devices with the help of which we get the
information from the computer. This unit is a link between the computer and the
users. Output devices translate the computer's output into a form understandable by
the users.
INPUT DEVICES
Input unit is a unit that accepts any input device. The input device is used to input
data into thecomputer system.
Function of input unit:
It converts inputted data into binary codes.
It sends data to main memory of computer
Insertion point: A digit I will be displayed in the serial number column and a small
vertical line called a cursor (or insertion point)
Input Unit:
The input unit is used for entering the data and instruction into the computer for
performing computation of the data. The input unit accepts or reads the list of
instructions and data and converts these instructions and data in computer
acceptable form. It supplies the converted instructions and data to the computer for
further processing.
The devices used for this purpose are called as Input Devices. Key Board and Mouse
are the important input devices used in our offices. Light pen, Joy stick, tracker ball,
Touch pad, Scanner and Pointing stick are some of the Input Devices.
Commonly Used Input Devices
*Keyboard devices *Point-and-draw devices *Data scanning devices
*Digitizer *Electronic cards-based devices *Speech recognition devices
*Vision based devices
WRITE A SHORT NOTE ON KEYBOARD
Is the most common way to enter text and data into a computer
Standard layout is basically like old typewriter keyboard (called a QWERTY keyboard)
The most commonly used keyboards are
101 – Key enhanced keyboard, 104 – key windows keyboard.
82 – Key Apple standard keyboard and 108- key Apple extended keyboard.
It contains alphabets (A to Z or a to z), digits (0 to 9), special characters (!@,#,$,
SIVA SIVNI DEGREE COLLEGE 18 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
%,^,&,*,<,>,? etc) and some control keys.
There are five key groups:
Alphanumeric keys
Letters of the alphabets
Numbers and symbols
Caps lock, tab, backspace and enter key do special functions but they arepart of the
alphanumeric key group.
Modifier Key group
Modify what happens when you press another key
Shift changes letter keys to upper case
Shift makes the number keys produce special symbols
Ctrl and alt used in combination with other keys change what that key does
Numeric Key Pad
Looks like a calculator keyboard
Used to enter numbers and operation symbols
Num lock forces keypad to enter numbers which is the normal default.
Function Keys
Middle of top row
Labeled F1 to F12
Could be assigned specific commands by the current application oroperating
system (or software dependent)
Cursor Movement keys
Direct movement of on-screen cursor
Up, down, left and right arrow
Other keys are insert, home, page up, delete, end and page down
Special purpose keys are in addition to the five key group are found on keyboards
specificallydesigned for windows operating system
Start key or windows key
When a key is pressed an electronic signal is produced which is detected by an
electronic circuitcalled keyboard encoder or controller.
The different types of mouse are, (i) Mechanical mouse (ii) Opt mechanical mouse
(iii) Optical mouse.
1. Mechanical Mouse: Mechanical mouse is one of the simple types of mouse
which was used by the computer users earlier. It consists of a small round shape
rubber ball and two fly wheels. The rubber ball is present at the bottom which comes
in contact with a mouse pad.
2. Opt mechanical Mouse: Opt mechanical mouse is an alternative to mechanical
mouse. It uses rollers and LED photodiode instead of wire mesh that is used in
mechanical mouse. It consists of a ball, LED, photodiode and two rollers.
3. Optical Mouse: Basic Computer Skills Optical mouse is quite opposite of
mechanical mouse. It does not have any moving parts as that of mechanical mouse.
It makes use of lasers or LEDs for detecting the movement of mouse.
The optical mouse mainly comprises the components such as inbuilt optical sensor,
high speed camera and Light Emitting Diodes (LED).
The optical mouse contains in-built optical sensors that are used for reading its
movements. The movements are read by means of light rays coming out from LEDs
(Light Emitting Diodes).
Joy sticks: Commonly used for video games, flight simulators, training simulators,
and for controlling industrial robots
Touch Screen:
Most simple, intuitive, and easiest to learn of all input Devices
Enables users to choose from available options by simply touching with their finger
the desired icon or menu item displayed on the screen
Most preferred human-computer interface used in information kiosks (unattended
interactive information systems such as automatic teller machine or ATM)
Data Scanning Devices
Input devices that enable direct data entry into a computer system from source
documents
Eliminate the need to key in text data into the computer
Due to reduced human effort in data entry, they improve data accuracy and also
increase the timeliness of the information processed
Demand high quality of input documents
Some data scanning devices are also capable of recognizing marks or characters
Form design and ink specification usually becomes
more critical for accuracy
1. Image Scanner
Input device that translates paper documents into
an electronic format for storage in a computer
Electronic format of a scanned image is its bit map
representation and Stored image can be altered or
manipulated with an image-processing software
DEFINE SCANNER: Scanner is an input device, which works more like a photocopy
machine. Scanner captures images from the source which are then converted into a
digital form that can be stored on the disk. These images can be edited before they
are printed.
Electronic--card Reader
Electronic cards are small plastic cards having encoded data appropriate for the
application for which they are used
PRINTER
A printer prints the output information from the computer onto a paper. Printers are
generally used to print textual information, but nowadays printers also print
graphical information.
The print quality (sharpness and clarity of print) of the printer is determined by the
resolution of the printer.
Resolution is measured in dots per inch (dpi). Printers with a high resolution (more
dpi) provide better quality output. Different kinds of printers are available for
different types of applications.
Printers are classified into two categories—impact printer and non-impact printer.
Impact printers use the typewriter approach of physically striking a typeface against
the paper and inked ribbon. Impact printers can print a character or an entire line at
a time. Impact printers are low-cost printers useful for bulk printing.
Non-Impact Printers do not hit or impact a ribbon to print. They use electro-static
chemicals and ink-jet technologies. Non-impact printers are faster and quieter than
impact printers.
.
Speech-To-Text (STT)
Speech to text is speech recognition software that enables the recognition and
translation of spoken language into text through computational linguistics. It is also
known as speech recognition or computer speech recognition. Specific applications,
tools, and devices can transcribe audio streams in real-time to display text and act on
it.
Speech to text is software that works by listening to audio and delivering an editable,
verbatim transcript on a given device. The software does this through voice
recognition.
COMPUTER MEMORY HIERARCHY
A memory is just like a human brain. It is used to store data and instructions.
Computer memory is the storage space in the computer, where data is to be processed
and instructions required for processing are stored.
The memory is divided into large number of small parts called cells. Each location or
cell has a unique address, which varies from zero to memory size minus one.
For example, if the computer has 64k words, then this memory unit has 64 * 1024 =
65536 memory locations. The address of these locations varies from 0 to 65535.
MEMORY HIERARCHY
The memory is characterized on the basis of two key factors—capacity and access
time. Capacity is the amount of information (in bits) that a memory can store. Access
time is the time interval between the read/ write request and the availability of data.
The lesser the access time, the faster is the speed of memory.
Ideally, we want the memory with fastest speed and largest capacity. However, the
cost of fast memory is very high. The computer uses a hierarchy of memory that is
organized in a manner to enable the fastest speed and largest capacity of memory.
The hierarchy of the different memory types is shown in
Secondary/ Auxiliary Memory : Auxiliary memory is much larger in size than main
memory but is slower. It normally stores system programs, instruction and data files.
It is also known as secondary memory. It can also be used as an overflow/virtual
memory in case the main memory capacity has been exceeded. Secondary memories
cannot be accessed directly by a processor. First the data/information of auxiliary
memory is transferred to the main memory and then that information can be accessed
by the CPU.
Main Memory : The main memory occupies the central position because it is
equipped to communicate directly with the CPU and with auxiliary memory devices
through Input/output processor (I/O).
Cache Memory : It is small in size but faster than the main memory. The CPU can
access it more quickly than the primary memory. It holds the data and programs
frequently used by the CPU. So if the CPU finds the required data or instructions in
cache memory it doesn't need to access the primary memory (RAM). Thus, it speeds
up the system performance.
Register Memory : Register memory is the smallest and fastest memory in a
computer. It is located in the CPU in the form of registers. A register temporarily holds
frequently used data, instructions and memory address that can be quickly accessed
by the CPU.
Memory Units :
1) The memory’s interface circuit is designed to logically access a byte or a multiple
of a byte of data from the memory during each access.
2) The smallest block of memory is considered to be a byte, which comprises eight
bits. The total memory space is measured in terms of bytes. Thus, the unit of
memory is a byte.
3) The capacity of memory is the maximum amount of information it is capable of
storing.
Memory units are used to measure and represent data. Some of the commonly
used memory units are:
Bit: The computer memory units start from bit. A bit is the smallest memory unit
to measure datastored in main memory and storage devices. A bit can have only
one binary value out of 0 and 1.
Byte: It is the fundamental unit to measure data.
It contains 8 bits or is equal to 8 bits. Thus a bytecan represent 2*8 or 256 values.
Kilobyte: A kilobyte contains 1024 bytes.
SIVA SIVNI DEGREE COLLEGE 32 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Megabyte: A megabyte contains 1024 kilobytes.
Gigabyte: A gigabyte contains 1024 megabyte.
Terabyte: A terabyte contains 1024 gigabytes.
BYTE = 8 BITS = 1 character/ 1 alphabet/ 1 key in keyboard
4bits-1Nibble
8bits=1Byte
1024byes= Kilobyte (KB)
Kilobyte (KB) = 1024 bytes
Megabyte (MB) = 1024 Kilobytes
Gigabyte (GB) = 1024 Megabytes
Terabyte (TB) = 1024 Gigabytes
Petabyte (PB) = 1024 Terabytes
Exabyte (EB) = 1024 Petabytes
Zettabyte (ZB) = 1024 Exabyte
Yottabyte (YB) = 1024 Zettabyte
Memory is logically organized as a linear array of locations.
For a processor, the range of the memory addresses is 0 to the maximum size of
memory. Figure shows the organization of a 16 MB block of memory for a processor
with a 32-bit word length.
Processor Register :
A processor register is a local storage space on a processor that holds data that is
being processed by CPU. Processor registers generally occupy the top-most position
in the memory hierarchy, providing high-speed storage space and fast access to data.
A register may include the address of the memory location instead of the real data
itself.
Every processor has a local storage area known as a register that performs most of the
operations that the processor cannot perform directly. Any kind of data must first be
identified by the register before it can be manipulated by the processor.
For example, if an arithmetic operation is to be performed on two numbers, the inputs
and the results are to be stored in the register. The processor registers are generally
measured in terms of bits to determine the amount of data they can hold. For example,
the two most frequently used terms, 32-bit processor’ and 64-bit processor, generally
refer to the size of the register on the processor.
Processor registers can be classified into general-purpose and special-purpose
registers.
Accumulator (ACC) stores the result of arithmetic and logic operations.
Instruction Register (IR) contains the current instruction most recently fetched.
Program Counter (PC) contains the address of next instruction to be processed.
RAM is volatile, i.e. data stored in it is lost when we switch off the computer or if
there is a power failure. Hence, a backup Uninterruptible Power System (UPS) is
often used with computers. RAM is small, both in terms of its physical size and in
the amount of data it can hold.
RAM is of two types −
Static RAM (SRAM)
Dynamic RAM (DRAM)
Static RAM (SRAM)
The word static indicates that the memory retains its contents as long as
power is being supplied. However, data is lost when the power gets down due to
volatile nature. SRAM chips use a matrix of 6-transistors and no capacitors.
Transistors do not require power to prevent leakage, so SRAM need not be refreshed
on a regular basis.SRAM is thus used as cache memory and has very fast access.
Characteristic of Static RAM
Long life
No need to refresh
Faster
Used as cache memory
Large size
Expensive
High power consumption
SIVA SIVNI DEGREE COLLEGE 36 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Dynamic RAM (DRAM)
DRAM, unlike SRAM, must be continually refreshed in order to maintain the data.
This is done by placing the memory on a refresh circuit that rewrites the data several
hundred times per second. DRAM is used for most system memory as it is cheap and
small. All DRAMs are made up of memory cells, which are composed of one
capacitor and one transistor.
Characteristics of Dynamic RAM
Short data lifetime
Needs to be refreshed continuously
Slower as compared to SRAM
Smaller in size
Less expensive and Less power consumption
SDRAM (synchronous DRAM) is a generic name for
various kinds of dynamic random access memory (DRAM) that are synchronized
with the clock speed that the microprocessor is optimized for. This tends to increase
the number of instructions that the processor can perform in a given time.
B) ROM (Read Only Memory) : The memory from which we can only read but cannot
write on it. This type of memory is non-volatile. The information is stored
permanently in such memories during manufacture. A ROM stores such instructions
that are required to start a computer. This operation is referred to as bootstrap. ROM
chips are not only used in the computer but also in other electronic items like washing
machine and microwave oven.
The various types of ROMs and their characteristics:
MROM (Masked ROM) :
The very first ROMs were hard-wired devices that contained a pre-programmed set
of data or instructions. These kind of ROMs are
known as masked ROMs, which are inexpensive.
PROM (Programmable Read Only Memory) :
PROM is read-only memory that can be modified
only once by a user. The user buys a blank PROM and
enters the desired contents using a PROM program.
Inside the PROM chip, there are small fuses which are
burnt open during programming. It can be
programmed only once and is not erasable.
EPROM (Erasable and Programmable Read Only
Memory) :
EPROM can be erased by exposing it to ultra-violet light for a duration of up to 40
minutes. Usually, an EPROM eraser achieves this function. During programming, an
electrical charge is trapped in an insulated gate region. The charge is retained for
more than 10 years because the charge has no leakage path. For erasing this charge,
ultra-violet light is passed through a quartz crystal window (lid). This exposure to
ultra-violet light dissipates the charge. During normal use, the quartz lid is sealed
with a sticker.
EEPROM (Electrically Erasable and Programmable Read Only Memory) :
EEPROM is programmed and erased electrically. It can be erased and reprogrammed
about ten thousand times.
Both erasing and programming take about 4 to 10 ms (millisecond). In EEPROM, any
location can be selectively erased and programmed. EEPROMs can be erased one
byte at a time, rather than erasing the entire chip. Hence, the process of
reprogramming is flexible but slow.
Secondary Memory :
This type of memory is also known as external memory or non-volatile. It is slower
than the main memory. These are used for storing data/information permanently.
CPU directly does not access these memories, instead they are accessed via input-
output routines. The contents of secondary memories are first transferred to the main
memory, and then the CPU can access it. For example, disk, CD-ROM, DVD, etc.
Characteristics of Secondary Memory
These are magnetic and optical memories.
It is known as the backup memory.
It is a non-volatile memory.
Data is permanently stored even if power is switched off.
There exists different types of secondary storage devices, each of them suitable
for a different purpose. They mainly differ in the following aspects:
Technology used to store data
Capacity of data they can hold
Size of storage device
Portability of storage device and
Access time to stored data.
Currently the most common forms of secondary storage device are:
Floppy disks
Hard disks
Magnetic Disks
Commonly used direct-access secondary storage device.
Physically, a magnetic disk is a thin, circular plate/platter made of metal or plastic
that is usually coated on both sides with a magnetizable recording material such as
iron-oxide
Data are recorded on the disk in the form of tiny invisible magnetized and non-
magnetized spots
(representing 1s and 0s) on the coated surfaces of the disk
The disk is stored in a specially designed protective envelope or cartridge, or several
of them are stacked together in a sealed, contamination-free container.
A disk’s surface is divided into a number of invisible concentric circles called tracks
The tracks are numbered consecutively from outermost to innermost starting from
zero to 200
The number of tracks on a disk may be as few as 40 on small, low-capacity disks, to
several thousand on large, high-capacity disks.
Each track of a disk is subdivided into sectors
There are 8 or more sectors per track
A sector typically contains 512 bytes
Floppy Disks:
Floppy disks are a storage medium made of a thin magnetic disk. Floppy disks often
referred to as diskettes have been and are still being widely used to store data of
small size. They were widely used from the 1970s to the early 2000s. On the 3 1⁄2-
inch microfloppy, common from the late 1980s onward, storage capabilities ranged
SIVA SIVNI DEGREE COLLEGE 40 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
from the standard 1.44 MB to 200 MB on some versions.
They are very easy to use and are portable. They consist of a flat Mylar plastic disk
that rotates within ahard plastic casing.
Data is stored as electromagnetic charges on a metal oxide film coating the Mylar
plastic.
Floppy disks also contain a write protect
notch that can prevent writing to the
disks.
There exist several types of floppy
disks but the most common one is the 3.5
inch floppy that can store data up to a
capacity of 1.44 megabytes, something like
400 typewritten pages.
A floppy drive is required to access a
floppy disk.
When the floppy is inserted in the
floppy drive, the sliding metal shutter is
opened exposing the Mylar plastic and a
read-write head moves across the exposed
disk to either store or retrieve data. Data is
recorded on the disk in closed concentric
circles known as tracks.
Hard Disks:
Hard disk drive is made up of a series of circular disks called platters arranged one
over the other almost ½ inches apart around a spindle. Disks are made of non-
magnetic material like aluminum alloy and coated with 10-20 nm of magnetic
material.
Standard diameter of these disks is 14 inches and they rotate with speeds varying
from 4200 rpm for personal computers to 15000 rpm for servers.
Data is stored by magnetizing or demagnetizing the magnetic coating. A magnetic
reader arm is used to read data from and write data to the disks. A typical modern
HDD has capacity in terabytes (TB).
Hard disks differ from floppy disk in that they have been designed to store very high
volume of data.
Currently hard disks can store gigabytes of data (e.g. 200GB) and they are an integral
part of the computer.
Most operating systems are stored in hard disks andall materials that you save on
your computer is stored in the hard disk.
OPERATING SYSTEM
An operating system (OS) is a software, that manages the computer hardware, and
provides common services for execution of various application software. For
hardware functions such as input and output and memory allocation, the operating
system acts as an intermediary between application programs and the computer
hardware.
An operating system is a collection of programs that acts as an interface between the
user of a computer and the computer hardware. In fact, it provides an environment
in which a user may execute programs.
An operating system is an important part of almost every computer system that
comprises three main components:
The hardware (memory, CPU, arithmetic-logic unit, various storage devices,
I/O, peripheral devices, etc.)
Systems programs (operating system, compilers, editors, loaders, utilities, etc.)
A pplication programs (database systems, business programs, etc.)
Loader
Loading is the process of bringing a program from secondary memory into main
memory so it can run. The system software responsible for it is known as loader.
The simplest type of loader is absolute loader which places the program into memory
at the location prescribed by the assembler. Bootstrap loader is an absolute loader
which is executed when computer is switched on or restarted to load the operating
system.
Linker
Most of the high-level languages provide libraries of subroutines or functions so that
certain common operations may be reused by system-supplied routines without
explicit coding. Hence, the machine language program produced by
the translator must normally be combined with other machine language programs
residing within the library to form a useful execution unit. This process of program
combination is called linking and the software that performs this operation is
variously known as a linker.
Compilation It is the second step of the compiling process.It takes the output of the
preprocessor and the source code, and generates assembler source code. The
compiler examines each program statement contained in the source program and
checks it to ensure that it conforms to the syntax and semantics of the language. If
mistakes are discovered by the compiler during this phase, they are reported to the
user. The errors then have to be corrected in the source program (with the use of an
editor), and the program has to be recompiled.
Interpreting(Assembly) It is the third stage of compilation. It takes the assembly
source code and produces an assembly listing with offsets. The assembler output is
stored in an object file. After the program has been translated into an equivalent
assembly language program, the next step in the compilation process is to translate
the assembly language statements into actual machine instructions. On most systems,
the assembler is executed automatically as part of the compilation process.
The assembler takes each assembly language statement and converts it into a binary
format known as object code, which is then written into another file on the system.
This file typically has the same name as the source file under UNIX, with the last
letter an ‘o’ (for object) instead of a ‘c’. Under Windows, the suffix letters “obj”
typically replace the “c” in the filename.
Loading a program involves reading the contents of the executable file containing
the program instructions into memory, and then carrying out other required
preparatory tasks to prepare the executable for running.
Linking It is the final stage of compilation. After the program has been translated
into object code, it is ready to be linked. The purpose of the linking phase is to get the
program into a final form for execution on the computer. The functions are the part
of the standard C library, provided by every C compiler. The program may use other
source programs that were previously processed by the compiler. These functions are
stored as separate object files which must be linked to the object file. Linker handles
this linking.
The process of compiling and linking a program is often called building. The final
linked file, which is in an executable object code format, is stored in another file on
the system ready to be run or executed. Under UNIX, this file is called a.out by
default. Under Windows, the executable file usually has the same name as the source
file, with the .c extension replaced by an exe extension.
SIVA SIVNI DEGREE COLLEGE 58 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Executing the Program: When the program is executed, each of the statements of the
program is sequentially executed. If the program requests any data from the user,
known as input, the program temporarily suspends its execution so that the input
can be entered. Or,
the program might simply wait for an event, such as a mouse being clicked, to occur.
Results that are displayed by the program, known as output, appear in a window,
sometimes called the console. Or, the output might be directly written to
a file on the system.
Write About Developing A Program
When we want to develop a program by using any programming language, we have
to follow a sequence of steps. These steps are called phases in program development.
The program development life cycle is a set of steps or phases which are used to
develop a program in any programming language.
Phases Of Program Development
Program development life cycle contains 6 phases, which are as follows –
Problem Definition.
Problem Analysis.
Algorithm Development.
Coding & Documentation.
Testing & Debugging.
Maintenance.
Problem Analysis
Here, we determine the requirements like variables, functions, etc. to solve the
problem. It means that we gather the required resources to solve the problem, which
are defined in the problem definition phase. Here, we also determine the bounds of
the solution.
Algorithm Development
Here, we develop a step-by-step procedure that is used to solve the problem by using
the specification given in the previous phase. It is very important phase for the
program development. We write the solution in step-by-step statements.
Coding & Documentation
Here, we use a programming language to write or implement the actual
programming instructions for the steps defined in the previous phase. We construct
the actual program in this phase. We write the program to solve the given problem
by using the programming languages like C, C++, Java, etc.
PSEUDO-CODE
The pseudo-code is a written form representation of the algorithm. However, it
differs from the step form as it uses a restricted vocabulary to define its action of
solving the problem. One problem with human language is that it can seem to be
imprecise. But the pseudo-code, which is in human language, tends toward more
precision by using a limited vocabulary.
It is one of the methods which can be used to represent an algorithm for a program.
It does not have a specific syntax like any of the programming languages and thus
cannot be executed on a computer.
Advantages of pseudocode:
Pseudocode is easily written, read and understood
Its implementation is very useful in structured design elements.
It takes less time then drawing equivalent flowchart
Converting it to programming code is much easier as compared to flowchart
Can be easily modified when program’s logic needs modification
Disadvantages of Pseudocode:
It is not visual
Not suitable for design
There is no standard format or style for writing, so one pseudocode may be
different from another.
It is difficult to follow the logic and write pseudocode for a beginner and often
gets confused with an algorithm.
WHY IS C POPULAR
It is reliable, simple and easy to use.
C is a small, block-structured programming language.
C is a portable language, which means that C programs written on one system can
be run on other systems with little or no modification.
C has one of the largest assortments of operators, such as those used for
calculations and data comparisons.
Although the programmer has more freedom with data storage, the languages do
not check data type accuracy for the programmer.
WHY TO STUDY C
By the early 1980s, C was already a dominant language in the minicomputer
world of Unix systems. Since then, it has spread to personal computers
(microcomputers) and to mainframes.
Many software houses use C as the preferred language for producing word
processing programs, spreadsheets, compilers, and other products.
C is an extremely flexible language—particularly if it is to be used to write
operating systems.
C is a Structures programming language which consists of a set of functions and
operators that can be used to write any complex programs. C is a highly portable
language and is so popular especially among software developers, whose
application have to run on any different platforms.
C is a platform dependent language.
Executable statements;
}
Sub Function definition (arguments)
{
Local variable declaration;
Executable Statements;
}
ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with
programming, we should be acquainted with the basic elements that build the
language.
Character Set : Communicating with a computer involves speaking the language the
computer understands. In C, various characters have been given to communicate.
C language is rich in built-in operators and provides the following types of operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Increment and decrement operators
• Conditional operators
• Misc Operators
Unary operators
The unary ‘–’ operator negates the value of its operand (clearly, a signed number).
Unary increment and decrement operators The unary ‘++’ and ‘--’ operators,
respectively, increment or decrementthe value of a variable by 1.
There are ‘pre’ and ‘post’ variants for both operators that do slightly different things
asexplained below.
var++ increment ‘post’ variant var-- decrement ‘post’variant
++var increment ‘pre’ variant --var decrement ‘pre’variant
Basic rules for using ++ and – – operators
The operand must be a variable but not a constant or an expression.
The operator ++ and -- may precede or succeed the operand.
Binary operators
Arithmetic operator:
These are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus.
Relational Operators:
These operators are used to compare the value of two variables. Following table
shows all the relational operators supported by C language. Assume variable A
holds 10 and variable B holds 20, then:
Logical Operators:
These operators are used to perform logical operations on the given two variables.
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then:
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Bitwise operators
are used in bit level programming. These operators can operate upon int and char
but not on float and double.
Showbits( ) function can be used to display the binary representation of any integer
or character value.
SIVA SIVNI DEGREE COLLEGE 90 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Bit wise operators in C language are; &(bitwise AND), | (bitwise OR), ~ (bitwise
OR), ^ (XOR), << (left shift) and >> (right shift).
Ternery operators:
Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e, executes
different statements according to test condition whether it is either true or false.
Syntax of conditional operators;
conditional_expression?expression1:expression2
If the test condition is true (that is, if its value is non-zero), expression1 is returned
and if false expression2 is returned.
Let us understand this with the help of a few examples:
int x, y ;
scanf ( “%d”, &x ) ;
y = ( x> 5 ? 3 : 4 ) ;
This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.
Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.
There are following assignment operators supported by C language:
Misc Operators:
There are few other operators supported by c language.
Misc operators
Comma Operator
The comma operator allows the evaluation of multiple expressions, separated by the
comma, from left to right in order and the evaluated value of the rightmost xpression
is accepted as the final result. The general form of an expression
using a comma operator is
expressionM = (expression1, expression2, …,expressionN);
where the expressions are evaluated strictly from left to right and their values
discarded, except for the last one, whose type and value determine the result of the
overall expression
sizeof Operator
C provides a useful operator, sizeof, for calculating the size of any data item or type.
It takes a single operand that may be a type name (e.g., int) or an expression (e.g.,
100) and returns the size of the specified entity in bytes. The outcome is totally
machine-dependent. The following program illustrates the use of sizeof on the built-
in types we have encountered so far.
int main()
{
printf(“char size = %d bytes\n”, sizeof(char));
printf(“short size = %d bytes\n”, sizeof(short));
printf(“int size = %d bytes\n”, sizeof(int));
printf(“long size = %d bytes\n”, sizeof(long));
printf(“float size = %d bytes\n”, sizeof(float));
printf(“double size = %d bytes\n”, sizeof(double));
printf(“1.55 size = %d bytes\n”, sizeof(1.55));
printf(“1.55L size = %d bytes\n”, sizeof(1.55L));
printf(“HELLO size = %d bytes\n”, sizeof(“HELLO”));
return 0;
}
Define Expression And Types Of It
An expression is nothing but a valid combination of constants, variables and
operators.
An expression consists of a combination of operators, operands, variables & function
calls.
An expression can be arithmetic, logical or relational.
This consists of a single entity like a constant, a variable, an array or a function name. it
also consists of some combinations of such entities interconnected by operators.
Example: a, a+b, x=y, c=a+b, x<=y etc……..
There are four types of expressions exist in C:
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of
operators. Evaluation of a particular expression produces a specific value.
For example:
x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal
is an expression.
SIVA SIVNI DEGREE COLLEGE 93 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic
operators. An arithmetic expression computes a value of type int, float or double.
An example.
6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)
Relational Expressions
A relational expression is an expression used to compare two operands.
It is a condition which is used to decide whether the action should be taken or
not.
In relational expressions, a numeric value cannot be compared with the string
value.
The result of the relational expression can be either zero or non-zero value.
Here, the zero value is equivalent to a false and non-zero value is equivalent to
true.
Ex: a>=9 It is used to check whether the value of a is greater than or
equal to 9.
Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero
value.
o It is a complex test condition to take a decision.
Ex: ( x > 4 ) && ( x < 6 ) It is a test condition to check whether the x is greater
than 4 and x is less than 6. The result of the condition is true only when both the
conditions are true.
Conditional Expressions
A conditional expression is an expression that returns 1 if the condition is true
otherwise 0.
A conditional operator is also known as a ternary operator.
The Syntax of Conditional operator
Suppose exp1, exp2 and exp3 are three expressions.
exp1 ? exp2 : exp3
status = (age>18) ? “eligible”: “not eligabl”;
Here are the steps that you need to follow to compile and execute your first C
program…
1. Start the compiler at C>prompt. The compiler (TC.EXE is usually present in
C:\TC\BIN directory).
2. Select New from the File menu.
3. Type the program.
4. Save the program using F2 under a proper name (say Program1.c).
5. Use alt+f9 to compile and Ctrl + F9 (run) execute the program.
6. Use Alt + F5 to view the output.
We can also limit the number of digits or characters that can be input or output, by
adding a number with the format string specifier, like "%1d" or "%3s", the first one
means a single numeric digit and the second one means 3 characters, hence if you
try to input 42, while scanf() has "%1d", it will take only 4 as input. Same is the case
for output.
Syntax: #define
Macro This macro defines constant value and can be any of the basic data
types.
Syntax: #include <file_name>
Header file
The source code of the file “file_name” is included in the main
inclusion
program at the specified place.
Syntax: #ifdef, #endif, #if, #else, #ifndef
Conditional
Set of commands are included or excluded in source program before
compilation
compilation with respect to the condition.
Syntax: #undef, #pragma
Other directives #undef is used to undefine a defined macro variable. #Pragma is used
to call a function before and after main function in a C program.
A program in C language involves into different processes.
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
}
Control statements embody the decision logic that tells the executing program what
action to carry out next depending on the values of certain variables or expression
statements.
The control statements include selection, iteration, and jump statements that work
together to direct program flow.
A selection statement is a control statement that allows choosing between two or
more execution paths in a program. The selection statements in C are the if statement,
the if-else statement, and the switch statement. These statements allow
us to decide which statement to execute next. Each decision is based on a Boolean
expression (also called a condition or test expression), which is an expression that
evaluates to either true or false. The result of the expression determines which
statement is executed next.
For one-way selection. if..... without else part is used. The if...else... construct is used
to implement two-way selection.
Nested-if and if...elseif... ladder is used to implement nested selection construct.
For implementing multi-way selection switch case is used.
One-way decision statements do a particular thing or they do not.
Twoway decision statements do one thing or do another.
Multiway decision statements can do one of many different things
depending on the value of an expression.
if Statement
if statement is the simplest decision control statement that is frequently used in
decision making.
The general form of a simple if statement is shown in Fig.
EX: #include<stdio.h>#include<conio.h>
intmain()
{
int x=10;if (x>0)
{
printf("\nx=%d",x);
}
getch():
return0;
}
Note:In case the statement block contains only one statement, putting curly
bracketsbecomes optional. If there are more than one statement in the statement
block, putting curly brackets becomes mandatory.
if–else Statement
This is also one of the most useful conditional statements used in C to check
conditions.
Two-way decisions are handled with if-else statements that either do one particular
thing or do another. Similar to one-way decisions, the decision here is based on a
test expression. The form of a two-way decision is as follows:
if(TestExpr)
stmtT;
else
stmtF;
In the if–else construct, first the test expression is evaluated. If the expression is
true, statement block 1 is executed and statement block 2 is skipped. Otherwise, if
the expression is false, statement block 2 is executed and statement block 1 is
ignored.
In any case after the statement block 1 or 2 gets executed, the control will pass to
statement x. Therefore, statement x is executed in every case.
Note that there is no break statement after case A, so if the character A is entered then
control will execute the statements given in case a.
The following code shows how to print the first n numbers using a for loop.
#include <stdio.h>
#include<conio.h>
int main()
{
int i, n; clrscr();
printf("\n Enter the value of n :");scanf("%d", &n); for(i=1;i<=n;i++)
printf("\n %d", i);getch();
return 0;
}
while loop
o The while loop provides a mechanism to repeat one or more statements while a
particular condition is true.
o This is an entry controlled looping statement. It is used to repeat a block of
statements until condition becomes true.
In above syntax, Note that in the while loop, the condition is tested before any of the
statements in the statement block is executed. If the condition is true, only then the
statements will be executed, otherwise if the condition is false, the control will jump
to statement y, that is the immediate statement outside the while loop block.
#include<stdio.h>
#include<conio.h>
int main()
{
int i = 1;
clrscr(); while(i<=10)
{
printf("\n %d", i);
i = i + 1; // condition updated
}
getch();
return 0;
}
Note that initially i = 1 and is less than 10, i.e., the condition is true, so in the while
loop the value of i is printed and its value is incremented by 1. When i=11, the
condition becomes false and the loop ends.
Consider the two versions of the same program that prints the sum of digits of a
number.
int main()
{
int n, s=0, r;
printf(“Enter the Number”);
scanf(“%d”, &n);
while(n>0)
{
r=n%10;
s=s+r;
n=n/10;
}
printf(“\nSum of digits %d”, s);
return 0;}
do–while Loop
Note that the test condition is enclosed in parentheses and followed by a semi-colon.
The statements in the statement block are enclosed within curly brackets. The curly
brackets are optional if there is only one statement in the body of the do–while loop.
The do–while loop continues to execute while the condition is true and when the
condition becomes false, the control jumps to the statement following the do–while
loop.
The major disadvantage of using a do–while loop is that it always executes at least
once, so even if the user enters some invalid data, the loop will execute.
However, do–while loops are widely used to print a list of options for menu-driven
programs.
int main()
{
int c=5;
do
{
printf(“Hello”);
c++;
} while(c<5);
return 0;}
Output Hello
Nested Loops:
A nested loop refers to a loop that is contained within another loop. If the program
has to repeat a loop more than once, it is a good candidate for a nested loop. In
nested loops, the inside loop (or loops) executes completely before the outside
loop’s next iteration. It must be remembered that each inner loop should be enclosed
completely in the outer loop; overlapping loops are not allowed.
You can use one or more loops inside any other while, for, or do...while loop.
Looping in a loop is called Nesting of Loops.
Syntax:
for (loop)
{
while (loop
{
Statements;
}
Statements;
}
int main()
{
int i = 0; while (i<=10)
{
if (i==5)
{
break;
}
printf("\t %d", i);i = i + 1;
} return 0;}
Output
01234
As soon as i becomes equal to 5, the break statement is executed and the control jumps
to the statement following the while loop. Hence, the break statement is used to exit
a loop from any point within its body, bypassing its normal termination expression.
continue Statement
Like the break statement, the continue statement can only appear in the body of a
loop. When the compiler encounters a continue statement, then the rest of the
statements in the loop are skipped and the control is unconditionally transferred to
the loop-continuation portion of the nearest enclosing loop. Its syntax is quite simple,
just type keyword continue followed by a semi-colon.
continue;
Again like the break statement, the continue statement cannot be used without an
enclosing for, while, or do–while loop. When the continue statement is encountered
in the while loop and in the do–while loop, the control is transferred to the code that
tests the controlling expression. However, if placed within a for loop, the continue
statement causes a branch to the code that updates the loop variable.
For example, consider the following code:
#include <stdio.h>
int main()
{
int i;
for(i=0; i<= 10; i++)
{
if (i==5)
{
continue;
}
printf("\t %d", i);
}
return 0;
}
Output
0 1 2 3 4 6 7 8 9 10
SIVA SIVNI DEGREE COLLEGE 121 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Note that the code is meant to print numbers from 0 to 10. But as soon as i becomes
equal to 5, the continue statement is encountered, so the printf () statement is skipped
and the control passes to the expression that increments the value of i.
goto Statement
The goto statement is another type of control statement supported by C. The control
is unconditionally transferred to the statement associated with the label specified in
the goto statement. The form of a goto statement is goto label_name;
Because the goto statement can interfere with the normal sequence of processing, it
makes a program more difficult to read and maintain. Often, a break statement, a
continue statement, or a function call can eliminate the need for a goto statement.
A statement label is defined in exactly the same way as a variable name, which is a
sequence of letters and digits, the first of which must be a letter.
The statement label must be followed by a colon (:) just like a case label in a switch.
Like other statements, the goto statement ends with a semicolon.
Goto Statement Syntax
The label specified after the goto statement in C Programming is the location where
we place the code block to execute. From the below syntax, you can understand that
we can place the label anywhere in the program. It doesn’t matter if you put before
the goto or after.
Type of Arrays
• One / Single Dimensional Array
• Two Dimensional Array
• Multi-Dimensional Array
Explain one / single dimensional array with suitable example
The array which is used to represent and store data in a linear form is called as 'single
or one dimensional array.' it can represent either one row or one column. When a list
of data items are stored under a variable name using only one subscript and such a
variable is called a single- subscripted variable or one dimensional array.
Declaration of array:
A one-dimensional array declaration is a data type followed by an identifier with a
bracketed constant integral expression.
The value of the expression, which must be positive, is the size of the array. It specifies
the number of elements in the array. The array subscripts can range from 0 to (size –
1). The lower bound of the array subscripts is 0 and the upper bound is (size –1).
Thus, the following relationships hold.
int a[size]; /* memory space for a[0],a[1],…, a[size –1] allocated */
lower bound = 0
upper bound = size –1
size = upper bound + 1
The syntax for declaration of a one-dimensional array is data_type array_name
[SIZE];
All the array elements hold values of type <data type>.
The size of the array is indicated by <SIZE>, the number of elements in the array.
<SIZE> must be an int constant or a constant expression.
Example: int rno[60];
int a[3] = {2, 3, 5};
char ch[20] = "programming" ;
float stats[3] = {5003.23, 1940.32, 123.20} ;
Show the memory representation of the array and calculate its length.
Solution : The memory representation of the array Age [5] is given as below.
Functions Description
checks whether character is alphabetic
You can get a different non-zero integer when alphabetic character
is passed to isalpha () on your system. But, when you pass non-
alphabetic character to isalpha (), it always returns 0.
isalpha()
The isdigit() function checks whether a character is numeric
character (0-9) or not.
Returns 1 if argument is a numeric character.
Returns 0 if argument is not a numeric.
isdigit()
Checks whether character is alphanumeric
isalnum() Return Value
Returns 1 if argument is an alphanumeric character.
isalnum() Returns 0 if argument is neither an alphabet nor a digit.
For example:
char ch []="sivasivani";
In such case, '\0' will be appended at the end of the string by the compiler.
The above format allows accepting only string which does not have any blank space,
tab, new line, forming feed, carriage return.
Displaying or Write Strings:
To write a string, we can use printf ( ) function with format specifier %s.
Writing Strings
Strings can be displayed on the screen using the following three ways:
1. using printf() function,
2. using puts() function, and
3. using putchar() function repeatedly.
Strings can be displayed using printf() by writing
Ex: printf("%s", str);
strcpy ( ): this string function is used to copy the one string characters to another
string.
( which copies second string to first string).
Syntax : strcpy(string1,string2);
strlen ( ); this string function is used to find the length (no. of characters) of the
given string.
Syntax : strlen(string);
strrev( ): this string function is used to convert the given string characters into
reverse order.
Syntax : strrev(“string”);
strlwr( ):- This function is used to convert the given string characters in to lower
caseformat.
Syntax : strlwr((“string”))
strupr( ):- This function is used to convert the given string characters in to
uppercaseformat.
Syntax : strupr((“string”))
strcmp( ): this string function is used to compare two strings. (which returns the
value 0 when both strings are equal, returns 1(positive) when strin1 is greater
than string 2, returns negative when the string 1 is less than string 2).
Syntax : strcmp(string1,string2);
1. strlen( ) Function :
strlen( ) function is used to find the length of a character string.
Example: int n;
char st[20] = “Bangalore”;
n = strlen(st);
• This will return the length of the string 9 which is assigned to an integer variable
n.
• Note that the null character “\0‟ available at the end of a string is not counted.
2. strcpy( ) Function :
strcpy( ) function copies contents of one string into another string. Syntax for strcpy
function is given below.
Syntax: char strcpy ( destination, source);
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
SIVA SIVNI DEGREE COLLEGE 135 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
If destination string length is less than source string, entire source string value won‟t
be copied into destination string.
For example, consider destination string length is 20 and source string length is 30.
Then, only 20 characters from source string will be copied into destination string
and remaining 10 characters won‟t be copied and will be truncated.
Example : char city[15];
strcpy(city, “BANGALORE”) ;
This will assign the string “BANGALORE” to the character variable city.
3. strcat( ) Function :
strcat( ) function in C language concatenates two given strings. It concatenates
source string at the end of destination string. Syntax for strcat( ) function is given
below.
Syntax : char strcat (destination, source );
Example :
strcat ( str2, str1 );
- str1 is concatenated at the end of str2. strcat ( str1, str2 );
- str2 is concatenated at the end of str1.
• As you know, each string in C is ended up with null character („\0′).
• In strcat( ) operation, null character of destination string is overwritten by source
string‟s first character and null character is added at the end of new destination
string which is created after
strcat( ) operation.
Program : The following program is an example of strcat() function
#include <stdio.h> #include <string.h> int main( )
{
char source[ ] = “ sai” ;
char target[ ]= “ welcome to” ;
printf (“\n Source string = %s”, source);
printf ( “\n Target string = %s”, target ) ;
strcat ( target, source ) ;
printf ( “\n Target string after strcat( ) = %s”, target ) ;
}
Output :
Source string = sai
Target string = welcome to
Target string after strcat() = welcome to sai
4. strcmp( ) Function :
strcmp( ) function in C compares two given strings and returns zero if they are same.
If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it
returns > 0 value.
Syntax : int strcmp ( const char * str1, const char * str2 );
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different
characters.
Example :
char city[20] = “Madras”; char town[20] = “Mangalore”; strcmp(city, town);
This will return an integer value “-10‟ which is the difference in the ASCII values of
the first mismatching letters “D‟ and “N‟.
* Note that the integer value obtained as the difference may be assigned to an integer
variable as follows:
int n;
n = strcmp(city, town);
Multi-Dimentinal Arrays
Write about two dimensional arrays with suitable examples
Arrays can have more than one dimension. Double dimensional arrays can
represent the data in the form of rows and columns means taking two indexes.
The array which is used to represent and store data in a tabular form is called
as 'two dimensional array.' Such type of array specially used to represent data
in a matrix form. It is also called as 'multidimensional array.'
The following syntax is used to represent two dimensional arrays.
Syntax: Data-type array_name [row size] [column-size];
Example: int a[3][3];
In above example, a is an array of type integer which has storage size of 3 *
3matrix.
The total size would be 3 * 3 * 2 = 18 bytes.
Memory Allocation :
Types of functions:
There are 2(two) types of functions as:
1. Pre-Defined (Built in) Functions
2. User Defined Functions
sqrt(4.0) is 2.0
sqrt(x) square root of x sqrt(10.0) is 3.162278
exp(1.0) is 2.718282
exp(x) exponential (ex) exp(4.0) is 54.598150
log(2.0) is 0.693147
log(x) natural logarithm of x (base e) log(4.0) is 1.386294
log10(10.0) is 1.0
log10(x) logarithm of x (base 10) log10(100.0) is 2.0
fabs(2.0) is 2.0
fabs(x) absolute value of x fabs(-2.0) is 2.0
#include <math.h>
int main() {
printf ("%f\n",sqrt(10.0));
printf ("%f\n",exp(4.0));
printf ("%f\n", log(4.0));
printf ("%f\n",log10 (100.0));
printf ("%f\n",fabs (-5.2));
printf ("%f\n",ceil(4.5));
printf ("%f\n",floor(-4.5));
printf ("%f\n",pow(4.0,.5));
printf ("%f\n",fmod(4.5,2.0));
printf ("%f\n", sin(0.0));
printf ("%f\n", cos(0.0));
printf ("%f\n",
tan(0.0));
return 0; }
Explain about time.h header file in C
The time.h header file contains definitions of functions to get and manipulate date
and time information.
It describes three time-related data types.
clock_t: clock_t represents the date as an integer which is a part of the calendar time.
time_t:: time_t represents the clock time as an integer which is a part of the calendar
time.
Program to calculate the time taken to add two numbers program.
#include <time.h>
int main(void) {
time_t start, end;
start = time(NULL);
int a, b;
scanf ("%d %d", &a, &b);
printf ("Sum of %d and %d is %d\n",a, b, a + b);
end = time(NULL);
printf ("Time taken to print sum is %.2f seconds", difftime (end, start));
}
SIVA SIVNI DEGREE COLLEGE 145 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
This function returns the date and time in the format day
month hours:minutes:seconds year
ctime() Eg: Sat Jul 27 11:26:03 2019
time is printed based on the pointer returned by
Calendar Time
EX:
add (int x, int y)
{
return x+y;
}
Note that the number of arguments and the order of arguments in the function
header must be the same as that given in the function declaration statement.
While return_data_type function_name (data_type variable1, data_type
variable2...) is known as the function header, the rest of the portion comprising of
program statements within the curly brackets { } is the function body which
contains the code to perform the specific task.
Note that the function header is same as the function declaration. The only
difference between the two is that a function header is not followed by a semi-colon.
The list of variables in the function header is also referred to as the formal
parameters.
Return type denote the type of value that function will return and return type is
optional if omitted it is assumed to be integer by default.
return statement
The general form of the return statement is as follows:
return expression;
or
return (expression);
where expression must evaluate to a value of the type specified in the function
header for the return value. The expression can be any desired expression as long
as it ends up with a value of the required type.
int sum(int, int);
int main ()
{
int a=5, b=10,res;
res=sum(a,b);
printf(“result=%d”, res);
return 0;
}
int sum(int x, int y)
{
return x+y; }
SIVA SIVNI DEGREE COLLEGE 148 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
Explain the main categories of the user defined functions
1. Function with no arguments and no return values.
2. Function with no arguments and a return value.
3. Function with arguments and no return values.
4. Function with arguments and return values.
1. Function with no arguments and no return values:
syntax:
void funct (void);
main ( )
{
funct ( );
}
void funct ( void );
{
}
NOTE: There is no communication between calling and called function.
Functions are executed independently, they read data & print result in
same block.
Example:
void link (void) ;
int main ()
{
link ();
}
void link ( void );
{
printf (“ link the file “)
}
2. Function with no arguments and a return value: This type of functions
has no arguments but a return value
example:
int msg (void) ;
int main ( )
{
int s = msg ( );
printf( “summation = %d” , s);
}
int msg ( void )
{
int a, b, sum ; sum = a+b ; return (sum) ;
}
NOTE: Here called function is independent, it read the value from the
keyboard, initialize and return a value .Both calling and called function are
partly communicated with each other.
3. Function with arguments and no return values:
Here functions have arguments so, calling function send data to called
function but called function does no return value. such functions are partly
dependent on calling function and result obtained is utilized by called
function .
Note: Order, number and type of actual argument in the function call should be
matched with the order , number and type of formal arguments in the function
definition .
Explain the concept of Passing Parameters to Functions
There are two ways in which arguments or parameters can be passed to the called
function. Call by value The values of the variables are passed by the calling function
to the called function.
Call by reference The addresses of the variables are passed by the calling function
to the called function.
Call by Value
In this method, the called function creates new variables to store the value of the
arguments passed to it. Therefore, the called function uses a copy of the actual
arguments to perform its intended task.
If the called function is supposed to modify the value of the parameters passed to
it, then the change will be reflected only in the called function.
In the calling function, no change will be made to the value of the variables. This is
because all the changes are made to the copy of the variables and not to the actual
variables. To understand this concept, consider the code given below. The function
add () accepts an integer variable num and adds 10 to it. In the calling function, the
value of num = 2.
In add (), the value of num is modified to 12 but in the calling function, the change
is not reflected.
EX:
void add(int n);
int main () {
int num = 2;
printf("\n The value of num before calling the function = %d",
num);add(num);
printf("\n The value of num after calling the function = %d",
num);
return 0; }
void add(int n) {
n = n + 10;
printf("\n The value of num in the called function = %d", n);
}
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 2
Following are the points to remember while passing arguments to a function
using the call-by value method:
When arguments are passed by value, the called function creates new variables of
the same data type as the arguments passed to it.
The values of the arguments passed by the calling function are copied into the newly
created variables.
Values of the variables in the calling functions remain unaffected when the
arguments are passed using the call-by-value technique.
1. Automatic variables(auto)
2. External variables(extern)
3. Static variables(static)
4. Register variables(register)
SIVA SIVNI DEGREE COLLEGE 158 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM
fun2()
{
printf("\nI am in function fun2. My value is %d", number);
}
I am in function main.
My value is 10 I am in function fun1.
My value is 20 I am in function fun2.
My value is 20
Here the global variable number is available to all three functions and thus, if one
function changes the value of the variable, it gets changed in every function.
Note: Declaring the storage class as global or external for all the variables in a
program can waste a lot of memory space because these variables have a lifetime till
the end of the program. Thus, variables, which are not needed till the end of the
program, will still occupy the memory and thus, memory will be wasted.
The chain of functions in indirect recursion may involve any number of functions.For
example suppose n number of functions are present starting from f1() to fn() and they
are involved as following: f1() calls f2(), f2() calls f3(), f3() calls f4() and so on with fn()
calls f1().
If a function calls itself directly i.e. function fun1() is called inside its own function
body, then that recursion is called as direct recursion.
Actual and formal arguments will Actual and formal arguments willbe
be created in different memory created in same memory location
location
Recursion Iteration
Repetitive execution of afunction Repetitive execution of one ormore
until stopping Condition is met, is statements is called Iteration, commonly
calledrecursion. known asloop.
Recursion is like a top-down Iteration is more of a bottom-upapproach
approach to problem solving asit as it begins with what is known and from
divides the problem into Pieces or this constructs the solution step by step.
selects one key step,postponing the
rest.
Ex:
Int *ip;
double *dp;
float *fp;
char *ch ;
Address of Operator (&)
The Address Operator in C also called a pointer. This address operator is denoted by
“&”. This & symbol is called an ampersand. This & is used in a unary operator. The
purpose of this address operator or pointer is used to return the address of the
variable.
Once we declared a pointer variable, we have to initialize the pointer with a valid
memory address; to get the memory address of the variable ampersand is used.
The value of each variable is written inside each cell. Under the cells are their
respective addresses in memory.
The new thing in this example is variable c, which can be used in three different
levels of indirection, each one of them would correspond to a different value:
c has type char** and a value of 8092
*c has type char* and a value of 7230
**c has type char and a value of 'z'
Features of Pointer :
Pointer variable should have prefix '*'.
Combination of data types is not allowed.
Pointers are more effective and useful in handling arrays.
It can also be used to return multiple values from a function using function
arguments.
It supports dynamic memory management.
It reduces complexity and length of a program.
It helps to improve execution speed that results in reducing program execution
time.Alternative way to access array elements information.
Every pointer variable will address only two bytes of memory occupy.
Elements of array are stored in the successive increasing locations of memory. For
example, if the array starts at memory location 2147478270 (considering a 32-bit
machine), then with the assumed size of an integer as four bytes, the first element is
stored at location 2147478270, the second element at location 2147478274, and so on.
Here, the locations are taken as arbitrary.
Array notation is a form of pointer notation. The name of an array is the beginning
address of the array, called the base address of the array., that is, the base address of
an array is the address of the zeroth element of the array.
The array name is referred to as an address constant. Mentioning the name of the
array fetches its base address. Consider the following
program.
Example
2. (a) #include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u %u”, array, &array[0]);
return 0;
}
Output
2147478270 2147478270
Again, consider the following program.
(b) #include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u %u”, array, &array);
return 0;
}
Output
2147478270 2147478270
Note
Array name is a pointer constant. It cannot be used as lvalue, that, is array names
cannot be used as variables on the left of an assignment operator.
Both array and &array would give the base address of the array, but the only
difference is under ANSI/ISO Standard C, &array yields a pointer, of type pointer-
to array of-the data type to the entire array.
The obvious thing to do is to sort the numbers in memory, not by moving the
numbers themselves around but by altering the order of the pointers to them
The following example uses three integers, which are stored in an array of pointers,
as follows −
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Another Example:
int main() {
int a[3][3]={1,2,3,4,5,6,7,8,9};
int *ptr[3]={a[0],a[1],a[2]};
int i;
for(i=0;i<3;++i)
printf(“%d”,*ptr[i]);
printf(“\n”);
for(i=0;i<3;++i)
printf(“%d”,*a[i]);
return 0;}
Output
147
147
C tends to treat arrays almost as though they were pointers, which is why we can set
a pointer to an array straight rather than using the address of operator. The
instruction p = v makes the pointer point to the address of the array. The number at
this address is the first element of the array; so that is the value produced when we
access *p.
p++ gives some extra arithmetic instructions that let us use the pointer to the array
more flexibly.
p++
This instruction increases the pointer so that it points to the next element of the array.
If it is followed by the instruction printf(“%d \n”, *p); then it would display the
number 2201, which is the content of element v[1] (i.e., the second element).
int main() {
int a[2][3]={{3,4,5},{6,7,8}};
int i; int(*pa)[3];
pa=a;
for(i=0;i<3;++i)
printf(“%d\t”,(*pa)[i]);
printf(“\n”);
pa++;
for(i=0;i<3;++i)
printf(“%d\t”,(*pa)[i]);
return 0; }
Output
345
678
Difference between an array of pointers and a pointer to an array
IMPORTANT QUESTIONS
1. Define function? Need of the function and advantages of functions?
2. How functions are works:
3. Explain function elements with syntax
4. Explain the main categories of the user defined functions
5. Define actual arguments and formal arguments
6. Explain the concept of passing parameters to functions
7. Explain call by reference with example
8. Explain in detailed recursion in c
9. How to write a recursive function?
10. Explain indirect and direct recursion
11. Explain the concept of inline funtion
12. Explain briefly about storage classes in c
13. Which storage class should be used and when
14. Define scope rules
15. Define pointer features of pointer :
16. Expain the concept of declaring and initializing of pointer variable
17. Explain the process of pointer memory allocation
18. Explain the concept of pointers to pointers
19. How pointer is associated with functions
20. Explain passing array to function using call by reference
21. How to pass an entire array to a function as an argument?
22. Write about array of pointers
23. Write about pointer to a structure in c
24. Discuss about pointers and strings
25. Explain the concept of pointers to pointers
26. Explain the concept dynamic memory allocation with example
Syntax:
struct structure_nm{
<data-type> element 1;
<data-type> element 2;
-----------
<data-type> element n;
}struct_var1.struct-var2;
int main()
{
struct employee ramesh={‘b’, 6500, 812.5};
struct employee vivek;
vivek = ramesh; /* copy respective members of ramesh to vivek */
printf(“\n vivek’s grade is %c, basic is Rs %d, \allowance is Rs %f”,
vivek.grade,vivek.basic,\
vivek.allowance);
return 0;
}
O utput
vivek’s grade is b, basic is Rs 6500, allowance
is Rs 812.500000
Bit filed Bit filed cannot be defined Bit field can be defined in a
in an array. structure.
Keyword There is no keyword to "struct" is a keyword used to
declare an array. declare the structure.
Example:
union techno
{
int comp_id;
char nm;
float sal;
}tch;
In above example, it declares tch variable of type union. The union contains three
members as data type of int, char, float. We can use only one of them at a time.
Declaring Union Variables:
After defining a union format, we can declare variables of that type. Union
variables are declared in two ways.
At the time of Union definition (Along with union definition)
After union definition.
1. At the time of union definition (Along with union definition)
Union variables are declared before closing the union definition. i.e., before
closing semicolon(;).
After declaration of the union variable the memory will be allocated to only one
member of union. i.e., same memory location, can be used to store multiple types of
data.
The memory occupied by a union is the size (memory) of largest member of the
union.
Consider the following example:
union book
{
char title[20];
int pages;
float price;
} b;
Here the union variable b occupies 20 bytes of memory space because this is the
maximum space which can be occupied by a character string title.
Note: A union is a special data type available in C that enables you to store different
data types in the same memory location.
1. Text file
2. Binary file
fclose(fp);
getch();
}
myfile2.txt
hello c programming
Reading File : fgets() function
The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax:char* fgets(char *s, int n, FILE *stream)
fclose(fp);
getch();
}
Output:hello c programming
Output
00
22
44
66
88
10 10
12 12
14 14
16 16
18 18
SIVA SIVNI DEGREE COLLEGE 210 | P a g e
PROGRAMMING IN C Bsc I YR/I-SEM