C Digital Notes All 5 Units
C Digital Notes All 5 Units
C Digital Notes All 5 Units
UNIT – 1
A program is a set of instructions that tell the computer to do various things; sometimes the
instruction it has to perform depends on what happened when it performed a previous
instruction. This section gives an overview of the two main ways in which you can give these
instructions or “commands” as they are usually called. One way uses an interpreter, the other
a compiler. As human languages are too difficult for a computer to understand in an
unambiguous way, commands are usually written in one or other languages specially designed
for the purpose.
Introduction to Computers:
A computer is a system made of two major components: hardware and software. The computer
hardware is the physical equipment. The software is the collection of programs (instructions)
that allow the hardware to do its job.
COMPUTER
SYSTEM
HARDWARE
Computer Hardware
The hardware component of the computer system consists of five parts: input devices, central
processing unit (CPU), primary storage, output devices, and auxiliary storage devices.
The input device is usually a keyboard where programs and data are entered into the
computers. Examples of other input devices include a mouse, a pen or stylus, a touch screen,
or an audio input unit.
The central processing unit (CPU) is responsible for executing instructions such as arithmetic
calculations, comparisons among data, and movement of data inside the system. Today’s
computers may have one ,two, or more CPUs .Primary storage ,also known as main memory,
is a place where the programs and data are stored temporarily during processing. The data in
primary storage are erased when we turn off a personal computer or when we log off from a
time-sharing system.
The output device is usually a monitor or a printer to show output. If the output is shown on
the monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard
copy.
Auxiliary storage, also known as secondary storage, is used for both input and output. It is
the place where the programs and data are stored permanently. When we turn off the computer,
or programs and data remain in the secondary storage, ready for the next time we need them.
Computer Software
Computer software is divided in to two broad categories: system software and application
software .System software manages the computer resources .It provides the interface between
the hardware and the users. Application software, on the other hand is directly responsible for
helping users solve their problems.
System Software:
System software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.
The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this
software is to keep the system operating in an efficient manner while allowing the users access
to the system.
System support software provides system utilities and other operating services. Examples of
system utilities are sort programs and disk format programs. Operating services consists of
programs that provide performance statistics for the operational staff and security monitors to
protect the system and data.
The last system software category, system development software, includes the language
translators that convert programs into machine language for execution, debugging tools to
ensure that the programs are error free and computer –assisted software engineering (CASE)
systems.
Application software
word processors, database management systems, and computer design systems. They are
labeled general purpose because they can solve a variety of user computing problems.
Application –specific software can be used only for its intended purpose.
A general ledger system used by accountants and a material requirements planning system used
by a manufacturing organization are examples of application-specific software. They can be
used only for the task for which they were designed they cannot be used for other generalized
tasks.
The relation ship between system and application software is shown in fig-2.In this figure, each
circle represents an interface point .The inner core is hard ware. The user is represented by the
out layer. To work with the system, the typical user uses some form of application software.
The application software in turn interacts with the operating system, which is apart of the
system software layer. The system software provides the direct interaction with the hard ware.
The opening at the bottom of the figure is the path followed by the user who interacts directly
with the operating system when necessary.
1.2.1Disk
When talking about a disk or diskette, you're referring to a floppy diskette or hard disk drive.
However, when talking about a Blu-ray, CD, or DVD, you should use "disc" and not "disk."
For example, saying "my movie is on that DVD disc" is the proper usage of "disc." An easy
way to remember this is that a "disk" is always a magnetic storage using magnets, and a "disc"
is always an optical media using a lasers or lights.
Hard drives
A hard-disk drive (HDD) is a non-volatile device used for storage, located inside the computer
case. Like the floppy drive, it holds its data on rotating platters with a magnetic upper exterior
which are changed or read by electromagnetic tipped arms that move over the disk as it spins.
1.2.2 Memory
A memory is just like a human brain. It is used to store data and instructions. Computer
memory is the storage space in the computer, where data is to be processed and instructions
required for processing are stored. The memory is divided into large number of small parts
called cells. Each location or cell has a unique address, which varies from zero to memory
size minus one. For example, if the computer has 64k words, then this memory unit has 64 *
1024 = 65536 memory locations. The address of these locations varies from 0 to 65535.
● Cache Memory
● Primary Memory/Main Memory
● Secondary Memory
Cache Memory
Cache memory is a very high speed semiconductor memory which can speed up the CPU. It
acts as a buffer between the CPU and the main memory. It is used to hold those parts of data
and program which are most frequently used by the CPU. The parts of data and programs are
transferred from the disk to cache memory by the operating system, from where the CPU can
access them.
Advantages
The advantages of cache memory are as follows −
Access time in RAM is independent of the address, that is, each storage location inside the
memory is as easy to reach as other locations and takes the same amount of time. Data in the
RAM can be accessed randomly but it is very expensive.
RAM is volatile, i.e. data stored in it is lost when we switch off the computer or if there is a
power failure. Hence, a backup Uninterruptible Power System (UPS) is often used with
computers. RAM is small, both in terms of its physical size and in the amount of data it can
hold.
RAM is of two types −
● Long life
● No need to refresh
● Faster
● Used as cache memory
● Large size
● Expensive
● High power consumption
Let us now discuss the various types of ROMs and their characteristics.
The very first ROMs were hard-wired devices that contained a pre-programmed set of data or
instructions. These kinds of ROMs are known as masked ROMs, which are inexpensive.
PROM (Programmable Read Only Memory)
PROM is read-only memory that can be modified only once by a user. The user buys a blank
PROM and enters the desired contents using a PROM program. Inside the PROM chip, there
are small fuses which are burnt open during programming. It can be programmed only once
and is not erasable.
EPROM (Erasable and Programmable Read Only Memory)
EPROM can be erased by exposing it to ultra-violet light for duration of up to 40 minutes.
Usually, an EPROM eraser achieves this function. During programming, an electrical charge
is trapped in an insulated gate region. The charge is retained for more than 10 years because
the charge has no leakage path. For erasing this charge, ultra-violet light is passed through a
quartz crystal window (lid). This exposure to ultra-violet light dissipates the charge. During
normal use, the quartz lid is sealed with a sticker.
Advantages of ROM
The advantages of ROM are as follows −
● Non-volatile in nature
● Easy to test
1.3 Compilers:
A compiler is a software program that transforms high-level source code that is written by a
developer in a high-level programming language into a low level object code (binary code) in
machine language, which can be understood by the processor. The process of converting high-
level programming into machine language is known as compilation.
The processor executes object code, which indicates when binary high and low signals are
required in the arithmetic logic unit of the processor.
Computer hardware understands a program only if it is coded in its machine language. It is the
job of the programmer to write and test the program .There are four steps in this process:
1.Writing and Editing the program2.Compiliing the program 3.Linking the program with the
required library modules 4.Executing the program.
The software used to write programs is known as a text editor. A text editor helps us enter,
change, and store character data. Depending on the editor on our system, we could use it to
write letters, create reports, or write programs. The main difference between text processing
and program writing is that programs are written using lines of code, while most text processing
is done with character and lines.
Text editor is a generalized word processor, but it is more often a special editor included with
the compiler. Some of the features of the editor are search commands to locate and replace
statements, copy and paste commands to copy or move statements from one part of a program
to another, and formatting commands that allow us to set tabs to align statements.
After completing a program, we save our file to disk. This file will be input to the compiler; it
is known as a source file.
Compiling Programs:
The code in a source file stored on the disk must be translated into machine language; this is
the job of the compiler. The c compiler is two separate programs: The preprocessor and the
translator. The preprocessor reads the source code and prepares it for the translator. While
preparing the code, it scans for special instructions known as preprocessor commands. These
commands tell the preprocessor to look for special code libraries, make substitutions in the
code, and in other ways prepare the code for translation into machine language. The result of
preprocessing is called the translation unit.
After the preprocessor has prepared the code for compilation, the translator does the actual
work of converting the program into machine language. The translator reads the translation
unit and writes the resulting object module to a file that can then be combined with other
precompiled units to form the final program. An object module is the code in machine
language. The output of the compiler is machine language code, but it is not ready to run; that
is ,it is not executable because it does not have the required C and other functions included.
Linking Programs:
A C program is made up of many functions. We write some of these functions, and they are a
part of our source program. There are other functions, such as input/output processes and,
mathematical library functions that exist elsewhere and must be attached to our program. The
linker assembles all of these functions, ours and systems into our final executable program.
Executing Programs:
Once program has been linked, it is ready for execution. To execute a program we use an
operating system command, such as run, to load the program into primary memory and execute
it. Getting the program into memory is the function of an operating system program known as
the loader. It locates the executable program and reads it into memory. When everything is
loaded, the program takes control and it begins execution.
In a typical program execution, the data is read for processing, either from the user or from a
file. After the program processes the data, it prepares the output. At output can be to the user’s
monitor or to a file. When the program has finished its job, it tells the operating system, which
then removes the program from memory.
Number systems are the technique to represent numbers in the computer system architecture,
every value that you are saving or getting into/from computer memory has a defined number
system.
Computer architecture supports following number systems.
● Binary number system
● Octal number system
● Decimal number system
● Hexadecimal (hex) number system
1) Binary Number System
A Binary number system has only two digits that are 0 and 1. Every number (value)
represents with 0 and 1 in this number system. The base of binary number system is 2,
because it has only two digits.
2) Octal number system
Octal number system has only eight (8) digits from 0 to 7. Every number (value) represents
with 0,1,2,3,4,5,6 and 7 in this number system. The base of octal number system is 8, because
it has only 8 digits.
CONVERSIONS:
BINARY SYSTEM:
Here is an example of converting binary directly into decimal. We simply add up the place
values of each 1 digit in the binary number.
1001012 = 3710:
Exponents 25 24 23 22 21 20
Place Values 32 16 8 4 2 1
Bits 1 0 0 1 0 1
Value 32 +4 +1 = 37
number multiply the each digit in the decimal part by ,m is the position of the digit from the decimal
point
Step 3: The resultant is the equivalent decimal number for the given binary number.
Step 4: Divide the decimal with 8
Step 5: Note the remainder
Step 6: Continue the above two steps with the quotient till the quotient is zero
Step 7: Write the remainder in the reverse order
Step 8: The resultant is the required octal number for the given binary number.
OCTAL SYSTEM
part by when the digit is in the mth position from the decimal point.
Step 4: Add all terms after multiplication
Step 5: The obtained value is the equivalent decimal number
Step 6: Consider the decimal number, divide it by 2
Step 7: Note the remainder
Step 8: Continue the above two steps for the quotient till the quotient is zero
Step 9: Write the remainders in the reverse order
Step 10: The obtained number is the equivalent binary number for the given octal number.
Solution:
418
= (4 * 81) + (1 * 80)
=4*8+1*1
= 32+1
= 33(Decimal number)
2 | 33
2 | 16 -- 1
2 | 8 -- 0
2 | 4 --0
2 | 2 -- 0
1 -- 0
418 = 1000012
Step 8: Multiply each digit after decimal with ,when the digit is the mth position.
All other steps are same as above.
57468
= (5 * 83)+ (7 * 82) + (4 * 81) + (6 * 80)
=5 * 512 + 7 * 64 + 4 * 8 + 6 * 1
= 2560+448+32+6
= 3046
57468 = 3046
number.If the number has decimalpart the multiply digits after decimal by where m is
position of the number from the decimal
Step 3: Add the terms after multiplication
Step 4: The obtained number is equivalent decimal number to the given octal
Step 5: Consider the decimal number, divide it by 16
Step 6: Note the remainder.
Step 7: Continue the process till the quotient in zero
Step 8: Write the remainder in the reverse order
Step 9: The obtained number is equivalent hexadecimal number to the given octadecimal
number.
10028
= (1 * 83) + (0 * 82) + (0 * 81) + (2 * 80)
=1 * 512 + 0 * 64 + 0 * 8 + 2 * 1
= 512 + 0 + 0+ 2
= 514(decimal number)
16 | 514
16 | 32 --2
2 -- 0
10028 = 20216
DECIMAL SYSTEM
-------
2 | 2 -- 0
--------
1 -- 0
Answer is (100011)2.
Solution:
146 is greater than 16, so we have to divide by 16.
After dividing by 16, quotient is 9 and remainder is 2.
Remainder is less than 16.
The hexadecimal number of remainder is 2.
Quotient is 9 and hexadecimal number of remainder is 2.
So, the 92 is the hexadecimal number is equivalent to decimal number 146.
16 | 146
-------------
16 | 9 -- 2
-------------
0–9
HEXADECIMAL CONVERSIONS
Hexadecimal to Binary conversion
Step 1: Take given hexadecimal number
Step 2: Find the number of digits in the decimal
Step 3: If it has n digits, multiply each digit with 2n-1where the digit is in the nth position
Step 4: Add the terms after multiplication
Step 5: The resultant is the decimal number equivalent to the given hexadecimal
number.Now we have to convert this hexadecimal to binary number.
Step 6: Divide the decimal number with 2
Step 7: Note the remainder
Step 8: Do the above 2 steps for the quotient till the quotient is zero
Step 9: Write the remainders in the reverse order.
Step 10: The resultant is the required binary number.
Example: Convert A2B16 to a equivalent binary number
Solution:
Given hexadecimal number is A2B
= 2603(Decimal number)
2 | 2603
2 |1301 -- 1
2 | 650 -- 1
2 | 325 -- 0
2 | 162 -- 1
2 | 81 -- 0
2 | 40 -- 1
2 | 20 -- 0
2 | 10 -- 0
2 | 5 -- 0
2 | 2 -- 1
2 | 1 -- 0
2 | 0 -- 1
A2B16 = 1010001010112
Solution:
Given hexadecimal number is C1
C116
= (C * 161) + (1 * 160)
= C * 16 + 1 * 1
=12 * 16 + 1
= 192 + 1
8 | 193
8 | 24 -- 1
8 | 3 -- 0
8 | 0 --3
C116 = 3018
= 112 + 1 ×× 11
= 112 + 11
= 123
Answer is 123
Definition of Algorithm
To write a logical step-by-step method to solve the problem is called algorithm, in other words,
an algorithm is a procedure for solving problems. In order to solve a mathematical or computer
problem, this is the first step of the procedure. An algorithm includes calculations, reasoning
and data processing. Algorithms can be presented by natural languages, pseudo code and
flowcharts, etc.
Definition of Flowchart
A Flow chart is a Graphical representation of an Algorithm or a portion of an Algorithm. Flow
charts are drawn using certain special purpose symbols such as Rectangles, Diamonds, Ovals
and small circles. These symbols are connected by arrows called flow lines.
(Or)
The diagrammatic representation of way to solve the given problem is called flow
Chart.
The following are the most common symbols used in drawing flowcharts:
Shape Type Name of the
Symbol Meaning
of the symbol Symbol
The graphics above represent different part of a flowchart. The process in a flowchart can be
expressed through boxes and arrows with different sizes and colors. In a flowchart, we can
easily highlight a certain element and the relationships between each part.
Now that we have the definitions of algorithm and flowchart, how do we use a flowchart to
represent an algorithm?
Algorithms are mainly used for mathematical and computer programs, whilst flowcharts can
be used to describe all sorts of processes: business, educational, personal and of course
algorithms. So, flowcharts are often used as a program planning tool to visually organize step-
by-step process of a program. Here are some examples:
Example 2: Flow chart for converting Temperature from Fahrenheit (℉) to Celsius (℃)
PSEUDOCODE:
Pseudo code is an artificial and informal language that helps programmers develop algorithms.
Pseudo code is similar to everyday English, it is convenient and user friendly although it is not
an actual computer programming language. Psuedo code programs are not actually executed
on computer rather they merely help the programmer “think out” a program before attempting
to write it in a programming language such as C.
1.7.1 Program Design Language (or PDL, for short) is a method for designing and
documenting methods and procedures in software. It is related to pseudo code, but unlike
pseudo code, it is written in plain language without any terms that could suggest the use of any
programming language or library.
PDL was originally developed by the company Caine, Farber & Gordon and has been modified
substantially since they published their initial paper on it in 1975. It has been described in some
detail by Steve McConnell in his book Code Complete.
carefully design each program using good structured development techniques, programs will
be efficient, error-free, and easy to maintain.
Today’s large-scale modern programming projects are built using a series of interrelates phases
commonly referred to as the system development cycle. Although the exact number and names
of the phases differ depending on the environment there is general agreement as to the steps
that must be followed. One very popular development life cycle developed, this modal consists
of between 5 and 6 phases.
The water fall modal starts with systems requirements in this phase the systems analyst defines
requirements that specify what the proposed system is to accomplish.
The requirements are usually stated in terms that the user understands.
The analysis phase looks at different alternatives from a systems point of view while the design
phase determined how the system will be built.
In the design phase the functions of the individual programs that will make up the system are
determined and the design of the files and / or the databases is completed.
Finally in the 4th phase code, we write the programs. After the programs have been written and
tested to the programmer’s satisfaction, the project proceeds to the system test.
All of the programs are tested together to make sure of the system works as a whole
The final phase maintenance keeps the system working once it has been put into production.
Although the implication of the water falls approach is that the phases flow in a continuous
stream from the first to the last, this is not really the case. As each phase is developed, errors
and omissions will often be found in the previous work. When this happens it is necessary to
go back to the previous phase to rework it for consistency and to analyze the impact caused by
the changes.
Program Development is a multistep process that requires that we understand the problem,
develop a solution, write the program, and then test it. When we are given the assignment to
develop a program, we will be given a program requirements statement and the design of any
program interfaces. We should also receive an overview of the complete project so that we will
take the inputs we are given and convert them to the outputs that have been specified. This is
known as program design.
The first step in solving any problem is to understand it. By reading the requirements statements
carefully, we fully understand it, we review our understanding with the user and the systems
analyst to know the exact purpose.
The structure chart is used to design the whole program .Pseudo code and flowcharts are used
to design the individual parts of the program.
Structure chart: A structure chart, also known as hierarchy chart, shows the functional flow
through our program. The structure chart shows how we are going to break our program into
logical steps each step will be a separate module. The structure chart shows the interaction
between all the parts (modules) of our program.
We can use flowchart or pseudo code to complete the design of your program will depend on
experience and difficulty of the program your designing.
When we write a program, we start with the top box on the structure chart and work our way
to the bottom. This is known as top-down implementation. We will write the programs by using
structure chart and flowchart or pseudo code.
Program testing can be a very tedious and time- consuming part of program development. As
the programmer we are responsible for completely testing our program. In large-development
projects test engineers are responsible for testing to make sure all the programs work together.
C is the programming language most frequently associated with UNIX. Since the 1970s, the
bulk of the UNIX operating system and its applications have been written in C. Because the C
language does not directly rely on any specific hardware architecture, UNIX was one of the
first portable operating systems. In other words, the majority of the code that makes up UNIX
does not know and does not care which computer it is actually running on. Machine-specific
features are isolated in a few modules within the UNIX kernel, which makes it easy for you to
modify them when you are porting to different hardware architecture.
C was first designed by Dennis Ritchie for use with UNIX on DEC PDP-11 computers. The
language evolved from Martin Richard's BCPL, and one of its earlier forms was the B
language, which was written by Ken Thompson for the DEC PDP-7. The first book on C was
The C Programming Language by Brian Kernighan and Dennis Ritchie, published in 1978.
Algorithms and flowcharts are two different tools used for creating new programs, especially
in computer programming. An algorithm is a step-by-step analysis of the process, while a
flowchart explains the steps of a program in a graphical way.
The program written in C language follows this basic structure. The sequence of sections
should be as they are in the basic structure. A C program should have one or more sections but
the sequence of sections is to be followed.
Documentation section
Linking section
Definition section
Global declaration section
Main function section
{
Declaration section Executable section
}
Sub program or function section
DOCUMENTATION SECTION: comes first and is used to document the use of logic or
reasons in your program. It can be used to write the program's objective, developer and logic
details. The documentation is done in C language with /* and */. Whatever is written between
these two are called comments.
LINKING SECTION: This section tells the compiler to link the certain occurrences of
keywords or functions in your program to the header files specified in this section.
DEFINITION SECTION: It is used to declare some constants and assign them some value.
Here #define is a compiler directive which tells the compiler whenever MAX is found in the
program replace it with 25.
GLOBAL DECLARATION SECTION: Here the variables which are used through out the
program (including main and other functions) are declared so as to make them global (i.e
accessible to all parts of program)
e.g. int i; (before main())
MAIN FUNCTION SECTION: It tells the compiler where to start the execution from
main()
{
point from execution starts
}
main function has two sections
• Declaration section: In this the variables and their data types are declared.
• Executable section: This has the part of program which actually performs the task we
need.
SUB PROGRAM OR FUNCTION SECTION: This has all the sub programs or the
functions which our program needs.
1.8.3 C-TOKENS:
Tokens are individual words and punctuations marks in English language sentence. The
smallest individual units are known as C tokens.
A C program can be divided into these tokens. A C program contains minimum 3 c tokens no
matter what the size of the program is.
To represent different types of data in C program we need different data types. A data type is
essential to identify the storage representation and the type of operations that can be performed
on that data. C supports four different classes of data types namely
All arithmetic operations such as Addition, subtraction, etc are possible on basic data types.
E.g.: int a, b;
Char c;
The following table shows the Storage size and Range of basic data types:
Derived data types are used in ‘C’ to store a set of data values. Arrays and Structures are
examples for derived data types.
C Provides a facility called typedef for creating new data type names defined by the user. For
Example, the declaration:
typedef int Integer;
makes the name Integer a synonym of int.Now the type Integer can be used in declarations
,casts, etc, like,
Which will be treated by the C compiler as the declaration of num1, num2 as int variables.
“typedef” ia more useful with structures and pointers.
1.9 VARIABLES:
A quantity that can vary during the execution of a program is known as a variable. To identify
a quantity we name the variable for example if we are calculating a sum of two numbers we
will name the variable that will hold the value of sum of two numbers as 'sum'.
IDENTIFIERS:
● Names of the variables and other program elements such as functions, array, etc, are
known as identifiers.
● There are few rules that govern the way variable are named (identifiers).
● Identifiers can be named from the combination of A-Z, a-z, 0-9, _ (Underscore).
● The first alphabet of the identifier should be either an alphabet or an underscore. Digits
are not allowed.
● It should not be a keyword. Eg: name, ptr, sum After naming a variable we need to
declare it to compiler of what data type it is. The format of declaring a variable is
Where data type could be float, int, char or any of the data id1, id2, and id3 are the names of
variable we use. In case of single variable no commas are required.
eg float a, b, c;
Int e, f, grand total;
char present_or_absent;
ASSIGNING VALUES:
When we name and declare variables we need to assign value to the variable. In some cases
we assign value to the variable directly like
a=10;
In our program
In some cases we need to assign values to variable after the user has given input for that.
Eg: we ask user to enter any no and input it.
#include<stdio.h>
main()
{
int a; float b;
printf("Enter any number\n"); b=190.5;
scanf("%d",&a); printf("user entered %d", a); printf("B's values is %f", b);
}
CONSTANTS:
A quantity that does not vary during the execution of a program is known as a constant supports
two types of constants namely Numeric constants and character constants.
NUMERIC CONSTANTS:
CHARACTER CONSTANTS:
A character constant is written as one character with in single quotes such as ‘a’. The value of
a character constant is the numerical value of the character in the machines character set.
Certain character constants can be represented by escape sequences like ‘\n’. These sequences
look like two characters but represent only one.
The following are the some of the examples of escape sequences:
\a Alert
\b Backspace
\f Form feed
\n New Line
\r Carriage return
\t Horizontal Tab
\v Vertical Tab
String constants or string literal is a sequence of zero or more characters surrounded by a double
quote. Example, “I am a little boy”. Quotes are not a part of the string.
To distinguish between a character constant and a string that contains a single character ex: ‘a’
is not same as “a”. ‘a’ is an integer used to produce the numeric value of letter a in the machine
character set, while “a” is an array of characters containing one character and a ‘\0’ as a string
in C is an array of characters terminated by NULL.
There is one another kind of constant i.e Enumeration constant, it is a list of constant integer
values.
For compiled languages, syntax errors are detected at compile-time. A program will not
compile until all syntax errors are corrected.
1 int a,b:
The above statement will produce syntax error as the statement is terminated with : rather than
;
Logical Error: A logic error is a bug in a program that causes it to operate incorrectly, but
not to terminate abnormally (or crash). A logic error produces unintended or undesired output
or other behaviour, although it may not immediately be recognized as such.
Logic errors occur in both compiled and interpreted languages. Unlike a program with a syntax
error, a program with a logic error is a valid program in the language, though it does not behave
as intended.
For example,
a=5/0;
1.11 Object and Executable code:
The programming language code is called as Source code or object code and is obtained after
compilation. Source code extension is .c file and object code extension is .obj and executable
file is .exe
1.12 OPERATORS :
An operator is a symbol that tells the compiler to perform certain mathematical or logical
manipulations. They form expressions.
C operators can be classified as
• Arithmetic operators
• Relational operators
• Logical operators
• Assignment operators
• Increment or Decrement operators
• Conditional operator
• Bit wise operators
• Special operators
operator meaning
+ add
- subtract
* multiplication
/ division
% modulo division(remainder)
An arithmetic operation involving only real operands(or integer operands) is called real
arithmetic(or integer arithmetic). If a combination of arithmetic and real is called mixed mode
arithmetic.
operator meaning
op-1 !op-1
non-zero Zero
zero non-zero
and == are called increment and decrement operators used to add or subtract. Both are unary
and as follows
Syntax: ++m or m++ --m or m--
The difference between ++m and m++ is
It work as
if exp1 is true then exp2 else exp3
7. BIT WISE OPERATORS: C supports special operators known as bit wise operators for
manipulation of data at bit level. They are not applied to float or double.
operator meaning
8. SPECIAL OPERATORS:
These operators which do not fit in any of the above classification are , (comma), sizeof,
Pointer operators(& and *) and member selection operators (. and ->). The comma operator is
used to link related expressions together. sizeof operator is used to know the sizeof operand.
#include<stdio.h>
main()
{
int sum, mul, modu; float sub, divi;
int i,j; float l, m;
printf("Enter two integers "); scanf("%d%d",&i,&j); printf("Enter two real numbers");
scanf("%f%f",&l,&m);
sum=i+j;
mul=i*j;
modu=i%j; sub=l-m; divi=l/m;
printf("sum is %d", sum); printf("mul is %d", mul); printf("Remainder is %d", modu);
printf("subtraction of float is %f", sub); printf("division of float is %f", divi);
}
#include<stdio.h>
main()
{
int i, j, k;
printf("Enter any three numbers "); scanf("%d%d%d", &i, &j, &k); if((i<j)&&(j<k))
printf("k is largest"); else if i<j || j>k
{
if i<j && j >k
printf("j is largest");
else
printf("j is not largest of all");
}
}
#include<stdio.h>
main()
{
int i;
printf("Enter a number"); scanf("%d", &i);
i++;
printf("after incrementing %d ", i); i--;
printf("after decrement %d", i); }
/* program using ternary operator and assignment */ #include<stdio.h>
main()
{
int i,j,large;
printf("Enter two numbers "); scanf("%d%d",&i,&j); large=(i>j)?i:j;
printf("largest of two is %d",large);
}
A simple expression contains only one operator. E.g: 2 + 3 is a simple expression whose value
is 5.A complex expression contains more that one operator. E.g: 2 + 3 * 2. To evaluate a
complex expression we reduce it to a series of simple expressions. In this first we will evaluate
the simple expression 3 * 2 (6)and then the expression 2 + 6,giving a result of 8.
The order in which the operators in a complex expression are evaluated is determined by a set
of priorities known as precedence, the higher the precedence ,the earlier the expression
containing the operator is evaluated. If two operators with the same precedence occur in a
complex expression ,another attribute of an operator ,its associativity ,takes control.
Associativity is the parsing direction used to evaluate the expression. It can be either left-to-
right or right-to-left. When two operators with the same precedence occur in an expression and
their associativity is left-to-right ,the left operator is evaluated first. For example ,in the
expression 3*4/6 ,there are two operators multiplication and division ,with the same precedence
and left-to-right associativity. Therefore the multiplication is evaluated before the division.
ARITHMETIC EXPRESSIONS:
Some examples A * B – C
(M + N) * (X + Y)
Eg:
x = x*y + z-3 *(z *y)
Storage Classes:- Not only data type is required to declare a variable but its storage class also
has to be mentioned. (or)
The variables declared in C programs are totally different from other languages. We can use
the same variable names in the C program in separate blocks. When we declare a variable it
is available only to specific part or block of the program. Remaining block or other function
cannot get access to the variable.
The area or block of the C program from where the variable can be accessed is known as the
scope of variable. The area or scope of the variable depends on its storage class i.e. where
and how it is declared. There are four scope variables in C.
1. Function
2. File
3. Block
4. Function prototype
(ii) The Scope of the variable i.e., in which region of the program the value of variable is
actually available for us active.
(iii) Life of the variable i.e., how long the variable i.e., how long the variable would be
active in the program(longevity or alive).
Any variable declared in C can have any one of the four storage classes:
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.
The variables may also be broadly categorized, depending on the place of their declaration,
as
1) Automatic variables are defined inside a function. A variable declared inside a function
without storage class name, by default is an auto variable.
These variables are created when the function is called and destroyed automatically when
the function is exited.
Automatic variables are local to the function in which they are declared. These values cannot
be accessed by any other function. The keyword used is „auto‟.
Eg:
void main ( )
clrscr ( );
getch ( );
Eg 4:
void show ( );
void main ( )
int I;
clrscr ( );
show ( )
getch ( );
void show ( )
int a= 10;
a++;
2)External variables are also known as global variables. These variables are declared outside
the function and the values of these variables are available to all the functions of the program.
Unlike Local Variables, Global Variables can be accessed by any function in the program.
If same name is given to both the global and local variables priority is given to the local
variable. The keyword “ extern” is used to declare these variables.
Example Program:
#include<stdio.h>
#include<conio.h>
int a=20;
void main( )
clrscr( );
fun1( );
fun2( );
fun3( );
fun1( )
fun2( )
int a = 10;
fun3( )
Explanation: In this program local variable and global variables are declared with the same
name in fun2( ). In this case, when fun2( ) is called, the local variable „a‟ of fun2( ) hides the
global variable „a‟.
Note:
We can declare external variables by using extern key word inside the function body. Ex:
extern int a;
Eg 1:
void main ( )
clrscr ( );
getch ( );
3) Static variables may be of Local (or) global depending upon where it is declared. If it is
declared outside the function, it is static global otherwise if it declared inside a function block,
it is static local.
A static variable is initialized only once and can never be re-initialized. The value of static
variable persists at each call and last change made in the variable remains throughout the
program execution.
Example Programs:-
Eg 1:
void main( )
incr( );
incr( );
incr( );
void incr( )
static int x;
x=x+1;
printf(“%d”, x);
4) Register Variables: Instead of storing in memory, variables can also be stored in register of
CPU. The advantage of storing in registers is register access is faster than memory access, so,
generally frequently accessed variables are kept in registers for faster execution of the
program.
The keyword register tells the compiler that the variable list followed by it is kept on the CPU
registers. If the CPU fails to keep the variables in CPU registers, in that case the variables are
assured as auto and stored in the memory.
Note:
1. CPU registers are limited in number. So, we cannot declare more variables as register
variables. Compiler automatically converts the register variables into non-register
variables once the limit is reached.
2. We cannot use register class for all types of variables. The CPU registers in microcomputer
are 16 bit registers. The data types float and double needs space of more than 16 bits. If
we define any variable of these types with register class, no errors will be shown. The
compiler treats them as auto variables.
The features of register variables are:-
(iv) Life time :until the control remains in that function block.
Example Programs:-
Eg 1:
void main( )
register int i;
In an expression that involves two different data types ,such as multiplying an integer and a
floating point number to perform these evaluations ,one of the types must be converted.
We have two types of conversions
For example ,to convert an integer ,a , to a float, we code the expression like (float) a
STATEMENT TYPES:
NULL STATEMENT :
Eg:
//null statement
Although they do not arise often, there are syntactical situations where we must have a
statement but no action is required .In these situations we use the null statement.
EXPRESSION STATEMENT :
Syntax:
expression; //expression statement
Eg: a=2;
RETURN STATEMENT :
A return statement terminates a function. All functions ,including main, must have a return
statement. Where there is no return statement at the end of the function ,the system inserts
one with a void return value.
COMPOUND STATEMENTS:
A compound statement is a unit of code consisting of zero or more statements .It is also known
as a block. The compound statement allows a group of statements to become one single entity.
A compound statement consists of an opening brace, an optional declaration and definition
section ,and an optional statement section ,followed by a closing brace.
Eg:
{
//Local Declarations int x;
int y; int z;
//Statements
x=1;
y=2;
…
} //End BlocK
We have a number of situations where we may have to change the order of execution
of statements based on certain conditions or repeat a group of statements until certain specified
conditions are met.
The if statement is a two way decision statement and is used in conjunction with an
expression. It takes the following form
If(test expression)
If the test expression is true then the statement block after if is executed otherwise it is not
executed
Syntax:
if (test expression)
{
statement block;
}
statement–x ;
/* program for if */
#include<stdio.h>
main()
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):
if a>b
printf(“ a is greater”);
if b>a
printf(“b is greater”);
}
If your have another set of statement to be executed if condition is false then if-else is
used
Syntax: if (test expression)
{
statement block1;
}
else
{
statement block2;
}
statement –x ;
#include<stdio.h>
main()
{
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):
if a>b
printf(“ a is greater”)
else
printf(“b is greater”);
}
If more than one if else statement exists in the program then it is said as Nesting of
statement
Syntax:
if(text cond1)
{
if (test expression2
{
statement block1;
}
else
{
statement block 2;
}
}
else
{
statement block2;
}
statement-x ;
if else ladder
if(condition1)
statement1; else
if(condition2)
statement 2; else
if(condition3)
statement n;
else
default statement.
statement-x;
The nesting of if-else depends upon the conditions with which we have to deal.
THE SWITCH STATEMENT: If for suppose we have more than one valid choices to
choose from then we can use switch statement in place of if statements.
Syntax: switch(expression)
{.
case value-1
block- 1
break;
case value-2
block- 2
break;
----------------
default:
default block;
break; }
statement–x
In case of
Syntax:
if(cond1)
{
statement-1
}
if (cond2)
{
statement 2
}
{
case 10 :
case 9: case
8: case 7:
case 6: grade=”first”;
break;
case 5 : grade=”second”;
break;
case 4 : grade=”third”;
break;
LOOPING :
WHILE STATEMENT :
It helps to execute the statements only if the condition is true.
Syntax:
While(test condition)
{
body of the loop
}
It is an entry controlled loop. The condition is evaluated and if it is true then body of
loop is executed. After execution of body the condition is once again evaluated and if is true
body is executed once again. This goes on until test condition becomes false.
DO WHILE STATEMENT:
The while loop does not allow body to be executed if test condition is false. The do
while is an exit controlled loop and its body is executed at least once.
Syntax:
do
{
body }while(test
condition);
#include<stdio.h>
#define COL 10
#define ROW 12
main()
{
int row,col,y;
row=1;
do
{
col=1; do
{
y=row*col;
printf(“%d”,y);
col=col+1;
}while(col<=COL);
printf(“\n”);
row=row+1;
}while(row<=ROW);
}
{
long int p; int
n; double q;
printf(“2 to power n “); p=1;
for(n=0;n<21;++n)
{
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 57
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
if(n==0)
p=1;
else
p=p*2;
q=1.0/(double)p;
printf(“%101d%10d”,p,n);
}
}
BREAK STATEMENT:
This is a simple statement. It only makes sense if it occurs in the body of a switch, do,
while or for statement. When it is executed the control of flow jumps to the statement
immediately following the body of the statement containing the break. Its use is widespread in
switch statements, where it is more or less essential to get the control .
The use of the break within loops is of dubious legitimacy. It has its moments, but is really
only justifiable when exceptional circumstances have happened and the loop has to be
abandoned. It would be nice if more than one loop could be abandoned with a single break but
that isn't how it works. Here is an example.
#include<stdio.h>
#include<stdlib.h>
main(){
int i;
printf("%d\n", i);
}
exit(EXIT_SUCCESS);
}
It reads a single character from the program's input before printing the next in a sequence of
numbers. If an ‘s’ is typed, the break causes an exit from the loop.
If you want to exit from more than one level of loop, the break is the wrong thing to use.
CONTINUE STATEMENT:
This statement has only a limited number of uses. The rules for its use are the same as for
break, with the exception that it doesn't apply to switch statements. Executing a continue starts
the next iteration of the smallest enclosing do, while or for statement immediately. The use of
continue is largely restricted to the top of loops, where a decision has to be made whether or
not to execute the rest of the body of the loop. In this example it ensures that division by zero
(which gives undefined behaviour) doesn't happen.
#include<stdio.h>
#include<stdlib.h>
main(){
int i;
The continue can be used in other parts of a loop, too, where it may occasionally help to
simplify the logic of the code and improve readability. continue has no special meaning to a
switch statement, where break does have. Inside a switch, continue is only valid if there is a
loop that encloses the switch, in which case the next iteration of the loop will be started.
There is an important difference between loops written with while and for. In a while, a
continue will go immediately to the test of the controlling expression. The same thing in a for
will do two things: first the update expression is evaluated, then the controlling expression is
evaluated.
goto L1;
/* whatever you like here */
L1: /* anything else */
A label is an identifier followed by a colon. Labels have their own ‘name space’ so they
can't clash with the names of variables or functions. The name space only exists for the function
containing the label, so label names can be re-used in different functions. The label can be used
before it is declared, too, simply by mentioning it in a goto statement.
Labels must be part of a full statement, even if it's an empty one. This usually only matters
when you're trying to put a label at the end of a compound statement—like this.
The goto works in an obvious way, jumping to the labelled statements. Because the name
of the label is only visible inside its own function, you can't jump from one function to another
one.
It's hard to give rigid rules about the use of gotos but, as with the do, continue and the
break (except in switch statements), over-use should be avoided. More than one goto every 3–
5 functions is a symptom that should be viewed with deep suspicion.
The simplest of input operator is getchar to read a single character from the input device.
The simplest of output operator is putchar to output a single character on the output device.
putchar(varname)
The getchar() is used only for one input and is not formatted. Formatted input refers to an
input data that has been arranged in a particular format, for that we have scanf.
scanf("control string", arg1, arg2,...argn);
Control string specifies field format in which data is to be entered.
arg1, arg2... argn specifies address of location or variable where data is stored.
eg scanf("%d%d",&a,&b);
Standard output is the stream where a program writes its output data. The program requests
data transfer with the write operation. Not all programs generate output. For example, the file
rename command (variously called mv, move, or ren) is silent on success.
Unless redirected, standard output is inherited from the parent process. In the case of an
interactive shell, that is usually the text terminal which initiated the program.
The file descriptor for standard output is 1 (one); the POSIX <unistd.h> definition
is STDOUT_FILENO; the corresponding C <stdio.h> variable is FILE* stdout
Syntax:
We can also give command-line arguments in C and C++. Command-line arguments are given
after the name of the program in command-line shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments : first
argument is the number of command line arguments and second is list of command-line
arguments.
Syntax:
TUTORIAL QUESTIONS
Ans:_____________________
2. #include <stdio.h>
int main(void) {
float x,y;
int i,j;
x = 1.5; y = 2.0;
i = 2; j = 4;
x = x * y + (float)i / j;
printf("%f",x);
return 0;
}
Ans:_____________________
3. #include <stdio.h>
int main(void) {
int i = 7, j = i - i;
while(i) {
i /= 2;
j++;
}
printf("%d",j);
return 0;
}
Ans:_____________________
4. #include <stdio.h>
int main(void) {
int i, j = 1;
for(i = 11; i > 0; i /= 3)
j++;
printf("%d",j);
return 0;
}
Ans:_____________________
5. #include <stdio.h>
int main(void) {
int i = 1, j = -2, k;
k = (i >= 0) || (j >= 00) && (i <= 0) || (j <= 0);
printf("%d",k);
return 0;
}
Ans:_____________________
ASSIGNMENT QUESTIONS
SET-1:
1. Design an algorithm and flow chart to find maximum among three numbers.
2. Implement a C program to find factors of given number.
SET-2:
1. Design an algorithm and flow chart to check given number is positive or negative or
zero
2. Implement a C program to print multiplication table for 1 to n numbers.
SET-3:
SET-4:
1. Implement a C program to check given number is perfect number or not.
2. Design a structure how to create and run C program.
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 64
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
SET-5:
1. Implement a C program to reverse a given number.
2. Design program Development steps.
SET-6:
1. Implement a C program to convert decimal number into binary.
2. Discuss about data types.
3. Implement a C program to add two numbers using command line argument.
6. Write the various steps involved in executing a C program and illustrate with the help
of flow chart?
7. What is the difference between break and continue statements ? Explain with examples.
8. What is the purpose of goto statement? How is the associated target statement
identified?
9. (a) What are constants?
B.Name the different data types that C supports and explain them in detail.
10. What is meant by looping? Describe any two different forms of looping with
Examples.
(b) Write a program to print the following outputs using for loop.
i) 1
2 2
3 3 3
4 4 4 4
ii) 1
2 2
3 3 3
4 4 4 4
10 What are the logical operators used in C and illustrate with examples?
11. Whar is the purpose of switch statement ? How does this statement differ from the other
statements?
12. State and explain various identifiers in C program. And also discuss about operator
precedence in expression evaluation with a suitable example.
13. Explain with a sample program about while, for, do-while and switch statements in C
programming
14. Explain the difference between break, goto and continue statements with an example
16. Explain the difference between while and do-while statements with suitable examples.
17. Write a C program to print digits in reverse order for a given number.
20. Write C program to print prime numbers in a given series of numbers. For example:
numbers from 1 to 100.
21. What is a flowchart? Discuss various symbols used in flowchart. Illustrate with an
example.
23. What is meant by assembly language? Give example. Differentiate between pre test
and post test loops.
24. What is the need of type conversion? Discuss type casting. b) List the demerits of go
to statement. c) Why is switch statement known as multi way selection?
25. Explain switch statement. Explain its usage with a sample C-program. What are the
storage classes in C? Explain their usage with a sample C-program.
26. Explain scope of a variable with an example. Write brief notes on computer languages
OBJECTIVE QUESTIONS
UNIT-II
ARRAYS
2.1 Arrays:
An array is a group of related data items that share a common name.
Ex:- Students
The complete set of students is represented using an array name students. A particular value is
indicated by writing a number called index number or subscript in brackets after array name.
The complete set of value is referred to as an array, the individual values are called elements.
A list of items can be given one variable index is called single subscripted variable or a one-
dimensional array.
Declaration of One - Dimensional Arrays :
This array is of type float. Its name is avg. and it can contains 50 elements only. The range
starting from 0 – 49 elements.
The subscript value starts from 0. If we want 5 elements the declaration will be
int number[5];
The elements will be number[0], number[1], number[2], number[3], number[4] There will not
be number[5]
The size may be omitted. In such cases, Compiler allocates enough space for all initialized
elements.
#include<stdio.h>
main(){
int i;
printf(“Enter 10 numbers\n”);
for(i=0;i<10;i++)
{
scanf(“%d”,&a[i]);
}
printf(“the entered numbers are\n”);
for(i=0;i<10;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
To store tables we need two dimensional arrays. Each table consists of rows and
columns. Two dimensional arrays are declare as
#include<stdio.h>
#include<math.h>
#define ROWS 5
#define COLS 5
main()
printf(“Multiplication table”);
for(j=1;j< =COLS;j++)
printf(“%d”,j);
for(i=0;i<ROWS;i++)
row = i+1;
printf(“%2d|”,row);
COLS=j;
They can be initialized by following their declaration with a list of initial values
enclosed in braces.
Initializes the elements of first row to zero and second row to one. The initialization is
done by row by row. The above statement can be written as
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 70
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
When all elements are to be initialized to zero, following short-cut method may be used.
MULTI-DIMENSIONAL ARRAYS:
#include <stdio.h>
void printArray( const int a[][ 3 ] );
int main()
{
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
printf( "Values in array1 by row are:\n" );
printArray( array1 );
printf( "Values in array2 by row are:\n" );
printArray( array2 );
printf( "Values in array3 by row are:\n);
printArray( array3 );
return 0;
}
void printArray( const int a[][ 3 ] )
{
int i; int
j;
for ( i = 0; i <= 1; i++ ) { for (
j = 0; j <= 2; j++ ) {
APPLICATIONS OF ARRAYS:
FREQUENCY ARRAYS:
Two common statistical applications that use arrays are frequency distributions and
histograms. A frequency array shows the number of elements with an identical value found in
a series of numbers.
For example ,suppose we have taken a sample of 100 values between 0 and 19.We want
to know how many of the values are 0,how many are 1,how many are 2,and so forth up through
19.
We can read these numbers into an array called numbers. Then we create an array of
20 elements that will show the frequency of each number in the series.
One way to do it is to assign the value from the data array to an index and then use the
index to access the frequency array.
F=numbers[i];
Frequency[F]++;
Since an index is an expression ,however ,we can simply use the value from our data
array to index us in to the frequency array .The value of numbers[i] is determined first ,and
then that value is used to index in to frequency.
Frequency[numbers[i]]++
HISTOGRAMS:
1 0
2 4 * * * * ————(four 1s)
3 7*******
4 7 * * * * * * *————(seven 3s)
18 2**
19 0 ————————(zero 19s)
RANDOM NUMBER PERMUTATIONS:
repeated. For example, given a random number permutation of 10 numbers, the values from 0
to 9 would all be included with no duplicates.
To generate a random integral in a range x to y, we must first scale the number and then
,if x is greater than 0 ,shift the number within the range. We scale the number using the modulus
operator.
Ex: To produce a random number in the range 0 …50,we simply scale the random
number and scaling factor must be one greater than the highest number needed.
rand ( ) %51
modulus works well when our range starts at 0.for example ,suppose we want a random number
between 10 and 20.for this we will use one formula
range = ( 20 - 10 ) +1;
Only the first five random numbers have been placed in the permutation. For each
random number in the random number array ,its corresponding location in the have-random
array is set to 1. Those locations representing numbers that have not yet been generated are still
set to 0.
2.4 STRINGS
The group of characters, digits, and symbols enclosed with in double quotation marks are
called as strings.
Ex: “MRECW”
“1234”
Every string terminates with “\0‟ (NULL) character. The decimal equivalent value of null
is zero. We use strings generally to manipulate text such as words and sentences. The
common operations that we can perform on strings are:
The last character of string is always “\0‟ (NULL). But it is not necessary to write “\0‟
character at the end of the string. The compiler automatically puts “\0” at the end of the
string / character array.
The characters or elements of the string are stored in contiguous memory locations.
H E L L O \0
3. Char name[9]={“H‟},{‟E‟},{‟L‟},{‟L‟},{‟O‟}};
In the above three formats we can initialize character arrays. We can also initialize character
array by using standard input functions like scanf( ), gets ( ) etc and we can display strings
by using puts ( ), printf ( ) functions.
The size of the character array: The argument / size of the character array or string =
Number of characters in the string + NULL character.
Note:
1. If NULL character is not taken in account then the successive string followed by the first
string will be displayed.
2. If we declare size of a string equal to the number of characters. i.e., without taking the NULL
character in to account and we print that will display some garbage value followed by the string.
To read strings from terminal we can use scanf ( ) function with “%s‟ format specifier.
scanf(“%s”, name);
Limitation: If we use scanf ( ) function for reading string in runtime it terminates its input on
the first white space it finds. The scanf ( ) function automatically append NULL character at
the end of the input string, so we have to declare a (size of) character array which can
accommodate input string and NULL character.
(White space: blanks, tab space, carriage returns, new lines etc.)
By using gets ( ) function we can read a text which consists of more than one word which i not
possible with scanf ( ) function. This function is available in <stdio.h> header file.
We know that getchar ( ) function is used to read single character from the terminal. By using
this function repeatedly we can read successive single characters from the input and place them
into a character array (string). The reading is terminated when the user enters new line character
(\n) or press enter key. After reading the new line character this function automatically appends
NULL character at the end of the string in the place of new line character.
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 75
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
Using printf ( ) function we can display the string on output screen with the help of format
specifier „%s‟.
Ex: printf(“%s”,name);
We can use different format specifications to display strings in various formats according to
requirements.
Using puts ( ) function we can display the string without using any format specifier. This
function is available in the <stdio.h> header file in C library.
Using putchar ( ) function we can display one character at a time. So, by using this function
repeatedly with the help of a loop statement we can display total string.
for (i=0;i<5;i++)
putchar (name[i]);
The following table provides frequently used string handling functions which are supported
by C compiler.
FUNCTIONS DESCRIPTION
strlen ( ) Determines Length of a string
strcpy ( ) Copies a string from source to destination
strncpy ( ) Copies specified number of characters of a string to another string
strcmp ( ) Compares two strings (Discriminates between small and capital letters)
Compares two strings (Doesn‟t Discriminates between small and capital
stricmp ( )
letters)
strncmp ( ) Compares characters of two strings upto the specified length
Compares characters of two strings upto the specified length. Ignores
strnicmp ( )
case.
strlwr ( ) Converts upper case characters of a string to lower case
strupr ( ) Converts lower case characters of a string to upper case
strdup ( ) Duplicates a string
Determines first occurrence of a given character
strchr ( )
in a string
Determines last occurrence of a given character
strrchr ( )
in a string
strstr ( ) Determines first occurrence of a given string in another string
strcat ( ) Appends source string to destination string
strncat ( ) Appends source string to destination string upto specified length
strrev ( ) Reverses all characters of a string
strset ( ) Sets all characters of string with a given argument or symbol
Sets specified number of characters of string with a given argument or
strnset ( )
Symbol
strspn ( ) Finds up to what length two strings are identical
Searches the first occurrence of the character in a given string and then
strpbrk ( )
it display the string from that character.
1. strlen ( ) function: This function counts the number of characters in a given string.
void main( )
char a[80];
int len;
clrscr( );
printf(“enter string:”);
len=strlen(a);
getch( );
(OR )
void main()
int s;
clrscr( );
s=strlen(“MRECW”);
getch( );
Output: Output:
2. strcpy ( ) function: This function copies the content of one string to another. Here string1
is source string and string2 destination string. String1 and string2 are character arrays.
String1 is copied into string2.
void main( )
clrscr( );
strcpy(s2,s1);
getch( );
Output:-
3. strncpy ( ) function: This function performs the same task as strcpy ( ). The difference
between them is that the strcpy( ) function copies the whole string to destination string.
Whereas strncpy( ) function copies specified length of characters from source to destination
string.
or
strcpy(destination, source,n);
void main()
int n;
clrscr( );
gets(s1);
gets(s2);
getch( );
Output:
Destination string=wonderful
4. strcmp ( ) function: This function is used to compare two strings identified by the
arguments and it returns a value “0‟ if they are equal. If they are not equal it will return
numeric difference (ASCII) between the first non-matching characters.
void main( )
int s;
clrscr( );
s=strcmp(m1, m2);
printf(“ %d ”, s);
getch( );
Output:-
-1
void main( )
int m;
clrscr( );
m = strcmp(s1, s2);
if(m==0)
else if(m<0)
getch( );
Output:-
enter 2 strings
mrecw
computers
mrecw computers
5. stricmp ( ) function: This function is used to compare two strings. The characters of the
strings may be in lower to upper case. This function does not determinate between the
cases.
This function returns zero when two strings are same and it returns non-zero value if they are
not equal
void main( )
}
Output:-
6. strncmp ( ) function: This function is used to compare two strings. This function is same
as strcmp( ) but it compares the character of the string to a specified length
or
void main( )
{
char sr[30], tr[30];
int s,n;
clrscr( );
printf (“\nEnter Source String:”);
gets(sr);
printf (“\nEnter Target String:”);
gets(tr);
printf(“\n Enter length up to which comparison is to be made:”); scanf(“%d”,&n);
s=strncmp(sr,tr,n);
if(s==0)
puts(“The two strings are Identical up to %d characters.”,n); else
puts(“The two strings are Different”);
getche( );}
Output:-
7. strnicmp ( ) function: This function is used to compare two strings. This function is same
as strcmp( ) but it compares the character of the string to a specified length.
(or)
void main( )
int s,n;
clrscr( );
gets(sr);
gets(tr);
scanf(“%d”,&n);
s=strnicmp(sr,tr,n);
if(s==0)
getche( );
Output:-
Enter length upto which comparison is to be made5 The two strings are different.Enter
Source String: goodmorning
8. strlwr ( ) function: This function can be used to convert any string to a lower case.
When you are passing any uppercase string to this function it converts into lower case.
Syntax: strlwr(string);
strupr ( ) function: This function is the same as strlwr( ) but the difference is that strupr( )
converts lower case strings to upper case.
Syntax: strupr(string);
void main ( )
clrscr( );
strlwr(a);
strupr(b);
getch( );
Output:-
SACHIN Karan
sachin KARAN
9. strdup( ) function: This function is used for duplicating a given string at the allocated
memory which is pointed by a pointer variable.
void main( )
clrscr( );
printf(“Enter text:”);
gets(s1);
s2 = strdup(s1);
getch();
Output:
10. strchr( ) function: This function returns the pointer to a position in the first occurrence
of the character in the given string.
Where, string is character array, ch is character variable & chp is a pointer which collects
address returned by strchr( ) function.
void main( )
clrscr( );
printf(“Enter text:”);
gets(s);
ch = getchar( );
chp = strchr(string,ch);
if(chp)
else
getch( );}
Output:
Character to find: r
11. strrchr( ) function: In place of strchr( ) one can use strrchr( ). The difference between
them is that the strchr( ) searches occurrence of character from the beginning of the string
where as strrchr( ) searches occurrence of character from the end (reverse).
Syntax: chp = strrchr(string, ch);
12. strstr( ) function: This function finds second string in the first string. It returns the pointer
location from where the second string starts in the first string. In case the first occurrence
in the string is not observed, the function returns a NULL character.
Syntax: strstr(string1,string2);
Example Program: To implement strstr( ) function for occurrence of second string in the
first string.
void main( )
clrscr( );
printf(“Enter text:”);
gets(s1);
printf(“\nEnter text:”);
gets(s2);
chp = strstr(s1,s2);
if(chp)
getch( );}
Output:
13. strcat ( ) function: This function appends the target string to the source string.
Concatenation of two strings can be done using this function.
#include<string.h>
void main ( )
clrscr( );
getch( );
Output:-
Hello Mrecw
HelloMrecw
14. strncat( ) function: This function is the same as that of strcat( ) function. The difference
between them is that the former does the concatenation of two strings with another up to
the specified length. Here, n is the number of characters to append.
Example Program: To append 2nd string with specified no. of characters at the end of the
string using strncat( ) function.
#include<string.h>
void main ( )
int n;
clrscr( );
scanf("%d",&n);
strcat(s," ");
strncat(s,a,n);
getch( );
Output:-
s= Hello a = Mrecw
Hello Mr
15. Strrev ( ) function: This function simply reverses the given string.
Syntax: strrev(string);
#include<string.h>
char s[30]=”hello”;
clrscr( );
strrev(s);
getch( );
Output:-
s1=hello
s2=olleh
void main( )
char t[30];
clrscr( );
printf(“enter string:”);
strrev(t);
getch( );
Output:
16. strset( ) function: This function replaces every character of a string with the symbol given
by the programmer i.e. the elements of the strings are replaced with the arguments given
by the programmer.
Syntax: strset(string,symbol);
Example:
void main( )
clrscr( );
puts(“Enter string:”);
gets(st);
scanf(“%c”,&symbol);
strset(st,symbol);
getch( );
Output:
17. strnset( ) function: This function is the same as that of strset( ). Here the specified length
is provided. Where, n is the no. of characters to be replaced.
Syntax: strnset(string,symbol,n);
Example:
void main( )
int n;
clrscr( );
puts(“Enter string:”);
gets(st);
scanf(“%c”,&symbol);
strnset(st,symbol,n);
getch( );
Output:
18. strspn( ): This function returns the position of the string from where the source array does
not match with the target one.
Syntax: strspn(string1,string2);
Example Program: To indicate after what character the lengths of the 2 strings have no
match.
void main( )
int len;
clrscr( );
printf(“Enter string1:”);
gets(s1);
printf(“\nEnter string2:”);
gets(s2);
len = strspn(s1,s2);
getch( );
Output:
19. strpbrk( ) function: This function searches the first occurrence of the character in a
given string and then it display the string starting from that character.
Example Program: To print given string from first occurrence of given character.
void main( )
char *ptr;
clrscr( );
printf(“Enter string:”);
gets(string1);
gets(string2);
ptr = strpbrk(string1,string2);
printf(ptr);
getch();
Output:
Enter a character: d
char x = “a‟;
printf (“%d”,x);
The above statement will display integer value 97 on the screen even though x is a character
variable, because when a character variable or character constant is used in an expression, it is
automatically converted in to integer value by the system. The integer value is equivalent to
ASCII code.
Ex: int x;
x=‟z‟-1;
printf(“%d”,x);
The above statement is valid statement and that will display 121 one as result, because ASCII
value of “z‟ is 122 and therefore the resultant value is 122 – 1 = 121.
atoi ( ) function:
This library function converts a string of digits into their integer values.
Ex: int x;
x = atoi(no);
printf(“%d”,x);
2.8 Structures:
Definition: In the C language structures are used to group together different types
of variables under the same name.
Structure is a collection of variables of different data types under single name. A structure
provides a convenience to group of related data types. A structure can contain variables,
pointers, other structures, arrays or pointers. All these variables may contain data items of
similar or dissimilar data types. Using these variables each item of a structure can be selected.
Each variable in the structure represents an item and is called member or field of the structure.
Each field has a type.
type1 member1;
type2 member2;
……..
……..
};
“struct” is the keyword which tells the compiler that a structure is being defined
member1, member2 … are called members of the structure.
The members are declared with curly braces. The members can be any of the data types such
as int, char, float etc.There should be semicolon at the end of closing brace.
Example:
struct lib_books
char title[20];
char author[15];
int pages;
float price;
};
struct lib_books
char title[20];
char author[15];
int pages;
float price;
To holds the details of four fields namely title, author pages and price,the keyword struct
declares a structure. These are the members of the structures. Each member may belong to
same or different data type. The tag name can be used to define the objects that have the tag
names structure. The structure we just declared is not a variable by itself but a template for the
structure. We can declare the structure variables using the tag name anywhere in the program.
For example the statement, struct lib_books book1,book2,book3; declares the
book1,book2,book3 as variables of type struct lib_books each declaration has four elements of
the structure lib_books.
A structure is a collection of variables under a single name. These variables can be of different
types, and each has a name which is used to select it from the structure. A structure is a
convenient way of grouping several pieces of related information together.
As variables are defined before they are used in the function, the structures are also defined
and declared before they are used. A structure can be declared using three different ways
Tagged structures
Structure Variables
Tagged structure means the structure definition associated with structure name is called
tagged structure (i.e. tag_name is the name of the structure).
char name[10];
int roll_number;
float avg_marks;
};
Here, student is an identifier representing the structure name. It is also called tagname.
char name[10];
int roll_number;
float avg_marks;
};
truct tag_name
type1 member1;
type2 member2;
Structure Variables:
struct student
char name[10];
int roll_number;
float avg_marks;
} ece, cse;
1.
name, roll_number and average_marks are members of a structure and are not
variables. So, they themselves do not occupy any memory.
But, once the structure definition is associated with variables such as ece and cse the
compiler allocates memory for the structure variables
typedef struct
type1 member1;
type1 member1;
………}typeid;
- Using typedef it is not possible to declare a variable. Here, TYPE_ID can be treated
as the new date type.
- Normally all typedef statements are defined at the beginning of the file immediately
after #include and #define statements in a file.
typedef struct
char name[10];
int roll_number;
float avg_marks;
} student;
Initialization of structures
Consider the structure definition for an employee with three fields name, salary and is as shown
below,
struct employee
char name[10];
int id;
float salary;
} a = {“Shivashankar”,1686,20000.28};
( OR )
struct emp
char name[10];
int id;
float salary;
};
Struct emp b = {“Shiva”,1886,18898.28}; //structure declaration with more than one value
We can access and assign values to the members of a structure in a number of ways. As
mentioned earlier, the members themselves are not variables. The link between a member and
a variable is established using the member operator „.‟ Which is also known as “dot operator”
or “period operator”.
char title[20];
char author[20];
int pages;
float price;
strcpy(book1.title, “basic”);
strcpy(book1.author, “balagurusamy”);
book1.pages=250;
book1.price=120.50;
scanf(“%s \n”,book1.title);
scanf(“%s \n”,&book1.pages);
Example2:
struct library_books
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct informs the compiler for holding fields ( title, author, pages and price in
the above example). All these are the members of the structure. Each member can be of same
or different data type.
The tag name followed by the keyword struct defines the data type of struct. The tag name
library_books in the above example is not the variable but can be visualized as template for
the structure. The tag name is used to declare struct variables.
The memory space is not occupied soon after declaring the structure, being it a template.
Memory is allocated only at the time of declaring struct variables, like book1 in the above
example. The members of the structure are referred as - book1.title, book1.author,
book1.pages, book1.price.
Two variables of the same structure type can be copied the same way as ordinary variables. If
person1 and person2 belong to the same structure, then the following statements are valid:
book2=book1;
C does not permit any logical operations on structure variables. In case, we need to compare
them, we may do so by comparing members individually.
book1 == book2
book1 != book2
The individual members are identified using the members are identified using the member
operator. A member with the dot operator along with its structure variable can be treated like
any other variable name and therefore can be manipulated using expressions and operator.
We can also apply increment and decrement operators to numeric type members.
student1.number++;
++student1.number;
We have used the dot operator to access the members of structure variables. In fact, there are
two other ways. The identifier ptr is known as pointer that has been assigned the address of
the structure variable n. now members can be accessed in three ways:
We may declare an array of structures, each element of the array representing a structure
variable. For example:
define an array called student, that consists of 100 elements. Each element is defined to be of
the type struct class.
Write a c program to calculate the subject wise and student wise totals and store them
as a part of the structure.
struct marks
int sub1;
int sub2;
int sub3;
int total;
};
void main( )
int i;
for(i=0;i<=2;i++)
student[i].total=student[i].sub1+ student[i].sub2+
student[i].sub3; total.sub1=total.sub1+student[i].sub1;
total.sub2=total.sub2+student[i].sub2;
total.sub3=total.sub3+student[i].sub3;
total.total=total.total+student[i].total;
printf(“Student Total\n\n”);
for(i=0;i<=2;i++)
”,total.sub3)
“subject1 ”,total.sub1, “subject2 ”,total.sub2, “subject3 ;
getch();
Output:
Student Total
student[1] 193
student[2] 197
student[3] 164
Subject Total
subject1 177
subject2 156
subject3 221
C permits the use of arrays as structure numbers. We have already used arrays of characters
inside a structure. Similarly, we can use single dimension or multidimensional arrays of type
int or float.
struct marks
int number;
float subject[3];
} student[2];
Here, the member subject contains three elements, subject[0], subject[1] and subject[2].
Example program:
void main( )
struct marks
int sub[3];
int total;
};
int i, j;
for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
student[i].total += student[i].sub[j];
total.sub[j] += student[i].sub[j];
total.total += student[i].total;
printf(“Student Total\n\n”);
for(i=0;i<=2;i++)
getch();
Output:
Student Total
student[1] 193
student[2] 197
student[3] 164
Subject Total
subject1 177
subject2 156
subject3 221
Write a C program to read and display car number, starting time and reaching time.
void main( )
struct time
int second;
int minute;
int hour;
};
struct tt
int carno;
};
struct tt r1;
clrscr( );
scanf(“%d”,&r1.carno);
printf(“\t%d\t”,r1.carno);
getch(); }
Output:
Like variables of standard data type structure variables also can be passed to the function by
value or address.
struct book {
char n[30];
char author[30];
int pages;
};
void main()
show(&b1);
getch();
clrscr();
If you want a pointer to a structure you have to use the -> (infix operator) instead of a dot.
#include<stdio.h>
char *name;
int number;
}TELEPHONE;
void main()
TELEPHONE index;
TELEPHONE *ptr;
ptr = &index;
ptr->number = 12345;
getch();
Note: The -> (infix operator) is also used in the printf statement.
A structure definition which includes at least one member as a pointer to the same structure
is known as self-referential structure.
Syntax: Example:
struct struct_name
{ Struct student
datatype datatypename;
Char n[50];
struct_name * pointer_name;
Int rollno;
};
};
2.13 UNIONS
Unions are like structures, in which the individual data types may differ from each other. All
the members of the union share the same memory / storage area in the memory. Every member
has unique storage area in structures. In this context, unions are utilized to observe
the memory space. When all the values need not assign at a time to all members, unions are
efficient. Unions are declared by using the keyword union, just like structures.
union tag_name {
type1 member1;
type1 member2;
};
int code;
floa the memory space. When all the values need not assign at a time to all members, unions
are efficient. Unions are declared by using the keyword union, just like structures.
int code;
float price;
};
A union is utilized to use same memory space for all different members of union. Union offers
a memory section to be treated for one variable type , for all members of the union. Union
allocates the memory space which is equivalent to the member of the union, of large memory
occupancy.
A union is like a structure in which all members are stored at the same address. Members of a
union can only be accessed one at a time. The union data type was invented to prevent memory
fragmentation. The union data type prevents fragmentation by creating a standard size for
certain data. Just like with structures, the members of unions can be accessed with the . and ->
operators. For example:
#include<stdio.h>
double PI;
int B;
}MYUNION;
void main()
MYUNION numbers;
numbers.PI = 3.14;
numbers.B = 50;
getch();
t price;};
UNION OF STRUCTURE
We know that one structure can be nested within another structure. It the same way a union can
be nested another union. We can also create structure in a union or vice versa.
Write a program to use structure within union. Display the contents of structure
elements.
{ st.set.f = 5.5;
{ st.set.p[1] = 66;
float f; clrscr();
}; printf(“\n%c”,st.set.p[0]);
union z printf(“\t%c”,st.set.p[1]);
{ }
}; A B
Structure Union
1. The keyword struct is used to define 1. The keyword union is used to define
a structure. a structure.
structure, the compiler allocates the union, the compiler allocates the
memory for each member. The size of memory by considering the size of the
the structure is greater than or equal to largest member. So, a size of union is
the sum of sizes of its members. The equal to the size of largest member.
slack bytes.
4. The address of each member will be 4. The address is same for all the
in ascending order. This indicates that members of a union. This indicates that
memory for each member will start at every member begins at offset values.
5. Altering the value of a member will 5. Altering the value of any of the
not affect other members of the member will alter other member values.
structure.
at a time. a time.
7. Several members of a structure can 7. Only the first member of a union can
2.14 POINTERS :
One of the powerful features of C is ability to access the memory variables by their
memory address. This can be done by using Pointers. The real power of C lies in the proper
use of Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say that
a pointer points to a variable that is stored at that address. A pointer itself usually occupies 4
bytes of memory (then it can address cells from 0 to 232-1).
Advantages of Pointers :
1. A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
2.15 Definition :
Declaration :
Datatype * Variable-name;
Eg:- int *ad; /* pointer to int */
char *s; /* pointer to char */
float *fp; /* pointer to float */
char **s; /* pointer to variable that is a pointer to char */
Here ‘&’ is called address of a variable. ‘p’ contains the address of a variable i
The operator & returns the memory address of variable on which it is operated, this is
called Referencing.
int *p,x; x
=5; p= &x;
Assume that x is stored at the memory address 2000. Then the output for the following
printf statements is :
Output
Printf(“The Value of x is %d”,x); 5
Printf(“The Address of x is %u”,&x); 2000
Printf(“The Address of x is %u”,p); 2000
Printf(“The Value of x is %d”,*p); 5
Printf(“The Value of x is %d”,*(&x)); 5
}
#include <stdio.h>
void bad_swap(int x, int y);
void good_swap(int *p1, int *p2);
main() {
int a = 1, b = 999;
printf("a = %d, b = %d\n", a, b);
bad_swap(a, b);
printf("a = %d, b = %d\n", a, b);
good_swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
}
Now both a and a[0] points to location 2000. If we declare p as an integer pointer, then we
can make the pointer P to point to the array a by following assignment
P = a;
We can access every value of array a by moving P from one element to another.
i.e., P points to 0th element
P+1 points to 1st element
P+2 points to 2nd element
P+3 points to 3rd Element
#include <stdio.h>
void swap(int,int);
main()
{
int a,b;
printf(“Enter the Values of a and b:”);
scanf(“%d%d”,&a,&b); printf(“Before
Swapping \n”); printf(“a = %d \t b = %d”,
a,b); swap(a,b);
printf(“After Swapping \n”);
printf(“a = %d \t b = %d”, a,b);
}
void swap(int a, int b)
{
int temp;
temp = a; a =
b;
b = temp;
}
#include<stdio.h>
main()
{
int a,b; a =
10; b = 20;
swap (&a, &b); printf(“After
Swapping \n”);
ADDRESS ARITHIMETIC :
We can add and subtract integers to/from pointers – the result is a pointer to another element
of this type
NULL POINTER :
‘Zero’ is a special value we can assign to a pointer which does not point to anything
most frequently, a symbolic constant NULL is used. It is guaranteed, that no valid address is
equal to 0.The bit pattern of the NULL pointer does not have to contain all zeros usually it does
or it depends on the processor architecture. On many machines, dereferencing a NULL pointer
causes a segmentation violation.
if (psz1)
/* use psz1 */
sizeof(psz1) // doesn't give you the number of elements in psz1. Need
additional size variable.
VOID POINTER :
In C ,an additional type void *(void pointer) is defined as a proper type for generic
pointer. Any pointer to an object may be converted to type void * without loss of information.
If the result is converted back to the original type ,the original pointer is recovered .
Ex:
main()
{
void *a; int
n=2,*m;
double d=2.3,*c;
a=&n;
m=a;
printf(“\n%d %d %d”,a,*m,m);
a=&d;
c=a;
printf(“\n%d %3.1f %d”,a,*c,c);
}
In the above program a is declared as a pointer to void which is used to carry the address of an
int(a=&n)and to carry the address of a double(a=&d) and the original pointers are recovered
with out any loss of information.
POINTERS TO POINTERS :
So far ,all pointers have been pointing directely to data.It is possible and with
advanced data structures often necessary to use pointers to that point to other pointers. For
example,we can have a pointer pointing to a pointer to an integer.This two level indirection
is seen as below:
//Local declarations
int a;
int* p; int
**q;
q p a
Ex:
234560 287650 58
There is no limit as to how many level of indirection we can use but practically we
seldom use morethan two.Each level of pointer indirection requires a separate indirection
operator when it is dereferenced .
In the above figure to refer to ‘a’ using the pointer ‘p’, we have to dereference it as
shown below.
*p
To refer to the variable ‘a’ using the pointer ‘q’ ,we have to dereference it twice toget
to the integer ‘a’ because there are two levels of indirection(pointers) involved.If we
dereference it only once we are referring ‘p’ which is a pointer to an integer .Another way to
say this is that ‘q’ is a pointer to a pointer to an integer.The doule dereference is shown below:
**q
In above example all the three references in the printf statement refer to the variable ‘a’. The
first printf statement prints the value of the variable ‘a’ directly,second uses the pointer ‘p’,third
uses the pointer ‘q’.The result is the value 58 printed 3 times as below
58 58 58
The data types defined by the user are known as the user-defined data types. C provides two
identifiers typedef and enum to create new data type names.
Typedef:
It allows the user to define an identifier that would represent an existing data type. The user-
defined data type identifier can later be used to declare variables.
Typedef cannot create a new type but it creates a new name to the existing type.
The main advantage of typedef is that we can create meaningful data type names for
increasing the readability of the program.
{ printf(“\n minutes=%d \t
Enumeration:
Identifier: it is a user defined enumerated data type which can be used to declare variables that
can have one of the values enclosed within the braces (enumeration constants).
The enumerated variables v1, v2, v3,…….,vn can only have one of the values value1,
value2, …….,valuen .
v4 = value2;
Ex: enum day {Monday, Tuesday, Wednesday, …. Sunday}; (definition of identifier „day‟)
week_st = Monday;
week_end= Friday;
Note:
2. The compiler automatically assigns integer digits beginning with 0 to all the enumeration
constants .i.e. 0 is assigned to value1, 1 is assigned to value2, 2 is assigned to value3, and
soon. User can also assign values explicitly to the enumeration constants.
Ex: enum day {Monday=1, Tuesday, Wednesday, …. Sunday};
Tutorial Questions
1. include <stdio.h>
struct student
{
char *name;
};
void main()
{
struct student s, m;
s.name = "st";
m = s;
printf("%s%s", s.name, m.name);
} Ans______________________
2. #include <stdio.h>
struct student
{
char *name;
};
struct student s[2];
void main()
{
s[0].name = "alan";
s[1] = s[0];
printf("%s%s", s[0].name, s[1].name);
s[1].name = "turing";
printf("%s%s", s[0].name, s[1].name);
} Ans__________________________
struct point
{
int x;
int y;
};
int main()
{
struct point p = {1};
struct point p1 = {1};
if(p == p1)
printf("equal\n");
else
printf("not equal\n");
}
#include <stdio.h>
int main(void) {
int i,t[3];
for(i = 2; i >=0 ; i--)
t[i] = i - 1;
printf("%d",t[1] - t[t[0] + t[2]]);
return 0;
}
Ans________________________
7. include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "Hello", str2[20] = " World";
printf("%s\n", strcpy(str2, strcat(str1, str2)));
return 0;
} Ans___________________________
8. #include<stdio.h>
#include<string.h>
int main()
char sentence[80];
int i;
printf("Enter a line of text\n");
gets(sentence);
for(i=strlen(sentence)-1; i >=0; i--)
putchar(sentence[i]);return o;}
Ans___________________
Assignment Questions
SET 1:
1. Implement a c program to transpose the given matrix.
2. Implement a C program to add elements of array by passing it as an argument.
SET 2:
SET 3:
1. Implement a c program to find the largest from given strings.
2. Discuss call by value and call by reference.
SET 4
1. Implement a c program to show the difference between gets() and scanf().
2. Explain the importance of reaaloc() and free().
SET 5:
1. Implement a C program to read and print an employee's detail using structure
SET-6
Important Questions
4. The elements or the members of the Array are accessed by _______________ names.
(same/different).
_______________.
Dimensional.
8. main() { int i=1; while (i<=5) { printf("%d",i); if (i>2) goto here; i++; } } fun() { here:
printf("PP");
int main()
int arr[5];
// is 32 bit
arr++;
printf("%u", arr);
return 0;
int n = sizeof(arr)/sizeof(arr[0]);
int i;
int main()
print(arr);
return 0;
int i;
return 0;
return 0;
}
18. Are the three declarations char **apple, char *apple[], and char apple[][] same?
19. What is the output of this C code?
int main()
{
char *p = NULL;
char *q = 0;
if (p)
printf(" p ");
else
printf("nullp");
if (q)
printf("q\n");
else
printf(" nullq\n");
}
20. #include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "Hello", str2[20] = " World";
printf("%s\n", strcpy(str2, strcat(str1, str2)));
return 0;
}
21. #include<stdio.h>
int main()
{
char p[] = "%d\n";
p[1] = 'c';
printf(p, 65);
return 0;
}
22. String manipulation functions use _________________library function.
23 Getchar() is _____________ function.
24 Int **p is ___________________ declaration.
26. Is String is data type?_____
28. Which operator connects the structure name to its member name______
void main()
{
struct student
{
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 131
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
int no;
char name[20];
};
struct student s;
s.no = 8;
printf("%d", s.no);
}
Number of bytes in memory taken by the below structure is?
struct test
{
int k;
char c;
};
31. Size of a union is determined by size of the____________
int main()
{
struct a
{
float category:5;
char scheme:4;
};
printf("size=%d", sizeof(struct a));
return 0;
}
34. #include<stdio.h>
int main()
{
struct emp
{
char name[20];
float sal;
};
struct emp e[10];
int i;
for(i=0; i<=9; i++)
scanf("%s %f", e[i].name, &e[i].sal);
return 0;
}
UNIT – III
PREPROCESSOR
3.1 Preprocessor
Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
1. #include
#include is used to insert specific header file into C program.
Syntax:
#include filename
● The content that is included in the filename will be replaced at the point where the directive is
written.
● By using the file inclusive directive, we can include the header files in the programs.
● Macros, function declarations, declaration of the external variables can all be combined in the
header file instead of repeating them in each of the program.
● The stdio.h header file contains the function declarations and all the information regarding the
input and output.
● If the first way is used, the file and then the filename in the current working directory and the
specified list of directories would be searched.
● If the second way, is used the file and then the filename in the specified list of directories would
be searched.
2. #define
#define is used to create symbolic constants (known as macros) in C programming language.
This preprocessor command can also be used with parameterized macros.
Syntax:
#define name replacement text
Where,
name – it is known as the micro template.
replacement text – it is known as the macro expansion.
#define LOWER 30
void main()
{
int i;
for (i=1;i<=LOWER; i++)
{
printf("\n%d", i);
}
}
3. #undef:
The #undef directive tells the preprocessor to remove all definitions for the specified macro. A
macro can be redefined after it has been removed by the #undef directive.
Syntax:
#undef macro_definition
Example:
#include <stdio.h>
#define PI 3.14
#undef PI
void main()
{
printf("%f",PI);
}
4. #if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code.
Syntax:
#if expression
//code
#endif
Example:
#include <stdio.h>
#include <conio.h>
#define NUMBER 0
void main() {
#if (NUMBER==0)
printf("Value of Number is: %d",NUMBER);
#endif
getch();
}
Output: Value of Number is: 0
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 135
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
5. #ifdef:
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the
code otherwise #else code is executed, if present.
Syntax:
#ifdef MACRO
//code
#endif
Example:
#include <stdio.h>
#include <conio.h>
#define NOINPUT
void main() {
int a=0;
#ifdef NOINPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output: Value of a: 2
6. #ifndef:
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it
executes the code otherwise #else code is executed, if present.
Syntax:
#ifndef MACRO
//code
#endif
Example:
#include <stdio.h>
#include <conio.h>
#define INPUT
void main() {
int a=0;
#ifndef INPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:
Enter a:5
Value of a: 5
3.2 FILES
File is a collection of bytes that is stored on secondary storage devices like disk. There are two
kinds of files in a system. They are,
Text Files
3.3 Creating and Reading and writing text and binary files
File Operations
In C, you can perform four major operations on the file, either text or binary:
When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and program.
FILE *fptr;
Opening a file is performed using the library function in the "stdio.h" header file: fopen().
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
File
Meaning of Mode During Inexistence of file
Mode
R Open for reading. If the file does not exist, fopen() returns NULL.
Rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing If the file exists, its contents are overwritten. If the file
wb+
in binary mode. does not exist, it will be created.
Closing a File
The file (both text and binary) should be closed after reading/writing.
fclose(fptr);
For reading and writing to a text file, we use the functions fprintf() and fscanf().
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 139
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL){
printf("Error! opening file"); // Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in
case of binary files.
To write into a binary file, you need to use the function fwrite(). The functions takes four
arguments: Address of data to be written in disk, Size of data to be written in disk, number of
such type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Example:
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","wb")) == NULL)
{
printf("Error! opening file"); // Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
fread(address_data,size_data,numbers_data,pointer_to_file);
Example:
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
C programming supports different file open mode to perform different operations on file. To
append data into a file you can use a file open mode.
● Input file path from user to append data, store it in some variable say filePath.
● Declare a FILE type pointer variable say, fPtr.
● Open file in a (append file) mode and store reference to fPtr using fPtr = fopen(filePath, "a");.
● Input data to append to file from user, store it to some variable say dataToAppend.
● Write data to append into file using fputs(dataToAppend, fPtr);.
● Finally close file to save all changes. Use fclose(fPtr);.
Example
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1000
void readFile(FILE * fPtr);
int main()
{
FILE *fPtr;
char filePath[100];
char dataToAppend[BUFFER_SIZE];
printf("Enter file path: ");
scanf("%s", filePath);
fPtr = fopen(filePath, "a");
if (fPtr == NULL)
{
printf("\nUnable to open '%s' file.\n", filePath);
printf("Please check whether file exists and you have write privilege.\n");
exit(EXIT_FAILURE);
}
printf("\nEnter data to append: ");
fflush(stdin); // To clear extra white space characters in stdin
fgets(dataToAppend, BUFFER_SIZE, stdin);
fputs(dataToAppend, fPtr);
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 142
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
Example:
#include<stdio.h>
#include<conio.h>
struct person
{
int id;
char fname[20];
char lname[20];
};
int main ()
{
FILE *outfile;
outfile = fopen ("person.dat", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
Example:
#include<stdio.h>
#include<conio.h>
struct person
{
int id;
char fname[20];
char lname[20];
};
int main ()
{
FILE *infile;
struct person input;
infile = fopen ("person.dat", "r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit (1);
}
while(fread(&input, sizeof(struct person), 1, infile))
printf ("id = %d name = %s %s\n", input.id,
input.fname, input.lname);
return 0;
}
There is no need to read each record sequentially, if we want to access a particular record. C
supports these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
We use the fseek() function to move the file position to a desired location.
Syntax:
fseek(fptr,offset,position);
Where, fptr is the file pointer. offset which is of type long, specifies the number of
positions (in bytes) to move in the file from the location specified by the position.
The position can take the following values.
Following are the list of operations we can perform using the fseek() function.
Operation Description
fseek(fptr, N, 1) This will take us N bytes forward from the current position in the
file.
fseek(fptr, -N, 1) This will take us N bytes backward from the current position in the
file.
fseek(fptr, -N, 2) This will take us N bytes backward from the end position in the
file.
Example:
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is tutorialspoint.com", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}
The ftell() function tells us about the current position in the file (in bytes).
Syntax:
pos=ftell(fptr);
Where, fptr is a file pointer. pos holds the current position i.e., total bytes read (or written).
Example:
If a file has 10 bytes of data and if the ftell() function returns 4 then, it means that 4 bytes
has already been read (or written).
#include<stdio.h>
int main()
{
FILE *fp = fopen("test.txt","r");
char string[20];
fscanf(fp,"%s",string);
printf("%ld", ftell(fp));
return 0;
}
We use the rewind() function to return back to the starting point in the file.
Syntax:
rewind(fptr);
Where, fptr is a file pointer.
Example
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
rewind(fp);//moves the file pointer at beginning of the file
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
getch();
}
The contents in file.txt is “ this is a simple text”
The output can be displayed as “this is a simple textthis is a simple text”.
TUTORIAL QUESTIONS
1. #include <stdio.h>
int main(void) {
FILE f;
f = fopen("file","wb");
printf("%d",f != NULL);
fclose(f);
return 0;
}
2. #include <stdio.h>
int main(void) {
int i;
i = fprintf(stdin,"Hello!");
printf("%d",i == EOF);
return 0;
}
3. #include <stdio.h>
int main(void) {
FILE *f = fopen("file","w");
char c;
fputs("12A",f);
fclose(f);
f = fopen("file","r");
fscanf(f,"%c",&c);
fclose(f);
printf("%c",c);
return 0;
}
4. Implement a c program to read the content of five students in a file.
ASSIGNMENT QUESTIONS
SET-1
SET-2
SET-3
SET-4
SET-5
1. Write a program to merge two given files and store in a target file.
2. How to handle errors in file management?
SET-6
SET-7
IMPORTANT QUESTIONS
1. Define file. Expalin how to open and read a file.
2. Discuss about the different modes available for opening a file.
3. Explain about fseek( ).
4. Write a ‘C’ program to count the number of characters in a file.
5. Explain various standard library functions for handling files.
6. Write a ‘C’ program to create a file contains a series of integer numbers and then
reads all numbers of this file and write all odd numbers to other file called odd and
write all even numbers to a file called even.
7. Discuss file positioning functions in C.
8. What are file streams? Discuss about state of file, opening and closing file with a
sample C program.
9. Write a program to merge two given files and store in a target file.
10. How to handle errors in file management?
11. Expalin about fprintf and fscanf functions.
12. Implement a C program to display the content of file.
13. Define preprocessor commands ? Explain its advantages?
14. #define is used for?
15. What Are Types Of Preprocessor In C
OBJECTIVE QUESTIONS
8. #include<stdio.h>i
int main()
{
FILE *fp;
fp=fopen("trial", "r");
return 0;
}
What does fp point to in the program ?
10 #include<stdio.h>
int main()
{
FILE *fp1, *fp2;
fp1=fopen("file.c", "w");
fp2=fopen("file.c", "w");
fputc('A', fp1);
fputc('B', fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
UNIT-IV
FUNCTIONS
4.1 Designing Structured Programs:
A function is a self contained program segment that carries out a specific, well-defined task.
1. Library Functions
2. User defined Functions
● The library functions are pre-defined set of functions. Their task is limited. A user
cannot understand the internal working of these functions. The user can only use the
functions but can‟t change or modify them.
Ex: sqrt(81) gives result 9. Here the user need not worry about its source code, but the result
should be provided by the function.
● The User defined functions are totally different. The functions defined by the user
according to his requirement are called as User defined functions. The user can modify
the function according to the requirement. The user certainly understands the internal
working of the function. The user has full scope to implement his own ideas in the
function. Thus the set of such user defined functions can be useful to another
programmer. One should include the file in which the user-defined functions are stored
to call the functions in the program.
Ex: Let square(9) is user-defined function which gives the result 81.
Here the user knows the internal working of the square() function, as its source code is visible.
This is the major difference between the two types of functions.
Why we use functions?
● If we want to perform a task repetitively then it is not necessary to re-write the particular
block of the program again and again. Shift the particular block of statements in a user-
defined function. The function defined can be used for any number of times to perform
the task.
● Suppose a section of code in a program calculates the simple interest for some specified
amount, time and rate of interest. Consider a scenario, wherein later on in the same
program the same calculation has to be done for a different amount, rate and time.
● Functions come to rescue here. Rather than writing the same instructions all over again,
a function can be written to calculate the simple interest for any specified amount, time
and rate. The program control is then transferred to the function, the calculations are
performed and the control is transferred back to the place from where it was transferred.
● Using functions large programs can be reduced to smaller ones.
● It is easy to debug and find out the errors in it. It also increases readability.
3. Like variables, function names and their types must be declared and defined before they are
used in a program.
In order to make use of a user-defined function, we need to establish three elements that are
related to functions.
1. Function declaration
2.Function call
3.Function defining
✔
4.3 Signature of function
For Example
● Declaration of a function with no input parameters
void printMatrix();
● Declaration of a function with one input parameter and integer return type
int isEvenNumber(int num);
● Declaration of a function with multiple input parameter and integer return type.
int getSum(int num1, int num2);
● Declaration of a function with no input parameters and integer return type.
int getRandomNumber();
✔ Function type
✔ function name,
✔ list of parameters (arguments)
✔ local variable declarations
✔ body of the functions (list of statements)
✔ a return statement.
All the six elements are grouped into two parts, namely,
▪ The type_specifier specifies the data type of the value, which the function will return.
If no data type is specified, the function is assumed to return an integer result. The
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 152
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
arguments are separated by commas. A function is not returning anything; then we need
to specify the return type as void. A pair of empty parentheses must follow the function
name if the function definition does not include any arguments.
▪ The parameters list / arguments list declares the variables that will receive the data
sent by the calling program. They serve as input data to the function o carry out the
specific task.
4.4.1 Parameters:
The body of the function may consist of one or many statements necessary for performing
the required task. The body consists of three parts:
1. Local variable declaration
2. Function statements that perform the task of the function
3. A return statement that returns the value evaluated by the function. If a function is not
returning any value then we can omit the return statement.
EX: 1. /* program to call main function from another user defined function*/
void main()
{
message();
}
void message ( )
{
printf(“\n welcome to C lab”);
main();
The value evaluated by any function is send back to the calling function by using return
statement. The called function can only return only one value per call. The return statement
has the following forms:
● return;
● return(expression);
⮚ The first form does not return any value to the calling function; it acts as the closing
brace of the function. When a return is encountered, the control is immediately passed
back to the calling function.
⮚ A function may have more than one return statement. This situation arises when the
value returned is based on certain conditions:
EX:
if(a>b)
return(1);
else
return(0);
Note:
⮚ All functions by default return integer type data. But, we can force a function to return
a particular type of data by using a type specifier in the function header as discussed
earlier.
⮚ Once a function is defined and called, it takes some data from the calling function and
returns a value to the called function.
⮚ Whenever a function is called, control passes to the called function and working of
the calling function is stopped. When the execution of the called function is
completed, control returns back to the calling function and execute the next statement.
⮚ The values of actual arguments passed by the calling function are received by the
formal arguments of the called function. The number of actual and formal arguments
should be the same.
⮚ Extra arguments are discarded if they are defined. If the formal arguments are more
than the actual arguments then the extra arguments appear as garbage. Any mismatch
in data type will produce the unexpected result.
⮚ The function operates on formal arguments and sends back the result to the calling
function. The return ( ) statement performs this task.
4.5 Passing parameters to function:
Depending upon the arguments present, return value send the result back to the calling
function. Based on this, the functions are divided into 4 types:
In this type neither the data is passed through the calling function nor is the data sent back
from the called function.
If the functions are used to perform any operations, they act independently. They read data
values and print result in the same block.
This type of functions may be useful to print some messages, draw a line or split the line etc.
{
void message ( ); /*FUNCTION PROTOTYPE*/
message ( ); /*FUNCTION CALL*/
}
void message ( ) /*FUNCTION DEFINITION*/
{
printf(“Have a nice day”); }
y=a+b;
return (y);
}
Calling function Analysis Called function
main() add ( )
{ {
int z; int a=2,b=3,y;
In this type of function no arguments are passed through the main ( ) function (calling
function). But the called function (add ( )) returns the values. Here the called function is
independent. It re data from the keyboard or generates form the initialization and returns the
values. In this type both the calling function and called function are partly communicated
with each other.
In this type of functions arguments are passed to the calling function. The called function
operates on the values. But no result is sent back. This called function is also partly
dependent on the calling function. The result obtained is utilized in the called function only.
void main ( )
{
void add (int, int); /* FUNCTION PROTOTYPE */
int a, b; add (int x,int y) /* FUN DEFINITION*/
clrscr( ); {
printf(“enter the values of a and b”); int z; /*Local variable declaration*/
scanf(“%d%d”, &a,&b); z = x+y;
add(a,b); /* FUNCTION CALL */ printf(“sum = %d”,z);
getch( ); }
}
Explanation: in this program two values are passed to add ( ) function. The add ( ) function
receives argument from main ( ) and displays sum of a and b. But it returns nothing.
In this type of functions a copy of actual argument is passed to the formal argument from the
calling function to the called function. Called function operates on those data values and it
will return the result to the calling function. Here data is transferred between calling and
called functions.
The technique of passing data from one function to another is known as parameters passing.
Parameter passing can be done in two ways:
Call by value
Call by reference
Changes made in the formal arguments are local to the block of the called function. Once the
control returns back to the calling function the changes made vanish.
void main( )
{
int a,b;
printf(“enter any two values\n”);
scanf(“%d%d”,&a,&b);
swap(a,b);
}
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
printf(“after interchange\n”);
printf(“%d %d”,x,y);
}
*x=10;
*y=12;
printf(“\n in display( ) after change \t a=%d \t b=%d \n”, *x, *y);
}
/* Ex 2: Swapping of 2 numbers */
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main( )
{
int a,b;
printf(“enter any two values\n”);
scanf(“%d%d”,&a,&b);
swap(&a,&b);
printf(“after interchange\n”);
printf(“%d %d”,a,b);
getch( );
}
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Function returning more values:
We know that a function can return only one value per call. But we can force the function to
return more than one value per call by using call by reference.
void main( )
{
int x,y, add, sub, change (int*,int*,int*,int*);
clrscr();
printf(“\n enter values of x&y”);
scanf(“%d %d”, &x, &y);
change(&x, &y, &add, &sub);
printf(“\n Addition=%d \n Subtraction=%d”, add, sub);
getch();
}
change(int *a, int *b, int *c, int *d)
{
*c=*a+*b;
*d=*a-*b;
}
Explanation: In this program return statement is not used. Still function returns more than one
value. Actually, no values are returned. Once the addresses of the variables are available, we
can directly access them and modify their contents.
Note:
The memory address of any variable is unique.
If we declare the same variable for actual and formal arguments, their memory addresses will
be different from each other.
In „c‟, a number of pre-defined functions are available to perform various tasks. To use
these functions, we have to include the corresponding header file in which the function is
available.
stdio.h:- (standard input output library functions)
When any of the functions getchar ( ), qets ( ), putchar ( ), puts ( ), scanf( ), printf ( ) is used
the header file stdio.h has to be included.
sqrt ( ):-This function performs square root of the given number. Syntax:- sqrt (n);
log ( ):-This function returns natural logarithm of the given number. Syntax:- log (n);
log10 ( ):-This functions returns logarithm value of the given number to the base 10.
ceil ( ):-This function returns the next higher integer value of the given number. Syntax:-
ceil(n);
Eg:- ceil (17.7)=18 ceil (16.1)=17.
floor( ):-This function returns the integer value less than or equal to the given number.
Cos, acos, cosh, sin, asin, sinh, tan, atan, tanh are also the functions under this header file.
abs( ):-This functions returns the absolute value of a given, integer. Syntax:- abs (integer
value);
fabs( ):-This functions returns absolute value (modulus) of a given floating point number.
atoi ( ):-This function converts the given string to an integer value. Syntax:- atoi(string);
atof ( ):-This function converts the given string into floating point value. Syntax:- atof
(string);
(i) isalpha( ):-This function checks whether the given character is an alphabet (or)
not. If it is an alphabet, it returns a non-zero value and otherwise a zero value.
isalnum( ):- This function checks whether the given character is an alphabet or a number. If
true it returns a non-zero value otherwise a zero value.
Eg:- isalnum(“1‟) True (non-zero)
isalnum(“q‟) False (zero)
isdigit ( ):-This function checks whether the given character is a digit or not. If true it returns
a non-zero value otherwise a zero value.
Eg:- isdigit (“a‟) True (non zero)
isdigit(“*‟) False (zero)
islower ( ):-This function checks whether the given character is a Lower case alphabet or not.
If it is a small letter it returns a non-zero value otherwise a zero value.
Eg:- islower (“b‟) True (non-zero)
islower(“A‟) False (zero)
isupper ( ):-This function checks whether the given character is a upper case alphabet or not.
If it is a capital letter is returns a non-zero value otherwise a zero value.
Eg: isupper (“B‟) True (non-zero)
Isupper(”q‟) False (zero)
toupper ( ):-This function converts the given small letters to an upper case letter.
tolower ( ):- This function converts the given capital letters to a Lower case letter.
toascii( ):-This function returns the equivalent ASCII value for the given character.
This function clears the previous output from the screen and displays the output of the current
program from the first line of the screen. This function is defined in conio.h header file.
Syntax: clrscr();
exit( ):
This function terminates the program. It is defined in the process.h header file.
Syntax: exit( );
4.9 Recursion
Recursion is a special case of process, where a function calls itself. A function is called
recursive if a statement within the body of a function calls the same function.
factorial(x)
int x;
{
if (x = =1)
return(1);
else
return(x * factorial(x-1));
}
When writing recursive functions, you must have an If stmt somewhere in the recursive
function to force the function to return without recursive call being executed. If you do not do
this and you call the function, you will fall in an indefinite loop, and will never return from the
called function.
/*program to find factorial of a given number using a Recursive function*/ #include<stdio.h>
int factorial(x)
int x;
{
if (x<=1)
return(1);
else
return(x*factorial(x-1));
}
main()
{
int n,fn;
clrscr();
printf("enter n");
scanf("%d",&n);
fn=factorial(n); /* Function Call */
printf("the factorial %d is %d\n",n,fn);
getch(); }
In case the value of n is 4, main() would call factorial() with 4 as its actual argument, and
factorial() will send back the computed value. But before sending the computed value,
factorial() calls factorial() and waits for a value to be returned.
scanf(“%d”,&n);
for(i=1;i<=n;i++)
printf(“%d “,fib(i));
getch( );
}
int fib(int x)
{
if(x==1)
return 0;
else if(x==2)
return 1;
else
return(fib(x-1)+fib(x-2));
}
Advantages
1. Reduce unnecessary calling of function.
2. Through Recursion one can Solve problems in easy way while its iterative solution is
very big and complex.
Disdvantages
1. Recursive solution is always logical and it is very difficult to trace.(debug and
understand).
2. In recursive we must have an if statement somewhere to force the function to return
without the recursive call being executed, otherwise the function will never return.
3. Recursion takes a lot of stack space, usually not considerable when the program is small
and running on a PC.
4. Recursion uses more processor time.
Four memory management functions are used with dynamic memory. Three of
them,malloc,calloc,and realloc,are used for memory allocation. The fourth ,free is used to
return memory when it is no longer needed. All the memory management functions are found
in standard library file(stdlib.h).
The malloc function allocates a block of memory that contains the number of bytes
specified in its parameter. It returns a void pointer to the first byte of the allocated memory.
The allocated memory is not initialized.
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 165
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
Declaration:
void *malloc (size_t size);
The type size_t is defined in several header files including Stdio.h. The type is usually
an unsigned integer and by the standard it is guaranteed to be large enough to hold the
maximum address of the computer. To provide portability the size specification in malloc’s
actual parameter is generally computed using the sizeof operator. For example if we want to
allocate an integer in the heap we will write like this:
Pint=malloc(sizeof(int));
Malloc returns the address of the first byte in the memory space allocated. If it is not
successful malloc returns null pointer. An attempt to allocate memory from heap when memory
is insufficient is known as overflow.
The malloc function has one or more potential error if we call malloc with a zero size,
the results are unpredictable. It may return a null pointer or it may return someother
implementation dependant value.
Ex:
If(!(Pint=malloc(sizeof(int)))) //
no memory available
exit(100);
//memory available
…
In this example we are allocating one integer object. If the memory is allocated successfully,ptr
contains a value. If does not there is no memory and we exit the program with error code 100.
3. REALLOCATION OF MEMORY(realloc):
The realloc function can be highly inefficient and therefore should be used
advisedly. When given a pointer to a previously allocated block of memory realloc
changes the size of the block by deleting or extending the memory at the end of the
block. If the memory can not be extended because of other allocations realloc
allocates completely new block,copies the existing memory allocation to the new
location,and deletes the old allocation.
18 55 33 121 64 1 90 31 5 77
10 Integers
New
Ptr=realloc(ptr,15*sizeof(int)); elements
not
initialized
ptr
18 55 33 121 64 1 90 31 5 77 ? ? ? ? ?
15 Integers
After
Releasing Memory(free):When memory locations allocated by malloc,calloc or realloc are no
longer needed, they should be freed using the predefined function free. It is an error to free
memory with a null pointer, a pointer to other than the first element of an allocated block, a
pointer that is a different type then the pointer that allocated the memory, it is also a potential
error to refer to memory after it has been released.
Ptr ptr
Before After
Free(ptr);
BEFORE AFTER
… …
Free(ptr);
In the above example the 200 elements were allocated with calloc. When we free the
pointer in this case, all 200 elements are return to heap. First, it is not the pointers that are being
released but rather what they point to. Second , To release an array of memory that was
allocated by calloc , we need only release the pointer once. It is an error to attempt to release
each element individually.
Releasing memory does not change the value in a pointer. Still contains the address in
the heap. It is a logic error to use the pointer after memory has been released.
return 0;
}
When you run the program, the output will be:
Address of charArr[0] = 28ff44
Address of charArr[1] = 28ff45
Address of charArr[2] = 28ff46
Address of charArr[3] = 28ff47
⮚ In C programming, name of the array always points to address of the first element of
an array.
⮚ In the above example, arr and &arr[0] points to the address of the first element.
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 168
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
TUTORIAL QUESTIONS
1. WACP to Check given number is Prime and Armstrong Number or not using
function.
2. Implement a c program to print 1 to 100 numbers without using loops.
ASSIGNMENT QUESTIONS
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 169
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
SET 1:
1. Differentiate call by value and call by reference.
2. Implement a C program to print factorial of given number using with
arguments and with return type.
SET 2:
1. Discuss recursive function with an example.
2. Implement a C program to find power and square root of any number using standard
functions.
SET 3:
3. Implement a c program to transpose the given matrix.
4. Implement a C program to factorial using recursive functions.
SET 4:
1. Discuss about storage classes.
2. Implement a C program to allocate memory for 10 integers dynamically.
SET 5:
3. Discuss about inter function communications.
4. List out the difference between malloc() and calloc()?
SET 6:
1. Explain the difference between static allocation and dynamic allocation?
2. Implement Fibonacci series using recursion.
Important questions
(c) Explain in detail about pass by value and pass by reference. Explain with a sample program?
(b) Write a C program to find the factors of a given integer using a function.
(i) What is meant by function prototype? Give an example for function prototype.
9. (a) Distinguish between getchar and scanf functions for reading strings.
(i) Write a program to count the number of words, lines and characters in a text.
10. (a) What do you mean by functions? Give the structure of the functions and explain
about the arguments and their return values.
(i) Write a C program that uses a function to sort an array of integers.
UNIT-V
INTRODUCTION TO ALGORITHMS
5.1 ALGORITHMS
Step 1: Start
Step 8: stop
Step 1: Start
Step 2: Declare variables n,i,flag.
Step 3: Initialize variables
flag←1
i←2
Step 4: Read n from user.
Step 5: Repeat the steps until i<(n/2)
5.1 If remainder of n÷i equals 0
flag←0
Go to step 6
5.2 i←i+1
Step 6: If flag=0
Display n is not prime
else
Display n is prime
Step 7: Stop
Searching:
Searching refers to an operation of finding the location of an item in a table or a file. Depending
on the location of the records to be searched, searching techniques are classified into two types.
External Searching:
When the records are stored in files, disk, tape any secondary storage, then the searching is
known as external searching.
Internal Searching:
When the records are stored in main memory, then it is known as internal searching. In C
language we have 2 types of searching techniques,
if(k==0)
return(-1);
else
return(k);
}
●
Repeat the procedure for lower half or upper half of array until the element is found.
Step 2: repeat thru step 4 while low is less than or equal to high i.e., while(low<=high) do
high = mid – 1
low = mid + 1
clrscr();
printf("enter the no. of elements u want in the list\n");
scanf("%d",&n);
printf("enter the %d elements of array\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the key u want to search\n");
scanf("%d",&key);
pos=binary(a,n,key);
if(pos==-1)
printf("key is not found");
else
printf("key is found at %d position",pos+1);
getch();
}
int binary(int a[],int n,int key)
{
int low=0,high=n-1,mid;
while(high>=low)
{
mid=(low+high)/2;
if(key>a[mid])
low=mid+1;
else if(key<a[mid])
high=mid-1;
else
return(mid);
}
return(-1);
}
5.3 Sorting:
Sorting is a method of arranging data in a file in ascending or descending order. Sorting
makes handling of records in a file is easier.
● Compare each pair of adjacent elements from the beginning of an array and, if they
are in descending order, swap them.
Algorithm
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 175
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
1. begin
2. for i := 0 to array_size - 1 do
3. begin
4. for j := 0 array_size–1-i do
5. if a [j] > a [j+1] then
6. begin
7. temp := a [j];
8. a [j] := a[j+1];
9. a[j+1] := temp;
10. end
11. end
12. end
● Bubble sort (to sort in ascending order) is performed as given below, Consider an
array of n elements a[0] to a[n-1]
●
In first pass, compare a[0] with a[1]. If a[0] > a[1], swap the numbers otherwise leave
it.
●
In second pass, Compare a[1] with a[2] and swap the numbers if a[1] > a[2] and so on
and compare a[n-2] with a[n-1] and swap the number if a[n-2] > a[n-1].
●
By this process the first largest element placed in nth position. This element is not
further compared in the remaining passes.
●
Now consider first n-1 elements in the list and repeat the above process to place the
next largest element in the (n-1)th position. Repeat this process until all the elements
are placed in proper positions.
}
printf("before sorting,the elements are\n");
for(i=0;i<n;i++)
{
printf("%3d",a[i]);
}
bubble(a,n);
printf("after sorting,the elements are\n");
for(i=0;i<n;i++)
{
printf("%3d",a[i]);
}
getch();
}
void bubble(int a[20],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=i;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
a) In the first iteration the 1st element 17 is compared with the 0th element 25. Since 17 is
smaller than 25, 17 is inserted at 0th place. The 0th element 25 is shifted one position to
the right.
b) In the second iteration, the 2nd element 31 and 0th element 17 is compared. Since, 31 is
greater than 17, nothing is done. Then the 2nd element 31 is compared with the 1st element
25.Again no action is taken as 25 is less than 31.
c) In the third iteration, the 3rd element 13 is compared with the 0th element 17.Since, 13
is smaller than 17, 13 is inserted at the 0th place in the array and all the elements from 0th
till 2nd position are shifted to right by one position.
d) In the fourth iteration the 4th element 2 is compared with the 0th element 13. Since, 2 is
smaller than 13, the 4th element is inserted at the 0th place in the array and all the elements
from 0th till 3rd are shifted right by one position. As a result, the array now becomes a
sorted array.
#include<stdio.h>
#include<conio.h>
void insertion(int [], int );
int main()
{
int arr[30];
int i,size;
printf("Enter total no. of elements : ");
scanf("%d",&size);
printf(“\n Enter the elements to sort:”);
for(i=0; i<size; i++)
scanf("%d",&arr[i]);
insertion(arr,size);
printf("\nAfter sorting\n");
for(i=0; i<size; i++)
printf(" %d",arr[i]);
getch();
return 0;
}
void insertion(int arr[], int size)
{
int i,j,tmp;
for(i=0; i<size; i++)
{
for(j=i-1; j>=0; j--)
{
if(arr[j]>arr[j+1])
{
tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 178
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
else
break;
}
}
}
5.3.3 Selection Sort
● Suppose that items in a list are to be sorted in their correct sequence. Using Selection
Sort, the first item is compared with the remaining n-1 items, and whichever of all is
lowest, is put in the first position.
● Then the second item from the list is taken and compared with the remaining (n-2)
items, if an item with a value less than that of the second item is found on the (n-2)
items, it is swapped (Interchanged) with the second item of the list and so on.
{
min = i;
for (j=i+1; j<n; j++)
{
if (a[j] > a[min])
min = j;
}
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
TUTORIAL QUESTIONS
1. Write a program to explain bubble sort. Which type of technique does it belong. (b)
What is the worst case and best case time complexity of bubble sort?
2. Explain the algorithm for bubble sort and give a suitable example. (OR) Explain the
algorithm for exchange sort with a suitable example.
3. Write a program to explain insertion sort . Which type of technique does it belong.
(or) Write a C-program for sorting integers in ascending order using insertion sort.
4. Explain the algorithm for insertion sort and give a suitable example
5. Demonstrate the insertion sort results for each insertion for the following initial array
of elements . 25 6 15 12 8 34 9 18 2
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 180
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
6. Demonstrate the selection sort results for each pass for the following initial array of
elements . 21 6 3 57 13 9 14 18 2
ASSIGNMENT QUESTIONS
SET-1:
1. Design an algorithm and flow chart to find maximum among three numbers.
2. Implement a C program to find roots of quadratic equation
SET-2:
SET-3:
SET-4:
1. Implement a C program to check given number is perfect number or not.
2. Explain selection sort with example.
SET-5:
1. Implement a C program to search a key using binary search.
2. Illustrate the complexity of bubble sort , selection sort and insertion sort.
IMPORTANT QUESTIONS
1. What is a flowchart? Explain the different symbols used in a flowchart.
2. (a) Define an Algorithm?
(d) What is the use of Flowchart?
(e) What are the different steps followed in the program development?
3. Write a program to explain selection sort. Which type of technique does it belong.
4. Explain the algorithm for selection sort and give a suitable example.
5. Formulate recursive algorithm for binary search with its timing analysis
6. Write a C program that searches a value in a stored array using linear search.
7. Implement a C program to find prime number from 1 to n.
8. Implement Fibonacci series using recursion
9. WACP to sort elements using insertion sort.
FACULTY: B.MADHURIKA, ASST.PROFESSORPage 181
PROGRAMMING FOR PROBLEM SOLVING DEPARTMENT OF CSE
3). Selection sort first finds the ………. element in the list and put it in the first position.
A. Middle element
B. Largest element
C. Last element
D. Smallest element
a) Insertion sort
b) Selection sort
c) Bubble sort
d) Merge sort
REFERENCES
1. Computer Science: A Structured Programming Approach Using C, B. A. Forouzan and R.
F. Gilberg, Third Edition, Cengage Learning.
3. The C Programming Language, B.W. Kernighan and Dennis M. Ritchie, Second Edition,
Pearson education.