Complete CP Notes
Complete CP Notes
1.1 Computer: It is an electronic machine which performs following major operations or functions
Functional Units:
a. Input Unit: This unit is used for entering data and programs into the computer system by the user for processing e.g.
Keyboard, Mouse etc.
b. Storage Unit: The storage unit is used for storing data and instructions before and after processing
c. Output Unit: The output unit is used for storing the result as output produced by the computer after processing e.g.
Monitor, Printer etc.
d. Processing: The task of performing operations like arithmetic and logical operations is called processing. The Central
Processing Unit (CPU) takes data and instructions from the storage unit and makes all sorts of calculations based on the
instructions given and the type of data provided. It is then sent back to the storage unit. CPU includes Arithmetic logic unit (ALU)
and control unit (CU)
1
Arithmetic Logic Unit: All calculations and comparisons, based on the instructions provided, are carried out within the ALU. It
performs arithmetic functions like addition, subtraction, multiplication, division and also logical operations like greater than, less
than and equal to etc.
Control Unit: Controlling of all operations like input, processing and output are performed by control unit. It takes care of step
by step processing of all operations inside the computer.
Memory
Computers memory can be classified into two types; primary memory and secondary memory
RAM or Random Access Memory is the unit in a computer system. It is the place in a computer where the operating system,
application programs and the data in current use are kept temporarily so that they can be accessed by the computers processor. It
is said to be volatile since its contents are accessible only as long as the computer is on. The contents of RAM are no more
available once the computer is turned off.
ROM or Read Only Memory is a special type of memory which can only be read and contents of which are not lost even when
the computer is switched off. It typically contains manufacturers instructions. Among other things, ROM also stores an initial
program called the bootstrap loader whose function is to start the operation of computer system once the power is turned on.
b. Secondary Memory
RAM is volatile memory having a limited storage capacity. Secondary/auxiliary memory is storage other than the RAM. These
include devices that are peripheral and are connected and controlled by the computer to enable permanent storage of programs and
data.
CD ROM
Secondary storage devices are of two types; magnetic and optical. Magnetic devices include hard disks and optical storage devices
are CDs, DVDs, Pen drive, Zip drive etc.
Hard Disk
Hard disks are made up of rigid material and are usually a stack of metal disks sealed in a box. The hard disk and the hard disk
drive exist together as a unit and is a permanent part of the computer where data and programs are saved. These disks have storage
capacities ranging from 1GB to 80 GB and more. Hard disks are rewritable.
Compact Disk
Compact Disk (CD) is portable disk having data storage capacity between 650-700 MB. It can hold large amount of information
such as music, full-motion videos, and text etc. CDs can be either read only or read write type.
Digital Video Disk (DVD) is similar to a CD but has larger storage capacity and enormous clarity. Depending upon the disk type it
can store several Gigabytes of data. DVDs are primarily used to store music or movies and can be played back on your television
or the computer too. These are not rewritable.
2
information INTO the computer and output devices bring information OUT of a computer system. These input/output devices are
also known as peripherals since they surround the CPU and memory of a computer system.
Input Devices
An input device is any device that provides input to a computer. There are many input devices, but the two most common ones are
a keyboard and mouse. Every key you press on the keyboard and every movement or click you make with the mouse sends a
specific input signal to the computer.
Keyboard: The keyboard is very much like a standard typewriter keyboard with a few additional keys. The basic QWERTY
layout of characters is maintained to make it easy to use the system. The additional keys are included to perform certain special
functions. These are known as function keys that vary in number from keyboard to keyboard.
Mouse: A device that controls the movement of the cursor or pointer on a display screen. A mouse is a small object you can roll
along a hard and flat surface. Its name is derived from its shape, which looks a bit like a mouse. As you move the mouse, the
pointer on the display screen moves in the same direction.
Trackball: A trackball is an input device used to enter motion data into computers or other electronic devices. It serves the same
purpose as a mouse, but is designed with a moveable ball on the top, which can be rolled in any direction.
Touchpad: A touch pad is a device for pointing (controlling input positioning) on a computer display screen. It is an alternative
to the mouse. Originally incorporated in laptop computers, touch pads are also being made for use with desktop computers. A
touch pad works by sensing the users finger movement and downward pressure. Touch Screen: It allows the user to
operate/make selections by simply touching the display screen. A display screen that is sensitive to the touch of a finger or stylus.
Widely used on ATM machines, retail point-of-sale terminals, car navigation systems, medical monitors and industrial control
panels.
Light Pen: Light pen is an input device that utilizes a light-sensitive detector to select objects on a display screen.
Magnetic ink character recognition (MICR): MICR can identify character printed with a special ink that contains particles of
magnetic material. This device particularly finds applications in banking industry.
Optical mark recognition (OMR): Optical mark recognition, also called mark sense reader is a technology where an OMR
device senses the presence or absence of a mark, such as pencil mark. OMR is widely used in tests such as aptitude test.
Bar code reader: Bar-code readers are photoelectric scanners that read the bar codes or vertical zebra strips marks, printed on
product containers. These devices are generally used in super markets, bookshops etc.
Scanner
Scanner is an input device that can read text or illustration printed on paper and translates the information into a form that
the computer can use.
3
Output Devices:
Output device receives information from the CPU and presents it to the user in the desired from. The processed data, stored in
the memory of the computer is sent to the output unit, which then converts it into a form that can be understood by the user.
The output is usually produced in one of the two ways on the display device, or on paper (hard copy).
Monitor: is often used synonymously with computer screen or display. Monitor is an output device that resembles the
television screen (fig. 1.8). It may use a Cathode Ray Tube (CRT) to display information. The monitor is associated with a
keyboard for manual input of characters and displays the information as it is keyed in. It also displays the program or
application output. Like the television, monitors are also available in different sizes.
Printer: Printers are used to produce paper (commonly known as hard copy) output. Based on the technology used, they
can be classified as Impact or Non-impact printers.
Impact printers use the typewriting printing mechanism wherein a hammer strikes the paper through a ribbon in order to
produce output. Dot-matrix and Character printers fall under this category.
Non-impact printers do not touch the paper while printing. They use chemical, heat or electrical signals to etch the symbols on
paper. Inkjet, Deskjet, Laser, Thermal printers fall under this category of printers.
Plotter: Plotters are used to print graphical output on paper. It interprets computer commands and makes line drawings on
paper using multi colored automated pens. It is capable of producing graphs, drawings, charts, maps etc.
Facsimile (FAX): Facsimile machine, a device that can send or receive pictures and text over a telephone line. Fax
machines work by digitizing an image.
Sound cards and Speaker(s): An expansion board that enables a computer to manipulate and output sounds. Sound cards
are necessary for nearly all CD-ROMs and have become commonplace on modern personal computers. Sound cards enable
the computer to output sound through speakers connected to the board, to record sound input from a microphone connected to
the computer, and manipulate sound stored on a disk.
2. Accuracy: The degree of accuracy of computer is very high and every calculation is performed with the same accuracy. The
errors in computer are due to human and inaccurate data.
3. Diligent: A computer is free from tiredness, lack of concentration, fatigue, etc. It can work for hours without creating any error.
If millions of calculations are to be performed, a computer will perform every calculation with the same accuracy. Due to this
capability it overpowers human being in routine type of work.
4. Versatility: It means the capacity to perform completely different type of work. You may use your computer to prepare payroll
slips. Next moment you may use it for inventory management or to prepare electric bills.
5. Storage capacity: The Computer has an in-built memory where it can store a large amount of data. You can also store data in
secondary storage devices such as floppies, which can be kept outside your computer and can be carried to other computers.
6. No feeling : It does not have feelings or emotion, taste, knowledge and experience. Thus it does not get tired even after long
hours of work. It does not distinguish between users.
4
7. No IQ: Computer is a dumb machine and it cannot do any work without instruction from the user. It performs the instructions
at tremendous speed and with accuracy. It is you to decide what you want to do and in what sequence. So a computer cannot take
its own decision as you can.
1.3 History of Computer:
(Period)
Fourth ICs with VLSI Operating system for Small, affordable IBM PC, Apple
technology, personal computers ,reliable ,easy to use, II,CRAY 1 etc.
(1975-1989)
Microprocessor, like UNIX, totally general
semiconductor Windows purpose machine
memory, larger
capacity hard disk
etc.
Fifth ICs with ultra large World Wide Web, Portable ,more IBM note books,
scale integration Multimedia powerful ,cheaper Pentium,Core2Duo,
(1989-Present)
technology, Applications ,reliable and easier PARAM etc.
to use.
Larger capacity main
memory and hard
disk
Size May be room or May be room May have size of May be on a desk
5
building Washing machine
Cost Very Expensive Less than super Less than mainframe Less than mini
Around 1000 million Around 75000 dollar May be in lacks May be in thousands
dollar
Purpose Weather forecasting, To run business In small business For personal use
operations and firms
Research &
Exploration In Bank and
Insurance company
Example CRAY YMP, DEC, ICL and IBM Hitachi 2800 IBM PC, PC-AT
CRAY2, NEC SX-3, 3000 series.
CRAY XMP and
PARAM
Analog computers: These are used to process analog data. Analog data is of continuous nature and which is not discrete or
separate. Such type of data includes temperature, pressure, speed weight, voltage, depth etc. It measures continuous changes in
some physical quantity e.g. The Speedometer of a car measures speed, the change of temperature is measured by a Thermometer,
the weight is measured by Weights machine. Analog computers are the first computers being developed and provided the basis for
the development of the modern digital computers. Analog computers are widely used for certain specialized engineering and
scientific applications, for calculation and measurement of analog quantities. They are frequently used to control process such as
those found in oil refinery where flow and temperature measurements are important. They are used for example in paper making
and in chemical industry. Analog computers do not require any storage capability because they measure and compare quantities in
a single operation. Output from an analog computer is generally in the form of readings on a series of dial (Speedometer of a car)
Digital Computer:
A Digital Computer, as its name implies, works with digits to represent numerals, letters or other special symbols. Digital
Computers operate on inputs which are ON-OFF type and its output is also in the form of ON-OFF signal. Normally, an ON is
represented by a 1 and an OFF is represented by a 0. So we can say that digital computers process information which is based on
6
A digital computer can be used to process numeric as well as non-numeric data. It can perform arithmetic operations like addition,
subtraction, multiplication and division and also logical operations. Most of the computers available today are digital computers.
The most common examples of digital computers are accounting machines and calculators.The results of digital computers are
more accurate than the results of analog computers. Analog computers are faster than digital. Analog computers lack memory
whereas digital computers store information. We can say that digital computers count and analog computers measures.
e.g. HP 530
Hybrid computer:
A hybrid is a combination of digital and analog computers. It combines the best features of both types of computers, i-e. It has the
speed of analog computer and the memory and accuracy of digital computer. They help the user, to process both continuous and
discrete data. For example a petrol pump contains a processor that converts fuel flow measurements into quantity and price values.
In hospital Intensive Care Unit (ICU), an analog device is used which measures patient's blood pressure and temperature etc,
which are then converted and displayed in the form of digits. Hybrid computers for example are used for scientific calculations, in
1.6 Memory Hierarchy in a computer: Following figure represents hierarchy of memory in terms of Access time and
storing capacity.
1 Byte = 8 bits
7
1 TB (Tera Bytes) = 1024 GB
1.8 What is operating System: It is the set of programs that controls a computer and works as an interface between user
and hardware.
e.g.
Its functions:
Process Management: It controls all processes from start to shutdown. It also control creation and deletion of user and system
processes.
Memory Management: It controls allocation and deallocation of memory space as per need. It controls loading of processes
when space is available.
File Management: It controls creation, deletion, renaming, copying and moving of file and directories.
Security Management: It performs many tasks like Alert message, password and firewall protection.
Command interpreter: It works as an interface between user and system. Two types of interface like Command line and
Graphical User Interface (GUI).In command line user interact with the system by command to perform specific task while in GUI
user interact with the help of mouse to access windows icons and menus.
Its types:
Single User: One user can access one computer at a time e.g. DOS
Multi User: Many users can access the same computer at the same time and different time e.g. Windows NT, UNIX
Multiprocessing: more than one processor is there e.g. UNIX, LINUX, and WINDOWS XP
Multitasking: It allows many software processes to run at the same time e.g. UNIX, LINUX, and WINDOWS 7.
Multithreading: It allows different parts of a software program to run concurrently e.g. LINUX, UNIX and WINDOWS XP (Ref.
http://www.computerhope.com/msdos.htm).
8
DOS (Disk Operating System): DOS was the first operating system used by IBM-compatible computers. It was originally
available in two versions that were essentially the same, but marketed under two different names. "PC-DOS" was the version
developed by IBM and sold to the first IBM-compatible manufacturers. "MS-DOS" was the version that Microsoft bought the
rights to, and was bundled with the first versions of Windows.
DOS uses a command line, or text-based interface, that allows the user to type commands. This made the operating system
difficult for novices to use, which is why Microsoft later bundled the graphic-based Windows operating system with DOS. The
first versions of Windows (through Windows 95) actually ran on top of the DOS operating system. Windows operating system was
rewritten for Windows NT (New Technology), which enabled Windows to run on its own, without using DOS. Later versions of
Windows, such as Windows 2000, XP, and Vista, also do not require DOS.
Windows operating system: It is a graphical user interface based operating systems developed, marketed, and sold by Microsoft.
It was developed by Microsoft to overcome the limitations of DOS OS. First successful version of this was windows 3.0 released
in 1990. It is basically an environment where different programs can run at the same time. It consists of several families
like Windows NT, Windows Embedded and Windows Phone. Microsoft Windows came to dominate the world's personal
computer market with over 90% market share, overtaking Mac OS, which had been introduced in 1984.
Linux: Open source operating system which is enhanced and backed by thousands of programmers worldwide. Its name is
derived from its originator Linus Torvalds who was a student at the university of Helsinki, Finland in early 1990. It is a multi
tasking and multiprocessing operating system (OS). It has two interfaces known as the shell or command-line interface (CLI) and
a graphical user interface (GUI. For desktop systems, the default mode is usually a graphical user interface,
1.9 A number system: Itdefines how a number can be represented using distinct symbols. A number can be represented
differently in different systems. For example, the two numbers (2A) 16 and (52)8 both refer to the same quantity, (42) 10, but their
representations are different.
In a positional number system, the position a symbol occupies in the number determines the value it represents. In this system, a
number represented as:
The word decimal is derived from the Latin root decem (ten). In this system the base b = 10 and we use ten symbols
S = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
The symbols in this system are often referred to as decimal digits or just digits.
The following shows the place values for the integer +224 in the decimal system.
9
Note that the digit 2 in position 1 has the value 20, but the same digit in position 2 has the value 200. Also note that we normally
drop the plus sign, but it is implicit.
The following shows the place values for the real number +24.13.
Binary Number: The word binary is derived from the Latin root bini (or two by two). In this system the base b = 2 and we use
only two symbols,
S = {0, 1}
The symbols in this system are often referred to as binary digits or bits (binary digit).
The following shows that the number (11001)2 in binary is the same as 25 in decimal. The subscript 2 shows that the base is 2.
The following shows that the number (101.11)2 in binary is equal to the number 5.75 in decimal.
The word hexadecimal is derived from the Greek root hex (six) and the Latin root decem (ten). In this system the base b = 16
and we use sixteen symbols to represent a number. The set of symbols is
S = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F}
Note that the symbols A, B, C, D, E, F are equivalent to 10, 11, 12, 13, 14, and 15 respectively. The symbols in this system are
often referred to as hexadecimal digits
The following shows that the number (2AE)16 in hexadecimal is equivalent to 686 in decimal.
10
The equivalent decimal number is N = 512 + 160 + 14 = 686.
The word octal is derived from the Latin root octo (eight). In this system the base b = 8 and we use eight symbols to represent a
number. The set of symbols is
S = {0, 1, 2, 3, 4, 5, 6, 7}
The following shows that the number (1256)8 in octal is the same as 686 in decimal.
1.10 Conversion:
We need to know how to convert a number in one system to the equivalent number in another system. Since the decimal system is
more familiar than the other systems, we first show how to covert from any base to decimal. Then we show how to convert from
decimal to any base. Finally, we show how we can easily convert from binary to hexadecimal or octal and vice versa.
11
Any base to decimal conversion
The following shows how to convert the binary number (110.11)2 to decimal: (110.11)2 = 6.75.
The following shows how to convert the hexadecimal number (1A.23)16 to decimal.
Note that the result in the decimal notation is not exact, because
2
3 16 = 0.01171875. We have rounded this value to three digits (0.012).
This means that (23.17)8 19.234 in decimal. Again, we have rounded up 7 82 = 0.109375.
12
1.11 Decimal to any base
The following shows how to convert 35 in decimal to binary. We start with the number in decimal, we move to the left while
continuously finding the quotients and the remainder of division by 2. The result is 35 = (100011) 2.
The following shows how to convert 126 in decimal to its equivalent in the octal system. We move to the right while continuously
finding the quotients and the remainder of division by 8. The result is 126 = (176)8.
The following shows how we convert 126 in decimal to its equivalent in the hexadecimal system. We move to the right while
continuously finding the quotients and the remainder of division by 16. The result is 126 = (7E) 16
13
Converting the fractional part of a number in decimal to other bases:
Since the number 0.625 = (0.101)2 has no integral part, the example shows how the fractional part is calculated.
The following shows how to convert 0.634 to octal using a maximum of four digits. The result is 0.634 = (0.5044) 8. Note that we
multiple by 8 (base octal).
14
The following shows how to convert 178.6 in decimal to hexadecimal using only one digit to the right of the decimal point. The
result is 178.6 = (B2.9)16 Note that we divide or multiple by 16 (base hexadecimal).
Binary-hexadecimal conversion:
Solution
Note that the leftmost pattern can have one to four bits. We then use the equivalent of each pattern shown in Table 2.2 on page 25
to change the number to hexadecimal: (4E2)16.
Solution
Binary-octal conversion:
Solution
15
Each group of three bits is translated into one octal digit. The equivalent of each 3-bit group is shown in Table 2.2 on page 25.
Solution
Octal-hexadecimal conversion:
16
1.13 Computer languages: we use a computer language to write a program in computer. A computer language is a set of
predefined words and predefined rules (syntax). Over the years, computer languages have evolved from machine language to
high-level languages.
In the earliest days of computers, the only programming languages available were machine languages. Each computer had its own
machine language, which was made of streams of 0s and 1s. It is the language understood by a computer. In this data and
operation is represented in terms of binary number. We use Opcode as shown in the table.
The next evolution in programming came with the idea of replacing binary code for instruction and addresses with symbols or
mnemonics. Because they used symbols, these languages were first known as symbolic languages. The set of these mnemonic
languages were later referred to as assembly languages.
17
High Level Language(3rd Generation Language):
Although assembly languages greatly improved programming efficiency, they still required programmers to concentrate on the
hardware they were using. Working with symbolic languages was also very tedious, because each machine instruction had to be
individually coded. The desire to improve programmer efficiency and to change the focus from the computer to the problem being
solved led to the development of high-level languages.
Over the years, various languages, most notably BASIC, COBOL, Pascal, Ada, C, C++ and Java, were developed. Program for
adding two integers in C is shown below.
These are easy to understand and use like Query Language SQL. Such languages enable a person to specify exactly what
information they require from the database and usually embedded within database management.
Writing query:
Natural-Language: Languages that use ordinary conversation in ones own language. Research and experimentation toward this
goal is being done. Intelligent compilers are now being developed to translate natural language (spoken) programs into structured
machine-coded instructions that can be executed by computers. Effortless, error-free natural language programs are still some
distance into the future.
18
1.14 Difference among hardware, software and firmware:
Compiler: It is a software which converts (or translates) source program written using high level language into object code.
It checks whole program lexically, syntactically and if error then give message to the programmer and does not convert into object
code.
Interpreter 19
Program machine code
It checks program statement by statement and convert into machine if there is no error. Therefore it is slower than compiler.
Example: Thin Basic for Windows, Java Script engine for Java Script.
Assembler: It converts program written in assembly language or symbolic language into machine code.
Linker: In high level languages, some built in header files or libraries are stored. These libraries are predefined and these
contain basic functions which are essential for executing the program. These functions are linked to the libraries by a program
called Linker. If linker does not find a library of a function then it informs to compiler and then compiler generates an error. The
compiler automatically invokes the linker as the last step in compiling a program .
Loader: It is a program that loads machine codes of a program into the system memory. It is the part of an Operating
System that is responsible for loading programs. It is one of the essential stages in the process of starting a program. Because it
places programs into memory and prepares them for execution. Loading a program involves reading the contents of executable
file into memory. Once loading is complete, the operating system starts the program by passing control to the loaded program
code. All operating systems that support program loading have loaders. In many operating systems the loader is permanently
resident in memory.
1.16 Algorithm: It is a well-ordered collection of unambiguous and effectively computable operations, that
when executed, produces a result and halts in a finite amount of time. It is for user understanding.
Characteristics of an Algorithm:
Unambiguous: the operations described are understood by a computing agent without further simplification
Effectively computable: the computing agent can actually carry out the operation Algorithm to find the average of two numbers
Step1: Start
Step 5: Stop
1. Pseudocode
2. Flow Chart
3. Program
20
1.17 Pseudocode (or Program Design Language): It is representation of an algorithm in code like format. It will be
closer to any high level language like C, Pascal, Fortran etc. It is for programmer understanding.
Read A ,B
Sum =A+B
Avg = Sum/2
Print Avg
1.18 Flow Chart: It is used to visualize an algorithm. It means it is pictorial representation of the algorithm which shows the
flow of steps in an algorithm.
Start/Stop
Input/ Output
Process
Flow of steps
Connector
1. Start
3. Calculate age
4. Print age
6. End
21
Flow chart:
Algorithm:
Step 1 Start.
Step 2. Input A, B
Step 5. Stop
Pdeudo code
Read A,B
If A>B
Print A
Else
Print B
22
Flow Chart:
Start
Read A, B
A False
>B? Print B
True
Print A
Stop
Questions
Q.1. What is an Algorithm. What are different types of algorithm? Write its properties. Find largest of 3 numbers.
Q.5. What are Symbols used in flowchart and flowchart of factorial of a number. Write about Generation of computers along with
advantages and disadvantages?
Q.9.Differentiate between:
a. High and low level.
23
b. Compiler and interpreter.
c. Logical and runtime error.
d. Algorithm and flowchart.
Q.12. Convert:
a. (999)10 = (? )16
b. (11011101999)2 = (? )8
c. (786)10 = ( ?)BCD
d. Twos complement of 1100100. And write the value in decimal.
Q.2. What do you mean by application software? Give any two examples.
Q.1. Write in brief about the components of central processing unit of a computer.
24
Q.5. Convert the following:
a) (FA1.2C)16=(?)8
b) (756)10=(?)4
c) (11011.011)2=(?)16
d) (574.32)8=(?)2
Q.6. Define algorithm? Make flowchart to find prime numbers between 101 and 999.
Q.1. What are the classification of computer? Explain any two in detail.
Q.4. Draw a flowchart to find the sum and reverse of a given number.
Q.6. Describe about the basic components of computer with a neat block diagram.
25
2.1 Introduction
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating
system at AT&T Bell Labs. C is a highly flexible and adaptable language because of which it withstood the test of time. Since its
creation in 1972, its been used for a wide variety of programs including general purpose and business applications, gaming,
operating systems, databases, device driver programming, graphics programming, firmware for micro-controllers,
compilers/assemblers of other programming languages and so on.C is the most widely used language in the world and has a large
developer community because of which it is very stable and robust.
26
2.3
Q 3.Features of note
Write a short C language
on history and development of C?
C is very fast and efficient as it directly interacts with hardware and because it provides variety of operators and data types.
C is portable as a program written in C can be run on a variety of devices
Note: The disadvantages of C will be more clear after you have thoroughly studied all the five units.
2.6.1 Comments: Lines 1, 3 and 8 begin with // (double forward slash), indicating that these two lines are comments. We insert
comments to documentprograms and improve program readability. Comments do not cause the computerto perform any action
when the program is run. Comments are ignored by the C compilerand do not cause any machine-language object code to be
generated. The preceding comments simply describe the purpose of the program, from where the program starts execution and
where the program stops execution. Comments also help other people read and understand our program.
Note: We can also use /**/ multi-line comments in which everything from /* on the first line to */ at the end of the last line is a
comment.
2.6.2 Preprocessor Directives: Line 2 (#include<stdio.h>) is a directive (command) to the C preprocessor which is a special
program. Lines beginning with # are processed by the preprocessorbefore compilation. Line 2 tells the preprocessor to include the
contents of the standardinput/output header (<stdio.h>) in the program. This header contains informationused by the compiler
when compiling calls to standard input/output library functions suchas printf(). A much detailed discussion about the c
preprocessor will follow in unit 5.
2.6.3 Blank Lines and White Space: Line 3 is simply a blank line. You use blank lines, space characters and tab characters
(i.e.,tabs) to make programs easier to read. Together, these characters are known as whitespace. White-space characters are
normally ignored by the compiler.
2.6.4 The main Function: Line 5 (void main() ) is called the main function. It is the point in a C program from where the
execution starts. The parentheses after main indicate that main() is a programbuilding block called a function. C programs contain
one or more functions, one of whichmust always be main(). Every program in C begins executing at the function main. Functions
canreturn information. The keyword void to the left of main indicates that here main()does not return any value.
A left brace, {, begins the body of every function (line 6). A corresponding right brace ends each function (line 8). This pair of
braces and the portion of the program betweenthe braces is called a block. A block is always executed in entirety i.e., either all the
statements inside are executed or none of them is executed.
2.6.5 An Output Statement: Line 7 (printf) instructs the computer to perform an action, namely to print on the screen the string
ofcharacters enclosed within quotation marks.A string is sometimes called a character string,a message or a literal. The entire line,
including the printf function (the f stands forformatted), its argument within the parentheses and the semicolon (;), is called a
statement.Every statement must end with a semicolon (also known as the statement terminator).When the preceding printf
statement is executed, it prints the message Welcome toC! on the screen. The characters normally print exactly as they appear
between the doublequotes in the printf statement. \n is a special symbol called the escape sequence that tells the compiler to move
to the cursor to the next line after displaying the message on the screen.
Step 1: Locate the TC.exe file and open it. You will usually find it at location C:\TC\BIN\.
Step 3: Save the program using F2 (or File > Save), remember the extension should be either .cpp or .c.
Step 5: Press Ctrl + F9 to Run (or select Run > Run in menu bar ) the C program.
Step 6: Alt+F5 to view the output of the program at the output screen.
28
Documentation Section
Link Section
Definition Section
Global Declaration Section
void main()
{
Declaration Section
Executable part
}
Subprogram section
Function 1
Function 2
.
.
Function n
The Documentation Section consists of a set of comment lines giving the name of the program and other details.
The Link Section provides instructions to the compiler to link functions from the system library.
The Global Declaration Section: There are some variables and those variables are declared in this section that is outside of all
functions.
main() function: Every C program must have one main function section. This section contains two parts, declaration and
executable part.
Declaration Part declares all the variables used in the executable part.
There should be at least one statement in the executable part which contains instructions to perform certain task.
The declaration and executable part must appear between the opening and closing braces. All statements in the declaration part
should end with the semicolon.
The Subprogram Section contains all the user defined functions that are called in the main function.
29
The compilation process of a C program involves following steps:
1. Preprocessing is the first step of any C compilation. It processes include-files, conditional compilation instructions and
macros.
2. Compilation is the second pass. It takes the output of the preprocessor, and the source code, and generates assembler
source code.
3. Assembly 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.
4. Linking is the final stage of compilation. It takes one or more object files or libraries as input and combines them to
produce a single (usually executable) file. In doing so, it resolves references to external symbols, assigns final addresses
to procedures/functions and variables, and revises code and data to reflect new addresses (a process called relocation).
There is one more step involved before actual execution of a C program takes place. It is called loading. In this step, the
loader brings the C program from secondary storage (e.g., hard disk) to main memory (i.e., RAM) and prepares it for
execution. It allocates memory and other necessary resources to the program and hands over the CPU control to it.
30
2.10 Standard Input/Output (I/O) in C
When we are saying Input that means to feed some data into program.C programming language provides a set of built-in
functions to read given input and feed it to the program as per requirement.
When we are saying Output that means to display some data on screen, printer or in any file. C programming language provides a
set of built-in functions to output the data on the computer screen as well as you can save that data in text or binary files.
C programming language treats all the devices as files. So devices such as the display are addressed in the same way as files and
following three file are automatically opened when a program executes to provide access to the keyboard and screen.
The file points are the means to access the file for reading and writing purpose. This section will explain how to read values from
the screen and how to print the result on the screen.
The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads
only single character at a time. We can use this method in the loop in case we want to read more than one characters from the
screen.
The int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only
single character at a time. We can use this method in the loop in case we want to display more than one character on the screen.
Check the following example:
#include <stdio.h>
void main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
}
When the above code is compiled and executed, it waits for you to input some text when you enter a text and press enter then
program proceeds and reads only a single character and displays it as follows:
The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF
(End of File).
The int puts(const char *s) function writes the string s and a trailing newline to stdout.
31
#include <stdio.h>
void main( )
{
char str[100];
printf( "Enter a value :");
gets( str );
printf( "\nYou entered: ");
puts( str );
}
When the above code is compiled and executed, it waits for us to input some text when we enter a text and press enter then
program proceeds and reads the complete line till end and displays it as follows:
The int scanf(const char *format, ...) function reads input from the standard input stream stdin and scans that input according to
format provided.
The int printf(const char *format, ...) function writes output to the standard output stream stdout and produces output according
to a format provided.
The format can be a simple constant string, but we can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or
float respectively. There are many other formatting options available which can be used based on requirements. For now let us
proceed with a simple example which makes things clear:
#include <stdio.h>
void main( )
{
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
}
When the above code is compiled and executed, it waits for us to input some text, when we enter a text and press enter then
program proceeds and reads the input and displays it as follows:
Here, it should be noted that scanf() expect input in the same format as we provided %s and %d, which means we have to provide
valid input like "string integer", if we provide "string string" or "integer integer" then it will be assumed as wrong input. Second,
while reading a string scanf() stops reading as soon as it encounters a space so "this is test" are three strings for scanf().
%csingle character
%uunsigned integer
#include<stdio.h>
void main()
{
int c=5;
printf("Number=%d",c);
}
Output
Number=5
Inside quotation of printf() there, is a format specifier "%d" (for integer). If this format specifier matches with remaining
argument,i.e, c in this case, value of c is displayed.
#include<stdio.h>
void main()
{
int c;
printf("Enter a number\n");
scanf("%d",&c);
printf("Number=%d",c);
}
Output
Enter a number
4
Number=4
The scanf() function is used to take input from user. In this program, the user is asked a input and value is stored in variable c.
Note the '&' sign before c. &c denotes the address of c and value is stored in that address.
33
2.10.4.3 I/O of floats in C
#include <stdio.h>
void main()
{
float a;
printf("Enter value: ");
scanf("%f",&a);
printf("Value=%f",a); //%f is used for floats instead of %d
}
Output
Format specifier "%f" is used for floats to take input and to display floating value of a variable.
#include <stdio.h>
void main()
{
char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.",var1);
}
Output
Enter character: g
You entered g.
When character is typed in the above program, the character itself is not recorded a numeric value(ASCII value) is stored. And
when we displayed that value by using "%c", that character is displayed.
#include <stdio.h>
void main()
{
char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.\n",var1);
/* \n prints the next line(performs work of enter). */
printf("ASCII value of %d",var1);
}
Output
34
Enter character:
g
103
We can display character if we know ASCII code only. This is shown by following example.
#include <stdio.h>
void main()
{
int var1=69;
printf("Character of ASCII value 69: %c",var1);
}
Output
The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly ASCII value of 'a' is 97, 'b' is 98 and so on to 'z' is 122.
#include<stdio.h>
void main()
{
printf("Case 1:%6d\n",9876);
/* Prints the number right justified within 6 columns */
printf("Case 2:%3d\n",9876);
/* Prints the number to be right justified to 3 columns but, there are 4 digits so number is not right justified */
printf("Case 3:%.2f\n",987.6543);
/* Prints the number rounded to two decimal places */
printf("Case 4:%.f\n",987.6543);
/* Prints the number rounded to 0 decimal place, i.e, rounded to integer */
printf("Case 5:%e\n",987.6543);
/* Prints the number in exponential notation(scientific notation) */
}
Output:
Case 1: 9876
Case 2:9876
Case 3:987.65
Case 4:988
Case 5:9.876543e+002
#include <stdio.h>
void main()
{
int a,b;
float c,d;
printf("Enter two intgers: ");
/*Two integers can be taken from user at once as below*/
35
scanf("%d%d",&a,&b);
printf("Enter intger and floating point numbers: ");
/*Integer and floating point number can be taken at once from user as below*/
scanf("%d%f",&a,&c);
}
A character denotes any alphabet, digit or special symbol used to represent information.
Alphabets A, B, .., Y, Z a, b, , y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols ~ ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; " ' <> , . ? /
2.11.2 Constants:
Constants are identifiers whose value does not change. Constants are used to define fixed values like PI or the charge on an
electron so that their value does not get changed in the program even by mistake. To declare a constant, precede the normal
variable declaration with const keyword and assign it a value. For example,
#define PI 3.14159
When the preprocessor reformats the program to be compiled by the compiler, it replaces each defined name with its
corresponding value wherever it is found in the source program. Hence, it just works like the Find and Replace command
available in a text editor.
Constants refers to fixed value that do not change during the execution of a program. C constants can be divided into two major
categories:
Numeric constant (Integer constant and Real constant)
Character constant (Single character constant and String constant)
#include<stdio.h>
void main()
{
const int x=10;
printf(%d,x);
}
2.11.3 Variables:
An entity that may vary during program execution is called a variable. Variable names are names given to locations in memory.
These locations can contain integer, real or character constants.
36
Rules for Constructing Variable Names:
A variable name is any combination of 1 to 31 alphabets, digits or underscores.
The first character in the variable name must be an alphabet or underscore.
No commas or blanks are allowed within a variable name.
No special symbol other than an underscore (as in gross_sal) can be used in a variable name.
e.g. simple_intrest,SUM, m1 etc.
2.11.4 Keywords:
Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). The
keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is
not allowed by the computer. There are only 32 keywords available in C.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
2.11.5 Identifiers:
Identifiers refers to the name of variables, functions and arrays. These are user-defined names and consists of a sequence of letters
and digits, with a letter as first character. Both upper case and lowercase letters are permitted. Underscore is permitted in
identifier. Rules for naming an identifier are same as rules for naming a variable.
Keyword: int
Minimum Range: -32768 to 32767
Format specifier: %d
An integer is a whole number (a number without a fractional part). It can be positive or negative numbers like 1, -2, 3, etc., or
0.The sizes of the integer variables depend on the hardware and operating system of the computer.
Keyword: float
Minimum Range:-3.4e38 to +3.4e38
Format specifier: %f
37
Floating point numbers are numbers with a decimal point. The float type can take large floating point numbers with a small degree
of precision (Precision is simply the number of decimal places to which a number can be calculated with accuracy. If a number
can be calculated to three decimal places, it is said to have three significant digits.)
Keyword: double
Minimum Range:-1.7e308 to +1.7e308
Format specifier: %lf
Double-precision floating point numbers are also numbers with a decimal point. We know that the float type can take large
floating point numbers with a small degree of precision but the double-precision double type can hold even larger numbers with a
higher degree of precision.
Keyword:char
Minimum Range:-128 to +127
Format specifier: %c
char is a special integer type designed for storing single characters. The integer value of a char corresponds to an ASCII
(American Standard Code for Information Interchange) character. E.g., a value of 65 corresponds to the letter A, 66 corresponds
to B, 67 to C, and so on.
Keyword: void
Minimum Range: nil
Format specifier: nil
The type specifier void indicates that no value is available. It has three main functions
The fundamental data types explained above have the following modifiers.
short
long
signed
unsigned
The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI
has the following rules:
38
short int <=int <= long int
What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int'
should be less or the same bytes than a 'long int'. What this means in the real world is:
These figures only apply to todays generation of PCs. Mainframes and midrange machines could use different figures, but would
still comply with the rule above. We can find out how much storage is allocated to a data type by using the sizeof operator.
#include<stdio.h>
void main()
{
printf("sizeof(char) == %d\n", sizeof(char));
printf("sizeof(short) == %d\n", sizeof(short));
printf("sizeof(int) == %d\n", sizeof(int));
printf("sizeof(long) == %d\n", sizeof(long));
printf("sizeof(float) == %d\n", sizeof(float));
printf("sizeof(double) == %d\n", sizeof(double));
printf("sizeof(long double) == %d\n", sizeof(long double));
printf("sizeof(long long) == %d\n", sizeof(long long));
}
The const qualifier is used to tell C that the variable value cannot change after initialisation.
Now pi cannot be changed at a later time within the program.Another way to define constants is with the #define preprocessor
which has the advantage that it does not use any storage
The volatile qualifier declares a data type that can have its value changed in ways outside the control or detection of the compiler
(such as a variable updated by the system clock or by another program). This prevents the compiler from optimizing code
referring to the object by storing the object's value in a register and re-reading it from there, rather than from memory, where it
may have changed. You will use this qualifier once you will become expert in "C". So for now just proceed.
39
Q 11. What are variables, constants, identifiers and keywords?
2.12 Storage rules
Q 12. Enumerate Classes in C variables and identifiers?
for naming
Q 13.variable
Every Write a in
short note on fundamental
C programming has twoand extendedtype
properties: datatypes in C language?
and storage class. Type refers to the data type of variable whether it is
character or integer or floating-point value etc. And storage class determines how long it stays in existence.
The storage class of a variable defines the scope (visibility) and life time of variables and/or functions declared within a
C Program. In addition to this, the storage class gives the following information about the variable or the function.
It is used to determine the part of memory where storage space will be allocated for that variable or function (whether the
variable/function will be stored in a register or in RAM)
it specifies how long the storage allocation will continue to exist for that function or variable.
It specifies the scope of the variable or function. That is, the part of the C program in which the variable name is visible,
or accessible.
It specifies whether the variable or function has internal, external, or no linkage
It specifies whether the variable will be automatically initialized to zero or to any indeterminate value
void Check();
int a=5;
/* a is global variable because it is outside every function */
int main(){
a+=4;
Check();
return 0;
}
void Check(){
++a;
/* ----- Variable a is not declared in this function but, works in any function as they are global variable ------- */
printf("a=%d\n",a);
}
Output
a=10
40
2.12.4 Static Storage Class
The value of static variable persists until the end of the program. A variable can be declared static using keyword: static. For
example:
static int i;
Here, i is a static variable.
#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int c=0;
printf("%d\t",c);
c=c+5;
}
Output
0 5 10
During first function call, it will display 0. Then, during second function call, variable c will not be initialized to 0 again, as it is
static variable. So, 5 is displayed in second function call and 10 in third call.
If variable c had been automatic variable, the output would have been:
0 0 0
Accessibility Accessible within the Accessible within all Accessible within the Local: Accessible
function or block in program files that are a function or block in within the function or
which it is declared part of the program which it is declared block in which it is
declared
Global: Accessible
within the program in
which it is declared
Storage Main Memory Main Memory CPU Register Main Memory
Existence Exists when the Exists throughout the Exists when the Local: Retains value
function or block in execution of the function or block in between function calls
which it is declared is program which it is declared is or block entries
entered. Ceases to entered. Ceases to Global: Preserves
exist when the control exist when the control value in program files
returns from the returns from the
function or the block function or the block
in which it was in which it was
declared declared
Default Garbage Zero Garbage Zero
value
2.13 Operators in C
C language supports a lot of operators to be used in expressions. These operators can be categorized into the following major
groups:
Arithmetic operators
Relational Operators
41
Equality Operators
Logical Operators
Unary Operators
Conditional Operators
Bitwise Operators
Assignment operators
Comma Operator
Sizeof Operator
Operator Meaning
42
A B A||B
0 0 0 A !A
0 1 1 0 1
1 0 1 1 0
1 1 1
The conditional operator operator (?:) is just like an if .. else statement that can be written within expressions. The syntax of the
conditional operator is
exp1 ? exp2 : exp3
Here, exp1 is evaluated first. If it is true then exp2 is evaluated and becomes the result of the expression, otherwise exp3 is
evaluated and becomes the result of the expression. For example,
large = ( a > b) ? a : b
Conditional operators make the program code more compact, more readable, and safer to use as it is easier both to check and
guarantee that the arguments that are used for evaluation.
Conditional operator is also known as ternary operator as it is neither a unary nor a binary operator; it takes three operands.
2.13.7Bitwise Operators
Bitwise operators perform operations at bit level. These operators include: bitwise AND, bitwise OR, bitwise XOR and shift
operators.
The bitwise AND operator (&) is a small version of the boolean AND (&&) as it performs operation on bits instead of
bytes, chars, integers, etc.
x y x&y
0 0 0
0 1 0
1 0 0
1 1 1
The bitwise OR operator (|) is a small version of the boolean OR (||) as it performs operation on bits instead of bytes,
chars, integers, etc.
x y x|y
0 0 0
0 1 1
1 0 1
1 1 1
43
The bitwise NOT (~), or complement, is a unary operation that performs logical negation on each bit of the operand. By
performing negation of each bit, it actually produces the ones' complement of the given binary value.
x ~x
0 1
1 0
The bitwise XOR operator (^) performs operation on individual bits of the operands. The result of XOR operation is
shown in the table
x y x^y
0 0 0
0 1 1
1 0 1
1 1 0
In bitwise shift operations, the digits are moved, or shifted, to the left or right. The CPU registers have a fixed number of available
bits for storing numerals, so when we perform shift operations; some bits will be "shifted out" of the register at one end, while the
same number of bits are "shifted in" from the other end.
In a left arithmetic shift, zeros are shifted in on the right. For example;
If a right arithmetic shift is performed on an unsigned integer then zeros are shifted on the left.
The assignment operator is responsible for assigning values to the variables. While the equal sign (=) is the
fundamental assignment operator, C also supports other assignment operators that provide shorthand ways to
represent common variable assignments. They are shown in the table.
sizeof is a unary operator used to calculate the sizes of data types. It can be applied to all data types. The operator returns the size
of the variable, data type or expression in bytes. 'sizeof' operator is used to determine the amount of memory space that the
variable/expression/data type will take. For example,
int a = 10;
result = sizeof(a);
then result = 2
Type casting is a way to convert a variable from one data type to another data type. For example, if we want to store a long value
into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast
operator as follows:
(type_name) expression
Consider the following example where the cast operator causes the division of one integer variable by another to be performed as
a floating-point operation:
#include <stdio.h>
void main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
When the above code is compiled and executed, it produces the following result:
It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to
type double and finally it gets divided by count yielding a double value.
Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the
use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are
necessary.
45
Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either
to int or unsigned int. Consider an example of adding a character in an int:
#include <stdio.h>
void main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}
When the above code is compiled and executed, it produces the following result:
Here, value of sum is coming as 116 because compiler is doing integer promotion and converting the value of 'c' to ascii before
performing actual addition operation.
The usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first
performs integer promotion, if operands still have different types then they are converted to the type that appears highest in the
following hierarchy:
The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||. Let us
take following example to understand the concept:
#include <stdio.h>
void main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}
When the above code is compiled and executed, it produces the following result:
46
Here, it is simple to understand that first c gets converted to integer but because final value is double, so usual arithmetic
conversion applies and compiler convert i and c into float and add them yielding a float result.
(a>b+c&&d)
((a>(b+c))&&d)
(a>b+c&&d)
((a>(b+c))&&d)
a==b!=c
Here, operators == and != have same precedence. The associativity of both == and != is left to right, i.e, the expression in left is
executed first and execution take pale towards right. Thus, a==b!=cequivalent to :
(a==b)!=c
The table below shows all the operators in C with precedence and associativity.
Note: Precedence of operators decreases from top to bottom in the given table.
48
<<= Assign bitwise OR
>>= Assign left shift
Assign right shift
, Separator of expressions Left to right
Questions
1. In C programming what will be the value of r if r=p%q where p=-17 and q=5.
2. In C programming, what will be the output of the following code? Explain your answer.
3. What are identifiers, variables and constants? Mention rules to construct an identifier. Give some examples.
4. What is the meaning of scope of a variable? Give various types of scope in C programming?
5. Write a Program (WAP) in C in which values of variables x, y, x are input by the user, then their values are rotated such
that x has value of y, y has value of z, and z has value of y.
6. Explain datatypes in C language, mentioning their range, space they occupy in memory and keyword used for their
representation in memory.
7. Explain four storage classes in C, mentioning their place of storage, default initial value, scope and life of each item
8. What do you mean by operator precedence and associativity?
9. What do you mean by implicit and explicit typecasting?
10. Give any four format specifiers used in printf()
11. Explain the ternary operator in detail with example.
12. Explain various operators present in C?
13. Explain the general structure of a C program?
14. Explain logical and bit operators with example.
15. Explain logical and bit operators with example.
16. Write about the formatted and unformatted Input/Output functions in C.
Unit 3
Introduction
49
We have seen that a C program is a set of statements which are normally executed sequentially in the order in which they appear.
However, in practice, we have a number of situations where we may have to change the order of execution of the statements based
on certain conditions or repeat a group of statements until certain specified conditions are met. This involves a kind of decision
making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements
accordingly.
3.1 IF Statement:
Theif statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a
two way decision statement and is used in conjunction with an expression. It takes the following form:
if (test expression)
{
statement block 1;
}
statement x;
The statement block 1 may be a single statement or a group of statements. If the testexpression is true, the statement block 1 will
be executed; otherwise the statement block 1 will be skipped and the control will jump to the statement-x. When the condition is
true both the statement block 1 and the statement x are executed in sequence.
Flowchart
Program
void main()
{
int age;
printf(\nEnter Age);
scanf(%d,&age);
if(age>=18)
printf(\nYou are eligible to vote);
}
Output
Enter Age
20
You are eligible to vote
Enter Age
10
No output
The second run of the program does not produced any message because the expression (age>=18) results to false.
50
3.2 IF-ELSE Statement:
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 and finally the control will pass to statement x. Therefore, statement x is
executed in every case. It takes the following form:
if (test expression)
{
statement block1;
}
else
{
statement block 2;
}
statement x;
Flowchart
Program
// Program to find whether a number is even or odd.
#include<stdio.h>
void main()
{
int a;
printf("\n Enter the value of a : ");
scanf("%d", &a);
if(a%2==0)
printf("\n %d is even", a);
else
printf("\n %d is odd", a);
return 0;
}
Output
Enter the value of a
20
20 is even
Enter the value of a
13
13 is odd
if(test condition1)
{
If(test condition2)
51
{
statement block 1;
}
else
{
statement block 2;
}
}
else
{
statement block x;
}
statement y;
If the condition 1 is false, the statement block x will be executed; otherwise it continues to perform second test. If the condition 2
is true the statementblock 1 will be evaluated otherwise statementblock 2 will be executed and then the control is transferred to
statementy.
Flowchart
Program
void main()
{
int A,B,C;
printf(\nEnter the numbers);
scanf(%d%d%d, &A,&B,&C);
if(A>B)
{
if(A>C)
printf(A);
else
printf(C);
}
else
{
if(B>C)
printf(B);
else
printf(C);
}
52
This construct is known as the else if ladder. The conditions are evaluated from the top (of the ladder) downwards. As soon as true
condition is found the statement associated with it is executed and the control is transferred to the statement-x (skipping the rest of
the ladders). When all the conditions are false then the final else containing default statement will be executed.
Flowchart
Program
// Program to classify a number as positive, negative or zero.
#include<stdio.h>
main()
{
int num;
printf("\n Enter any number : ");
scanf("%d", &num);
if(num==0)
printf("\n The value is equal to zero");
else if(num>0)
printf("\n The number is positive");
else
printf("\n The number is negative");
return 0;
53
}
switch ( expression )
{
case value-1:
block-1
break;
case value-2:
block-2
break;
default:
default-block
}
statement-x;
Flowchart
Program
void main()
{
char grade;
printf(Enter the grade of student);
scanf(%c,&grade);
switch(grade)
{
case 'A':
printf("\n Excellent");
break;
case 'B':
printf("\n Good");
break;
case 'C':
printf("\n Fair");
break;
54
default:
printf("\n Invalid Grade");
} }
The label can be anywhere in the program either before or after the goto label; statement.
55
Program
int num, sum=0;
read: // label for go to statement
printf("\n Enter the number. Enter 999 to end : ");
scanf("%d", &num);
if (num != 999)
{
if(num < 0)
goto read; // jump to label- read
sum += num;
goto read; // jump to label- read
}
printf("\n Sum of the numbers entered by the user is = %d", sum);
The conditional expression is evaluated first. If the result is nonzero, expression1 is evaluated and is returned as the value of the
conditional expression. Otherwise expression2 is evaluated and its value is returned. For example the segment
if (x<0)
flag=0;
else
flag=1;
Can be written as
flag=(x<0)?0:1;
Program
#include <stdio.h>
main()
{
int a , b;
a = 10;
printf( "Value of b is %d\n", (a == 1) ? 20: 30 );
56
printf( "Value of b is %d\n", (a == 10) ? 20: 30 );
}
The entry controlled loop is also known as pre-test loop and exit controlled loop is known as post-test loop.
Iterative statements are used to repeat the execution of a list of statements, depending on the value of an integer expression. In this
section, we will discuss all these statements.
statement x;
while (condition)
{
statement_block;
}
statement y;
57
Program to print numbers from 0 to 10 using while loop
#include<stdio.h>
int main()
{
int i = 0;
while(i<=10)
{
printf(\n %d, i);
i = i + 1; // condition updated
}
return 0;
}
statement x;
do
{
statement_block;
} while (condition);
statement y;
58
printf(\n %d, i);
i = i + 1;
} while(i<=10);
return 0;
}
When a for loop is used, the loop variable is initialized only once.
With every iteration of the loop, the value of the loop variable is updated and the condition is checked. If the condition is true,
the statement block of the loop is executed else, the statements comprising the statement block of the for loop are skipped and
the control jumps to the immediate statement following the for loop body.
Updating the loop variable may include incrementing the loop variable, decrementing the loop variable or setting it to some
other value like, i +=2, where i is the loop variable.
Look at the code given below which print first n numbers using a for loop.
Program
#include<stdio.h>
int main()
{
int i, n;
printf(\n Enter the value of n :);
scanf(%d, &n);
for(i=0; i<= n; i++)
{
printf(\n %d, i);
}
return 0;
}
59
The break statement is used to terminate the execution of the nearest enclosing loop in which it appears. When compiler
encounters a break statement, the control passes to the statement that follows the loop in which the break statement appears. Its
syntax is quite simple, just type keyword break followed with a semi-colon.
break;
In switch statement if the break statement is missing then every case from the matched case label to the end of the switch,
including the default, is executed.
Program
int i;
for(i=1; i<= 5; i++)
{ if (i==3)
break;
printf(\t %d, i);
}
Output
1
2
continue;
If placed within a for loop, the continue statement causes a branch to the code that updates the loop variable.
Program
int i;
for(i=1; i<= 5; i++)
{ if (i==3)
continue;
printf(\t %d, i);
}
Output
1
2
4
5
Functions
3.14 Introduction
60
C enables its programmers to break up a program into segments commonly known as functions, each of which can be written
more or less independently of the others. Every function in the program is supposed to perform a well-defined task. Therefore, the
program code of one function is completely insulated from that of other functions. Every function has a name which acts as an
interface to the outside world in terms of how information is transferred to it and how results generated by the function are
transmitted back from it.
In the fig, main() calls another function, func1() to perform a well-defined task. main() is known as the calling function and
func1() is known as the called function. When the compiler encounters a function call, instead of executing the next statement in
the calling function, the control jumps to the statements that are a part of the called function. After the called function is executed,
the control is returned back to the calling program.
61
Example, float avg ( int a, int b);
The no. and the order of arguments in the function header must be same as that given in function declaration statement.
function_name(variable1, variable2, );
Program
#include<stdio.h>
int sum(int a, int b); // FUNCTION DECLARATION
int main()
{
int num1, num2, total = 0;
printf(\n Enter the first number : );
scanf(%d, &num1);
printf(\n Enter the second number : );
scanf(%d, &num2);
total = sum(num1, num2); // FUNCTION CALL
printf(\n Total = %d, total);
return 0;
}
// FUNCTION DEFNITION
int sum ( int a, int b) // FUNCTION HEADER
{ // FUNCTION BODY
return (a + b);
}
62
3.21.1 Call by value
In the Call by Value 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.
#include<stdio.h>
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);
}
The output of this program is:
The value of num before calling the function = 2
The value of num in the called function = 20
The value of num after calling the function = 2
#include<stdio.h>
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);
}
The output of this program is:
The value of num before calling the function = 2
The value of num in the called function = 20
The value of num after calling the function = 20
Recursive case of the factorial function will call itself but with a smaller value of n, this case can be given as
#include<stdio.h>
int Fact(int)
{ if(n==1)
retrun 1;
return (n * Fact(n-1));
}
main()
{ int num;
scanf(%d, &num);
printf(\n Factorial of %d = %d, num, Fact(num));
return 0;
}
main()
{ int n;
printf(\n Enter the number of terms in the series : );
scanf(%d, &n);
for(i=0;i<n;i++)
printf(\n Fibonacci (%d) = %d, i, Fibonacci(i));
}
int Fibonacci(int num)
{ if(num == 0 || num==1)
return num;
return ( Fibonacci (num - 1) + Fibonacci(num 2));
}
64
3.23.1 Direct Recursion
A function is said to be directly recursive if it explicitly calls itself. For example, consider the function given below.
65
3.24 Pros and cons of recursion
Pros: Recursive solutions often tend to be shorter and simpler than non-recursive ones.
Code is clearer and easier to use
Recursion represents like the original formula to solve a problem.
Follows a divide and conquer technique to solve problems
In some (limited) instances, recursion may be more efficient
Cons: For some programmers and readers, recursion is a difficult concept.
Recursion is implemented using system stack. If the stack space on the system is limited, recursion to a deeper level will
be difficult to implement.
Aborting a recursive process in midstream is slow and sometimes nasty.
Using a recursive function takes more memory and time to execute as compared to its non-recursive counter part.
It is difficult to find bugs, particularly when using global variables
return 0;
}
printf("Enter an integer\n");
scanf("%d", &n);
t = n;
while (t != 0)
{
remainder = t % 10;
sum = sum + remainder;
t = t / 10;
}
return 0;
}
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
printf("Enter an integer\n");
scanf("%d",&number);
temp = number;
while( temp != 0 )
{
remainder = temp%10;
sum = sum + remainder*remainder*remainder;
temp = temp/10;
}
if ( number == sum )
printf("Entered number is an armstrong number.\n");
else
printf("Entered number is not an armstrong number.\n");
return 0;
}
67
}
gcd = a;
lcm = (x*y)/gcd;
68
Question
1. Describe about the types of looping statements in C with necessary syntax.
2. Write a C program to find the multiplication of two matrices.
3. What are the types of function? Write a C program to find the factorial of a given number using recursion.
4. What is the difference between break and continue? Describe the structure of switch-case with neat example.
5. What are the different types of functions? Write a program in C to short list of names of students in an ascending order.
6. Write a program to print following pattern
1
23
456
7 8 9 10
7. Define recursive function. Write a program in C to generate Fibnocii series (0 1 1 2 3 5 8 13) using recursive function.
8. Write a C program to find the sum of individual digits in a five digit number.
9. Write the difference between call by value and call by reference with suitable example.
10. Write a program to find greatest among three numbers using conditional operator.
11. Differentiate between nested-if and switch statements in C with example.
12. Write a program in C to sort list of 10 integers in an ascending order.
13. Write a program to multiply the two matrices of MxN.
14. Write the purpose and syntax of at least two iterative statements in C.
15. WAP to generate fabonacci series up to the last term less than 100. Also calculate sum and total count of the fabonacci
numbers.
16. What is sorting? Give flowchart and algorithm to sort the integer numbers.
17. Given two matrices of 4x4. Write the functions sum_matrix() and multiply_matix() to add and multiply two matices.
18. Differentiate between call by value and call by reference.
19. Write a program to calculate GCD.
20. WAP to calculate the multiplication of all the digits of a 5 digit number.
21. Write a program which stores the marks of N students in integer array. Calculate average marks obtained and deviation from
the average.
22. Explain ternary operator.
23. Define user defined and library functions.
24. What are iterative control statements? Differentiate between while loop and do-while loop.
25. Define recursion. Give its advantage. Which data structure is used to implement recursion? Write a program to calculate
factorial of a number using recursion.
26. Write a program to check whether a number is perfect number or not. If the sum of factor is equal to number itself then it is a
perfect number. E.g Factor of 6 are 1, 2, 3 whose sum 1+2+3=6.
27. Write a program to find the prime numbers between the given range.
69
Unit 4
4.1 Array
An array is a collection of data items, all of the same type, accessed using a common name.
A one-dimensional array is like a list. A two dimensional array is like a table; The C language places no limits on the
number of dimensions in an array, though specific implementations may.
Array variables are declared identically to variables of their data type, except that the variable name is followed by one
pair of square [ ] brackets for each dimension of the array.
Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets.
Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.
Examples:
int i_Array[ 10 ];
float f_Array[ 1000 ];
Arrays may be initialized when they are declared, just as any other variables.
Place the initialization data in curly {} braces following the equals sign. Note the use of commas in the examples below.
An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array
elements will be automatically initialized to zero.
If an array is to be completely initialized, the dimension of the array is not required. The compiler will automatically size
the array to fit the initialized data. ( Variation: Multidimensional arrays - see below. )
Examples:
int i_Array[ 6 ] = { 1, 2, 3, 4, 5, 6 };
float f_Array[ 100 ] = { 1.0, 5.0, 20.0 };
VERY IMPORTANT: Array indices start at zero in C, and go to one less than the size of the array. For example, a five
element array will have indices zero through four. This is because the index in C is actually an offset from the beginning
of the array. ( The first element is at the beginning of the array, and hence has zero offset. )
The first sample program uses loops and arrays to calculate the first twenty Fibonacci numbers. Fibonacci numbers are
used to determine the sample points used in certain optimization methods.
#include <stdlib.h>
#include <stdio.h>
70
int i, fibonacci[ 20 ];
fibonacci[ 0 ] = 0;
fibonacci[ 1 ] = 1;
Multi-dimensional arrays are declared by providing more than one set of square [ ] brackets after the variable name in the
declaration statement.
One dimensional arrays do not require the dimension to be given if the array is to be completely initialized. By analogy,
multi-dimensional arrays do not require the first dimension to be given if the array is to be completely initialized. All
dimensions after the first must be given in any case.
For two dimensional arrays, the first dimension is commonly considered to be the number of rows, and the second
dimension the number of columns.
Two dimensional arrays are considered by C/C++ to be an array of ( single dimensional arrays ). For example, "int
numbers[ 5 ][ 6 ]" would refer to a single dimensional array of 5 elements, wherein each element is a single dimensional
array of 6 integers.
C stores two dimensional arrays by rows, with all elements of a row being stored together as a single unit.
Multidimensional arrays may be completely initialized by listing all data elements within a single pair of curly {} braces,
as with single dimensional arrays.
#include <stdlib.h>
#include <stdio.h>
4.6 Structures
A structure is a collection of variables referenced under one name, providing a convenient means of keeping related information
together. A structure declaration forms a template that can be used to create structure objects (that is, instances of a structure). The
variables that make up the structure are called members. (Structure members are also commonly referred to as elements or fields.)
The following code fragment shows how to declare a structure that defines the name and address fields. The keyword struct tells
the compiler that a structure is being declared.
struct addr
{
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int zip;
};
Notice that the declaration is terminated by a semicolon. This is because a structure declaration is a statement. Also, the structure
tag addr identifies this particular data structure and is its type specifier. At this point, no variable has actually been created. Only
the form of the data has been defined.
When you declare a structure, you are defining an aggregate type, not a variable. Not until you declare a variable of that type does
one actually exist. To declare a variable (that is, a physical object) of type addr, write:
struct addr info;
This declares a variable of type addr called addr_info. Thus, addr describes the form of a structure (its type), and addr_info is
an instance (an object) of the structure. When a structure variable (such as addr_info) is declared, the compiler automatically
allocates Sufficient memory to accommodate all of its members. The general form of a structure declaration is
struct tag {
type member-name;
type member-name;
type member-name;
} structure-variables;
The general form for accessing a member of a structure is object-name.member-name Therefore, to print the ZIP code on the
screen, write
printf("%lu", addr_info.zip);
In the same fashion, the character array addr_info.name can be used in a call to gets( ), as shown here:
gets(addr_info.name);
This creates 100 sets of variables that are organized as defined in the structure addr. To access a specific structure, index the array
name. For example, to print the ZIP code of structure 3, write
printf("%lu", addr_list[2].zip);
Like all array variables, arrays of structures begin indexing at 0.
When you want to refer to a specific structure within an array of structures, index the structure array name. When you want to
index a specific element of a structure, index the element. Thus, the following statement assigns 'X' to the first character of name
in the third structure of addr_list.
addr_list[2].name[0] = 'X';
For example,
consider this structure:
struct fred
{
char x;
int y;
float z;
char s[10];
} mike;
Here are examples of each member being passed to a function:
func(mike.x); /* passes character value of x */
func2(mike.y); /* passes integer value of y */
func3(mike.z); /* passes float value of z */
func4(mike.s); /* passes address of string s */
func(mike.s[2]); /* passes character value of s[2] */
In each case, it is the value of a specific element that is passed to the function. It does not matter that the element is part of a larger
unit.
If you wish to pass the address of an individual structure member, put the & operator before the
structure name. For example, to pass the address of the members of the structure mike, write
func(&mike.x); /* passes address of character x */
func2(&mike.y); /* passes address of integer y */
func3(&mike.z); /* passes address of float z */
func4(mike.s); /* passes address of string s */
func(&mike.s[2]); /* passes address of character s[2] */
Note that the & operator precedes the structure name, not the individual member name.
73
When a structure is used as an argument to a function, the entire structure is passed using the normal call-by-value method. Of
course, this means that any changes made to the contents of the parameter inside the function do not affect the structure passed as
the argument.
When using a structure as a parameter, remember that the type of the argument must match the type of the parameter. For
example, in the following program both the argument arg and the parameter parm are declared as the same type of structure.
#include <stdio.h>
/* Define a structure type. */
struct struct_type {
int a, b;
char ch;
};
void f1(struct struct_type parm);
int main(void)
{
struct struct_type arg;
arg.a = 1000;
f1(arg);
return 0;
}
void f1(struct struct_type parm)
{
printf(''%d", parm.a);
}
As this program illustrates, if you will be declaring parameters that are structures, you must make the declaration of the structure
type global so that all parts of your program can use it. For example, had struct_type been declared inside main( ), it would not
have been visible to f1( ).
When a structure is a member of another structure, it is called a nested structure. For example, the structure address is nested
inside emp in this example:
struct emp {
struct addr address; /* nested structure */
float wage;
} worker;
Here, structure emp has been defined as having two members. The first is a structure of type addr, which contains an employee's
address. The other is wage, which holds the employee's wage. The following code fragment assigns 93456 to the zip element of
address.
worker.address.zip = 93456;
4.7 Unions
A union is a memory location that is shared by two or more different types of variables. A union provides a way of interpreting the
same bit pattern in two or more different ways. Declaring a union is similar to declaring a structure. Its general form is
union tag {
type member-name;
type member-name;
type member-name;
.
.
.
} union-variables;
For example:
union u_type {
int i;
char ch;
};
This declaration does not create any variables. You can declare a variable either by placing its name at the end of the declaration
or by using a separate declaration statement. To declare a union variable called cnvt of type u_type using the definition just
given, write
union u_type cnvt;
In cnvt, both integer i and character ch share the same memory location. Of course, i occupies 2
bytes (assuming 2-byte integers), and ch uses only 1.
When a union variable is declared, the compiler automatically allocates enough storage to hold the largest member of the union.
For example, (assuming 2-byte integers) cnvt is 2 bytes long so that it can hold i, even though ch requires only 1 byte.
74
To access a member of a union, use the same syntax that you would use for structures: the dot and arrow operators. If you are
operating on the union directly, use the dot operator. If the union is accessed through a pointer, use the arrow operator. For
example, to assign the integer 10 to element i of cnvt, write
cnvt.i = 10;
4.8 Enumerations
An enumeration is a set of named integer constants. Enumerations are common in everyday life. For example, an enumeration of
the coins used in the United States is penny, nickel, dime, quarter, half-dollar, dollar.
Enumerations are defined much like structures; the keyword enum signals the start of an enumeration type. The general form for
enumerations is
enum tag { enumeration list } variable_list ;
Here, both the tag and the variable list are optional. (But at least one must be present.) The following code fragment defines an
enumeration called coin:
enum coin { penny, nickel, dime, quarter, half_dollar, dollar};
The enumeration tag name can be used to declare variables of its type. The following declares
money to be a variable of type coin:
enum coin money;
Given these declarations, the following types of statements are perfectly valid:
money = dime;
if(money==quarter)
printf(''Money is a quarter.\n");
The key point to understand about an enumeration is that each of the symbols stands for an integer value. As such, they can be
used anywhere that an integer can be used. Each symbol is given a value one greater than the symbol that precedes it. The value of
the first enumeration symbol is 0. Therefore,
printf("%d %d", penny, dime);
displays 0 2 on the screen.
You can specify the value of one or more of the symbols by using an initializer. Do this by
following the symbol with an equal sign and an integer value. Symbols that appear after an
initializer are assigned values greater than the preceding value. For example, the following code
assigns the value of 100 to quarter:
enum coin { penny, nickel, dime, quarter=100, half_dollar, dollar};
Now, the values of these symbols are
penny 0
nickel 1
dime 2
quarter 100
half_dollar 101
dollar 102
4.9 Strings
The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array.
Character arrays are many a time also called strings.
A string constant is a one-dimensional array of characters terminated by a null ( \0 ). For example,
char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;
Each character in the array occupies one byte of memory and the last character is always \0. \0 is called null character. A string
not terminated by a \0 is not really a string, but merely a collection of characters.
/* Program to demonstrate printing of a string */
main( )
{
char name[ ] = "Klinsman" ;
int i = 0 ;
while ( i <= 7 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
And here is the output...
Klinsman
Can we write the while loop without using the final value 7? We can; because we know that each character array always ends with
a \0. Following program illustrates this.
main( )
{
75
char name[ ] = "Klinsman" ;
int i = 0 ;
while ( name[i] != `\0' )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
And here is the output...
Klinsman
The %s used in printf( ) is a format specification for printing out a string. The same specification can be used to receive a string
from the keyboard, as shown below.
main( )
{
char name[25] ;
printf ( "Enter your name " ) ;
scanf ( "%s", name ) ;
printf ( "Hello %s!", name ) ;
}
And here is a sample run of the program...
Enter your name Debashish
Hello Debashish!
Note that the declaration char name[25] sets aside 25 bytes under the array name[ ], whereas the scanf( ) function fills in the
characters typed at keyboard into this array until the enter key is hit. Once enter is hit, scanf( ) places a \0 in the array.
While entering the string using scanf( ) we must be cautious about two things:
a) The length of the string should not exceed the dimension of the character array. This is because the C compiler doesnt perform
bounds checking on character arrays. Hence, if you carelessly exceed the bounds there is always a danger of overwriting
something important, and in that event, you would have nobody to blame but yourselves.
b) scanf( ) is not capable of receiving multi-word strings. Therefore names such as Debashish Roy would be unacceptable. The
way to get around this limitation is by using the function gets( ). The usage of functions gets( ) and its counterpart puts( ) is
shown below.
main( )
{
char name[25] ;
printf ( "Enter your full name " ) ;
gets ( name ) ;
puts ( "Hello!" ) ;
puts ( name ) ;
}
And here is the output...
Enter your name Debashish Roy
Hello!
Debashish Roy
unlike printf( ), puts( ) places the cursor on the next line.
76
Suppose we wish to store Hello. We may either store it in a string or we may ask the C compiler to store it at some location in
memory and assign the address of the string in a char pointer. This is shown below:
char str[ ] = "Hello" ;
char *p = "Hello" ;
There is a subtle difference in usage of these two forms. For example, we cannot assign a string to another, whereas, we can assign
a char pointer to another char pointer. This is shown in the
following program.
main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ;
char *q ;
str2 = str1 ; /* error */
q = s ; /* works */
}
Also, once a string has been defined it cannot be initialized to another set of characters. Unlike strings, such an operation is
perfectly valid with char pointers.
main( )
{
char str1[ ] = "Hello" ;
char *p = "Hello" ;
str1 = "Bye" ; /* error */
p = "Bye" ; /* works */
}
Out of the above list we shall discuss the functions strlen( ), strcpy( ), strcat( ) and strcmp( ), since these are the most commonly
used functions.
strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in the following program.
main( )
{
char arr[ ] = "Bamboozled" ;
int len1, len2 ;
len1 = strlen ( arr ) ;
77
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\nstring = %s length = %d", arr, len1 ) ;
printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
}
The output would be...
string = Bamboozled length = 10
string = Humpty Dumpty length = 13
Note that in the first call to the function strlen( ), we are passing the base address of the string, and the function in turn returns the
length of the string. While calculating the length it doesnt count
\0. Even in the second call,
len2 = strlen ( "Humpty Dumpty" ) ;
what gets passed to strlen( ) is the address of the string and not the string itself. Can we not write a function xstrlen( ) which
imitates the standard library function strlen( )? Let us give it a try...
strcpy( )
This function copies the contents of one string into another. The base addresses of the source and target strings should be supplied
to this function. Here is an example of strcpy( ) in action...
main( )
{
char source[ ] = "Sayonara" ;
char target[20] ;
strcpy ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Sayonara
target string = Sayonara
Let us now attempt to mimic strcpy( ),via our own string copy function, which we will call xstrcpy()
main( )
{
char source[ ] = "Sayonara" ;
char target[20] ;
xstrcpy ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
78
xstrcpy ( char *t, char *s )
{
while ( *s != '\0' )
{
*t = *s ;
s++ ;
t++ ;
}
*t = '\0' ;
}
The output of the program would be...
source string = Sayonara
target string = Sayonara
Note that having copied the entire source string into the target string, it is necessary to place a \0 into the target string, to mark its
end.
strcat( )
This function concatenates the source string at the end of the target string. For example, Bombay and Nagpur on
concatenation would result into a string BombayNagpur. Here is an example of strcat( ) at work.
main( )
{
char source[ ] = "Folks!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Folks!
target string = HelloFolks!
strcmp( )
This is a function which compares two strings to find out whether they are same or different. The two strings are compared
character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first. If the two strings
are identical, strcmp( ) returns a value zero. If theyre not, it returns the numeric difference between the ASCII values of the first
non-matching pairs of characters. Here is a program which puts strcmp( ) in action.
main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
And here is the output...
0 4 -32
In the first call to strcmp( ), the two strings are identicalJerry and Jerryand the value returned by strcmp( ) is zero. In the
second call, the first character of Jerry doesn't match with the first character of Ferry and the result is 4, which is the numeric
difference between ASCII value of J and ASCII value of F. In the third call to strcmp( ) Jerry doesnt match with Jerry
boy, because the null character at the end of Jerry doesnt match the blank in Jerry boy. The value returned is -32, which is
the value of null character minus the ASCII value of space, i.e., \0 minus
, which is equal to -32.
#define FOUND 1
#define NOTFOUND 0
main( )
{
79
char masterlist[6][10] = {
"akshay",
"parag",
"raman",
"srinivas",
"gopal",
"rajesh"
};
int i, flag, a ;
char yourname[10] ;
printf ( "\nEnter your name " ) ;
scanf ( "%s", yourname ) ;
flag = NOTFOUND ;
for ( i = 0 ; i <= 5 ; i++ )
{
a = strcmp ( &masterlist[i][0], yourname ) ;
if ( a == 0 )
{
printf ( "Welcome, you can enter the palace" ) ;
flag = FOUND ;
break ;
}
}
if ( flag == NOTFOUND )
printf ( "Sorry, you are a trespasser" ) ;
}
And here is the output for two sample runs of this program...
Enter your name dinesh
Sorry, you are a trespasser
Enter your name raman
Welcome, you can enter the palace
The order of the subscripts in the array declaration is important. The first subscript gives the number of names in the array, while
the second subscript gives the length of each item in the array. Instead of initializing names, had these names been supplied from
the keyboard, the program segment would have looked like this...
for ( i = 0 ; i <= 5 ; i++ )
scanf ( "%s", &masterlist[i][0] ) ;
80
Questions
1. Write a program in C to read a (54) matrix using array and to calculate the following:
81
Unit 5
Here we declare that we will have an integer valued variable named number. On the computer each variable is stored in some
memory location. You can visualize the memory layout of a computer as a consecutive set of cells, each of which has an
address. A cell is typically a byte. Say your computer has 64 KB of memory. What this means is that it has 64 X 1024 = 65536
bytes available. (1 KB is 1024 bytes.) On computer each memory location will have an address. For instance, the first location
could have the address of 0 and the last location could have the address of 65535. Size of an integer variable depends on the
architecture of a computer, but 4 bytes is typical for an integer value. Lets say your computer represents an integer in a 4 -byte
memory location. The declaration above can be visualized as in Figure 1 below.
What this declares is a variable that holds the address of an integer variable, in other words, it is a pointer to an integer . To link
the pointer variable to the variable whose address it will hold, the following initialization is necessary:
The & sign in front of a variable defines the address of that variable. Note that in steps 1, 2, and 3 we defined an integer
variable, a pointer to an integer variable, and assigned the pointer to the address of the integer variable. This is a typical set of
steps. See Figure 2 below for the relation between the two visually.
Now, lets say you want to use the value represented by integer variable number in an arithmetic expression. There is a direct
way by using the variable itself as we are accustomed to- and an indirect way by using the pointer to the variable. Lets say you
want to calculate the divide the number by 10:
Direct way:
k = number / 10;
Indirect way:
k = *pointerToNumber / 10;
The notation *pointerToNumber means the value held in the address pointed by pointerToNumber variable. The notation
*pointerToNumber (star sign in front of a pointer) is also called dereferencing a pointer; it yields the value held in the pointed
address.
82
You might be asking yourself why we need pointers. Being able to have access to the address of any given variable (and later you
will see access to the functions) is very powerful: primarily, this will allow us to change values of function arguments within
functions and handle dynamical memory management. Remember the matrix multiplication example from the previous lecture or
the homework you worked on to calculate the average and standard deviation of a given set of numbers. In these exercises we had
to keep the size of arrays constant. In other words, we had to specify the number of array elements; we could not determine the
number of elements at run-time dynamically. Now that we have introduced pointers, we can dynamically allocate memory for any
number of elements. First, we need to learn the relationship between arrays and pointers.
83
Arrays and Pointers
p = &a[0];
Note that what we do here is to set p to point to the address of the first element of array a. See Figure 3 below. (An
alternative way to set p to the first element of array a is to just state p=a; in other words, array variables
themselves are pointers in C.)
i = *p;
This is equivalent to
i = a[0];
This is because p points to a[0] and *p refers to the value held in a[0].
Another example:
p = &a[5];
and
i = *p;
If you use a pointer to access the elements of an array, there is a powerful way of traversing the arrays elements.
Consider
int* p; int a[10];
p = &a[0];
which set pointer p to the first element (indexed by 0) of array a. Now, say you want to refer to element i of array
a. You can do this directly as
a[i];
or indirectly by using the pointer p as
*(p + i);
Note that in the indirect way (p+i) takes you to the address of element i and *(p+i) gives you the value stored in
address (p+i).
Important note: Adding i to a pointer does not mean adding i bytes to the address held by the pointer. If the size
of the variable maintained in the address is k, what this means is to add i * k to the address maintained by the
pointer. For instance, if you are pointing to an integer array and your machine represents integers in 4 bytes, *(p +
3) means the 3rd element of the array and the address is calculated internally as
84
address of element 0 + 3 * 4
In other words, the expression *(p+3) will take you to element 3 by jumping 12 bytes from the beginning address of
the array. We will see more examples of this later when we cover structures.
Pointer is used for different purpose. Some of the pointer application is listed below:
1. Call by Reference
2. Accessing Array element
3. Dynamic Memory allocation
4. Some other pointer application in different data structure, such as tree, such as linked list, tree, graph etc.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("-------Call By Reference---------");
printf("\nEnter the value of a and b");
scanf("%d%d",&a,&b);
swap(&a,&b);
#include<stdio.h>
void sendarr(int [],int n);
void main()
{
int a[5]={4,5,3,2,6};
int i,n=5;
sendarr(a,n);
}
void sendarr(int a[],int n)
85
{
int i;
for(i=0;i<5;i++)
printf("%d\t",*(a+i));
}
aptr=(int *) malloc(n*sizeof(int)) ;
if(aptr==NULL)
{
printf("memory not avialable\n");
}
scanf("%d",(aptr+i));
}
aptr=(int *)realloc(aptr,m*sizeof(int));
if(aptr==NULL)
{
printf("memory not avialable\n");
exit(1);
}
printf("printf enter %d more elements\n",m) ;
for(i=n;i<=n+m-1;i++)
scanf("%d",(aptr+i));
86
In this topic you will come to know, how C programmers can create, open, close text or binary files for their data
storage.
A file represents a sequence of bytes, does not matter if it is a text file or binary file. C programming language
provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices.
This chapter will take you through important calls for the file management.
Opening Files
You can use the fopen( ) function to create a new file or to open an existing file, this call will initialize an object of
the type FILE, which contains all the information necessary to control the stream. Following is the prototype of this
function call:
Here, filename is string literal, which you will use to name your file and access mode can have one of the
following values:
Mode Description
Access
r mode Open an existing file for reading only.
w Open a file for writing only. If the file does not exist create a new one. If the file exists it will
be overwritten.
a Open a file for appending only. If the file does not exist create a new one. New data will be
added to the end of the file.
r+ Open an existing file for reading and writing
w+ Open a new file for reading and writing
a+ Open a file for reading and appending. If the file does not exist create a new one.
If you are going to handle binary files then you will use below mentioned access modes instead of the above
mentioned:
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is:
int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This function actually,
flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The
EOF is a constant defined in the header file stdio.h.
There are various functions provide by C standard library to read and write a file character by character or in the
form of a fixed length string. Let us see few of the in the next section.
Writing a File
Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the
written character written on success otherwise EOF if there is an error. You can use the following functions to write
a null-terminated string to a stream:
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on
success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char
*format, ...) function as well to write a string into a file. Try the following example:
Make sure you have /tmp directory available, if its not then before proceeding, you must create this directory on
your machine.
#include <stdio.h>
87
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines
using two different functions. Let us read this file in next section.
Reading a File
Following is the simplest function to read a single character from a file:
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or
in case of any error it returns EOF. The following functions allow you to read a string from a stream:
The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string
into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum
number of characters, then it returns only the characters read up to that point including new line character. You can
also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it stops reading after
the first space character encounters.
#include <stdio.h>
main()
{
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
When the above code is compiled and executed, it reads the file created in previous section and produces the
following result:
1 : This
Let's see a little more detail about what happened here. First fscanf() method read just This because after that it
encountered a space, second call is for fgets() which read the remaining line till it encountered end of line. Finally
88
last call fgets() read second line completely.
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
Both of these functions should be used to read or write blocks of memories - usually arrays or structures.
fp=fopen(fname,"w");
if(fp==NULL)
{
printf("File can not open\n");
}
else
{
printf("\nEnter text:\n");
while((ch=getchar())!=EOF)
{
fputc(ch,fp);
}
printf("File created Successfully.....\n");
}
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char fname[20];
int ch;
clrscr();
fp=fopen(fname,"r");
89
if(fp==NULL)
{
printf("File can not open\n");
}
else
{
while((ch=getc(fp))!=EOF)
{
printf("%c",ch);
}
printf("File Opened Successfully.....\n");
}
fclose(fp);
getch();
}
Questions
90
1. Define double pointer with example.
5. Write the difference between call by value and call by reference with suitable example.
6. What is pointer arithmetic? Write advantage and disadvantage of using pointer variable.
7. Write short notes on: Macros, Linked List, and Mathematical Function.
9. Macros. How they are different from C variables. Advantage of macro. Explain conditional compilation
and how does it help the programmers.
11. File program: Odd number in ODD file and even number in EVEN file.
13. Write a program in C that takes ten integers from a file and write square of these integers into another file
14. How macros are defined and called in C? Explain with example.
16. What are pointers in 'C' ? How is a pointer initialized? Explain with a suitable example.
17. Using pointer, write a function that receives a character string and a character as argument and deletes all
occurrences of this character in this string. Function should return the corrected string without space.
18. Write a C-program to display the address and the content of a pointer variable.
19. Discuss different modes in which a file can be opened by giving suitable examples.
20. Differentiate between: int abc [5] [10] and int * b [5];
21. Write a 'C' program using pointer to read in line of text, store it in memory and print the line backward.
22. Write a 'C' program to search and replace in a string using pointer and functions provided by the 'C'
library.
91