Sei sulla pagina 1di 177

NEW GENERATION COMPUTERS

(Regd by Govt of T.S)

“Quality work comes from quality people.”

C LANGUAGE
COURSE MATERIAL

BY RAMESH REDDY P
B.Tech, Msc(Comp), M.B.A

Special features:
 Complete study material for any graduation
 In depth subject covered
 More than 200+ programs covered
 Technical interview questions

Our branches:
OPP: BSNL OFFICE, BESIDE ZPHS SCHOOL.

L.B NAGAR Hanuman temple road, L B Nagar ring road.


PH: 9848293727, 040 64608727
Visit @ www.newgentech.in

BODUPPAL beside univercell mobiles, opp: city


union bank, uppal depot.

UPPAL Gandhi statue, beside SBH bank

shivalayam road, near E-Seve, R.T.C


RAMANTHAPUR colony.

AMBERPET govindula residency, opp: SBH bank,


opp: irani hotel.

GHATKESAR ABOVE SBH BANK, MAIN ROAD,


PHONE BOOK

Name Phone Number Email id


New Generation Computers 040 6460 8727, ngcomputershyd@gmail.com
9848293727
About Us
New Generation Computers (NGC) is one of the largest Computer and IT training institutes
in Hyderabad region that trains youth, students, Employees and house wives in multiple
segments of Information Technology. The wide Spread network of our centers is the mark
of quality education and training that serve the Information Technology needs of the
students and the industry.
Founded in 1998, New Generation continues its mission through quality training at
affordable fee structure. Our uniquely designed and comprehensive curriculum makes our
students an employable and future ready.
New Generation Computers has a dedicated team of skilled teachers and counselors to
make sure the regular up gradation of curriculum and quality delivery along with career
guidance. Our professional team works harmoniously in unison, happily pushing the
frontiers growth and quality in imparting education.
Mission
To make Computer & IT education affordable to one and all.
Vision
Establishing a wide network of it training centers to reach out to maximum number of
aspiring youth, students and Employees.
Values
Create an organization that nurtures and nourishes talent, integrity and efficiency.

We offer Fast-Track Computer Courses to students who wish to complete their learning
in a short period. We have High Emphasis on Projects and Live Assignments.
There are so many reasons to choose New Generation Computers, here are a few
features
1. One Computer One Student
2. Small Batches 10-15 Students leads to Personal Attention
3. Honest Counseling: Choose the Right Course @ Right price
4. Break or Leave granted for Exams and Holidays
5. Employment Guaranteed Training
6. Change of Timing provided
7. Demo classes before joining for fresher‟s and experienced.
8. Well experienced faculties.
9. Interview Questions on each and every concept.
10. Free course materials
WE OFFER
1. MS-OFFICE
2. D.C.A(BASICS, TYPING, MS-WORD, MS-EXCEL, MS -POWER POINT, INTERNET)
3. A.D.C.A(BASICS, TYPING, MS-OFFICE, MANUAL ACCOUNTING, TALLY-ERP9)
4. P.G.D.C.A(BASICS, MS-OFFICE, C LANGUAGE, C++ , DS, ORACLE, INTERVIEW SKILLS)
5. JAVA(CORE JAVA, ADV JAVA, J2EE, HIBERNATE, SPRING, STRUCTS)
6. .NET(C#.NET, ASP.NET, ADO.NET, MVC.NET, SQL SERVER)
7. C LANGUAGE & DATA STRUCTURE
8. C++ WITH OOPS
9. ORACLE
10. SPOKEN ENGLISH
11. HARDWARE & NETWORKING
12. DTP(PAGE MAKER, PHOTOSHOP, COREL DRAW, TELUGU TYPING)
13. ACCOUNTING PACKAGE(MANUAL ACCOUNTING , TALLY ERP9, WINGS, FOCUS)
14. WEB-DESIGNING(HTML5, CSS3, JAVA SCRIPT, JQUERY, PHP WITH MY-SQL, PROJECT)
15. AUTOCAD 2D&3D
16. SAP(FICO, HR, BASIS, MM, SD, ABAP)
17. MULTIMEDIA WITH 2D & 3D ANIMATIONS
18. TESTING TOOLS WITH PROJECT
19. PROE
20. SOLID WORKS
21. ADVANCED EXCEL
22. VIDEO EDITING
23. LINUX AND UNIX ADMINISTRATION
24. CTTC( COMPUTER TEACHER TRAINING COURSE)
25. HADOOP(BIG DATA)
26. Digital Marketing
27. Android

WE ALSO OFFERS

 LIVE PROJECTS FOR B.TECH/M.TECH/MCA/MBA


 WEEKEND BATCHES AVAILABLE
 ONLINE TRAINING
 We also provide web site development
TABLE OF CONTENT

S.No Chapter Name Page Number

1 Introduction To Computers & Programming Languages 9-17


2 Introduction To C Language & C Tokens 18-24
3 Structure Of A C Program 25-26
4 Comments In C 26-27
5 Escape Sequence Characters 27-28
6 Data Types 29-33
7 Variables & Operators 34-43
8 Lab Practice Programs 44-46
9 Loops(Control Statements) 47-58
10 Conditional Statements 59-69
11 Arrays 70-74
12 Strings 75-82
13 Functions 83-90
14 math.h 91-92
15 Buffer Manipulation Functions 92-96
16 Miscellaneous Functions 96-99
17 Time Related Functions 99-103
18 Pointers 104-112
19 Dynamic Memory Allocation 113-116
20 Storage Classes 117-118
21 Structures 119-124
22 Unions, Typedef, Enum, Bit Fields 125-128
23 Files 129-132
24 Command Line Arguments 133-134
25 C Preprocessor 134-140
26 Header Files In C Language 140-141
27 Lab Practice Programs 142-155
28 Interview Questions 155-177
8 www.newgentech.in C LANGUAGE BY Mr.PRR

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
9 www.newgentech.in C LANGUAGE BY Mr.PRR

INTRODUCTION TO COMPUTERS AND LANGUAGES

1. COMPUTER SYSTEM:
Q) What is computer?
Computer is a device capable of performing computations and making logical decisions at
speed of millions and even billions of times faster than human being can.
Or
Computer is an electronic device which performs arithmetic and logical operations
Or
A computer is a programmable machine designed to sequentially and automatically carry out a
sequence of arithmetic or logical operations.
Q) What are the major components of a computer?
A computer system made of two major components. They are
1. Software,
2. Hardware.
The block diagram of a computer system as given below:
Computer system

Hard ware Soft ware

I O
N Central Processing unit (CPU) U
P CONTROL UNIT T
U P
T U
DEVICES Arithmetic and Logical Unit T
DEVICES

Memory unit

COMPUTER HARDWARE:
The computer hardware is the physical equipment. It consists of five parts. They are
1. Input devices
2. Central processing unit (C.P.U)
3. Primary storage
4. Output devices
5. Auxiliary storage devices or Secondary storage devices
 The input device is usually a key board. Where programs and data are extended (enter)
in to the computer. Ex: Mouse, Key board, Touch screen etc.
 Central processing unit is responsible for instructions such as arithmetic calculations.
Comparing among data and moment of data inside the system.
 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 closed when we turn off a personal computer or when
we log off from a time sharing computer.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
10 www.newgentech.in C LANGUAGE BY Mr.PRR

 The output device is usually a monitor or a printer to show output. If the output is
shows 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 of
is the place where the programs and data are stored permanently.
When we turn off the computer our programs and data are remain in the secondary storage
ready for the next time we need them.
COMPUTER SOFTWARE:
Software is the process which brings imaginaries into praticals. It is developed by grouping
individual programs where each program is going to perform some designed operation. Or
simply we can say “software is a collection of programs that allow the hardware to do its job”.
Computer softwares are divided into types.
1. System Softwares
2. Application softwares.
SYSTEM SOFTWARES:
System software consists of programs that manage the hardware resources from computer and
perform required information processing tasks.
Examples: operating systems, driver softwares, mobile applications ……… etc
APPLICATION SOFTWARES:
Application softwares are broken into two classes.
1. General purpose softwares,
2. Application specific softwares.
General purpose softwares are purchased from a software developer or from software company
or from market and can be used for more than one word application processors. Example is
Data base management system etc.
Application specific softwares can be used only for its intended purpose.
A general ledger system used by accountant and a material requirement. Planning system used
by a manufacturing organization are the examples of application specific software.
3. COMPUTER LANGUAGES:
To develop instructions for a computer we must use a computer language. A summary of
computer languages as shown below
Machine language symbolic language high level language
1940S 1950S 1960S
MACHINE LEVEL LANGUAGE:
 The only language understood by computer is machine level language.
 Each computer has its own machine language, which is made streams of Os and 1‟s
because the internal circuits of a computer are made of switches, transistors and other
electronic devices that can be in one of two states off and on.
 In this the off state is represented by “O” and the on state is represented by 1.
ADVANTAGES:
1. Machine level language easily understood by the CPU.
2. The time taken for executing the program is very less.
3. The execution speed is very high because of machine instructions are directly understood
by the CPU and no translation of the program is required.
DISADVANTAGES:
1. It is machine dependent language.
2. Length of the program is very high so difficult to modify.
3. Machine language is difficult to program. It is necessary for the programmer either to
memorize the dozens of code numbers.
4. Difficult to check the errors

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
11 www.newgentech.in C LANGUAGE BY Mr.PRR

SYMBOLIC LEVEL LANGUAGE:


 Symbolic language uses symbols or mnemonics to represent the various machine
language instructions. It is developed by admiral grace happen in the early 1950s.
 It is also called as Assembly level language.
 Computer does not understand symbolic language. So it must be translated to the
machine language.
 A special program called as assembler translates symbolic code into machine language.
ADVANTAGES:
1. It is easier to understand and use.
2. It reduces the cost of associated ROM chips because of reduced code size.
3. It is easy to modify the program.
4. It is easy to rectify the errors.
DISADVANTAGES:
1. It is Machine dependent language.
2. To develop the assembly code, knowledge of hardware compulsory required.
3. Execution time is more because of translating of assembly code into machine level code.
HIGH LEVEL LANGUAGE:
 The languages which are developed in general language (English) are called as high level
languages.
 High level having greater efficiency.
 These are portable languages.
 FORTAN, COBOL, C, C++, JAVA etc are the examples of high level languages.
 Machine does not understand high level languages directly. So to convert high level
languages into its equivalent machine level languages translators are used.
 The translators are interpreter and compiler.
ADVANTAGES:
1. High level languages are always Machine independent.
2. These languages are easy to learn and use.
3. Preparation cost is less due to it takes less time and effort to develop the application.
4. Easy to maintain compare to machine level and assembly level languages.
DISADVANTAGES:
1. The efficiency of the program less compared with machine and assembly level languages.
2. Execution time is more because of translation i.e. high level to machine level languages.
3. This are having less flexible than assembly language.
4. CREATIES AND RUNNING PROGRAMMS:
It is the job of the programmer to write test the program. There are four steps in this process.
1. Writing and editing the program,
2. Competing the program,
3. Linking the program with equaled library modules,
4. Executing the program.
Q) What is a programming language?
A programming language is an artificial language, designed to communicate instructions to a
machine, particularly a computer. Programming languages can be used to create programs
that control the behavior of a machine and/or to express algorithms precisely.
A programming language is usually split into the two components of syntax (form) and
semantics (meaning). Some languages are defined by a specification document (for example,
the C programming language is specified by an ISO Standard).

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
12 www.newgentech.in C LANGUAGE BY Mr.PRR

CREATIES AND RUNNING PROGRAMMS:


It is the job of the programmer to write and test the program. There are four steps in this
process.
5. Writing and editing the program,
6. Competing the program,
7. Linking the program with equaled library modules,
8. Executing the program.
BLOCK DIAGRAM:
PROGRAMMER

TEXT EDITIOR Program


SOURCE CODE(.c)

01101011 OBJECT CODE(.obj)


COMPILER
01110101
LIBRARY

LINKER 00011101 EXECUTABLE CODE(.exe)


01110111

RUNNER(OS) OUTPUT
RESULT
 The software used to write programs is as a text editor.
 The file created from a text editor is known as a source file.
 The code in a source file must be translated into machine languages using the „c‟
compiler, which is made of two separate programs: the preprocessor and the translator.
 The file created from the compiler is known as an object module.
 An object module is linked to the standard functions necessary for running the program
by the linker.
 Linker generates new code called executable code i.e the code which is having the
functionality of the application that code is called as executable code.
 Executable code given to the runner or loader which will give the final result of our
application.
PROGRAM DEVELOPMENT STEPS:
TO DEVELOP A PROGRAM, A PROGRAMMER MUST COMPLETE THE FOLLOWING STEPS
1. Understand the problem
2. Develop a solution using structure charts and either flow charts or Pseudo code.
3. Write the program.
4. Test the program.
Q) What is the difference between language and software?
A language is a specification which is used to develop the softwares. Software is a designed
thing which is having a specified functionality.
Q) What are the different approaches we have to design the languages?
Basically we have three types approaches to design the languages
1. Monolithic
EX: machine level language, Assembly level language
2. Procedure or structure oriented

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
13 www.newgentech.in C LANGUAGE BY Mr.PRR

Ex: C language
3. Object oriented
Ex: java, c++
Q) What is source code and Executable code?
Source code: Group of instructions which are present in high level language is known as
source code. Generally source code visible in English
Executable code: Group of instructions which are present in low level language is known as
Executable code. Generally Executable code visible in machine language format
Q) What is Object code?
Object code is a translated code of C compiler i.e. C compiler takes the source code and
generates the object code. Source code is visible in the form of high level language but whereas
object code is visible in the form of machine level language.
Q) What is aTranslator?
Translator is defined as a computer program that converts instructions written in one language
to another without changing the initial logic in terms of computer language.
Assembler, Compilers and Interpreters:
As stated earlier, any program that is not written in machine language has to be translated in
machine language before it is executed by the computer. There are three types of translator
programs i.e. Assembler, Compilers and Interpreters.
Assembler:
Assembler is a computer program which is used to translate program written in Assembly
Language in to machine language. The translated program is called as object program.
Assembler checks each instruction for its correctness and generates diagnostic messages, if
there are mistakes in the program. Various steps of assembling are:
1. Input source program in Assembly Language through an input device.
2. Use Assembler to produce object program in machine language.
3. Execute the program.
Compiler:
A compiler is a program that translates a programme written in HLL to executable machine
language. The process of transferring HKK source program in to object code is a lengthy and
complex process as compared to assembling. Compliers have diagnostic capabilities and prompt
the programmer with appropriate error message while compiling a HLL program. The
corrections are to be incorporated in the program, whenever needed, and the program has to
be recompiled. The process is repeated until the program is mistake free and translated to an
object code. Thus the job of a complier includes the following:
1. To translate HLL source program to machine codes.
2. To trace variables in the program
3. To include linkage for subroutines.
4. To allocate memory for storage of program and variables.
5. To generate error messages, if there are errors in the program.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
14 www.newgentech.in C LANGUAGE BY Mr.PRR

Interpreter:
The basic purpose of interpreter is same as that of complier. In compiler, the program is
translated completely and directly executable version is generated. Whereas interpreter
translates each instruction, executes it and then the next instruction is translated and this goes
on until end of the program. In this case, object code is not stored and reused. Every time the
program is executed, the interpreter translates each instruction freshly. It also has program
diagnostic capabilities. However, it has some disadvantages as below:
1. Instructions repeated in program must be translated each time they are executed.
2. Because the source program is translated fresh every time it is used, it is slow process or
execution takes more time. Approx. 20 times slower than complier.
Q) What do mean by Algorithm? Give its properties?
Algorithm:
1. The word algorithm is derived from the name of the Persian mathematician Al
Khwarizmi.
2. An algorithm can be defined as a step-by-step procedure for solving a problem.
Properties:
An algorithm has five important properties
Finiteness: an algorithm terminates after a finite number of steps
Definiteness: - Each step in an algorithm is unambiguous. This means that the action specified
by the step cannot be interpreted in multiple ways and can be performed without any confusion.
Input: -An algorithm accepts zero or more inputs
Output: -An algorithm produces at least one output.
Effectiveness: - An algorithm consists of basic instructions that are realizable. This means that
the instructions can be performed by using the inputs in a finite amount of time.
Q) What Pseudo Code?
Pseudo Code:
A pseudo code, as its name suggests is just a false code that intends to explain the functionality
or execution sequence of the Program. It is generally written using programming constructs like
IF, WHILE etc... It‟s not actually the code but a set of normal statements explaining the
execution of the program. It is written before developing the actual program. It is like
developing the skeleton of the program before actually starting programming.
There can be ways to design programs automatically from its pseudo code given that there's
always a fixed format for writing pseudo codes. Since pseudo codes does not have any
particular syntax for writing, they cannot be interpreted to develop a corresponding code for it
automatically.
Pseudo codes makes easier for a non - technical person to understand what the program does,
rather than looking through all that technical code.
So you need to understand every step of pseudo code and convert it into corresponding code in
whatever programming language you are using.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
15 www.newgentech.in C LANGUAGE BY Mr.PRR

For example, Following is the pseudo code for finding whether a given number is even or odd.
1) Input number 'X' from user
2) Divide the X by 2 and store its remainder As 'R'
3) if R is 0 then print 'X' is an even number
4) if R is not 0 then print 'X' is an odd number.
5) Exit
Now you can understand from the above program that if a given number is divisible by 2 then it
is an even number else it is an odd number. So you can translate above pseudo code steps into
a proper code as below :
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int x,r;
x = 0;
r = 0;
clrscr();
printf("Enter a number ");
scanf("%d", x);
r = x/2;
if (r = 0)
printf("Given number is Even");
else
printf("Given number is Odd.");
getch();
}
Q) What is Flowchart? Explain its symbols?
Flow Chart:-
 By representing the various steps in the form of a diagram called as “flow chart”
 In Algorithm and flow chart each step can be called as an “instructions”.
 In flow chart each symbol have unique operation.
 Flow charts avoid confusion whenever designing the application.
Standard symbols in flow chart:

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
16 www.newgentech.in C LANGUAGE BY Mr.PRR

Other symbols In Flow charts:

Q) What are the differences between algorithm and pseudocode?


An algorithm is a well-defined sequence of steps that provides a solution for a given problem,
while a pseudo code is one of the methods that can be used to represent an algorithm. While

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
17 www.newgentech.in C LANGUAGE BY Mr.PRR

algorithms can be written in natural language, pseudo code is written in a format that is closely
related to high level programming language structures. But pseudo code does not use specific
programming language syntax and therefore could be understood by programmers who are
familiar with different programming languages. Additionally, transforming an algorithm
presented in pseudo code to programming code could be much easier than converting an
algorithm written in natural language.
Q) Write a algorithm and flow chart for swap two numbers
Algorithm:

Step1: start

Step2: input a,b

Step3: a=a+b

Step4: b=a-b

Step 5: a=a-b

Step6: Result a, b

Step7: stop

Flow Chart:

strat

take a,b

a=1,b=10

a=a+b;b=a-b; a=a-b

Display a and b

Display a and b

stop

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
18 www.newgentech.in C LANGUAGE BY Mr.PRR

INTRODUCTION TO C LANGUAGE AND C TOKENS

C PROGRAMMING LANGUAGE:
C is a procedural programming language developed by Dennis Ritchie in 1972 at AT&T Bell
Labs. C is considered as the most powerful programming languages ever. It was originally
developed to re-implement UNIX operating system. C is a High Level Programming
language but often referred as Middle level programming language because of its ability to
provide rich support to low level programming.
C is also called as mother of all modern programming languages as many of current
programming languages such as C++, Java, C#, PHP, Python, Perl, JavaScript etc. are directly
or indirectly influenced from C. It is the also the most popular programming language ever and
is widely used for Operating Systems implementations and Embedded programming's.
C Language History:
 The C programming language is a structure oriented programming language, developed at
Bell Laboratories in 1972 by Dennis Ritchie
 C programming language features were derived from an earlier language called “B” (Basic
Combined Programming Language – BCPL)
 C language was invented for implementing UNIX operating system.
 In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C
Programming Language” and commonly known as K&R C
 In 1983, the American National Standards Institute (ANSI) established a committee to
provide a modern, comprehensive definition of C. The resulting definition, the ANSI
standard, or “ANSI C”, was completed late 1988.
Year Lang Developed by Remarks

1960 ALGOL International Committee too general, too abstract


1963 CPL Cambridge university Hard to Learn &
implementation

1967 BCPL Cambridge university could deal only special


problem
1970 B AT&T could deal only special
problem
1972 C AT & T Lost Generality of BCPL, B
restored

C PROGRAMMING LANGUAGE STANDARDS:


 C89/C90 standard – First standardized specification for C language was developed by the
American National Standards Institute in 1989. C89 and C90 standards refer to the same
programming language.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
19 www.newgentech.in C LANGUAGE BY Mr.PRR

 C99 standard – Next revision was published in 1999 that introduced new features like
advanced data types and other changes.
C11 AND EMBEDDED C LANGUAGE:
 C11 standard adds new features to C programming language and library like type generic
macros, anonymous structures, improved Unicode support, atomic operations, multi-
threading and bounds-checked functions. It also makes some portions of the existing C99
library optional and improves compatibility with C++.
 Embedded C includes features not available in C like fixed-point arithmetic, named address
spaces, and basic I/O hardware addressing.
 Operating systems, C compiler and all UNIX application programs are written in C language
 It is also called as procedure oriented programming language. The C language is reliable,
simple and easy to use. C has been coded in assembly language.
FEATURES OF C PROGRAMMING LANGUAGE:
Simple and Robust:
C is considered as simplest and easiest language ever. Its simplicity lies in the lesser number of
programming constructs that are used to create any complex program.
C is a robust programming language with rich set of in-built library functions and operators that
can even write the most complex programs ever.
Portability:
C is a machine independent programming language i.e. C program can run on any machine that
has C compiler with few or no modification. Although C is doesn‟t provide platform
independency as Java provides.
Modularity:
C programs are modular in nature i.e. they are basically divided into modules by
modules. Modular programming is a programming construct where we divide our program into
different modules and combine them together in a single module to form a Program.
Extensibility:
C provides a rich set of in-build library functions. But we can also write our custom library
function and attach with the C programs to use them in future.
Speed:
C programs compiles and executes faster than any other modern programming languages. And
this is also the fact that it is used for Operating System development.
Memory management:
C provides an efficient way to access and manage memory through the use of Pointers.
ADVANTAGES OF LEARNING C
Whether you are beginning your programming with C or you have learnt some other
programming languages earlier. Learning C has its own importance, here are few advantages of
C, over other programming languages.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
20 www.newgentech.in C LANGUAGE BY Mr.PRR

 C is much simpler language as compared to any other programming language. It has


less number of constructs which makes easier to learn.
 Almost every hardware have a C compiler.
 Compilation and execution of a C program is way faster than other modern programming
languages.
 Being a high level programming language, its ability to support low level operations
makes it different from other programming languages.
 C language is considered as a backbone of the Operating System development. As all
popular OS are fully or partially written in C.
 C language is also widely used for developing Compilers, Assemblers, Language
interpreters, Device drivers, Databases etc.
 All modern programming languages are directly or indirectly inherited from C. Hence
learning C will make easier to learn C influenced programming language.

C LANGUAGE IS A STRUCTURED LANGUAGE:


Structure oriented language:
 In this type of language, large programs are divided into small programs called functions
 Prime focus is on functions and procedures that operate on the data
 Data moves freely around the systems from one function to another
 Program structure follows “Top Down Approach”
Examples: C, Pascal, ALGOL and Modula-2
Object oriented language:
 In this type of language, programs are divided into objects
 Prime focus is in the data that is being operated and not on the functions or procedures
 Data is hidden and cannot be accessed by external functions
 Program structure follows “Bottom UP Approach”
Examples: C++, JAVA and C# (C sharp)
Non structure oriented language:
 There is no specific structure for programming this language. Examples: BASIC, COBOL,
FORTRAN
KEY POINTS TO REMEMBER IN C LANGUAGE:
1. The C language is a structure oriented programming language developed by Dennis Ritchie.
2. The C language is belonging to middle level programming language.
3. Operating system programs such as Windows, Unix, Linux are written in C language.
4. C89/C90 and C99 are two standardized editions of C language.
5. C has been written in assembly language.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
21 www.newgentech.in C LANGUAGE BY Mr.PRR

C Tokens

Q) What Are Tokens?


Tokens are the smallest individual elements of a program. Tokens are the basic building blocks
of any program. They are
1. Key word
2. Identifiers
3. Constants
4. Operators
Key words:
 Keywords are pre-defined words in a C compiler.
 Each keyword is meant to perform a specific function in a C program.
 Since keywords are referred names for compiler, they can‟t be used as variable name. C
language supports 32 keywords which are given below.
auto double if static
break else int struct
case enum long switch
char extern near type def
const float register union
continue far short voids
default for return unsigned
do goto signed while
Identifiers:
 Identifiers are user defined words or names which doesn‟t have specific meaning with in
language. The meaning of these words understood by programmer/developer.
 In C, the names of variables, functions, labels, and various other user-defined items are
called identifiers.
 Identifiers are used to identify the data instruction or user defined types.
Rules for Identifiers:
1. It consists of sequence of letters and digits.
2. Identifier name always start with alphabet.
3. The only special characters allowed is under score (-)
4. The length of the Identifier is up to 32 characters.
5. Identifiers should not be a keyword.
6. No two successive underscores are not allowed
7. It can be defined in uppercase or lowercase letters.
8. Identifiers are case sensitive in programming.
CONSTANTS
Q) What is constant?
A constant is a value which never changes throughout the program. These values are
represented in different formats.
Q) What are the different types of constants?
Constants mainly classified in the two types.
1. Numeric Constants
2. Alpha - numeric Constants
Numeric constants are again classified into two types
1. Integer Constant:
 integer constants again classified into three types

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
22 www.newgentech.in C LANGUAGE BY Mr.PRR

Decimal integer:
 An integer value with base 10 is called decimal integer.
 This integer value consists of digits from 0 to 9.
 This integer is prefix with 1-9 sign(+/-)
 Valid decimal integers are 100, 456, -345, 23456, -19202…. Etc
Octal integers:
 An integer value with base 8 is called octal integer.
 This integer value consists of digits from 0 to 7.
 This integer is prefix with „0‟
Ex: 0123, 0725 … etc are the valid octal integers.
Ex: 0128, 4647……etc are the invalid octal integers.
Hexa decimal integer:
 An integer value with base 16 is called Hexa decimal integer.
 This integer value consists of digits from 0 to9 and A-F or a-f.
 This integer value is prefix with “ox”
Ex: 1ab – invalid Ox1ab - valid
2. Real constants:
 Real constants are also called as floating point constants.
 Real constants are having both decimal and fractional parts.
Alpha numeric constants:
Character constants again classified into two types.
1. Single character constant:
 A non numeric value represented with in „ „ is called single character value or constant.
 Every character occupies 1 byte of memory.
2. String constant:
 A non numeric value represented with in “ “ is called string or constant.
 A string is collection of characters.
Examples:
“rama” – Alphabetic string
“A101” - Alphabetic string
“a**” - Alphabetic string
 Every string is terminated with a special character called NULL which occupies 1- byte.
Note: In C language constants are declared by using “ const” keyword.
Input and output Functions
Use of printf() function:
Printf() function in c is used to print any message to output screen. This function is the
commonly used function to print a message, a value or result to the console output screen.
Printf() is an in built function defined in the stdio.h header file. The return type of the printf is
int type.
Library Syntax for the printf():
int printf ( const char *format [, argument, ...]);
The printf functions do the following:
 Accept a series of arguments
 Apply to each argument a format specifier contained in the format string *format
 Output the formatted data (to the screen, a stream, stdin, or a string)
Syntax for Printf() function to print some text on the console:
Printf("your message here ");
The above syntax is followed to print a message to the console output screen. The message
which you want to be printed should be placed inside the double quotes. you can print any
message and any number of characters using this printf() function.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
23 www.newgentech.in C LANGUAGE BY Mr.PRR

Example to print a message:


printf(" Hello Friends Our web site is www.ngsoftsolutions.com");
output:
Hello Friends Our web site is www.ngsoftsolutions.com
In the similar way you can print any message by using the printf() function.
Rules to be followed while using Printf() function:
-> The message which is to be printed should be placed in between double quotes(" ").
-> separate the format specifiers and variables using comma (,).
-> The printf() function should follow a semi colon at the end. This indicates the compiler that It
is the end of the statement.
-> As C is a case sensitive language so you should not use capital letters while writing printf()
function. how ever you can use capital letters in the body of the message which is to be printed.
Use of scanf() function in c:
Scanf() function in c is used to read and store the value in a variable during run time. i, e by
using scanf() function we can store the values in a variable during the execution of the
program. so by using scanf() function in c we can assign different values to a variable with out
changing the source code. With out modifying the source code, we can assign the values to a
variable at run time and use them according to our need.
Syntax for scanf():
scanf("<format specifiers>",&<variables>);
The above syntax is to be followed to read values from a console input during the execution of a
program. here The format specifiers are the operators used to indicate the data type of a
variable. and the variables are the identifiers used to represent the data.
Here the symbol '&' is used to represent the address of the variable. If you declare the &
symbol, then the compiler stores the value given as input at run time in the address of that
particular variable.
Example to read a variable:
scanf("%d",&a);
The above example will read an integer value from the input and stores it at the address of the
variable a.
Rules to be followed while using scanf() function:
-> The format specifiers should always be placed in between double quotes(" ").
-> separate the format specifiers and variables using comma (,).
->scanf() statement should be ended with a semi colon (;). This indicates the compiler that it is
the end of the statement.
-> Always use a right format specifier while using scanf() function in c. If you are reading an
integer variable, then use %d format specifier.
-> As C is a case sensitive language we should not use capital letters while writing scanf()
function.
MORE EXAMPLES ON printf() AND scanf():
1.
int a,b;
scanf(“%d%d”,&a,&b);
printf(“\nValue of a %d and value of b is %d”,a,b);
2.
int a;
float b;
scanf(“%d%f”,&a,&b);
printf(“\nValue of a %d and value of b is %f”,a,b);

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
24 www.newgentech.in C LANGUAGE BY Mr.PRR

3.
int a;
float b;
scanf(“%d,%f”,&a,&b);
printf(“\nValue of a %d and value of b is %f”,a,b);
4.
int a;
float b;
scanf(“%d ngc %f”,&a,&b);
printf(“\nValue of a %d and value of b is %f”,a,b);
5.
int a;
float b;
scanf(“%d%f”,a,&b);
printf(“\nValue of a %d and value of b is %f”,a,b);
6.
int a;
float b;
scanf(“%d%f”,&a,&b);
printf(“\nValue of a %d and value of b is %f”,&a,&b);

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
25 www.newgentech.in C LANGUAGE BY Mr.PRR

STRUCTURE OF A C PROGRAM

Structure of a „C‟ program:


<Preprocessor commands>
<Global declarations>
void main ()
{
<Local declarations>;
<Statements>;
}
Function (arguments)
{
<Local declarations>;
<Statements>;
}
Exaplanation:
Preprocessor commands:
The commands which start with a hash (#) symbol are called Preprocessor commands. These
commands are used to place library information in our program. Generally in C programs library
information placed in the form of header files.
Ex:
# include <stdio.h>
# include “conio.h”
# define PI 3.14159
Global declarations:
To use any variable it must be declared with its data type before the first executable statement.
The variables which declared inside a block are available in that block only. Such variables are
called as local variable.
To use the variable in entire program with same effect it must be declared as global. These
global variables are declared outside the functions.
main ():
 It is starting point for program execution. This function has no arguments and no
parameters.
 C language does not allow more than one main () function in a single program.
 main () function always write in small caps only.
 Every function must and should call through main () only (directly or indirectly).
 This function consists of declarations and executable statements.
 C compiler does not consider anything out of the main.
EXAMPLES 1:
/* Write a program to print your name on the console screen */
#include <stdio. h>
#include <conio. h>
void main()
{
printf(“ my name is New Generation Computers”);
}
Output:
my name is New Generation Computers
How to Execute C program:
Save this program (F2) as FIRST.C

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
26 www.newgentech.in C LANGUAGE BY Mr.PRR

After compilation (Alt-F9) it creates an object file, and an executable file


Run the program by pressing “ Ctrl + F9” .
Common Short cut Keys Description
F2 press to save current work
F3 press to open an existing file
ALT-F3 press to close current
ALT-F9 press to compile only
F9–to compile and link the program
ALT-F5 press to view the desired output of the program.
CTRL-F9 press to compile+run
ALT-X or ALT-F-X press to exit from TC IDE
clrscr():
This function is used to clear the screen. This function‟s prototype has defined in the header file
conio.h (CONIO ==> Console Input Output )
Syntax:
clrscr();
getch() and getche() functions:
These two functions are available in CONIO.H header file.
 getch() gets a character from console but does not echo to the screen
 getche() gets a character from console, and echoes to the screen
Declaration:
■ int getch(void);
■ int getche(void);
Comments in C
Comments in C language are used to provide information about lines of code. It is widely used
for documenting code. There are 2 types of comments in C language.
1. Single Line Comments
2. Multi Line Comments
Single Line Comments
Single line comments are represented by double slash \\.
Let's see an example of single line comment in C.
#include <stdio.h>
#include <conio.h>
void main(){
clrscr();
//printing information
printf("Hello C");
getch();
}
Output:
Hello C
Even you can place comment after statement. For example:
printf("Hello C");//printing information

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
27 www.newgentech.in C LANGUAGE BY Mr.PRR

Mult Line Comments:


Multi line comments are represented by slash asterisk \* ... *\. It can occupy many lines of
code but it can't be nested.
Syntax:
/*
code
to be commented
*/
Let's see an example of multi line comment in C.
#include <stdio.h>
#include <conio.h>
void main(){
clrscr();
/*printing
information*/
printf("Hello C");
getch();
}
Output:
Hello C
Escape Sequence in C:
An escape sequence in C language is a sequence of characters that doesn't represent itself
when used inside string literal or character.
It is composed of two or more characters starting with backslash \. For example: \n represents
new line.
List of Escape Sequences in C

Escape Sequence Meaning

\a Alarm or Beep

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Tab (Horizontal)

\v Vertical Tab

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
28 www.newgentech.in C LANGUAGE BY Mr.PRR

\\ Backslash

\' Single Quote

\" Double Quote

\? Question Mark

\nnn octal number

\xhh hexadecimal number

\0 Null

Programs :
/* Using Escape Sequences Program2:
*/ # include <stdio.h>
# include <stdio.h> # include <conio.h>
# include <conio.h> main()
main() {
{ clrscr() ;
clrscr() ; printf(“Hello \t Krishna \n Welcome “) ;
printf(“Hello \t “) ; }
printf(“Uday \n”) ; Output :
printf(“Welcome “) ; Hello Bhanu
} Welcome
Output:
Hello Uday
Welcome

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
29 www.newgentech.in C LANGUAGE BY Mr.PRR

Data Types In C Language


Data type defines the type of the data that any variable can store. It is a system of declaring
variables of different types. Data types are broadly categorized into three categories which are:
1. Primitive/Pre-defined

2. User defined

3. Derived

Primitive/Pre-defined data type:

Primitive data types are the basic data types that are needed for performing general
operations.
Example: int, char, float, double
User defined data type:

User defined data types are defined by user according to their need. They are defined or
created from the primitive data types.
Example: struct, union, array, pointer

Derived data types:

Derived data types are basically the primitive data type with increased range of values it can
store.
Example: short, long long int, double
INTEGER DATA TYPE:
 Integer data type allows a variable to store numeric values.
 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use. If we are using 16 bit
processor, 2 byte (16 bit) of memory will be allocated for int data type.
 Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for
64 bit processor is allocated for int datatype.
 int (2 byte) can store values from -32,768 to +32,767
 int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
 If you want to use the integer value that crosses the above limit, you can go for “long int”
and “long long int” for which the limits are very high.
Note:
 We can‟t store decimal values using int data type.
 If we use int data type to store decimal values, decimal values will be truncated and we will
get only whole number.
 In this case, float data type can be used to store decimal values in a variable.
CHARACTER DATA TYPE:
 Character data type allows a variable to store only one character.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
30 www.newgentech.in C LANGUAGE BY Mr.PRR

 Storage size of character data type is 1. We can store only one character using character
data type.
 “char” keyword is used to refer character data type.
 For example, „A‟ can be stored using char data type. You can‟t store more than one
character using char data type.
FLOATING POINT DATA TYPE:
Floating point data type consists of 2 types. They are,
1. float
2. double
1. FLOAT:
 Float data type allows a variable to store decimal values.
 Storage size of float data type is 4. This also varies depend upon the processor in the CPU
as “int” data type.
 We can use up-to 6 digits after decimal using float data type.
 For example, 10.456789 can be stored in a variable using float data type.
2. DOUBLE:
 Double data type is also same as float data type which allows up-to 10 digits after decimal.
 The range for double datatype is from 1E–37 to 1E+37.
SIZEOF() FUNCTION IN C LANGUAGE:
sizeof() function is used to find the memory space allocated for each C data types.
#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d));
return 0;
}
Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
31 www.newgentech.in C LANGUAGE BY Mr.PRR

MODIFIERS IN C LANGUAGE:
 The amount of memory space to be allocated for a variable is derived by modifiers.
 Modifiers are prefixed with basic data types to modify (either increase or decrease) the
amount of storage space allocated to a variable.
 For example, storage space for int data type is 4 byte for 32 bit processor. We can increase
the range by using long int which is 8 byte. We can decrease the range by using short int
which is 2 byte.
 There are 5 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
5. long long
Below table gives the detail about the storage size of each C basic data type in 16 bit processor.
Please keep in mind that storage size and range for int and float datatype will vary depend on
the CPU processor (8,16, 32 and 64 bit)

C Data types / storage Range


Size

char / 1 –127 to 127

int / 2 –32,767 to 32,767

float / 4 1E–37 to 1E+37 with six digits of


precision

double / 8 1E–37 to 1E+37 with ten digits of


precision

long double / 10 1E–37 to 1E+37 with ten digits of


precision

long int / 4 –2,147,483,647 to 2,147,483,647

short int / 2 –32,767 to 32,767

unsigned short int / 2 0 to 65,535

signed short int / 2 –32,767 to 32,767

long long int / 8 –(2power(63) –1) to 2(power)63 –1

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
32 www.newgentech.in C LANGUAGE BY Mr.PRR

signed long int / 4 –2,147,483,647 to 2,147,483,647

unsigned long int / 4 0 to 4,294,967,295

unsigned long long int / 8 2(power)64 –1

Void Data Type In C Language:


 Void is an empty data type that has no value.
 This can be used in functions and pointers.
List of all format specifiers in C programming
In C programming we need lots of format specifier to work with various data types. Format
specifiers defines the type of data to be printed on standard output. Whether to print formatted
output or to take formatted input we need format specifiers. Format specifiers are also called as
format string.
Here is a complete list of all format specifiers used in C programming language.

Format Supported data


Description
specifier types

char
%c Character
unsigned char

short
unsigned short
%d Signed Integer
int
long

float
%e or %E Scientific notation of float values
double

%f Floating point float

float
%g or %G Similar as %e or %E
double

%hi Signed Integer(Short) short

%hu Unsigned Integer(Short) unsigned short

short
unsigned short
%i Signed Integer
int
long

%l or %ld or %li Signed Integer long

%lf Floating point double

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
33 www.newgentech.in C LANGUAGE BY Mr.PRR

Format Supported data


Description
specifier types

%Lf Floating point long double

unsigned int
%lu Unsigned integer
unsigned long

%lli, %lld Signed Integer long long

%llu Unsigned Integer unsigned long long

short
unsigned short
%o Octal representation of Integer. int
unsigned int
long

%p Address of pointer to void void * void *

%s String char *

unsigned int
%u Unsigned Integer
unsigned long

short
unsigned short
Hexadecimal representation of Unsigned
%x or %X int
Integer
unsigned int
long

%n Prints nothing

%% Prints % character

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
34 www.newgentech.in C LANGUAGE BY Mr.PRR

VARIABLES AND OPERATORS


Variable:
 A variable is an identifier. It can be consider as a name which is given to the memory
location where values will be stored.
 The quantities which can be changed during the execution of program are called Variables.
 Variable is a container which contains data or Information.
 Before using any variable in a program it must be declared first.
SYNTAX:
<Data-type><variable-name>;
Ex: int count;
float X;
char name;
Rules:
1) Variable names can consist of alphabets, Digits, underscore, dollar character etc.
2) A variable name should not begin with a digit or any special symbol except #.
3) White spaces are not allowed in variable names.
4) Upper and lower case distinct i.e.,”A” Is differed from „a‟.
5) The maximum length of variable length is 32 characters.
Important points to remember:
1. In c programming language variable declaration must be exist top of the program i.e. after
opening the curly braces and before writing the first executable instruction.
2. In variable declaration existing keyword, operators, separators, and constants values are
not allowed as a names.
3. At least once space should be required in between data-type and variable-name.
4. All data-types must write in small caps only.
5. Variable names are case sensitive.
Note: one variable contain only one value. If you change the value of the variable then old
value will be erased and new value will be stored.
Q) What variable contain?
Variable contain mainly three things
1. Name of the variable
2. Value of the variable
3. Address of the variable
Example:
int a=10;
a variable name
content or value of the variable
20
1000 Address of the variable
How to initialize a variable:
 A variable can be initialized in two ways. They are
1. Static variable initialization
2. Dynamic variable initialization
Static variable initialization:
 Declaring a variable by assigning constant value is called Static variable initialization.
 The value assigned to variable is known before compiling program is called Static
variable initialization.
Ex:
int x=10;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
35 www.newgentech.in C LANGUAGE BY Mr.PRR

float y=200;
char c=”New generation”;
Dynamic Variable Initialization:
 Declaring a variable by assigning expression or variable is called Dynamic variable
initialization.
Or
 The value assigned to variable is not known during compiling time is called Dynamic
variable initialization.
 Dynamic initialization can be done by using pre defined functions which available in c
library.
Example:
int c;
scanf(“%d”,&c); // dynamic initialization
c= 10; //static initialization
OPERATORS
 Operator are predefined symbols which performs operations on operands.
 In c programming language total number of operators are 44
 Depending upon the number of operands operators are classified into three types
1. Unary operators: It takes only one argument
2. Binary operator: it takes two arguments.
3. Ternary operators: it takes three arguments.

But based on the functionalities of the operators, they are divided into 8 types. They are

Arithmetic operators:
The operators which are used for Arithmetic operations (general mathematical calculations)
Operators Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% modulo division

Modulus operator:
 Modulus operator returns remainder value. Output sign depends on numerators value
sign only.
 When a numerator value is less than of denominator value then it returns numerator
value as return value.
Ex: a=8%5; o/p: 3 a=18%9; o/p: 0 a= 3.0*5/2*2; o/p: error
 Modulus operator required two arguments and both arguments should be an integer
type only.
 In implementation when we need to find the floating data modulus value then go for
fmod(), or fmodl() functions.
 Fmod() and fmodl() functions are available in <stdlib.h> which is used to find the
modulus of floating data values.
Example:
/* W.A.P. to calculate Addition of two numbers */
# include<stdio.h >
# includ<conio.h >
void main ()

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
36 www.newgentech.in C LANGUAGE BY Mr.PRR

{
int a, b, c;
clrscr ();
printf (“ enter a, b, values = “); Output:
scanf (“ %d %d”, &a , &b); enter a, b values= 10 20
c=a+b; Addition=30
printf (“Addition =% d”, C);
getch();
}
Relational Operators:
 In c all relational operators returns one or zero
 If the expression is true then returns with ‟1‟ and if the expression is false then returns
with zero.
 Every non zero is called true when value become zero it is called false.
Relational operators Action

< is less than


<= Is less than or equal
> Is greater than
>= is greater than equal
== is equal to
!= is not equal
Example:
/* write a program to verify relational operators */
#include<stdio.h> printf("\n value of a<b:%d",c);
#include<conio.h> c=a==b;
void main() printf("\n value of a==b:%d",c);
{ c=a>=b;
int a,b,c; printf("\n value of a>=b:%d",c);
clrscr(); c=a<=b;
printf("\n Enter a,b values:"); printf("\n value of a<=b:%d",c);
scanf("%d%d",&a,&b); c=a!=b;
c=a>b; printf("\n value of a!=b:%d",c);
printf("\n value of a>b:%d",c); getch();
c=a<b; }
Logical Operators:
 Logical expressions combine two (or) more relational expressions. And also used to test
more than a one condition one and make decision.
Logical Operators Action

&& Logical AND


|| Logical OR
! Logical NOT
 In c all logical operators returns one or zero.
 If the expression is true then returns with ‟1‟ and if the expression is false then returns
with zero.
 Every non zero is called true when value become zero it is called false.
Example:
/* write a program to verify logical operators */
#include<stdio.h> #include<conio.h>

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
37 www.newgentech.in C LANGUAGE BY Mr.PRR

void main() printf("\n value of AND operator:%d",d);


{ d=((a>b)||(a>c));
int a,b,c,d; printf("\n value of OR operator:%d",d);
clrscr(); d=((a>b)!=(a>c));
printf("\n enter a,b,c values:"); printf("\n value of NOT operator:%d",d);
scanf("%d%d%d",&a,&b,&c); getch();
d=((a>b)&&(a>c)); }
Assignment Operators:
 Assignment operator is a binary category operator.
 Binary category means it required two operands that is left and right argument.
 Among those to arguments any one missing it gives an error. And left side argument
must be variable type only.
Syntax:
V op = exp;
Where V is a variable
Exp is an expression.
Op is a “C” binary arithmetic operator
These operators also called as short hand operators.

Increment and Decrement Operators:


These operators are represent as „++‟ and „- -„increments opened by 1 and -- decrements
operands by 1 they are unary operators.
Operator Action
A ++ Post – Increments
++a Pre – decrements
A -- Post– decrements
--A Pre - decrement

Example:
/* write a program to perform increment and decrement */
#include<stdio.h> scanf("%d",&a);
#include<conio.h> printf("\n Value Of a++:%d",a++);
void main() printf("\n Value Of a++:%d",++a);
{ printf("\n Value Of a++:%d",a--);
int a; printf("\n Value Of a++:%d",--a);
clrscr(); getch();
printf("\n Enter a,b values:"); }
Conditional Operators:
 Conditional operator are ternary category operators
 Ternary category means it required three arguments i.e, left, middle, and right side
arguments.
 In ternary category operators if the expression is true then returns with middle
arguments. If expression is false then returns with right side argument and left side
wxpression is treated as condition.
Syntax:
Expression =left term? Middle term: right term;
Notes:
1. Number of question marks and colon marks should be equal
2. Every colon should match with just before the question mark
3. Every colon should followed by question mark only.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
38 www.newgentech.in C LANGUAGE BY Mr.PRR

Example:
/* TO FIND GREATEST OF TWO NUMBERS USING CONDITIONAL OPERATOR. */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("\n Enter value of 'a': ");
scanf("%d",&a);
printf("\n Enter value of 'b': ");
scanf("%d",&b)
c = (a>b) ?a:b;
printf("\n The number %d is greater",c);
getch();
}

Bitwise Operators
Bitwise operators are special types of operators that are used in programming the
processor. In processor, mathematical operations like: addition, subtraction, addition
and division are done using the bitwise operators which makes processing faster and
saves power.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Bitwise AND operator in C programming.
The output of logical AND is 1 if both the corresponding bits of operand is 1. If either of
bit is 0 or both bits are 0, the output will be 0. It is a binary operator(works on two
operands) and indicated in C programming by & symbol. Let us suppose the bitwise AND
operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
39 www.newgentech.in C LANGUAGE BY Mr.PRR

As, every bitwise operator works on each bit of data. The corresponding bits of two
inputs are check and if both bits are 1 then only the output will be 1. In this case, both
bits are 1 at only one position,i.e, fourth position from the right, hence the output bit of
that position is 1 and all other bits are 0.
#include <stdio.h>
int main()
{
int a=12,b=39;
printf("Output=%d",a&b);
return 0;
}
Output
Output=4
Bitwise OR operators:
The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1. In C
Programming, bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)

#include <stdio.h>
int main()
{
int a=12,b=25;
printf("Output=%d",a|b);
return 0;
}
Output
Output=29
C Programming Bitwise XOR(exclusive OR) operator
The output of bitwise XOR operator is 1 if the corresponding bits of two operators are
opposite(i.e., To get corresponding output bit 1; if corresponding bit of first operand is
0 then, corresponding bit of second operand should be 1 and vice-versa.). It is denoted
by ^.
12 = 00001100 (In Binary)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
40 www.newgentech.in C LANGUAGE BY Mr.PRR

25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
| 00011001
________
00010101 = 21 (In decimal)

#include <stdio.h>
int main()
{
int a=12,b=25;
printf("Output=%d",a^b);
return 0;
}
Output=21
Bitwise compliment operator
Bitwise compliment operator is an unary operator(works on one operand only). It
changes the corresponding bit of the operand to opposite bit,i.e., 0 to 1 and 1 to 0. It is
denoted by ~.
35=00100011 (In Binary)
Bitwise complement Operation of 35
~ 00100011
________
11011100 = 220 (In decimal)
Twist in bitwise complement operator in C Programming
Output of ~35 shown by compiler won't be 220, instead it shows -36. For any integer n,
bitwise complement of n will be -(n+1). To understand this, you should understand the
concept of 2's complement.
2's Complement
Two's complement is the operation on binary numbers which allows number to write it in
different form. The 2's complement of number is equal to the complement of number
plus 1. For example:
Decimal Binary 2's complement
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
41 www.newgentech.in C LANGUAGE BY Mr.PRR

Note: Overflow is ignored while computing 2's complement.


If we consider the bitwise complement of 35, 220(in decimal) is converted into 2's
complement which is -36. Thus, the output shown by computer will be -36 instead of
220.
How is bitwise complement of any number N=-(N+1)?
bitwise complement of N= ~N (represented in 2's complement form)
2'complement of ~N= -(~(~N)+1) = -(N+1)
#include <stdio.h>
int main()
{
printf("complement=%d\n",~35);
printf("complement=%d\n",~-12);
return 0;
}
complement=-36
Output=11
Shift Operator in C programming
There are two shift operators in C programming: Right shift operator and Left shift
operator.
Right Shift Operator
Right shift operator moves the all bits towards the right by certain number of bits which
can be specified. It is denoted by >>.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)

Left Shift Operator


Left shift operator moves the all bits towards the left by certain number of bits which
can be specified. It is denoted by <<.
212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 =11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)
#include <stdio.h>
int main()
{
int num=212,i;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
42 www.newgentech.in C LANGUAGE BY Mr.PRR

for (i=0;i<=2;++i)
printf("Right shift by %d: %d\n",i,num>>i);
printf("\n");
for (i=0;i<=2;++i)
printf("Left shift by %d: %d\n",i,num<<i);
return 0;
}
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53
Left Shift by 0: 212
Left Shift by 1: 424
Left Shift by 2: 848
Interesting thing to note in Left and Right Shift
For any positive number, right shift is equal to integer division of that number by (shift
bit plus one) and for any integer left shift is equal to the multiplication of that number
by (shift bit plus one).

A B A&B A|B A^B ~A

1 1 1 1 0 0

1 0 0 1 1 0

0 1 0 1 1 1

0 0 0 0 0 1

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
43 www.newgentech.in C LANGUAGE BY Mr.PRR

Precedence and Associativity of Operators:

Precdence Group Operators Associativity


(Highest to Lowest )
(param) subscript etc., ( ) [ ] –>. LR
Unary operators - + ! ~ ++ – – (type) * & sizeof RL
Multiplicative */% LR
Additive +– LR
Bitwise shift <<>> LR
Relational <<= >>= LR
Equality = = != LR
Bitwise AND & LR
Bitwise exclusive OR ^ LR
Bitwise OR | LR
Logical AND && LR
Logical OR || LR
Conditional ?: RL
Assignment = += –= *= /= %= &= ^= RL
|= <<= >>=
Comma , LR

 Precedence is used to determine the order in which different operators in a complex


expression are evaluated.
 Associativity is used to determine the order in which operators with the same
precedence are evaluated in a complex expression

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
44 www.newgentech.in C LANGUAGE BY Mr.PRR

Programs: Output:
/* Using Escape Sequences */ enter a,b values = 10
# include <stdio.h> 20
# include <conio.h> given values after swaping a=20
main() b=10
{ /* WAP to calculate months and
clrscr() ; years*/
printf(“Hello \t “) ; #include<stdio.h>
printf(“New generation \n”) ; #include<conio.h>
printf(“how are you “) ; main ()
} {
Output: int months,days,years;
Hello New generation clrscr();
how are you printf("enter the no of days = ");
EXAMPLE 3: scanf("%d",&days);
/* W A P to calculate multiplication of months = days/30 ;
two numbers */ years = months/12;
#include<stdio.h > printf("in months = %d, years =
#include<conio.h > %d",months, years);
main () getch();
{ }
float a,b,c; Output: - enter the no of days = 365
clrscr (); in months = 12, years = 1
printf ("enter a,b, values = "); /* find the output of following program
scanf ("%f%f" , &a, &b); */
c= a*b; #include<stdio.h>
printf (" multiplication = %f " , c); #include<conio.h>
getch (); void main()
} {
Output: int i=-1,j=-1,k=0,l=2,m;
enter a,b, values = 10 clrscr();
5 m=i++&&j++&&k++||l++;
multiplication = 50.000000 printf("%d %d %d %d %d",i,j,k,l,m);
/* W A P to swap two numbers */ getch();
#include<stdio.h> }
#include<conio.h> Output:
main () 0 0 1 3 1
{ /* find the value of a and b */
int a,b,temp; #include<stdio.h>
clrscr(); #include<conio.h>
printf("enter a,b values = "); void main()
scanf("%d%d",&a,&b); {
temp = a; int a,b;
a = b; clrscr();
b = temp; a = 200*200/200;
printf("\n given values after swaping a=%d b = 200/200*200;
\n b=%d",a ,b); printf("\n *** values of a and b is ***\n ");
getch(); printf("\n a = %d \t b = %d",a,b);
} getch();
}
OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
45 www.newgentech.in C LANGUAGE BY Mr.PRR

Output: - Output:
*** values of a and b is *** ENTER THE RADIUS: 10
a = -127 b = 200 AREA COMES TO BE: 314.000000
/* find the output of the following getchar() function:
program */ By using getchar() function we can store
#include<stdio.h> only one character. If you give multiple
#include<conio.h> characters also system will take only one
void main() character i.e. first character.
{ /* PRINT OUT THE RESULTS USING
int i=10; getchar(). */
clrscr();
printf("%d %d %d %d",i++,++i,i--,--i); #include<stdio.h>
printf("\n value of i after increment=%d",i); #include<conio.h>
getch(); void main()
} {
Output: char ch;
9 9 9 9 clrscr();
value of i after increment=10 printf("\n Enter a character...\n ");
/* find the output of the following ch=getchar();
program*/ printf("\n Result is...\n %c",ch);
#include<stdio.h> getch();
#include<conio.h> }
void main() Output:
{ Enter a character...
int a,b; R
clrscr(); Result is...
a=1; R
b=a++*++a*a++;
putchar() function:
printf("%d \t %d",a,b);
By using putchar() function we can print
getch();
single character value on the console
}
screen. If you give multiple characters also
Output:
putchar() print only single character (First
4 8
character).
/*TO PRINT THE OUTPUT USING
/* TO CALCULATE THE AREA OF A
putchar(). */
CIRCLE. */
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
#include<conio.h>
#define PI 3.14
void main()
void main()
{
{
char ch='s';
int r;
clrscr();
float a;
printf("\n Result is as...\n ");
clrscr();
putchar(ch);
printf("\n ENTER THE RADIUS: ");
getch();
scanf("%d",&r);
}
a=PI*r*r;
Output:
printf("\n AREA COMES TO BE: %f",a);
Result is as...
getch();
S
}
OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
46 www.newgentech.in C LANGUAGE BY Mr.PRR

/* TO PRINT THE VALUE OBTAINED BY Enter value of 'a': 10


VARIOUS OPERATORS. */ Enter value of 'b': 3
#include<stdio.h> Result is as...
#include<conio.h> 13 7 30 3 1
void main() #include<stdio.h>
{ #include<conio.h>
int a,b,c,d,e,f,g;
clrscr(); EXAMPLE:
printf("\n Enter value of 'a': "); #include<stdio.h>
scanf("%d",&a); #include<conio.h>
printf("\n Enter value of 'b': "); void main()
scanf("%d",&b); {
c = a + b; int a=10;
d = a - b; int b=20;
e = a * b; int c=30;
f = a / b; clrscr();
g = a % b; printf("a* b+c is:%d\n", a * b+c);
printf("\n Result is as..."); printf("a*(b+c) is:%d\n",a*(b+c));
printf("\n %d \t %d \t %d \t %d \t getch();
%d",c,d,e,f,g); }
getch(); Output:
} a* b+c is:230
Output: a*(b+c) is:500

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
47 www.newgentech.in C LANGUAGE BY Mr.PRR

CONTROL STATEMENTS(LOOPS)
Q) Why Iterative Statements?
=>Iteration means repeated execution of statements. In most situations, we need to execute a
set of statements repeatedly for a given number of times.
=>Writing the same set of statements repeatedly will have the following drawbacks.
1)Wastage of time.
2)Wastage of memory.
3)Chances of creating errors.
=>To overcome this problem, we go to the concept of loops. Using loops,we will write the
statements only once,and execute them as many no. of times as required.
Q) What do meant by conditional control statement?
=> The statements which can be executed for specified set of times until the given condition
satisfies are known as conditional controlled statements. These statements are supported under
C language with following key words such as
1. while
2. do-while
3. for
Q) What is a loop?
=>Loop is a group of instructions compiler executes repeatedly while some condition remains
true.
Or
Looping is the process of repeating of same code until a specific condition doesn‟t satisfy. In c
there are three types of loop:
Q) Explain types of loops?
 Loops are classified into two types. They are
1. Entry control loop
2. Exit control loop
Entry control loop:
 In this control loop compiler will check condition first. If condition is true then compiler move
into the body. If condition fail compiler doesn‟t execute body atleast once.
 Entry control loop is also called as Pre-checking control loop.
Ex: while, for
Exit control loop:
 In this kind of control loop compiler first executes the body then it go for the condition. If
condition is true again it goes to the body.
 If condition fails it goes out of the body.
 So in exit control loop without knowing condition compiler execute body minimum one time.
 Exit control loop is also as post control loop.
Q) Explain steps how to implements loops in a program?
=> Generally every loop require three steps
1. Initialization 2. Condition 3. Iteration
Q) Explain the need of initialization, condition, iteration in a loop?
=> Initialization indicates the starting point of the loop
=> Condition indicates ending point of loop (i.e. .when condition fail automatically loop
terminated)
=> To rotate the body of the loop either in clock or anti clock wise direction iteration required in
a loop.
for loop:
This loop is used when we have to execute a part of code in finite times. It is per tested loop.
Syntax of for loop:

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
48 www.newgentech.in C LANGUAGE BY Mr.PRR

Syntax:
for (Expression 1; Expression 2; Expression 3){
Loop body
}
Order of movement of control in for loop:
First time:
Expression 1-> Expression 2->Loop body -> Expression 3
Second time and onward:
Expression 2->Loop body -> Expression 3
That is expression 1 only executes in the first iteration. From second iteration and onward
control doesn‟t go to at the expression 1.
For example:
#include<stdio.h>
int main(){
int i;
for(i=0;i<=4;i++){
printf("%d ",i);
}
return 0;
}
Output: 0 1 2 3 4
Explanation of each term of syntax:
Expression 1:
It is called initialization expression. Task of this expression is to initialize the looping variables.
Properties of expression 1: int main(){
1. Expression1 can initialize the more than for(int i=0;i<=10;i++){
one variable. For example: printf("%d ",i);
#include<stdio.h> }
int main(){
int i,j,k; return 0;
for(i=0,j=2,k=1;i<=4;i++){ }
printf("%d ",i+j+k); Output: compilation error
} Expression 2:
return 0; It is called as conditional expression. Task of
} expression is to check the condition and if it
Output: 3 4 5 6 7 is false then it terminates the loop. For
2. Expression1 is optional. For example: example:
#include<stdio.h> #include<stdio.h>
void main(){ int main(){
int i=1; int i;
for(;i<=4;i++){
printf("%d ",i); for(i=1;i<=3;i++){
} printf("hi ");
return 0; }
} printf("%d",i);
Output: 1 2 3 4 return 0;
3. Unlike to the java in c we cannot }
declare the variable at the expression1. Output: hi hi hi 4
For example:
#include<stdio.h>

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
49 www.newgentech.in C LANGUAGE BY Mr.PRR

Properties of expression2: int i;


1. Expression2 can have more than one
checking condition and if any condition is for(;i=0,i<=3 ;i++){
false loop will terminate. For example: printf("%d ",i);
(a) }
#include<stdio.h> return 0;
void main(){ }
int i,j=2; Output: Infinite Loop
for(i=0;i<=5,j>=0;i++){ (b)
printf("%d ",i+j); #include<stdio.h>
j--; int main(){
} int i=0;

return 0; for(;i+=2,i<5 ;i++){


} printf("%d ",i);
Output: 2 2 2 }
(b) return 0;
#include<stdio.h> }
int main(){ Output: 2
int i,j=2; 4. If expression2 is zero means
condition is false and any non zero
for(i=0;j>=0,i<=5;i++){ number means condition is true. For
printf("%d ",i+j); example
j--; (a)
} #include<stdio.h>
return 0; int main(){
} int i;
Output: 2 2 2 2 2 2
for(i=0;-5 ;i++){
2. Expression2 is also optional. For printf("%d ",i);
example: if(i==3)
#include<stdio.h> break;
int main(){ }
int j; return 0;
}
for(j=0; ;j++){ Output: 0 1 2 3
printf("%d ",j); (b)
if(j>=2) #include<stdio.h>
break; int main(){
} int i;
return 0;
} for(i=5;0 ;i++){
Output: 0 1 2 printf("%d ",i);
3. It can perform task of expression1 as }
well as expression3. That is it can return 0;
initialize the variables as well as }
increment the variables. For example: Output: 5
(a)
#include<stdio.h>
int main(){
OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
50 www.newgentech.in C LANGUAGE BY Mr.PRR

Expression 3: 1. If loop body contain only one statement


It is called as instrumentation expression. then brace is optional. For example:
Task of this expression is to increment the (a)
variable. Properties: #include<stdio.h>
1. We can increment more than one int main(){
variable at the same time in the int i,j=0;
expression3. For example for(i=0;i<=3;++i,i++,++j )
(a) printf("%d %d ",i,j);
#include<stdio.h> }
int main(){ return 0;
int i,j,k; }
for(i=0,j=0,k=0;i<=5,j<=4,k<=3;i++,+ Output: 0 0 2 1
+j,k+=2){
printf("%d ",i+j+k); (b)
} #include<stdio.h>
return 0; int main(){
} int x,y=5;
Output: 0 4 for(x=0;x<3;x++)
(b) if(y>=5)
#include<stdio.h> printf(" %d",x);
void main(){ return 0;
int i,j=0; }
for(i=0;i<=3;++i,i++,++j ){ Output: 0 1 2
printf("%d %d ",i,j); 2. Loop without body is possible. For
} example
return 0; #include<stdio.h>
} int main(){
Output: 0 0 2 1 int i;
for(i=0;i<=10;i++);
2. Expression 3 is also optional. For printf("%d",i);
example return 0;
#include<stdio.h> }
int main(){ Output: 11
int i; 3. Braces of loop body behave as block.
For example
for(i=0;i<=3; ){ #include<stdio.h>
printf("%d ",i++); int main(){
} int i;
return 0; for(i=0;i<=2;i++){
} int i=8;
Output: 0 1 2 3 printf("%d ",i);
Loop body: }
Loop body contains the part of code which printf("%d",i);
we have to execute multiple numbers of return 0;
times. }
Properties of loop body: Output: 8 8 8 3
While loop:
It is pre tested loop. It is used when we have to execute a part of code in unknown numbers of
times.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
51 www.newgentech.in C LANGUAGE BY Mr.PRR

Syntax:
while (Expression){
Loop body
}
Properties of while loop:
1. Task of the expression is to check the condition. Loop will execute until condition is true
otherwise loop will terminate.
2. If any expression returns zero then condition will false and if it returns any non- zero number
then condition will true. For example:
(a) (b)
#include<stdio.h> #include<stdio.h>
int main(){ int main(){
int x=3,y=2; float a=1.5f;
while(x+y-1){
printf("%d ",x--+y); while(a){
} printf("%.f ",a);
return 0; a-=.5f;
} }
Output: return 0;
5432 }

Output:
210
3. In while loop condition expression is compulsory. For example:
#include<stdio.h>
int main(){
while(){
printf("Hello world");
}
return 0;
}
Output:
Compilation error
4. While loop without any body is possible. For example:
#include<stdio.h>
int main(){
int i=0;
while(i++,i<=8);
printf("%d ",i);
return 0;
}
Output:
9
5. In while loop there can be more than one conditional expression. For example
#include<stdio.h>
int main(){
int x=2,y=2;
while(x<=5,y<=3)
printf("%d %d ",++x, ++y);
return 0;
OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
52 www.newgentech.in C LANGUAGE BY Mr.PRR

}
Output:
3344
6. If loop body contain only one statement the brace is optional. For example:
#include<stdio.h>
int main(){
while(!printf("Hello world"));
return 0;
}
Output: Hello world
do while:
It is also called as post tested loop. It is used when it is necessary to execute the loop at least
one time.
Syntax:
do { Output:
Loop body 3344
} while (Expression);
Example:
void main(){
int num,i=0;
clrscr();
do{
printf("To enter press 1\n");
printf("To exit press 2");
scanf("%d",&num);
++i;
switch(num){
case 1:printf("You are welcome\n");break;
default : exit(0);
}}
while(i<=10);
}
1. If there is only one statement in the loop body then braces is optional. For example:

(c)
(a) (b)
void main(){
void main(){ void main(){
int x=25,y=1;
double i=5.5678 double i=5.63333
do
; ;
if(x>5)
clrscr(); clrscr();
printf(" ONE");
do do
else if(x>10)
printf("hi"); printf("hi");
printf(" TWO");
while(!i); while(!i);
else if(x==25)
} getch();
printf(" THREE");
Output: }
else
3344 Output:
printf(" FOUR");
hi
while(y--);}

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
53 www.newgentech.in C LANGUAGE BY Mr.PRR

break and continue Keywords:


break:
It is keyword of c programming. Task of this keyword is to bring the control from out
of the loop in the case of looping. For example:
#include<stdio.h>
int main(){
int i;
for(i=0;i<=4;i++){
printf("%d",i);
break;
printf("Label 1");
}
printf("Label 2");
return 0;
}
Output:
0Label2
Another task of break keyword is to switch the control from one case to another case
in case of switch case control statement. For
example: Note:In any other case we cannot use
#include<stdio.h> break keyword.
int main(){ #include<stdio.h>
int i=0; int main(){
++i; float a=5.5f;
switch(i){ if(a==5.5){
case 1:printf("case 1"); printf("equal");
case 2:printf("case 2");break; }
case 3:printf("case 3"); else{
default: printf("default"); break;
} }
return 0; return 0;
} }
Output: Output:
case 1case 2 Compilation error
continue:
It is keyword of c and task of this keyword is to transfer the control of program at the
beginning of loop. For example:
#include<stdio.h>
#include<stdio.h>
int main(){
int main(){
int i=5;
int i=5;
do{
do{
printf("%d",i);
printf("%d",i);
continue;
continue;
i++;
i++;
}
}while(i<=10);
while(i<=10);
return 0;
return 0;
}
}
Output:
Output:
Infinite loop
Infinite loop

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
54 www.newgentech.in C LANGUAGE BY Mr.PRR

1. Except looping, we cannot use continue


keyword.
#include<stdio.h>
int main(){
int x;
scanf("%d",&x);
switch(x){
case 1:printf("1");break;
case 2:printf("2");continue;
default:printf("3");
}
return 0;
}
Output: Compilation error
goto keyword:
In C programming, goto statement is used for altering the normal se quence of program
execution by transferring control to some other part of the program.
Syntax of goto statement
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto
statement, the control of the program will jump to the label: and executes the code
below it.

Example of goto statement


# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
55 www.newgentech.in C LANGUAGE BY Mr.PRR

scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump; /* control of the program moves to label jump */
sum=sum+num;
}
jump:
average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}
Though goto statement is included in ANSI standard of C, use of goto statement should
be reduced as much as possible in a program.
Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto
statement makes the logic of the program complex and tangled. In modern
programming, goto statement is considered a harmful construc t and a bad programming
practice.
The goto statement can be replaced in most of C program with the use of break and
continue statements. In fact, any program in C programming can be perfectly written
without the use of goto statement. All programmer should try to avoid goto statement
as possible as they can.
Nested loops:
A loop inside another loop is known as nested loop. We can write any loop inside any loop in c
i.e. we can write for loop inside the loop or while loop or do while loop etc. For example:

(a)
(b)
#include<stdio.h>
#include<stdio.h>
int main(){
int main(){
int i,j,k;
int i,j,k;
for(i=0;i<3;i++){
do
for(j=0;j<3;j++){
while(0)
printf(" %d",i+j);
for(;0;)
}
printf("cbyexample");
}
while(0);
return 0;
return 0;
}
}

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
56 www.newgentech.in C LANGUAGE BY Mr.PRR

Practice programs:
EXAMPLE1: EXAMPLE3:
/* W A P to print one to given values*/ /* write a program to find the
#include<stdio.h> following result for a given number
#include<conio.h> 1. Reverse number2)sum of digits
void main() 3)number of digits*/
{ #include<stdio.h>
int n,i; #include<conio.h>
clrscr(); void main()
printf("enter n values="); {
scanf("%d",&n); int n,rn,sd,nd;
i=1; /* n->number, rn->reverse number, sd->
while (i<=n) sum of digits
{ nd-> number of digits */
printf("\t%d",i); clrscr();
i++; printf("enter n value=");
} scanf("%d",&n);
getch(); rn=sd=nd=0;
} while(n>0)
Output: {
enter n values=5 rn=rn*10+n%10;
1 2 3 4 5 sd=sd+n%10;
EXAMPLE2: nd=nd+1;
/* write a program to print given n=n/10;
number table */ }
#include<stdio.h> printf("\n reverse number : %d", rn);
#include<conio.h> printf("\n sum of digits : %d", sd);
void main() printf("\n number of digits : %d", nd);
{ getch();
int i,n; }
clrscr(); Ouput: -
printf("enter n value="); enter n value=4567
scanf("%d",&n); reverse number : 7654
i=1; sum of digits : 22
while(i<=10) number of digits : 4
{ EXAMPLE4:
printf("\n %d * %2d = %2d",n,i,n*i); //finonacci service
i=i+1; #include<stdio.h>
} #include<conio.h>
getch(); void main()
} {
Output: int i,j,n,f;
enter n value=2 clrscr();
2* 1= 2 printf("enter a value=");
2 * 6 = 12
2* 2= 4 scanf("%d",&n);
2 * 7 = 14
2* 3= 6 i=0;
2 * 8 = 16
2* 4= 8 j=1;
2 * 9 = 18
2 * 5 = 10 printf("%d\t%d",i,j);
2 * 10 = 20
f=i+j;
while(f<=n)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
57 www.newgentech.in C LANGUAGE BY Mr.PRR

{
printf("\t %d",f); Output:
i=j; enter the number=5
j=f; factorial=120
f=i+j;
} EXAMPLE7:
getch(); /*calculate average of n numbers */
} #include<stdio.h>
Output: #include<conio.h>
enter a value=125 void main()
0 1 1 2 3 5 8 {
13 21 34 int i,n, no, sum=0;
55 89 float average;
EXAMPLE5: clrscr();
/* program on for loop*/ printf("enter total no.of number=");
#include<stdio.h> scanf ("%d",&n);
#include<conio.h> for (i=1;i<=n;i++)
void main() {
{ printf("enter the number=");
int i,n; scanf ("%d",&no);
clrscr(); sum=sum+no;
printf("enter n values="); }
scanf("%d",&n); average=sum/n;
for(i=1;i<=n;i++) printf ("\n average=%f", average);
{ getch();}
printf("\t %d",i); Output:
} enter total no.of number=5
getch(); enter the number=1
} enter the number=2
Output: enter the number=3
enter n values=10 enter the number=4
1 2 3 4 5 6 7 enter the number=5
8 9 10 average=3.000000
EXAMPLE6: EXAMPLE8:
/*WAP to find out factorial of a given /* write a program to implement
number*/ follwing format
#include<stdio.h> 1
#include<conio.h> 12
void main() 123
{ 1234
int n,i,fact=1; 12345
clrscr(); (assume in this case n value is 5) */
printf("enter the number="); # include <stdio.h>
scanf("%d",&n); # include <conio.h>
for(i=n; i>0; i--) void main()
{ {
fact=fact*i; int n, k, j ;
} clrscr() ;
printf("factorial=%d",fact); printf("Enter any number ") ;
} scanf("%d", &n) ;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
58 www.newgentech.in C LANGUAGE BY Mr.PRR

for(k=1; k<=n; k++) #include<stdio.h>


{ #include <conio.h>
printf("\n ") ; void main()
for(j=1; j<=k; j++) {
printf("%d ", j); int n, k, j ;
} clrscr() ;
} printf("Enter any number ") ;
EXAMPLE9: scanf("%d", &n) ;
/* write a program for following format for(k=1; k<=n; k++)
1 {
22 printf("\n ") ;
333 for(j=1; j<=k; j++)
4444 printf("%d ", k) ;
55555 }
(assume here n value is 5) */ }

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
59 www.newgentech.in C LANGUAGE BY Mr.PRR

CONDITIONAL STATEMENTS
Q) Why conditional statements?
=> If we want to execute some logic inside a program based on some condition then we go for
conditional statements. Conditional statements are also called as selection statements. And also
called as Branching Statements. Because they are used to transfer control from one statement
to another
Q) What are the types of conditional statements?
Conditional statements are mainly classified into two types they are
1. If statements,
2. Switch statement.
If statements are again classified into three types
if():
In c language “if” is a one of the keyword of 32. It is used to implement conditional statements
or selection statements in a program.
The general form of its statement looks like is
Syntax:
If (<expression>)
{
Statements 1;
.
Statements n;
}
Working:
If the expression is true then compiler executes the body of if statements otherwise it does not
execute the statements.
If the body is not specified then automatically condition path terminated with next semi colon.
Properties of if statements:
1. If expression is zero means condition is
false and any non zero number means b)
condition is true. For example #include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> void main()
void main() {
{ int a;
int a; clrscr();
clrscr(); a=0;
a=10; if(a)
if(a) {
{ printf("\n I am inside a if block");
printf("\n I am inside a if block"); }
} Printf(“\n I am out of the if block “);
getch(); getch();
} }
Ouput: Output:
I am inside a if block I am out of the if block

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
60 www.newgentech.in C LANGUAGE BY Mr.PRR

2. Expression is compulsory else it if(a<=50);


leads compilation error printf("\n I am inside a if block");
#include<stdio.h> getch();
#include<conio.h> }
void main() Output:
{ I am inside a if block
int a; 5. We can write nested if statements.
clrscr(); In this case if outer condition is true
a=10; then only compiler will check about
if() inner condition.
{ #include<stdio.h>
printf("\n I am inside a if block"); #include<conio.h>
} void main()
getch(); {
} int a,b;
Output: clrscr();
Compilation error a=10;
b=2;
3. If we place semicolon to if statment, if(a>b)
compiler execute the body irrespective {
of the condition printf("\n I am in body");
Example: if(a==10)
#include<stdio.h> {
#include<conio.h> printf("\n I am inside a if block");
void main() printf("\n I am learning C language in
{ NGC");
int a; }
clrscr(); }
a=10; getch();
if(a<=50); }
{ Output:
printf("\n I am inside a if block"); I am in body
printf("\n I am learning C language in I am inside a if block
NGC"); I am learning C language in NGC
} 6. We can write more than one if
getch(); statements in a single program. This
} time compiler executes the bodies
Output: based on condition which is true. If all
I am inside a if block condition are true, that time compiler
I am learning C language in NGC executes all bodies of the statements
which are true.
4. Block is optional when we have only A)
statement as a body Example:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a; int a,b;
clrscr(); clrscr();
a=10; a=10;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
61 www.newgentech.in C LANGUAGE BY Mr.PRR

b=2; void main()


if(a>b) {
{ int a,b;
printf("\n I am in body"); clrscr();
} a=10;
if(a==10) b=2;
{ if(a>b)
printf("\n I am inside a if block"); {
printf("\n I am learning C language in printf("\n I am in body");
NGC"); }
} if(a==100)
} {
getch(); printf("\n I am inside a if block");
} printf("\n I am learning C language in
Output: NGC");
I am in body }
I am inside a if block }
I am learning C language in NGC }
B) Output:
#include<stdio.h> I am in body
#include<conio.h>

Q) What is the limitation of if statement?


If keyword meant for verifying some condition, based on condition compiler want to execute
some logic (body of if). But we know condition nothing but it contain two possible, one is true
and other one is false.
Here if condition is true, then we have solution (body of the loop) but if condition is false then
there is no any solution for the user to understand.
So to overcome this limitation we are adding one extra block for if statement to execute some
logic whenever condition is fail. This extra block is known as “else block”.
Syntax:
else
{
Block of statements; //true block
}
Usage of else block:
Syntax:
If(<expression>){
Body
}
else
{
Body
}
Properties of else block:
1. else block is always associated with void main()
the if block. {
Example: int a,b;
#include<stdio.h> clrscr();
#include<conio.h> a=10;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
62 www.newgentech.in C LANGUAGE BY Mr.PRR

b=2; if(a>b)
if(a>b) {
{ printf("\n a is big value");
printf("\n a is big value"); }
} else
else {
{ Printf(“\n else block”);
Printf(“\n b is big value”); If(a>=5)
} {
getch(); Printf(“\n a value is greater than five”);
} }
2. We can‟t add any statements in }
between if block and else block getch();
Example: }
#include<stdio.h> 4. If we place semicolon after else
#include<conio.h> (else;) , by default compiler will
void main() execute else block whether condition is
{ true or false.
int a,b; For example
clrscr(); #include<stdio.h>
a=10; #include<conio.h>
b=2; void main()
if(a>b) {
{ int k;
printf("\n a is big value"); clrscr();
} printf("enter any number=");
printf(“ I am in between if and else”); scanf("%d", &k);
else if(k==0)
{ {
Printf(“\n b is big value”); printf("the number is zero");
} }
} else if(k>0)
Output: {
Compilation error printf("the number is positive");
3. We can write if block inside else }
block Else;
#include<stdio.h> {
#include<conio.h> printf("\n the number is negative");
void main() }
{ }
int a,b; Output:
clrscr(); enter any number=25
a=10; the number is positive
b=2; the number is negative numbers
Note: We can write if block inside else block. But it is not advisable in programs, because by
default compiler dose not execute else block. Else block executed when if condition flase.
Q) What is the limitation of if –else block?
In above approach we can implement only one condition. So if you want to implement multiple
conditions above approach is not suitable. So we go for next concept called if-else ladder.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
63 www.newgentech.in C LANGUAGE BY Mr.PRR

If -else –if ladder statements:


General form is
Syntax:
if (condition)
{
Block of statements;
}
else if (condition)
{
Block of statements;
}
.
.
else
{
Block of statements;
}
If the condition is true then it executes the block statements otherwise it executes the else
block statements .if, 1st if condition is not true then compiler moves into second if condition, if it
is true then compiler enter into body of that particular block. Compiler follows same mechanism
until some condition is true. Suppose if above all mentioned conditions are fail then finally
compiler moves into else block, which is default block whenever all conditions are fail.
Properties of if-else-if ladder:
1. Space is mandatory in between if and Output:
else. Compilation error (statement missing;)
For example 2. We can‟t place any statements in
#include<stdio.h> between if – else blocks.
#include<conio.h> For example
void main() #include<stdio.h>
{ #include<conio.h>
int k; void main()
clrscr(); {
printf("enter any number="); int k;
scanf("%d", &k); clrscr();
if(k==0) printf("enter any number=");
{ scanf("%d", &k);
printf("the number is zero"); if(k==0)
} {
elseif(k>0) compilation error printf("the number is zero");
{ }
printf("the number is positive"); printf(“\n”); compilation error
} else if(k>0)
else {
{ printf("the number is positive");
printf("the number is negative"); }
} else
getch(); {
} printf("the number is negative");
}
getch();

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
64 www.newgentech.in C LANGUAGE BY Mr.PRR

} compiler executes only one body which


Output: is encountered first.
Compilation error (misplaced else) For example
3. If block is mandatory whenever we #include<stdio.h>
writing if–else-if ladder. #include<conio.h>
For example void main()
#include<stdio.h> {
#include<conio.h> int k;
void main() clrscr();
{ printf("enter any number=");
int k; scanf("%d", &k);
clrscr(); if(k==0)
printf("enter any number="); {
scanf("%d", &k); printf("the number is zero");
else if(k>0) }
{ else if(k==0)
printf("the number is positive"); {
} printf("the number is positive");
else }
{ else
printf("the number is negative"); {
} printf("the number is negative");
getch(); }
} getch();
Output: }
Compilation error (misplaced else) Ouput:
4. We can write same expression in Enter any number: 0
multiple if blocks. But this time Number is zero
SWITCH STATEMENT:
 Switch is keyword, by using switch we can constructs multiple blocks of a selection
statements.
 Multiple blocks can be constructed with “case” keyword.
 It provides an easy way to dispatch execution to different parts of your code based on
the value of an expression. As such it often provides a better alternative than a large
series of if-else statements.
Syntax:
switch (expression)
{
case value1:
//statement sequence
break;
case value 2;
//statement sequence
break;
.
case value n;
//statement sequence
Break;
default:
//default statement sequence

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
65 www.newgentech.in C LANGUAGE BY Mr.PRR

}
 The switch statement works like this: the value of the expression is compared with each of
the constant values in the case statement. If a match is found, the code sequence following
that case statement is executed. If none of the constants matches the value of the
expression then the default statement is executed.
 Default is a special kind of case which will be executed automatically when the matching case
is not found.
 Using default is always optional. It is recommended to use when we are not handling all
provisions of switch block.
 The switch differs from the if in that switch can only test for equality, whereas if can
evaluate any type of relational or logical expression.
 No two case constants in the same switch can have identical values. Of course, a switch
statement enclosed by an outer switch may have case constants that are in common.
 If character constants are used in the switch statement, they are automatically converted to
integers.
EXAMPLE:
/*WAP to implement Arithmetic operation in a switch */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,k;
clrscr();
printf("enter two numbers=");
scanf("%d%d", &a, &b);
printf("\n 1.addition:");
printf("\n 2. Substraction:"); break;
printf("\n 3.multiplication:"); case 2:printf("the subtraction =%d",a-b);
printf("\n 4.division"); break;
printf("\n select your choice:"); case 3:printf("the multiplication=%d", a*b);
scanf("%d", &k); break;
printf("\n"); case 4:printf("the division=%d", a/b);
switch(k) break;
{ default:printf("in valid choice");
case 1:printf("the addition=%d", a+b); }
}

MORE EXAMPLES ON CONDITIONAL STATEMENTS


/*WAP to print big value of given two {
numbers by using if statement k*/ printf("a is greater than b", a, b);
#include<stdio.h> }
#include<conio.h> if(b>a)
void main() {
{ printf("b is greater than a", b, a);
int a,b; }
clrscr(); getch();
printf ("enter a,b, values ="); }
scanf("%d%d",&a,&b); Output:
if(a>b) enter a,b, values =10 20

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
66 www.newgentech.in C LANGUAGE BY Mr.PRR

b is greater than a {
Example2: printf("a is even ", a );
/*WAP to print the given value is even }
or odd */ else
#include<stdio.h> {
#include<conio.h> printf("a is odd", a);
void main() }
{ getch();
int a; }
clrscr(); Output:
printf("enter a value="); enter a value=50
scanf("%d", &a); a is even
if(a%2==0)
EXAMPLE3: Output:
/*WAP to check the given character is enter a character=o
vowel or not */ it is vowel
#include<stdio.h> EXAMPLE4:
#include<conio.h> /*WAP to check the given number is
void main() positive or negative */
{ #include<stdio.h>
char ngc; #include<conio.h>
clrscr(); void main()
printf("enter a character="); {
scanf("%c", &ngc); int k;
if(ngc=='a') clrscr();
{ printf("enter any number=");
printf("a is vowel", ngc); scanf("%d", &k);
} if(k==0)
else if(ngc=='e') {
{ printf("the number is zero");
printf("it is vowel", ngc); }
} else if(k>0)
else if (ngc =='o') {
{ printf("the number is positive");
printf("it is vowel", ngc); }
} else
else if(ngc=='i') {
{ printf("the number is negative");
printf("it is a vowel",ngc); }
} getch();
else if ( ngc =='u') }
{ Output:
printf("u is vowel", ngc); enter any number=25
} the number is positive
else EXAMPLE5:
{ /* WAP to print the given year value is
printf("%c is a not vowel", ngc); leap year or not */
} #include<stdio.h>
getch(); #include<conio.h>
} void main()

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
67 www.newgentech.in C LANGUAGE BY Mr.PRR

{ }
int a; Output:
clrscr(); enter marks in three subjects=45
printf("enter a value="); 65
scanf("%d", &a); 89
if(a%4==0) first division
{ EXAMPLE7:
printf("%d is leap year", a); /* w a p to find the given number is
} armstrong number or not*/
else #include<stdio.h>
{ #include<conio.h>
printf("%d is not a leap year",a); void main()
} {
getch(); int n,temp,i,sum=0;
} clrscr();
Output: printf("enter n value=");
enter a value=2012 scanf("%d",&n);
2012 is leap year for(temp=n;temp!=0;)
EXAMPLE6: {
/*Determine the division obtained by a i=temp%10;
student */ sum=sum+(i*i*i);
#include<stdio.h> temp=temp/10;
#include<conio.h> }
void main() if(sum==n && n!=1)
{ {
int m1,m2,m3; printf("\n %d is armstrong number ",n);
float per; }
clrscr(); else
printf("enter marks in three subjects="); {
scanf("%d", &m1); printf("%d is not a armstrong number",n);
scanf("%d", &m2); }
scanf("%d", &m3); getch();
per=(m1+m2+m3)/3; }
if(per>=60) Output:
{ enter n value=153
printf("first division"); 153 is armstrong number
} EXAMPLE8:
else if(per>=50) /* w a p find the given number is
{ perfect number or not */
printf("second division"); #include<stdio.h>
} #include<conio.h>
else if (per>=40) void main()
{ {
printf("third division"); int n,i,sum=0;
} clrscr();
else printf("enter n value=");
{ scanf("%d",&n);
printf("fail"); for(i=1;i<n;i++)
} {
getch(); if(n%i==0)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
68 www.newgentech.in C LANGUAGE BY Mr.PRR

{ 1 2 3 5 7 11 13
sum=sum+i; 17 19 23 29 31 37 41
} 43 47 53 59 61 67 71
} 73 79 83 89 97
if(n==sum) EXAMPLE10:
{ /* Write a C program to find the roots
printf("\n %d is perfect number ",n); of a quadratic equation. */
} #include<stdio.h>
else #include<conio.h>
{ #include<math.h>
printf("%d is not a perfect number",n); void main()
} {
getch(); float a,b,c,root1,root2;
} clrscr();
Output: printf("\n Enter values of a,b,c for finding
enter n value=6 roots of a quadratic eq:\n");
6 is perfect number: scanf("%f%f%f",&a,&b,&c);
EXAMPLE9: /*checking condition*/
/* Write a C program to generate all if(b*b>4*a*c)
the prime numbers between 1 and n, {
where n is a value supplied by the user. root1=-b+sqrt(b*b-4*a*c)/2*a;
*/ root2=-b-sqrt(b*b-4*a*c)/2*a;
#include <stdio.h> printf("\n*****ROOTS ARE*****\n");
void main() printf("\n root1=%f\n
{ root2=%f",root1,root2);
int no,counter,counter1,check; }
clrscr(); else
printf("\nINPUT THE VALUE OF N:"); printf("\n Imaginary Roots.");
scanf("%d",&no); getch();
printf("\n\nTHE PRIME NO. SERIES B/W 1 }
TO %d : \n\n",no); Output:
for(counter = 1; counter <= no; Enter values of a,b,c for finding roots of a
counter++) quadratic eq:
{ 12
check = 0; 14
for(counter1 = counter-1; counter1 > 1 ; 16
counter1--) Imaginary Roots.
if(counter%counter1 == 0) EXAMPLE12:
{ /* write a program to find given
check++; number is less than or greater than five
break; by using switch*/
} # include <stdio.h>
if(check == 0) # include <conio.h>
printf("%d\t",counter); void main()
} {
getch(); int k ;
} clrscr() ;
Output: printf("Enter any number " );
INPUT THE VALUE OF N:100 scanf("%d", &k) ;
THE PRIME NO. SERIES B/W 1 TO 100 : switch(k)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
69 www.newgentech.in C LANGUAGE BY Mr.PRR

{
case 0 : printf("\n Number is zero " );
case 1 :
case 2 :
case 3 :
case 4 : printf("\n Number is less than five
") ;
break ;
case 5 : printf("\n Number is five " );
break ;
default : printf("\n Number is greater than
five ") ;
}
getch() ;
}
Output:
Enter any number 4
Number is less than five
EXAMPLE13:
# include <stdio.h>
# include <conio.h>
main()
{
char k;
clrscr() ;
printf("Enter any one of the alphabets " );
k = getche() ;
switch(k)
{
case 'a' :
case 'A' : printf("\n A for Active ") ;
break ;
case 'b' :
case 'B' : printf("\n B for Brave ") ;
break ;
case 'c' :
case 'C' : printf("\n C for Courage ");
break ;
case 'd' :
case 'D' : printf("\n D for Dare ") ;
break ;
default : printf("\n You are timid ") ;
}
getch() ;
}
Output:
Enter any one of the alphabets A
A for Active

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
70 www.newgentech.in C LANGUAGE BY Mr.PRR

ARRAYS
Q) What is array? Explain its properties?
 An array is a set of consecutive memory locations used to store homogeneous data.
Each item in the array is called an element. The number of elements in an array is called
the dimension of the array.
 Each storage location in an array is called an array index.
 Array is derived data type.
 Array is a composite data type.
Properties:
1. Array index values always start from zero(0).
2. The variable name of array contains the base address of the memory block.
3. The array variable is created at the time of compilation.
4. The size of the array can‟t be alerted at runtime.
5. The address held by the array variable is static.
6. The array size must be constant and integer type.
Q) What are the advantages and disadvantages of array?
Advantages:
 Array supporting grouping of similar data elements.
 Referring more than one value with the same name which decreases complexity in
reading and writing values.
Disadvantages:
 The disadvantage of array is wastage of memory because of its static behavior.
Q) Explain types of arrays?
Arrays are broadly classified in two types. They are
1. Single Dimensional arrays.
2. Multi Dimensional arrays.
Q) What is single dimensional array? Explain with examples?
 One dimensional array is a list of values of the same data type. A one dimensional array
contains only one subscript.
 A subscript is a number inside a bracket that follows an array's name. This number can
identify the number of individual elements in the array.
 Array elements are stored in sequential memory locations
Syntax:
<data-type> <variable> [size] ;
Example:
int rno[100];
float sal[200];
char name[50];
 Before going to use any array we have to declare first.
 The data-type can be int, float, char, double, long etc.
 The size must be integer value only.
 Size must be constant.
 We can‟t store different data type values into single array.
Initialization:
Arrays are initialized both statically and dynamically like normal variable. Static initialization is
nothing but giving values in side a program, and dynamic initialization nothing but accepting
input values from the console screen.
Static initialization:
Syntax:
Data-type arrayname [size]={ele1,ele2,ele3,..,.,.,.,.,.elen};

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
71 www.newgentech.in C LANGUAGE BY Mr.PRR

Example:
int eno[5] = { 56, 67, 45, 89, 45};
float bas[] = { 56.67, 900.45, 567 } ;
Dynamic initialization:
Dynamic initialization can be done by using pre defined input functions.
Syntax:
scanf(“format speifier”,&variable_name[index_number]);
Example:
Int a[4];
Scanf(“%d”,&a[0]);
Scanf(“%d”,&a[1]);
Scanf(“%d”,&a[2]);
Scanf(“%d”,&a[3]);
NOTE:
Remember that array elements start with 0, not 1. Also remember that the last element is one
less than the number of elements in the array. For example, an array with 10 elements contains
elements 0 through 9.

EXAMPLE1:
/* write a program to enter 10 number entered numbers are=10
into a single variable*/ entered numbers are=20
#include<stdio.h> entered numbers are=30
#include<conio.h> entered numbers are=40
void main() entered numbers are=50
{ entered numbers are=60
int num[10],i; entered numbers are=70
clrscr(); entered numbers are=80
for(i=0;i<10;i++) entered numbers are=90
{ entered numbers are=100
printf("enter number value="); EXAMPLE2:
scanf("%d",&num[i]); /* Write a C program to find both the
} larges and smallest number in a list of
for(i=0;i<10;i++) integers.*/
{ #include<stdio.h>
printf("\nentered numbers #include<conio.h>
are=%d",num[i]); void main()
} {
getch(); char name[25];
} int sub[100];
OUTPUT: int n,min,max,i;
enter number value=10 clrscr();
enter number value=20 printf("enter student name=");
enter number value=30 scanf("%s",&name);
enter number value=40 printf("\n how many subjects=");
enter number value=50 scanf("%d",&n);
enter number value=60 printf("\n enter subject marks=");
enter number value=70 for(i=0;i<n;i++)
enter number value=80 scanf("%d",&sub[i]);
enter number value=90 min=max=sub[0];
enter number value=100 for(i=0;i<n;i++)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
72 www.newgentech.in C LANGUAGE BY Mr.PRR

{ Output:
if(sub[i]>max) enter student name=ravi
max=sub[i]; how many subjects=6
else enter subject marks=89
if(sub[i]<min) 65
min=sub[i]; 45
} 84
printf("\n student name=%s",name); 98
printf("\n minimum marks=%d",min); 72
printf("\n maximum marks=%d",max); student name=ravi
getch(); minimum marks=45
} maximum marks=98

Q) What is multidimensional array? Explain with examples?


Multidimensional Arrays:
 A multidimensional array has more than one subscript. I.e. A two-dimensional array has
two subscripts; a three-dimensional array has three subscripts, and so on. There is no
limit to the number of dimensions C array can have.
 A two-dimensional array has a row-and-column structure.
Initializing Multidimensional Arrays:
 Multidimensional arrays can also be initialized. The list of initialization values is assigned
to array elements in order, with the last array subscript changing first. For example:
EXAMPLE:
int array[4[3]={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
Results in the following assignments:
array[0][0] is equal to 1
array[0][1] is equal to 2
array[0][2] is equal to 3
array[1][0] is equal to 4
 When you initialize multidimensional arrays, you can make your source code clearer by using
extra braces to group the initialization values and also by spreading them over several lines.
The following initialization is equivalent to the one just given:
EXAMPLE:
int array[4][3] = { { 1, 2, 3 } , { 4, 5, 6 } ,{ 7, 8, 9 } , { 10, 11, 12 } };
Remember, initialization values must be separated by a comma even when there is a brace
between them. Also, be sure to use braces in pairs. a closing brace for every opening brace or
the compiler becomes confused.
SOME MORE EXAMPLES ON MULTIDIMENSTIONAL ARRAYS:
int a[10][5][3];
float sqr[3][3][3][3];
float area[5][5][5][5]…….[n];
EXAMPLE1:
/* Write a program to perform addition printf("\n enter the array a elements");
of two matrices*/ for(i=0; i<2; i++)
#include<stdio.h> {
#include<conio.h> for(j=0;j<3;j++)
void main() {
{ scanf("%d", &a[i][j]);
int i,j, a[2][3],b[2][3],c[2][3]; }
clrscr(); }

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
73 www.newgentech.in C LANGUAGE BY Mr.PRR

printf("\n enter the array B elements"); }


for(i=0; i<2; i++) printf("\n the product of a and b is in");
{ for(i=0;i<3;i++)
for(j=0; j<3; j++) {
{ for(j=0;j<3;j++)
scanf("%d", &b[i][j]); {
} c[i][j]=0;
} for(k=0;k<3;k++)
printf("\n sum of a and b is="); {
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
for (i=0; i<2; i++) }
{ }
for(j=0; j<3; j++) }
{ printf("\n\n");
c[i][j] = a[i][j]+b[i][j]; for(i=0; i<3; i++)
printf("\t%d", c[i] [j]); {
} for(j=0; j<3; j++)
} printf("\t%d", c[i][j]);
getch(); printf("\t\n");
} }
output: getch();
enter the array a elements 10 20 30 }
40 50 60 Output:
enter the array B elements10 20 30 enter a array elements:
40 50 60 1 1 1
sum of a and b is= 20 40 60 1 1 1
80 100 120 1 1 1
EXAMPLE2: enter b array element=1
/*write a to print multiplication of two 1 1 1
vectors*/ 1 1 1
#include<stdio.h> 1 1 1
#include<conio.h> the product of a and b is in
void main() 3 3 3
{ 3 3 3
int a[3][3],b[3][3],c[3][3]; 3 3 3
int i,j,k; EXAMPLE3:
clrscr(); /*wap to find out entered matrix is unit
printf("enter a array elements:"); or not */
for(i=0;i<3;i++) #include<stdio.h>
{ #include<conio.h>
for(j=0;j<3;j++) main()
scanf("%d", &a[i][j]); {
} int a[3][3],i,j;
printf("in enter b array element="); int t=0;
for (i=0;i<3;i++) printf("enter array elements=");
{ for(i=0;i<3;i++)
for(j=0;j<3;j++) {
{ for(j=0;j<3;j++)
scanf("%d", &b[i][j]); {
} scanf("%d", &a[i] [j]);
OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
74 www.newgentech.in C LANGUAGE BY Mr.PRR

} void main()
} {
for (i=0; i<3; i++) int i,j, a[3][3], sum=0;
{ clrscr();
for (j=0; j<3; j++) printf("enter array element=");
{ for (i=0; i<3; i++)
if(a[i][j]!=1) {
t=t+1; for (j=0; j<3; j++)
} {
} scanf ("%d", &a[i][j]);
if (t==0) }
printf("\n unit matrix"); }
else for (i=0; i<3; i++)
printf(" not a unit matrix"); {
getch(); for (j=0; j<3; j++)
} {
Output: if (i==j)
enter array elements=1 1 1 sum=sum+a[i][j];
111 }
111 }
unit matrix printf("sum of diagonals=%d", sum);
getch();
}
EXAMPLE4: Output:
/* wap to find sum of diagonals of an enter array element=1 2 3
square matrix*/ 213
#include<stdio.h> 321
#include<conio.h> sum of diagonals=3

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
75 www.newgentech.in C LANGUAGE BY Mr.PRR

STRINGS
Introduction:
A string is a sequence of characters. The characters include alphabets, digits, special symbols.
Example:
New generation
College
Ramana143
Civilengineering
C- Strings:
In C Language, strings are sequence of characters enclose in double quotes (“ “). They are also
called as character constants.
In C, a string is also defined as array of characters. Similarly, there is no separate data type
available to represent string. Such arrays of strings are terminated by a Null characters(„\0‟),
that is slash followed by zero.
For example, the following array represents a string,

Example,
“New generation”
“College”
“Ramana143”
“Civilengineering” are all treated as strings in C- Language.
Similarly, the C declarations,
char *string1 = "Hello";
char string2[] = "Hello";
char string3[6] = "Hello"; are string constants.
The C–Program to demonstrate how to assign and print strings
#include <stdio.h>
void main()
{
int a = 'H'; /* character constants */
char b = 'm';
char str1[6] = {'H','E','L','L','O'}; /* a character array */
char str2[7] = {'C','o','f','f','e','e','\0'}; /* extra element for a null character! */
char str3[] = "Hello world";
char *str4;
Output:
str4 = "Hyderabad";
a:H
clrscr();
b:m
printf("a : %c\n", a);
str1[] : HELLO
printf("b : %c\n", b);
str2[] : Coffee
printf("str1[] : %s\n", str1);
str3[] : Hello world
printf("str2[] : %s\n", str2);
str4 : Hyderabad
printf("str3[] : %s\n", str3);
printf("str4 : %s\n", str4);
getch();}
Note that you can only use the string format specifier, %s, for string constants.
In the above, the strings assigned in from program only. Those strings holder are fixed for the
string assigned to them, so they are constants.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
76 www.newgentech.in C LANGUAGE BY Mr.PRR

String Input/Output Functions


The scanf(), gets() are predefined functions for reading strings or array of characters thru
standard input called keyboard, the printf(), puts() predefined functions are used to for printing
strings or array of characters on standard output called monitor.
There is a difference between scanf and gets while reading string. The scanf considers space
and newline in input as end of string, where as gets considers newline input as end of string.
The printf() and scanf() for input/output and, the gets() and puts() for string input/output are
defined in header file stdio.h, so, include it to program which uses these functions.
There are some more input/output function in C, they will be discussed in coming chapters.
Example:
Program that uses the scanf() and the printf() functions for reading and printing the
array of characters or strings.
#include <stdio.h>
void main() Output:
{ Enter str1[]:Hello world
char str1[15]; str1[] : Hello
char *str2=""; Enter str2:
clrscr(); str2 : world
printf("Enter str1[]:"); Enter str1[]:JNTU <press enter key>
scanf("%s", str1); str1[] : JNTU
printf("str1[] : %s\n", str1); Enter str2: University,Hyd
str2 : University,Hyd
printf("Enter str2:");
scanf("%s", str2);
printf("str2 : %s\n", str2);
getch();
}
Program using gets() and puts() for reading and printing respectively the array of
characters or strings.
#include <stdio.h>
void main() Output:
{ Enter str1[]:Hello world
char str1[15]; Hello world
char *str2=""; Enter str2: ramesh
clrscr(); ramesh
puts("Enter str1[]:");
gets(str1);
puts(str1);
puts("Enter str2:");
gets(str2);
puts(str2);
}
Arrays of Strings:
In C, the array of string is defined as two-dimensional array of characters. This is defined as
follows,
char names[4][20];
this a array, for storing 4 names, each name can has at most 20 characters, but last character
reserved for null characters(„\0‟).
Similarly,
char *names[4];

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
77 www.newgentech.in C LANGUAGE BY Mr.PRR

this is array of 4 names, each name can has at most specified number of characters,
certainly, the last character would be null character („\0‟).
For example,
char names[4][15] ={“Sachin”, “Ravindar Kumar”, “Suresh”, “Vijay Kumar”};
stores the strings into array of strings as shown below.

Similarly, with the statement,


char *names[4] ={ “Damodhar”, “Surya Prakash”, “Nagesh Babu”, “ ”};
stores the strings into array of strings as shown below.

We can read and print the strings using program.


Program to demonstrate reading/printing strings from C-program
#include<stdio.h>
void main()
{
}
char name[4][15];
Output:
int i;
Enter 4 names:
clrscr();
Sachine
printf("Enter 4 names:\n");
Suresh
for(i=0;i<4;i++)
Vijay
scanf("%s", name[i]);
rahul
printf("\nThe names[][] are:\n");
The names[][] are:
i=0;
name[0] : Sachine
while(i<4)
name[1] : Suresh
{
name[2] : Vijay
printf("name[%d] : %s\n", i, name[i]);
name[3] : rahul
i = i + 1;
}
getch();
Another program to demonstrate reading/printing strings from C-program
#include<stdio.h>
void main()
{
char *name[4];
int i;
clrscr();
printf("Enter 4 names:\n");
for(i=0;i<4;i++)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
78 www.newgentech.in C LANGUAGE BY Mr.PRR

scanf("%s", name[i]);
Output:
printf("\nThe names[][] are:\n");
Enter 4 names:
i=0;
Damodhar
while(i<4)
Ragul
{
Nagesh
printf("name[%d] : %s\n", i, name[i]);
Vijay
i = i + 1;
}
The names[][] are:
getch();
name[0] : Damodhar
}
name[1] : Ragul
The gets, puts can also be used in above program. The scanf,
name[2] : Nagesh
printf, gets, and puts function can be in any combination in any C-
name[3] : Vijay
program.
String Manipulation Functions
The string manipulation functions are predefined functions, they are used to perform operations
on strings. They are defined in header file called “string.h”. Therefore, the program using such
functions should include this header file(#include<string.h>).
Most frequently used string functions from “string.h” are,
strcat strlen
strncpy stricmp
strcmpi strupr
strlwr strstr
strtok() strncat()
and many more, each of these are discussed in following explanation.
strcpy():
This function copies a string into another string.
The general structure of function is,
char *strcpy(char *dest, char *source);
Example:
/* wap to copy a string to another */ printf("\n copied(a) string=%s",a);
#include<stdio.h> printf(" \n original(b) string=%s", b);
#include<conio.h> getch();
void main() }
{ Output:
char a[100],b[100]; enter a string=
clrscr(); New generation
puts("enter a string="); enter b string=
gets(a); ramesh
puts("enter b string="); copied(a) string=ramesh
gets(b); original(b) string=ramesh
strcpy(a,b);
strcmp():
This function compares two strings with case sensitivity.
Syntax:
#include<string.h>
int strcmp( char *str1, char *str2 );
The function strcmp() compares str1 and str2, then returns,

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
79 www.newgentech.in C LANGUAGE BY Mr.PRR

Return value Explanation


less than 0(-ve) str1 is less than str2

equal to 0 str1 is equal to str2

greater than 0(+ve) str1 is greater than str2

Example:
/* write a program to compare two strings */
#include<stdio.h>
#include<conio.h>
void main()
Output:
{
enter a string=
char a[100],b[100];
ravi
int i;
enter b string=
clrscr();
ramesh
puts("enter a string=");
comparing string=9
gets(a);
puts("enter b string=");
gets(b);
i=strcmp(a,b);
printf("\n comparing string=%d",i);
getch();
}
strcat()
This function concatenates two strings, and returns the resultant string.
Syntax:
#include <string.h>
char *strcat( char *str1, char *str2 );
The strcat() function concatenates str2 onto the end of str1, and returns str1.
Example:
/* write a program to combine two string */
#include<stdio.h> puts("enter b string=");
#include<conio.h> gets(b);
void main() strcat(a,b);
{ printf("\n concated string=%s",a);
char a[100],b[100]; getch();}
int i; Output:enter a string=
clrscr(); ramesh
puts("enter a string="); enter b string=reddy
gets(a); concated string=rameshreddy
strlen()
This function finds the length of a given string and returns integer value.
Syntax:
#include <string.h>
int strlen( char *str );
The strlen() function returns the length of str (determined by the number of characters
excluding null character which indicate termination of string).
Example:

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
80 www.newgentech.in C LANGUAGE BY Mr.PRR

char *str = “Hello world”;


int length;
length = strlen(str);
strncpy()
This function copies the specified number of characters from a string into another string.
Syntax:
#include <string.h>
char *strncpy( char *str1, char *str2, int n );
The strncpy() function copies at most n characters of str2 to the string str1. If str2 has less
than n characters, the remaining cells is padded with '\0' characters. The return value is the
resulting string in str1.
Example:
/* wap to copy required number of characters into anotherstring */
#include<stdio.h>
#include<conio.h>
void main()
{
char a[100],b[100];
int i,n;
puts("enter a string=");
gets(a);
puts("enter b string=");
gets(b);
puts("enter how many characters=");
scanf("%d",&n);
strncpy(a,b,n);
printf("\n copied string=%s",a);
}
stricmp(), strcmpi():
These functions compare two strings without case sensitivity.
Syntax: Return value Explanation
#include<string.h> less than 0 str1 is less than str2
int stricmp( char *str1, char *str2 ); equal to 0 str1 is equal to str2
int strcmpi( char *str1, char *str2 ); greater than 0 str1 is greater than
The function stricmp() or strcmpi() compares str1 str2
and str2, then returns,
strupr(), strlwr():
The strupr() function converts all lower case letters in a given string into upper case.
The strlwr() function converts all upper case letters in a given string into lower case.
Syntax:
char *strupr( char *str );
char *strlwr( char *str );
strtok() function
strtok( ) function in C tokenizes/parses the given string using delimiter. Syntax for strtok( )
function is given below.
char * strtok ( char * str, const char * delimiters );

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
81 www.newgentech.in C LANGUAGE BY Mr.PRR

EXAMPLE:
In this program, input string “Test, string1, Test, string2:Test:string3” is parsed using strtok()
function. Delimiter comma (,) is used to separate each sub strings from input string.
#include <stdio.h>
#include <string.h>
int main ()
{
char string[50] ="Test,string1,Test,string2:Test:string3";
char *p;
printf ("String \"%s\" is split into tokens:\n",string);
p = strtok (string,",:");
while (p!= NULL)
{
printf ("%s\n",p);
p = strtok (NULL, ",:");
}
return 0;
}
OUTPUT:
String “Test,string1,Test,string2:Test:string3” is split into tokens:
Test
string1
Test
string2
Test
string3
strncat() function
 strncat( ) function in C language concatenates (appends) portion of one string at the end of
another string. Syntax for strncat( ) function is given below.
char * strncat ( char * destination, const char * source, size_t num );
 Example :
strncat ( str2, str1, 3 ); – First 3 characters of str1 is concatenated at the end of str2.
strncat ( str1, str2, 3 ); – First 3 characters of str2 is concatenated at the end of str1.
 As you know, each string in C is ended up with null character („\0‟).
 In strncat( ) operation, null character of destination string is overwritten by source string‟s
first character and null character is added at the end of new destination string which is
created after strncat( ) operation.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
82 www.newgentech.in C LANGUAGE BY Mr.PRR

EXAMPLE:
In this program, first 5 characters of the string “new generation” is concatenated at the end of
the string “C tutorial” using strncat( ) function and result is displayed as “C tutorial fres”.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " new generation" ;
char target[ ]= "C tutorial" ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ;
strncat ( target, source, 5 ) ;
printf ( "\nTarget string after strncat( ) = %s", target ) ;
}
OUTPUT:
Source string = new generation
Target string = C tutorial
Target string after strcat( ) = C tutorial fres

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
83 www.newgentech.in C LANGUAGE BY Mr.PRR

FUNCTIONS
DEFINITION:
A function is a named, independent section of C code that performs a specific task and
optionally returns a value to the calling program.
The Advantages of Structured Programming:
Why is structured programming so great? There are two important reasons:
1. It's easier to write a structured program, because complex programming problems are
broken into anumber of smaller, simpler tasks. Each task is performed by a function in
which code and variablesare isolated from the rest of the program. You can progress
more quickly by dealing with theserelatively simple tasks one at a time.
2. It's easier to debug a structured program. If your program has a bug (something that
causes it towork improperly), a structured design makes it easy to isolate the problem to
a specific section ofcode (a specific function).
Q) How to write a function? Give it‟s description?
Syntax:
<Return type> <function name (argument list)>
{
Local variable declarations,
Executable statement1;
Executable statement2‟
..
Return (expression);
}
 The first line of every function is the function header, which has three components, each
serving a specific function.
 The function return type specifies the data type that the function returns to the calling
program. The return type can be any of C's data types: char, int, long, float, or double. You
can also define a function that doesn't return a value by using a return type of void.
 You can name a function anything you like, as long as you follow the rules for C variable
names.
 Many functions use arguments, which are values passed to the function when it's called. A
function needs to know what kinds of arguments to expect i.e the data type of each
argument. You can pass a function any of C's data types. Argument type information is
provided in the function header by the parameter list. For each argument that is passed to
the function, the parameter list must contain one entry. This entry specifies the data type
and the name of the parameter.
Function Body:
 The function body is enclosed in braces, and it immediately follows the function header. It's
here that the real work is done. When a function is called, execution begins at the start of the
function body and terminates (returns to the calling program) when a return statement is
encountered or when execution reaches the closing brace.
Function Statements:
 There is essentially no limitation on the statements that can be included within a function.
The only thing you can't do inside a function is define another function. You can, however,
use all other C statements, including loops, if statements, and assignment statements. You
can call library functions and other user-defined functions.
Returning a Value:
 To return a value from a function, you use the return keyword, followed by a C expression.
When execution reaches a return statement, the expression is evaluated, and execution
passes the value back to the calling program.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
84 www.newgentech.in C LANGUAGE BY Mr.PRR

Q) What are the advantages of functions?


Reusability: write the code once and use many times which decreases the size of the
program.
Modularity: dividing problem into small parts (modules) in which each and every module
having separate operation. Due to this we can easily develop the programs and we can
easily debug the program.
Efficiency: Avoid redundant instructions which decreases size of the program and
increases efficiency.
Some more advantages
1. Debugging is easier
2. It is easier to understand the logic involved in the program
3. Testing is easier
4. Recursive call is possible
5. Irrelevant details in the user point of view are hidden in functions
6. Functions are helpful in generalizing the program
Q) Explain types of functions?
Basically we have two types of functions.
1. Pre defined,
2. User defined.
PREDEFINED:
A function which has own definition and comes along with the language is called as predefined
functions. Or library functions are called as predefined.
Ex: printf, scanf, get char() , put char() etc.
 We can‟t change the predefine function operation.
 We can‟t modify predefined function.
USER DEFINED:
A function which is defined by user for a particular purpose is called as user defined functions.
 User defined functions follow the c language functions pre- defined rules.
 Pre defined rules user can‟t change.
 In user defined functions user can implement their own operation.
 User defined functions names and the operations can change when user want.
Example:
void main()
int abc(int a, int b);
float addition(float a, float b);
Q) What are the Parameters? Explain types of parameters?
In c language parameters are classified into two types. They are
1. Actual parameter
2. Formal parameter
Actual parameter:
 The values which are send/pass from calling function to called function are called actual
parameters are actual arguments
Formal parameter:
 Function parameters are called formal parameters. These are local variable which receive
values from calling function.
Q) Explain about Local Variables?
 You can declare variables within the body of a function. Variables declared in a function
are called local variables.
 The term local means that the variables are private to that particular function and are
distinct from other variables of the same name declared elsewhere in the program.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
85 www.newgentech.in C LANGUAGE BY Mr.PRR

Q) Explain about Global Variables?


 You can declare variables outside of the body of a function(main). Variables declared
outside of the function are called as global variables.
 The term global means that the variables are public.
CATEGORY OF FUNCTIONS:
Functions are categories depending on whether arguments are present or not and whether a
value is returned or not. In C language functions May belong to one of the following categories
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and returns values.
NO ARGUMENTS AND NO RETURN VALUES:
When a function has no arguments it does not receive, any data from the calling function.
Similarly, when it does not return a value the calling function does not receive any data from
the called function. It shows in the figure. The dotted lines indicate that there is only a transfer
of control but not data..

Fun1() No input Fun2()


{ {
….. …..
….. …
} }
No output

No data communication between functions.


ARGUMENTS BUT NO RETURN VALUES:
When a function has arguments it receive data from the calling function. Similarly when it does
not return a value the calling function does not receive any data from the called function.
The nature of data communication between the calling function and the called function with
arguments but no return values as shown below.

Fun1() Fun2()
{ Values of arguments {
….. …..
….. …
No return value
} }

One -way data communication.


ARGUMENTS WITH RETURN VALUES:
When a function have arguments it receive data from the calling function similarly when
function having return a value the calling function receive data from the called function. In
effect the data transfer between the calling function and called function happened.
Two -way data communication between the called function and calling function as shown below.
Arguments values
Fun1() Fun2()
{ {
….. …..
…..
}
}
Return value

two -way data communication

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
86 www.newgentech.in C LANGUAGE BY Mr.PRR

EXAMPLES:
/* no arguments and no return type*/ printf("%c", ch);
#include<stdio.h> }
#include<conio.h> void main()
void first (void); {
void second (void); clrscr();
void third (void) replicate (10, 'x');
{ printf("\n hello \n");
printf("\n this is in third function"); replicate (5, '#');
} printf("\n bhano daya \n");
void fourth (void) replicate (10, '%');
{ printf("\n welcome \n");
printf("\n this is in fourth function"); replicate (5, '@');
} getch();
void main() }
{ Output:
clrscr(); xxxxxxxxxx
printf("this is in main"); hello
first(); #####
second(); bhano daya
third(); %%%%%%%%%%
fourth(); welcome
printf("\n this is in main again"); @@@@@
getch(); EXAMPLE3:
} /*arguments with return value
void first (void) functions*/
{ #include<stdio.h>
printf("\n this is in first function"); #include<conio.h>
} int add (int x, int y)
void second (void) {
{ int z;
printf("\n this is in second function"); z=x+y;
} return z;
Output: }
this is in main int subtr(int p, int q)
this is in first function {
this is in second function return (p-q);
this is in third function }
this is in fourth function int mult (int, int);
this is in main again int div (int, int);
int main()
EXAMPLE2: {
/*arguments with no return value int a,b,c;
functions*/ clrscr();
#include<stdio.h> printf("enter any two numbers \n");
#include<conio.h> scanf("%d%d", &a, &b);
void replicate (int n, int ch) c=add(a, b);
{ printf("\n the addition is %d", c);
int k; printf("\n the subtraction %d", subtr(a,
for (k=1; k<=n; k++) b));
OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
87 www.newgentech.in C LANGUAGE BY Mr.PRR

c=mult(a, b); char string[40];


printf("\n the multiplication %d", clrscr();
mult(a,b)); printf("Enter a string:");
printf("\n the division %d", div(a,b)); scanf("%s",string);
getch(); palindrome(string);
return(0); getch();
} }
int mult (int a, int b) void palindrome(char *str)
{ {
return a*b; int left, right;
} left =0;
int div(int m, int n) right = strlen(str);
{ right = right - 1;
int p=m/n; while(left <= right)
return p; {
} if(str[left] == str[right])
Output: {
enter any two numbers left++;
10 right--;
3 }
the addition is 13 else
the subtraction 7 {
the multiplication 30 printf("\nString is not palindrome.");
the division 3 break;
EXAMPLE4: }
/* write a program to find given string }
is palindrome or not*/ if(left>right)
#include<stdio.h> printf("\nString is palindrome.");
#include<conio.h> }
#include<string.h> Output:
void palindrome(char*); Enter a string:mom
void main() String is palindrome.
{
Parameter passing techniques:
In c language two types of techniques are available for passing parameters to the functions.
they are
1. Call by value.
2. Call by reference.
Call by value:
In this technique the values of actual arguments in the calling function are copied into the
formal arguments in the called function.
Here the data transfer done in only one direction i.e. from calling function to called function,
so any changes happen in formal arguments does not effect on the actual arguments.
But if any changes will happen in the actual arguments, formal arguments automatically
effected.
EXAMPLE:
//write a program to send value by call by calue
#include<stdio.h>
#include<conio.h>

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
88 www.newgentech.in C LANGUAGE BY Mr.PRR

void change();
void main()
{ Output:
int x,y; enter values of xand y=10 20
printf("\n enter values of xand y="); in change() a=20,b=10
scanf("%d%d",&x,&y); in main () x=10, y=20
change(x,y);
printf("\n in main () x=%d, y=%d",x,y);
getch();
}
void change(int a,int b)
{
int k;
k=a;
a=b;
b=k;
printf("\n in change() a=%d,b=%d",a,b);
}
Call by reference:
In this technique the addresses of actual arguments in the calling function are copied into the
formal arguments in the called function.
Any changes happen in formal arguments does effect on the actual arguments.
But if any changes will happen in the actual arguments, formal arguments automatically
effected.
EXAMPLE:
/* write a program swaping of two numbers by using call by reference technique*/
#include<stdio.h>
#include<conio.h>
void main() Output:
{ enter value of x,y:10 20
int x,y; in change() x=20,y=10
clrscr(); in main() x=20,y=10
printf("\n enter value of x,y:");
scanf("%d%d",&x,&y);
change(&x,&y);
printf("\n in main() x=%d,y=%d",x,y);
}
change(int *a,int *b)
{
int *k;
*k=*a;
*a=*b;
*b=*k;
printf("\n in change() x=%d,y=%d",*a,*b); }
Recursive Function in C:
Recursive function is defined as a function which calls itself. if any function will call the same
function(itself) in its function body, then that function is said to be as recursive function.
Advantages of Using Recursive Function:
Using recursive function is a good programming practice as it decreases the length of the code.
How To Use a Recursive Function:
OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
89 www.newgentech.in C LANGUAGE BY Mr.PRR

we can use a recursive function by simply placing a function call of the same function in the
function body.
Syntax To Declare a Recursive Function:
<datatype><function name>(<formal arguments>)
{
----------------------
----------------------
block of statements
<same function name>(<parameters>);
-----------------------
-----------------------
}
Example C Program To Use Recursive Function:
c program to find factorial of a given number by using recursive function.
#include<stdio.h>
#include<conio.h>
int recr_factorial(int n);
void main()
{
int n,i;
long fact;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);
if(n==0)
printf("Factorial of 0 is 1\n");
else
{
printf("Factorial of %d Using Recursive Function is %d\n",n,recr_factorial(n));
}
getch();
}
/* Recursive Function*/
unsigned int recr_factorial(int n)
{
return n>=1 ? n * recr_factorial(n-1) : 1;
}
Point To Remember While Using Recursive Function:
Recursive function is similar to a loop construct. so recursive function should be placed inside a
conditional statement. So that at a particular case, the condition gets failed and the recursion
stops there
Note: recursion eliminates the looping structures.
Passing array as arguments to functions:
 An array can be passed to a function as on argument in a manner similar to that used to
passing variables.
 To pass an array to a called function, it is sufficient to list the names of the array, without
any subscripts and the size of the array as argument.
 The called function with array as parameters contains minimum two parameters, the array
and the size of the array.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
90 www.newgentech.in C LANGUAGE BY Mr.PRR

Syntax:
<function-name> (<array-name>[array-size])
 When we pass an array as an argument to a function we need not specify the array size in
the arguments declaration part of the function.
 The array-name is followed by empty square brackets is an array.
Things to note:
 Remember one main distinction from passing ordinary variables, if a function changes
the value of an array elements, the changes will be made to the original array that was
passed to the function.
EXAMPLE:
//display elements using arrays and function
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],num;
void getarray(int a[], int);
void printarray(int a[],int);
printf("\n size of array not>10"); Output:
scanf("%d",&num); enter size of array not>10=5
getarray(a,num); enter a[0] element:10
printarray(a,num); enter a[1] element:20
} enter a[2] element:30
void getarray(int a[], int n) enter a[3] element:40
{ enter a[4] element:50
int k;
for(k=0;k<n;k++)
{
printf("\n enter a[%d] element:",k);
scanf("%d",&a[k]);
}
return 0;
}
void printarray(int a[], int n)
{
int k;
for(k=0;k<n;k++)
return;
}

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
91 www.newgentech.in C LANGUAGE BY Mr.PRR

C Math.h
C Programming allows us to perform mathematical operations through the functions defined in
<math.h> header file. The <math.h> header file contains various methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor() etc.
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.

No. Function Description

1) ceil(number) rounds up the given number. It returns the integer value


which is greater than or equal to given number.

2) floor(number) rounds down the given number. It returns the integer


value which is less than or equal to given number.

3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of given number.

Let's see a simple example of math functions found in math.h header file.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
clrscr();
printf("\n%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));
getch();
}
Output:
4.000000
4.000000

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
92 www.newgentech.in C LANGUAGE BY Mr.PRR

3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
Buffer manipulation functions
 Buffer manipulation functions in C work on the address of the memory block rather than
the values inside the address.
 Example programs for memset(), memcpy(), memmove(), memcmp(), memicmp() and
memchr() functions are given below.

Functions Description

memset() It is used to initialize a specified number of bytes to


null or any other value in the buffer

memcpy() It is used to copy a specified number of bytes from


one memory to another

memmove() It is used to copy a specified number of bytes from


one memory to another or to overlap on same
memory.
Difference between memmove and memcpy is,
overlap can happen on memmove whereas memcpy
should be done in non-destructive way

memcmp() It is used to compare specified number of


characters from two buffers

memicmp() It is used to compare specified number of


characters from two buffers regardless of the case
of the characters

memchr() It is used to locate the first occurrence of the


character in the specified string

EXAMPLE PROGRAM FOR MEMSET() FUNCTION:


memset( ) function is used to initialize specified number of bytes to null or to any other value in
the buffer.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
93 www.newgentech.in C LANGUAGE BY Mr.PRR

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
int i;
/* allocate memory for array of 5 elements */
char *a = (char *) malloc(5*sizeof(char));
printf("Values before memset\n");
for (i = 0; i < 5; ++i)
printf(" a[%d] = %d ,", i, a[i]);
/* All elements are set to 3. It can be set to any value */
memset(a, 3, 5*sizeof(char));
printf("\nValues after memset\n");
for (i = 0; i < 5; ++i)
printf(" a[%d] = %d ,", i, a[i]);
// remove x from memory
free(a);
return 0;
}
OUTPUT:
Values before memset
a[0] = 0 , a[1] = 0 , a[2] = 0 , a[3] = 0 , a[4] = 0
Values after memset
a[0] = 3 , a[1] = 3 , a[2] = 3 , a[3] = 3 , a[4] = 3
EXAMPLE PROGRAM FOR MEMCPY() FUNCTION:
memcpy( ) function is used to copy a specified number of bytes from one memory to another.
#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";
char str2[10] ;
if (memcpy(str2,str1, strlen(str1)))
{
printf("Elements in str1 are copied to str2 .\n");
printf("str1 = %s\n str2 = %s \n", str1, str2);

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
94 www.newgentech.in C LANGUAGE BY Mr.PRR

}
else
printf("Error while coping str1 into str2.\n");
return 0;
}
OUTPUT:
Elements in str1 are copied to str2 .
str1 = fresh
str2 = fresh
EXAMPLE PROGRAM FOR MEMMOVE() FUNCTION:
memmove( ) function is used to copy a specified number of bytes from one memory to another
or to overlap on same memory.
#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";
printf("str1 before memmove\n");
printf("str1 = %s\n ", str1);
if (memmove(str1+2,str1, strlen(str1)))
{
printf("Elements in str1 are moved/overlapped on str1.\n");
printf("str1 = %s \n", str1);
}
else
printf("Error while coping str1 into str2.\n");
return 0;
}
OUTPUT:
str1 before memmove
str1 = fresh
Elements in str1 are moved/overlapped on str1 .
str1 = frfresh
EXAMPLE PROGRAM FOR MEMCMP() FUNCTION:
memcmp( ) function is used to compare specified number of characters from two buffers.
#include <stdio.h>
#include <string.h>
int main()

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
95 www.newgentech.in C LANGUAGE BY Mr.PRR

{
// define two identical arrays
char str1[10] = "fresh";
char str2[10] = "refresh";
if (!memcmp(str1,str2, 5*sizeof(char)))
printf("Elements in str1 and str2 are same.\n");
else
printf("Elements in str1 and str2 are not same.\n");
return 0;
}
OUTPUT:
Elements in str1 and str2 are not same.
EXAMPLE PROGRAM FOR MEMICMP() FUNCTION:
 memicmp( ) function is used to compare specified number of characters from two
buffers regardless of the case of the characters.
 If we use memcmp() function instead of memicmp, the output of the below program will be
“Elements in str1 and str2 are not same”.
#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";
char str2[10] = "FRESH";
if (!memicmp(str1,str2, 5*sizeof(char)))
printf("Elements in str1 and str2 are same.\n");
else
printf("Elements in str1 and str2 are not same.\n");
return 0;
}
OUTPUT:
Elements in str1 and str2 are same.
EXAMPLE PROGRAM FOR MEMCHR() FUNCTION IN C:
memchr( ) function is used to locate the first occurrence of the character in the specified string.
#include <stdio.h>
#include <string.h>
int main ()
{
char *ptr;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
96 www.newgentech.in C LANGUAGE BY Mr.PRR

char string[] = "fresh2refresh";


ptr = (char *) memchr (string, 'h', strlen(string));
if (ptr != NULL)
printf ("character 'h' is found at " \
"position %d.\n", ptr-string+1);
else
printf ("character 'h' is not found.\n");
return 0;
}
OUTPUT:
character „h‟ is found at position 5.
C Miscellaneous functions
Descriptions and example programs for C environment functions such as getenv(), setenv(),
putenv() and other functions perror(), random() and delay() are given below.

Miscellaneous functions Description

getenv() This function gets the current value of


the environment variable

setenv() This function sets the value for


environment variable

putenv() This function modifies the value for


environment variable

perror() Displays most recent error that


happened during library function call

rand() Returns random integer number


range from 0 to at least 32767

delay() Suspends the execution of the


program for particular time

EXAMPLE PROGRAM FOR GETENV() FUNCTION:


 This function gets the current value of the environment variable.
 Let us assume that environment variable DIR is assigned to “/usr/bin/test/”. Below
program will show you how to get this value using getenv() function.
#include <stdio.h>
#include <stdlib.h>
int main()

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
97 www.newgentech.in C LANGUAGE BY Mr.PRR

{
printf("Directory = %s\n", getenv("DIR"));
return 0;
}
OUTPUT:
/usr/bin/test/
EXAMPLE PROGRAM FOR SETENV() FUNCTION IN C:
 This function sets the value for environment variable.
 Let us assume that environment variable “FILE” is to be assigned
“/usr/bin/example.c”. Below program will show you how to set this value using setenv()
function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
setenv("FILE","/usr/bin/example.c",50);
printf("File = %s\n", getenv("FILE"));
return 0;
}
OUTPUT:
File = /usr/bin/example.c
EXAMPLE PROGRAM FOR PUTENV() FUNCTION IN C:
 This function modifies the value of environment variable.
 Below example program shows that how to modify an existing environment variable value.
#include <stdio.h>
#include <stdlib.h>
int main()
{
setenv("DIR","/usr/bin/example/",50);
printf("Directory name before modifying = " \
"%s\n", getenv("DIR"));
putenv("DIR=/usr/home/");
printf("Directory name after modifying = " \
"%s\n", getenv("DIR"));
return 0;
}
OUTPUT:
Directory name before modifying = /usr/bin/example/
Directory name after modifying = /usr/home/

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
98 www.newgentech.in C LANGUAGE BY Mr.PRR

EXAMPLE PROGRAM FOR PERROR() FUNCTION IN C:


This function displays most recent error that happened during library function call.
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char filename[40] = "test.txt";
/* Let us consider test.txt not available */
fp = f open(filename, "r");
if(fp == NULL)
{
perror("File not found");
printf("errno : %d.\n", errno);
return 1;
}
printf("File is found and opened for reading");
fclose(fp);
return 0;
}
OUTPUT:
errno : 22.
File not found: No such file or directory
EXAMPLE PROGRAM FOR RAND() FUNCTION IN C:
This function returns the random integer numbers range from 0 upto 32767.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main ()
{
printf ("1st random number : %d\n", rand() % 100);
printf ("2nd random number : %d\n", rand() % 100);
printf ("3rd random number: %d\n", rand());
return 0;}
OUTPUT:
1st random number : 83
2nd random number : 86
3rd random number: 16816927

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
99 www.newgentech.in C LANGUAGE BY Mr.PRR

EXAMPLE PROGRAM FOR DELAY() FUNCTION IN C:


This function suspends the execution of the program for particular time.
#include<stdio.h>
#include<stdlib.h>
int main ()
{
printf("Suspends the execution of the program " \
"for particular time");
delay(5000); // 5000 mille seconds
return 0;
}
OUTPUT:
Suspends the execution of the program for particular time
Time related functions In C Language
Time functions in C are used to interact with system time routine and formatted time outputs
are displayed. Example programs for the time functions are given below.

Function Description

setdate() This function used to modify the system date

getdate() This function is used to get the CPU time

clock() This function is used to get current system time

time() This function is used to get current system time as


structure

difftime() This function is used to get the difference between


two given times

strftime() This function is used to modify the actual time format

mktime() This function interprets tm structure as calendar time

localtime() This function shares the tm structure that contains


date and time informations

gmtime() This function shares the tm structure that contains


date and time informations

ctime() This function is used to return string that contains

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
100 www.newgentech.in C LANGUAGE BY Mr.PRR

date and time informations

asctime() Tm structure contents are interpreted by


this functionas calendar time. This time is converted
into string.

EXAMPLE:
This function is used to modify the system date. Please note that other C compilers may not
support this setdate() function except turbo C.
#include<stdio.h>
#include<dos.h>
#include<conio.h>
int main()
{
struct date dt;
printf("Enter new date in the format(day month year)");
scanf("%d%d%d",&dt.da_day,&dt.da_mon,&dt.da_year);
setdate(&dt);
printf("Now, current system date is %d-%d-%d\n",dt.da_day,dt.da_mon,dt.da_year);
return 0;
}
OUTPUT:
Enter new date in the format (day month year)
01 12 2012
Now, current system date is 01-12-2012
EXAMPLE PROGRAM FOR GETDATE() FUNCTION:
This function is used to get the CPU time. Please note that other C compilers may not support
this getdate() function except turbo C.
#include<stdio.h>
#include<dos.h>
int main()
{
struct date dt;
getdate(&dt);
printf("Operating system's current date is %d-%d %d\n" ,dt.da_day,dt.da_mon,dt.da_year);
return 0; }
OUTPUT:
Operating system‟s current date is 12-01-2012

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
101 www.newgentech.in C LANGUAGE BY Mr.PRR

EXAMPLE PROGRAM FOR CLOCK() FUNCTION IN C:


This function is used to get current system time.
#include <stdio.h>
#include <time.h>
#include <math.h>
int main()
{
int i;
clock_t CPU_time_1 = clock();
printf("CPU start time is : %d \n", CPU_time_1);
for(i = 0; i < 150000000; i++);
clock_t CPU_time_2 = clock();
printf("CPU end time is : %d", CPU_time_2);
}
OUTPUT:
CPU start time is : 0
CPU end time is : 380000
EXAMPLE PROGRAM FOR TIME() FUNCTION:
This function is used to get current system time as structure.
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time (NULL);
printf ("Number of hours since 1970 Jan 1st " \
"is %ld \n", seconds/3600);
return 0;
}
OUTPUT:
Number of hours since 1970 Jan 1st is 374528
EXAMPLE PROGRAM FOR DIFFTIME() FUNCTION IN C:
This function is used to get the difference between two given times.
#include <stdio.h>
#include <time.h>
int main()
{
time_t begin,end;
long i;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
102 www.newgentech.in C LANGUAGE BY Mr.PRR

begin= time(NULL);
for(i = 0; i < 150000000; i++);
end = time(NULL);
printf("for loop used %f seconds to complete the " \ "execution\n", difftime(end, begin));
return 0;}
OUTPUT:
for loop used 15.000000 seconds to complete the execution
EXAMPLE PROGRAM FOR STRFTIME(), ASCTIME() AND LOCALTIME() IN C:
 strftime() – This function is used to modify the actual time format.
 asctime() – tm structure contents are interpreted by asctime() function as calendar time.
This time is converted into string.
 localtime() – This function shares the tm structure that contains date and time
informations.
#include <stdio.h>
#include <time.h>
#define LEN 150
int main ()
{
char buf[LEN];
time_t curtime;
struct tm *loc_time;
//Getting current time of system
curtime = time (NULL);
// Converting current time to local time
loc_time = localtime (&curtime);
// Displaying date and time in standard format
printf("%s", asctime (loc_time));
strftime (buf, LEN, "Today is %A, %b %d.\n", loc_time);
fputs (buf, stdout);
strftime (buf, LEN, "Time is %I:%M %p.\n", loc_time);
fputs (buf, stdout);
return 0;
}
OUTPUT:
Sat Sep 22 01:15:03 2012
Today is Saturday, Sep 22.
Time is 01:15 AM.
EXAMPLE PROGRAM FOR MKTIME() AND CTIME() FUNCTIONS IN C:
 mktime() function interprets tm structure as calendar time.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
103 www.newgentech.in C LANGUAGE BY Mr.PRR

 ctime() function is used to return string that contains date and time informations.
#include <stdio.h>
#include <time.h>
int main()
{
struct tm strtime;
time_t timeoftheday;
strtime.tm_year = 2008-1900;
strtime.tm_mon = 1;
strtime.tm_mday = 4;
strtime.tm_hour = 02;
strtime.tm_min = 30;
strtime.tm_sec = 38;
strtime.tm_isdst = 0;
timeoftheday = mktime(&strtime);
printf(ctime(&timeoftheday));
return 0;
}
OUTPUT:
Mon Feb 4 02:30:38 2008
EXAMPLE PROGRAM FOR GMTIME() FUNCTION IN C:
This function shares the tm structure that contains date and time informations.
#include <stdio.h>
#include <time.h>
int main()
{
time_t orig_format;
time(&orig_format);
printf ("Universal Time is %s",
asctime(gmtime(&orig_format)));
return 0;}
OUTPUT:
Universal Time is Sat Sep 22 08:11:40 2012

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
104 www.newgentech.in C LANGUAGE BY Mr.PRR

POINTERS
Introduction
A pointer is a variable that stores the memory address of other variables. Then, pointer variable
will start referring the variable whose address is stored in it.
The pointer is a variable, so it is declared just like any other variable. The only difference is that
pointer variables must have the dereferencing operator, *, before its name.
The pointer variable of one data type will only hold the address of variable of same data type.
Generally, the pointer variable are declared as,
datatype *ptr_varname;
where “ptr_varname” name of pointer variable of type “datatype”.
Example,
int *x; /* read as, x is a pointer to int */
Example, declaring pointer and storing address,
int x, *ptr;
ptr = &x; /*read as, address is assigned to ptr.*/
the &x gives “the address of x”, and is stored into pointer variable “ptr”. This is as viewed
below,

x
4533
2000 (address of x)
ptr 2000

3000 (address of ptr)


i) The number in the box labeled x is value of x, which is a garbage because, we did not assign
any value.
ii) The number in the box labeled ptr is address of memory of x.
Accessing values of variables by using pointers:
The value from memory location of variable is accessed by using its pointer variable.
This is explained by following statements,
int a, *ptr, b; /* The ptr is a pointer, a, b are variables */
a = 50; /* a is assigned with value 50 */
ptr = &a; /* the pointer ptr points the memory location of a */
/*The *ptr retrieves value from memory location whose address is stored in it*/
b = *ptr; /* b is stored with *ptr value, which is value of a */
/* value of a is modified, now it would be 105.*/
*ptr = *ptr + 55;
This is also illustrated by small program given below,
#include <stdio.h>
void main() output:
{ Address of x: 1000
int x = 12; Address of x: 1000
int *ptr = &x; Address of ptr: 2000
printf("Address of x: %u\n", ptr); Value of x: 12
printf("Address of x: %u\n", &x);
printf("Address of ptr: %u\n", &ptr);
printf("Value of x: %d\n", *ptr);
return 0; }

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
105 www.newgentech.in C LANGUAGE BY Mr.PRR

Q) In which situtation Pointers are used ?


Pointers are used in situations when passing actual values is difficult or not desired. Some of
the situations where pointers can be used are –
1. To return more than one value from a function.
2. To pass arrays and strings more conveniently from one function to another
3. To manipulate arrays easily by moving pointers to them instead of moving the arrays itself
4. To allocate memory and access it (Direct Memory Allocation).
5. To create complex data structures, such as linked lists
Q) What is pointer?
 Pointer is a derived data type.
 A variable of type pointer is called pointer variable.
 A pointer variable holds an address of memory location.
Q) What is address?
 The address is integer value given to each location or byte within memory.
 These addresses are generated by operating system.
 Addressing method is depends on compiler , if compiler is 16 bit , it uses 16 bit addressing
method and if compiler is 32 bit it uses 32 bit addressing methods.
Q) What are the advantages of pointer?
1. Dynamic memory allocation
2. Avoid wastage of memory
3. Pointers increases efficiency of program
4. Complex data types
5. Dynamic data structures
Q) What are the disadvantages of pointer?
1. Pointers are not secured.
2. Memory leak.
Q) What is Reference operator (&)?
The address that locates a variable within memory is what we call a reference to that variable.
This reference to a variable can be obtained by preceding the identifier of a variable with an
ampersand sign (&), known as reference operator, and which can be literally translated as
"address of".
Q) What is Dereference operator (*)?
Using a pointer we can directly access the value stored in the variable which it points to. To do
this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as
dereference operator and that can be literally translated to "value pointed by".
Q) What is a pointer value and address?
A pointer value is a data object that refers to a memory location. Each memory locaion is
numbered in the memory. The number attached to a memory location is called the address of
the location.
Pointers for Inter Function Communication:
The pointer are used for inter function communication, which means, communication between
called and caller function is can established. Base on the this,
we call function with,
i) call by value
ii) call by reference or address.
These are explained in the following topics.
Functions with Call-by-Value:
The function with call by value is named, by looking the way the arguments are passed. In this,
the values of actual parameters are copied into formal parameters. The changes in values of
these parameters will not reflect into actual parameters.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
106 www.newgentech.in C LANGUAGE BY Mr.PRR

This is illustrated with the program given below,


#include<stdio.h>
#include<conio.h>
void swap( int, int );
void main() Output:
{ Enter value of a, b: 12 25
int a, b; Before swap function called, a= 12, b= 25
printf(“\nEnter value of a, b: “); After swap function called, a= 12, b= 25
scanf(“%d%d”, &a, &b);
printf(“\n Before swap function called, a= %d, b= %d”, a, b);
swap(a, b);
printf(“\n After swap function called, a= %d, b= %d”, a, b);
}
/* Try to Exchange a, b value */
void swap(int m, int n)
{
int temp;
temp = m;
m = n;
n = temp;
}
The output of above program is observed, that no change in the values of a, b.
Functions with Call-by-Reference or Address:
The function with call by reference or address is named, by looking the way the arguments are
passed. In this, the addresses of actual parameters are copied into formal parameters. So, the
formal parameters have to be pointers to data type of actual parameters. Then changes in
values of formal parameters will reflect into actual parameters.
This is illustrated with the program given below,
#include<stdio.h>
#include<conio.h>
Output:
void swap( int* , int* );
Enter value of a, b: 12 25
void main()
Before swap function called, a= 12, b= 25
{
After swap function called, a= 25, b= 12
int a, b;
printf(“\nEnter value of a, b: “);
scanf(“%d%d”, &a, &b);
printf(“\n Before swap function called, a= %d, b= %d”, a, b);
swap( &a, &b);
printf(“\n After swap function called, a= %d, b= %d”, a, b);
}
/* Try to Exchange a, b value */
void swap(int *m, int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
The output of above program is observed that, changes take place in the values of a, b.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
107 www.newgentech.in C LANGUAGE BY Mr.PRR

Pointers to Pointers:
A pointer variable can also be pointed by another pointer variable. This, means, a pointer
variable stores address of another pointer variable.
In general it is declared as,
datatype **ptr;
this is read as, “ptr is pointer to pointer to datatype.“
Example,
int **x; /*x is a pointer to pointer to int*/
Example, this time we take float data type.
float *p, **ptp, n, m;
n = 45.25;
p = &n;
ptp = &p
m = **ptp;
another example,
int ***Ptr /*ptr is pointer to pointer to pointer to int */
float ****pf /*pf is pointer to pointer to pointer to pointer to float */
Pointer to void:
In C, the void is a keyword. This is used to create variables of functions of type void. We might
have observed that, void main(), void swap() etc
The void main() means, the function main is defined to returns no data or nothing.
We can also declare pointer to void. Then, such pointer is generally called as generic pointer,
which means, we can convert or type cast into other data types.
Its declaration is similar to pointers of other data type. This is,
void *vptr; /*the vptr is a pointer to void.*/
Example,
int *ptr;
float *pf;
void *vptr;
ptr = (int *)vptr; /*( int* ) is type casting to data type of ptr */
………………
………………
pf = (float*)vptr; /*( float* ) is type casting to data type of pf */
In C, some predefined functions return data of pointer to void type, which data may used by
program by converting or type casting to required data type.
Q) What is a dangling pointer?
A dangling pointer arises when you use the address of an object after its lifetime is over.This
may occur in situations like returning addresses of the automatic variables from a function or
using the address of the memory block after it is freed.
We can also define like as it is a pointer variable which holds an address of unreserved memory
location is called dangling pointer.
To avoid dangling pointer it has to be initiated with null.
This pointer variable leads to logical error.
Q) What is null pointer?
A pointer variable which holds null address is called null pointer. This pointer variable cannot
point to any memory location.
Pointer Arithmetic:
As pointers are variables, there should be operators those can be used with pointers.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
108 www.newgentech.in C LANGUAGE BY Mr.PRR

If a pointer variable is made to point a certain variable then, we can either reassign it another
variable's address, or performing arithmetic operations to point other memory location. The
operator permitted to use with pointers are,
If we have,
int *ptr, *py, x, y;
ptr = &x;
py = &y;
then,
Addition:
ptr = ptr +1, ptr +=1, ++ptr, ptr++ are same.
These are calculated internally by computer as, if ptr contains address of x which 1000 then,
ptr = (1000+ sizeof(int))
=(1000+2) = (1002);
Which means, moving the pointer forward by 2 bytes (i.e. the size of its data type).
ii) ptr = ptr + 2;
ptr = (1000 + 2*sizeof(int))
=(1004)
iii) ptr + py is not allowed. Adding of two pointer variable is not allowed.
In general,
ptr = ( ptr + n * sizeof (datatype) ), where n =0, 1, 2, 3… and datatype is
char int, float, double, long int, etc.
Subtraction:
Similarly, ptr = ptr -1 , ptr--, --ptr and ptr -=1 will move the pointer "back" 2 bytes, assuming
ptr is an int pointer. The calculation is as,
i) ptr = (1000 - sizeof(int)) is allowed
=(1000 - 2) = (998)
ii) ptr – py and py – ptr are allowed. If ptr is holding 1000, and py is holding
1024, then, these expression are internally calculated as follows, so, it can
be used to know how number of values stored,
(py – ptr)/sizeof(int) = (1024 – 1000 )/2 = 24/2 = 12 locations or values.
In general,
ptr = ( ptr - n * sizeof (datatype) ), where n =0, 1, 2, 3… and datatype is
char int, float, double, long int, etc.
Cannot be used:
The operators multiplication and division cannot be used, because those operation on pointer
are meaningless.
Pointers to Arrays
The pointer variables are also used to point arrays. If a pointer is made to point an array of
some data type then, such pointer can be used to access cells of that array and values stored in
those cells.
For example, with the statement,
int x[7];
an array of 7 integers is created, and it may be viewed as,

Array x cells:x[0] x[1] x[2] x[3] x[4] x[5] x[6]

Addresses 1000 1002 1004 1006 1008 1010 1012

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
109 www.newgentech.in C LANGUAGE BY Mr.PRR

Now, &x[0] or simply x, indicates 1000, which is the base address of array x[] is stored into
pointer variable, then it points the array x[].
int *pa;
pa = x;
this would be as shown below,
Array x cellsx[0] x[1] x[2] x[3] x[4] x[5] x[6]

1000 1002 1004 1006 1008 1010 1012Addresses


pa 1000

2000
Now, pa can be is used for accessing array x[]. This can be understood as
x[0] = *(p+0) and &x[0] = (pa+0)
x[1] = *(p+1) and &x[1] = (pa+1)
x[2] = *(p+2) and &x[2] = (pa+2) and in general,
x[i] = *(p+i) and &x[i] = (pa+i).
In general, ith cell address is caluculated as, if i=5, address of x[5],
= (baseaddress + ( i * sizeof(datatype))
= (1000 + 5 * sizeof(int))
= (1000 + 5 * 2)
= (1010).
The address calculations shown above are also applicable for other data type like char, float,
double, etc. In this case, sizeof(data type) will be equivalent those sizes.
Example:
// A Program to illustrate the concept of pointers to single dimensional arrays.
#include<stdio.h>
#include<conio.h>
void main() return 0;
{ }
int x[5] = {10, 11, 12, 13, 14};
int *pa, i; Output:
pa = x; Value printed using pa pointer
printf(“ Value printed using pa pointer .\n”); 10 11 12 13 14
for( i= 0; i<5; i++) Value printed using x[] pointer
{ 10 11 12 13 14
printf("%3d", *(pa+i));
}
printf(“ Value printed using x[].\n”);
for( i= 0; i<5; i++)
{
printf("%3d", x[i] );
}

Arrays of Pointers:
A pointer is a variable that stores the memory address of another variable. So it's possible to
have an array of pointers. In other words, an array of memory addresses:
These pointers may pointing individual variables or arrays of some data type.
In general it is declared as,
datatype *array_ptrs[n];

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
110 www.newgentech.in C LANGUAGE BY Mr.PRR

In the above declaration, the array_ptrs[] is a single dimensional array of n pointers to


datatype.
Example,
int *ptrs[5];
where ptrs[] is a array of 5 pointers to int data type.
Example,
float x1, x2, x3;
float *ptrs[3];
prts[0] = &x1;
prts[1] = &x3;
prts[2] = &x2;
Example:
A Program to illustrate the concept of array of pointers.
#include <stdio.h>
#include <conio.h>
void main()
{
int *ptrs[3], *p1, *p2;
int x1,x2,x3;
Output:
x1=10; Values of x1,x2, x3 are:
x2=20;
x1 = 10
x3=30; x2 = 20
p1 = &x1; x3 = 30
p2 = &x3;
ptrs[0] = p1;
ptrs[1] = p2;
ptrs[2] = &x2;
clrscr();
printf(“\nValues of x1,x2, x3 are:\n”);
printf("\nx1 = %d", *p1);
printf("\nx2 = %d", *ptrs[2]);
printf("\nx3 = %d", *ptrs[1]);
getch();
}
Example:
//Program on concept of arrays of pointers
#include <stdio.h>
#include <conio.h>
void main()
Output:
{
The value of array[0] at 65520 is 1
int array[3] = {1,2,3};
The value of array[1] at 65522 is 2
int *ptr1 = &array[0];
The value of array[2] at 65524 is 3
int *ptr2 = &array[1];
int *ptrs[3];
ptrs[0] = ptr1;
ptrs[1] = ptr2;
ptrs[2] = &array[2];
clrscr();
printf("The value of array[0] at %u is %d\n", ptrs[0], *ptrs[0]);
printf("The value of array[1] at %u is %d\n", ptrs[1], *ptrs[1]);

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
111 www.newgentech.in C LANGUAGE BY Mr.PRR

printf("The value of array[2] at %u is %d\n", ptrs[2], *ptrs[2]);


getch();
}
The above example will be modified to work also for floats and doubles.
Pointers to Functions:
The pointer variable is also used to point functions. Such pointer can be used to call or invoke
that function. Extending this concept, we can also pass function name as an argument to
another function. These, can be understood with explanation given below,
In general a pointer to function is declared as,
datatype (*ptr_function)(datatype, datatype, ….datatype);
where “datatype” is the data type allowed in C,
“and ptr_function” is pointer name which points to function.
Example,
int (*ptrfun)(int, float);
defines a pointer name “ptrfun” which points the function with two parameters, and return type
int, where first parameter is of type int, and latter is of type float.
Similarly, Example,
float * (*pfun)(float [], int *);
defines a pointer “pfun” , which points the function with two parameters, and return type float*,
where first parameter is array of type float and later is point of type int.
Example,
int add(int, int);
int (*ptr)(int, int);
ptr = add; /*ptr point add() function*/
The ptr is a point which holds address of a function. The name of function itself is a address, so,
this assignments makes to ptr to point the function add().
Note: int (*ptrfun)(int, float) is different from int *ptrfun(int, float). So, parentheses around
the pointer name to function are mandatory.
Example:
//Program to demonstrate how to use pointer to function.
#include<stdio.h>
int add(int, int); /*prototype of add()*/ Output:
void main() Enter x and y values:15 48
{ 15 + 48 = 63
int x, y, sum;
int (*ptr)(int, int);
/* assigning add() to pointer ptr.*/
ptr = add;
clrscr();
printf("Enter x and y values:");
scanf("%d%d", &x, &y);
/* invoking add() using its pointer ptr */
sum = (*ptr)(x, y);
printf("%d + %d = %d\n", x, y, sum);
getch();
}
/* definition of add() function */
int add(int x, int y)
{
return(x+y);

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
112 www.newgentech.in C LANGUAGE BY Mr.PRR

}
Just remember to enclose the function pointer with brackets when declaring it. Notice that I
only included the arguments' types in the parameters in the pointer declaration. I think adding
variable names in there are optional, so this would still compile successfully,
int (*ptr)(int x, int y); or
int (*ptr)(int a, int b);
Also note that, the type of the pointer has to match that of the functions return type it pointing
to.
Example: Program to illustrate concept of pointer to function.
#include<stdio.h>
float average(float [], int*);
void main()
{
float avg, marks[20];
int n, i;
float (*pf)(float [], int*);
/* assigning average() to pointer pf.*/
pf = average;
clrscr();
printf("\nEnter size of array:");
scanf("%d", &n);
printf("\nEnter %d float values into array:\n", n);
for(i=0; i<n;i++)
scanf("%f", &marks[i]);
/* invoking average() using its pointer pf */
avg = (*pf)(marks, &n);
printf("Average of marks=%.2f",avg);
getch();
}
/* definition of add() function */
float average(float *m, int *size)
{
int i;
float sum=0;
for(i=0; i < (*size); i++)
sum += *(m + i);
return(sum/(*size));
}
Output:
Enter size of array:5
Enter 5 float values into array:
55.25
65.5
79.0
45.95
45.25
Average of marks=58.19

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
113 www.newgentech.in C LANGUAGE BY Mr.PRR

DYNAMIC MEMORY ALLOCATION


The computer main memory is divided into some regions. These are used for different specific
purpose. This is viewed as,
Memory
Program code

Global or auto

Local variable
or Stack

Heap

The program code area is stored with part or entire program source code to be executed.
The global or auto variables are allocated memory from this area of memory.
The memory for these variables is created at the time of compilation of the program, which is
fixed, and it can not be changed during the running of the program. This is called static memory
allocation.
The local variables are allocated memory from this area only. This may increase or shrink as
such variables are created or deleted. The variable local to function are allotted memory from
here only.
Heap storage is a dynamic memory. This reserved for dynamic memory allocation.
The memory is created at the running time of program on demand by the program. This is
called dynamic memory allocation.
It is the responsibility of the programmer to de-allocate such memory for use by the next
variables. This insisted, because computer memory is limited. If we go on allocating, may
encounter a situation from there no memory can not be created, if entire memory is consumed.
In C, the dynamic memory allocation or deletion is done by predefined functions. They are,
i) malloc()
ii) calloc()
iii) realloc()
iv) free() to de-allocate memory created by above functions.
The malloc() function:
The malloc() allocates a block of specified number of bytes from the memory heap. It allows a
program at run-time to allocate memory in specified number of bytes
The general structure of malloc() is,
void *malloc(int n);
where n is the number bytes. It allocates memory block of n bytes.
Return Value:
i) On success, malloc returns a pointer to the newly allocated block of memory.
ii) On error, means, if not enough space exists for the new block, malloc returns NULL.
iii) If the argument size == 0, malloc returns NULL.
This can be vied in following diagram,
char *str;
int n;
n=10;
star = (char *) malloc (n * sizeof (char)) ;
This allocates n bytes of memory from heap as shown below,

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
114 www.newgentech.in C LANGUAGE BY Mr.PRR

1000 1001 1002 ……………………………. 1007 1008 1009


Str 1000 addresses

2000
Example to illustrate malloc() function:
#include <stdio.h>
#include <string.h>
#include <alloc.h>
void main(void)
{
char *str;
int n;
/* allocate memory for string */
n=10;
str = (char *) malloc(n);
if (str == NULL)
{
printf("Not enough memory to allocate buffer\n");
exit(1); /* terminate program if out of memory */
}
printf("Memory is allocated\n");
/* free memory */
free(str);
return 0;
}
The calloc() function:
The calloc() function allocates n blocks each of size number of bytes, and assigns 0 to all bytes.
To allocate a block larger than 64K, use farcalloc.
The calloc() is similar to malloc(), but the main difference is that the values stored in the
allocated memory space is zero by default. With malloc, the allocated memory could have any
value.
The calloc() function requires two arguments. The first is the number of variables you'd like
to allocate memory for. The second is the size of each variable.
The general structure of calloc() function is,
void *calloc(int nblocks, int m);
where nblocks is number of blocks, m is the size of each block.
It creates nblocks number of blocks each of size m bytes
Retun values:
i) On success, returns a pointer to the newly allocated block.
ii) On failure, if not enough space exists for the new block
iii) If size is zero, returns NULL.
This can be vied in following diagram,
float *ptr;
int n;
n=7;
ptr = (float *) calloc (n, sizeof (float)) ;
This allocates n bytes of memory from heap and stores 0‟s by default, as shown below,

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
115 www.newgentech.in C LANGUAGE BY Mr.PRR

0
0 0 0 0 0 0

1000 1004 1008 1012 1016 1020 1024.


ptr 1000 addresses

2000
Example program to illustrate calloc() funtion:
#include <stdio.h>
#include <alloc.h>
#include <string.h>
void main(void)
{
int n;
char *str = NULL;
/* allocate memory for string */
n=0;
str = (char *) calloc(n, sizeof(char));
if( str == NULL)
{
printf(“ Unable to create memory.\n”);
exit(1);
}
printf("\nMemory is created.\n);
/* free memory */
free(str);

return 0;
}
The free() function:
This function frees or de-allocates the allocated blocks.
The general structure of free() function is,
void free(void *ptrtoblocks);
where ptrtoblocks is the pointer to the allocated blocks.
The free() function deallocates a memory block allocated by a previous call to calloc, malloc, or
realloc.
Return Value: None.
The realloc() function:
The realloc() function adjusts the size of the previously allocated block by creating new block of
specified size of bytes and copies the contents from the previous block to newly created block, if
necessary.
The realloc() function takes two arguments. The first is the pointer referencing the old memory.
The second is the total number of bytes you want to reallocate.
The general structure of realloc() function is,
void *realloc(void *ptrtoblocks, int n);
where,
-“ptrtoblocks” is the pointer to the previously allocated block by malloc(),
calloc(),realloc(). If this is NULL, then realloc() works like malloc().
-n in bytes, is the size of blocks to be adjusted or created newly.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
116 www.newgentech.in C LANGUAGE BY Mr.PRR

Return Value:
i) On success, returns the address of the reallocated block, which might be different
than the address of the original block.
ii) On failure (if the block can't be reallocated, or if size == 0 for realloc), the functions
return NULL.
This can be vied in following diagram,
int *ptr, n;
n=7;
ptr = ( int* ) malloc (n * sizeof (int)) ;
This allocates n bytes of memory from heap, as shown below,
Also assume that some values are stored into allocated locations.

12 30 11 17 8 25 6

1000 1002 1004 1006 1008 1010 1012.


ptr 1000 addresses

2000
Let that, if we require more memory to store some more values, then resize or extend this
allocated memory with loosing existing date as follows,
n=9;
ptr = (int*) realloc (ptr, n*sizeof (int)) ;

12 30 11 17 8 25 6

1000 1002 1004 1006 1008 1010 1012. 1014 1016


ptr 1000 addresses(can be different from older address)

2000
Example program illustrating the realloc() function.
#include <stdio.h> printf("\nAddress is %u\n", str);
#include <alloc.h> /* reallocate memory for string */
#include <string.h> n=15;
int main(void) str = (char *) realloc(str, n);
{ printf("\n New address is %u\n", str);
char *str; /* free memory */
int n; free(str);
/* allocate memory for string */ return 0;
n=10; }
str = (char *) malloc(n);

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
117 www.newgentech.in C LANGUAGE BY Mr.PRR

STORAGE CLASSES
INTRODUCTION:
Storage class specifiers in C language tells the compiler where to store a variable, how to store
the variable, what is the initial value of the variable and life time of the variable.
TYPES OF STORAGE CLASSES:-
There are four storage classes in c, which is supported with respect to „os‟.
1. Auto storage class
2. Static storage class
3. External storage class
4. Register storage class
AUTO STORAGE CLASS:
The features of a variable defined to have an automatic storage class are as under:
Storage - Stack of memory
Default value - An unpredictable value, which is often called a garbage value. It
refers to Base address of the variable.
Scope - local to the block in which the variable defined or within the function.
Life - Till the control remains within the blocks in which the variable is defined.
Note: the keyword for this storage class is auto and not automatic.
STATIC STORAGE CLASS:-
The features of a variable defined to have an automatic storage class are as under:
Storage - PMA of memory
Default value - zero
Scope - local to the block in which the variable defined or with in the function
Life - value of the variable persists between different function calls.
Note: static variable are initialized only once at the declaration.
EXTERNAL STORAGE CLASS:
The features of a variable defined to have an automatic storage class are as under:
Storage - PMA of memory
Default value - zero
Scope - as long as the program‟s execution
Life - doesn‟t come to an end.
Note:
1. External variables are declared outside all functions.
2. The keyword for this storage class is „extern‟.
Register storage class:
Storage - CPU registers
Default value - garbage value
Scope - local to the block in which the variable is defined
Life - Till the control remains within the block in which the variable is defined.
Note:
1. A value stored in a cpu register can always be accessed faster than the one which is stored in
Memory.
2. A good example of frequently used variables is loop counters.
3. We cannot use register storage class for all types of variables. Because the CPU registers in a
Microcomputer are usually 16 bit registers and therefore cannot hold a float value or a
doubleValue, which require 4 and 8 bytes respectively for storing a value.
EXAMPLES:
1. /* w a p to implement auto keyword #include<conio.h>
*/ void main()
#include<stdio.h> {
OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
118 www.newgentech.in C LANGUAGE BY Mr.PRR

clrscr(); increment();
increment(); f2=f1;
increment(); f1=f;
} return f;
increment() }
{ 4. /* write a program to use register
auto int i=1; keyword*/
printf("%d\n",i); # include <stdio.h>
i=i+1; # include <conio.h>
} main()
2. /* w a p to implement static {
keyword */ register int k ;
#include<stdio.h> clrscr() ;
#include<conio.h> printf(“%d \n”, k );
void main() for(k=1; k<=100; k++)
{ printf(“%d “, k) ;
clrscr(); getch() ;
increment(); }
increment(); 5. /* w a p to implement extern
increment(); keyword*/
} # include <stdio.h>
increment() # include <conio.h>
{ int k ;
Static int i=1; main()
printf("%d\n",i);i=i+1; {
} clrscr() ;
3. /* Write a program to display the printf(“\n %d”, k) ;
Fibonacci Series upto the given k=5;
number disp1() ;
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, disp2() ;
21,35,55… printf(“\n %d”, k) ;
In this series every element is the sum getch() ;
of its previous two numbers */ }
#include<stdio.h> disp1()
#include<conio.h> {
void main() printf(“\n %d”, k );
{ k += 3 ;
int count, n; }
long int fibonacci(int count);
printf("how many fibonacci number :"); disp2()
scanf("%d",&n); {
for(count=1;count<=n;count++) int k = 20 ;
printf("%ld\n",fibonacci(count)); printf(“\n %d”, k );
getch(); disp3() ;
} }
long int fibonacci(int count)
{ disp3()
static long int f1=1,f2=1; {
long int f; printf(“\n %d”, k );
f=(count<3)?1:f1+f2; }
OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
119 www.newgentech.in C LANGUAGE BY Mr.PRR

STRUCTURES
Q) What is a structure? Explain it‟s syntax?
A structure is a collection of one or more variables grouped under a single name for easy
manipulation. The variables in a structure, unlike those in an array, can be of different variable
types. A structure can contain any of C's data types, including arrays and other structures. Each
variable within a structure is called a member of the structure.
Syntax:
struct structure_ name
{
Data_type member1;
Data_type member2;
.
.
data _type membern;
};
Note:
The struct keyword is used to declare structures; the keyword struct identifies the beginning of
a structure definition. It's followed by a tag that is thename given to the structure.
Defining and Declaring Structures:
If you're writing a graphics program, your code needs to deal with the coordinates of points on
thescreen. Screen coordinates are written as an x value, giving the horizontal position, and a y
value, givingthe vertical position. You can define a structure named coord that contains both the
x and y values of ascreen location as follows:
struct coord {
int x;
float y;
};
The struct keyword, which identifies the beginning of a structure definition, must be followed
immediately by the structure name, or tag (which follows the same rules as other C variable
names).Within the braces following the structure name is a list of the structure's member
variables. You must give a variable type and name for each member. The preceding statements
define a structure type named coord that contains one integer variables x and one float variable
y. They do not, however, actually create any instances of the structure coord. In other words,
they don'tdeclare (set aside storage for) any structures. There are two ways to declare
structures. One is to followthe structure definition with a list of one or more variable names, as
is done here.
struct coord {
nt x;
float y;
} first, second;
These statements define the structure type coord and declare two structures, first and second,
of typecoord. first and second are each instances of type coord; first contains one integer
member named x and other floating member y, and so does second.This method of declaring
structures combines the declaration with the definition. The second method isto declare
structure variables at a different location in your source code from the definition. The following
statements also declare two instances of type coord
struct coord {
int x;
float y;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
120 www.newgentech.in C LANGUAGE BY Mr.PRR

};
/* Additional code may go here */
struct coord first, second;
Accessing Structure Members:
Individual structure members can be used like other variables of the same type. Structure
members areaccessed using the structure member operator (.), also called the dot operator,
between the structurename and the member name. Thus, to have the structure named first
refer to a screen location that has
coordinates x=50, y=100, you could write
first.x = 50;
first.y = 100;
To display the screen locations stored in the structure second, you could write
printf("%d%f", second.x, second.y);
At this point, you might be wondering what the advantage is of using structures rather than
individualvariables. One major advantage is that you can copy information between structures
of the same typewith a simple equation statement. Continuing with the preceding example, the
statement
first = second;
is equivalent to this statement:
first.x = second.x;
first.y = second.y;
When your program uses complex structures with many members, this notation can be a great
time saver. Other advantages of structures will become apparent as you learn some advanced
techniques.In general, you'll find structures to be useful whenever information of different
variable types needs to betreated as a group. For example, in a mailing list database, each
entry could be a structure, and each pieceof information (name, address, city, and so on) could
be a structure member.
Example 1
/* declare a structure template called struct date {
SSN */ char month[2];
struct student { char day[2];
int rollno; char year[4];
char sname[30];
int sum; } current_date;
char grade; Example 3
float avg; /* Declare and initialize a structure */
} struct time {
/* Use the structure template */ int hours;
struct students1; int minutes;
Example 2 int seconds;
/* declare a structure and instance } time_of_birth = { 8, 45, 0 };
together */

Program:
/* wap to print the student details using structure */
#include<stdio.h>
#include<conio.h>
struct student

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
121 www.newgentech.in C LANGUAGE BY Mr.PRR

{ Output:
int rno,m1, m2, m3; enter name=Praveen
float total, avg; enter rno, m1, m2, m3=100 98 85 94
char name[50]; *** STUDENT DETAILS***
}; name is Praveen
main() rno 100
{ sub1 98
struct student b; sub2 85
clrscr(); sub3 94
printf("enter name="); total 277.000000
scanf("%s", &b.name); avg 92.333336
printf("enter rno, m1, m2, m3=");
scanf("%d%d%d%d", &b.rno, &b.m1, &b.m2, &b.m3);
b.total=b.m1+b.m2+b.m3;
b.avg=b.total/3;
printf("\n*** STUDENT DETAILS***\n");
printf("\n name is %s", b.name);
printf("\n rno \t %d", b.rno);
printf("\n sub1 \t %d", b.m1);
printf("\n sub2 \t %d", b.m2);
printf("\n sub3 \t %d", b.m3);
printf("\n total\t %f", b.total);
printf("\n avg \t %f", b.avg );
getch();
}
Arrays of Structures:
As we know array is a collection of similar data types. In the same way we can also define array
of structures. In such type of array every element is of structure type. Array of structure can be
declared as follows. Output:
struct cricket Enter first name: praveen
{ Enter last name: kumar
int balls; Enter phone in 123-4567 format: 040-1234
float srate;
char name[25]; Enter first name: ravi
}match[10]; Enter last name: kiran
Example: Enter phone in 123-4567 format: 040-1235
/* Demonstrates using arrays of structures.
*/ Enter first name: manoj
#include<stdio.h> Enter last name: kumar
#include<conio.h> Enter phone in 123-4567 format: 040-1236
struct entry {
char fname[20]; Enter first name: laxmi
char lname[20]; Enter last name: rani
char phone[10]; Enter phone in 123-4567 format: 040-1237
};
struct entry list[4]; Name: praveen kumar Phone: 040-1234
int i; Name: ravi kiran Phone: 040-1235
void main() Name: manoj kumar Phone: 040-1236
{ Name: laxmi rani Phone: 040-1237

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
122 www.newgentech.in C LANGUAGE BY Mr.PRR

clrscr();
for (i = 0; i < 4; i++)
{
printf("\nEnter first name: ");
scanf("%s", list[i].fname);
printf("Enter last name: ");
scanf("%s", list[i].lname);
printf("Enter phone in 123-4567 format: ");
scanf("%s", list[i].phone);
}
printf("\n\n");
for (i = 0; i < 4; i++)
{
printf("Name: %s %s", list[i].fname, list[i].lname);
printf("\tPhone: %s\n", list[i].phone);
}
return 0;
}
Pointers to structure:
We know that pointer is a variable that holds the address of another data variable. The variable
may be of any data type i.e. int, float or double. In the same way we can also define pointer to
structure. Here, starting address of the member variable can be accessed. Thus, such pointers
are called structure pointers.
Example:
struct book
{
char name[25];
char author[25];
int pages;
};
struct book *ptr;
in the above example *ptr is pointer to structure book. The syntax for using pointer with
member is as given below.
ptr->name
ptr->author
ptr->pages
Example:
/* A program to display book details using pointers and structures*/
#include<stdio.h>
#include<conio.h>
struct book
{
char name[20];
Output:
char author[20];
c language material by Ramesh of 150 pages
int pages;
c language material by Ramesh of 150 pages
};
void main()
{
struct book b1={"c language material","Ramesh",150};

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
123 www.newgentech.in C LANGUAGE BY Mr.PRR

struct book *p;


p=&b1;
clrscr();
printf("\n%s by %s of %d pages",b1.name,b1.author,b1.pages);
printf("\n%s by %s of %d pages",p->name,p->author,p->pages);
getch();
}
Passing Structures as Arguments to Functions:
Like other data types, a structure can be passed as an argument to a function.
Example:
/* Demonstrates passing a structure to a function. */
#include <stdio.h>
struct data{
float amount;
char fname[30];
char lname[30];
} rec;
void print_rec(struct data x);
void main()
{
clrscr();
printf("Enter the donor's first and last names,\n");
printf("separated by a space: ");
scanf("%s %s", rec.fname, rec.lname);
printf("\nEnter the donation amount: ");
scanf("%f", &rec.amount);
print_rec( rec );
return 0;
}
void print_rec(struct data x)
{
printf("\nDonor %s %s gave $%.2f.\n", x.fname, x.lname,
x.amount);
}
Nested structure:
We can take any data type for declaring structure members like int, float, char etc. in the same
way we can also take object of one structure as member in another structure. Thus, structure
can be used to create complex data application.
Example:
struct coord {

int x;
int y;
};
struct rectangle {
struct coord topleft;
struct coord bottomrt;
}mybox;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
124 www.newgentech.in C LANGUAGE BY Mr.PRR

To access the actual data locations (the type int members), you must apply the member
operator (.) twice.Thus, the expression
mybox.topleft.x;
Refers to the x member of the topleft member of the type rectangle structure named mybox. To
define arectangle with coordinates (0,10),(100,200), you would write.
mybox.topleft.x = 0;
mybox.topleft.y = 10;
mybox.bottomrt.x = 100;
mybox.bottomrt.y = 200;
Example:
/* Demonstrates structures that contain other structures. */
/* Receives input for corner coordinates of a rectangle andcalculates the area. Assumes that the
y coordinate of theupper-left corner is greater than the y coordinate of the
lower-right corner, that the x coordinate of the lower-right corner is greater than the x
coordinate of the upper-left corner, and that all coordinates are positive. */
#include <stdio.h>
int length, width;
long area;
Output:
struct coord{
Enter the top left x coordinate: 10
int x;
Enter the top left y coordinate: 5
int y;
Enter the bottom right x coordinate: 5
};
Enter the bottom right y coordinate: 2
struct rectangle{
The area is 15 units.
struct coord topleft;
struct coord bottomrt;
} mybox;
void main()
{
printf("\nEnter the top left x coordinate: ");
scanf("%d", &mybox.topleft.x);
printf("\nEnter the top left y coordinate: ");
scanf("%d", &mybox.topleft.y);
printf("\nEnter the bottom right x coordinate: ");
scanf("%d", &mybox.bottomrt.x);
printf("\nEnter the bottom right y coordinate: ");
scanf("%d", &mybox.bottomrt.y);
width = mybox.bottomrt.x - mybox.topleft.x;
length = mybox.bottomrt.y - mybox.topleft.y;
area = width * length;
printf("\nThe area is %ld units.\n", area);
return 0;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
125 www.newgentech.in C LANGUAGE BY Mr.PRR

Unions
Unions are similar to structures. A union is declared and used in the same ways that a structure
is. Aunion differs from a structure in that only one of its members can be used at a time. The
reason for this issimple. All the members of a union occupy the same area of memory. They are
laid on top of each other.
Defining, Declaring, and Initializing Unions:
Definition:
The union keyword is used for declaring unions. A union is a collection of one or more variables
(union_members) that have been grouped under a single name. In addition, each of these
union members occupies the same area of memory. The keyword union identifies the beginning
of a union definition. It's followed by a tag that is the name given to the union.
Unions are defined and declared in the same fashion as structures. The only difference in the
declarationsis that the keyword union is used instead of struct. To define a simple union of a
char variable and aninteger variable, you would write the following:
union shared {
char c;
int i;
};
This union, shared, can be used to create instances of a union that can hold either a character
value c oran integer value i. This is an OR condition. Unlike a structure that would hold both
values, the union canhold only one value at a time. A union can be initialized on its declaration.
Because only one member can be used at a time, only onecan be initialized. To avoid confusion,
only the first member of the union can be initialized. The
following code shows an instance of the shared union being declared and initialized:
union shared generic_variable = {`@'};
Notice that the generic_variable union was initialized just as the first member of a structure
would beinitialized.
Accessing Union Members:
Individual union members can be used in the same way that structure members can be used by
using themember operator (.). However, there is an important difference in accessing union
members. Only oneunion member should be accessed at a time. Because a union stores its
members on top of each other, it'simportant to access only one member at a time.
Example:
/* Example of using more than one union member at a time */
#include <stdio.h>
void main()
Output:
{
char c = $
union shared_tag {
int i = 4900
char c;
long l = -1888873692
int i;
float f = -0.000000
long l;
double d = -0.000000
float f;
char c = 7
double d;
int i = -30409
} shared;
long l = 1468107063
shared.c = '$';
float f = 284852666499072.000000
clrscr();
double d = 123456789.876500
printf("\n char c = %c", shared.c);
printf("\n int i = %d", shared.i);
printf("\n long l = %ld", shared.l);

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
126 www.newgentech.in C LANGUAGE BY Mr.PRR

printf("\n float f = %f", shared.f);


printf("\n double d = %f", shared.d);
shared.d = 123456789.8765;
printf("\n\nchar c = %c", shared.c);
printf("\n int i = %d", shared.i);
printf("\n long l = %ld", shared.l);
printf("\n float f = %f", shared.f);
printf("\n double d = %f\n", shared.d);
return 0;
}
Typedef:
By using typedef we can create new data type. The statement typedef is to be used while
defining the new data type. The syntax is as given under.
Syntax:
typedef type dataname;
here, type is the data type and dataname is the user defined name for that type.
typedef int rollno;
Here rollno is the another name for int and we can use rollno instead of int in the program.
Example:
/* write a program to create userdefined data type rollno on intdata type and use it in
the program*/
#include<stdio.h>
#include<conio.h>
void main()
{
typedef int rollno;
rollno sno;
clrscr();
printf("enter student serial number=");
scanf("%d",&sno);
printf("\n student serial number=%d",sno);
getch();
}
Output:
enter student serial number=100
student serial number=100
BitFields:
 The Bit-field are used to reserve the memory space in terms of bits.
 we cant use the pointers to bit fields and hence we cant supply the value at runtime through
scanf()function.
 Unlike some other computer languages, C has a built–in feature called a bit-field that allows
you to access a single bit.
 Bit –fields a can be useful for a number of reasons such as
 It storage is limited, you can store several Boolean (true/false), variables in one byte.
 the general from of a bit –field definition is
<datatype> name: length;
Here , type is the type of the bit-fields and length is the number of bits the field the type of
bitfield must be int, signed or unsigned.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
127 www.newgentech.in C LANGUAGE BY Mr.PRR

Example:
/* write a program to reserve memory in the form of bits */
#include<stdio.h>
#include<conio.h>
main()
{
struct dare
{
unsigned int dd:5;
unsigned int mm:4;
unsigned int yy:7;
};
struct dare d={26,5,11};
clrscr();
printf("\n date=%u %u %u\n",d.dd,d.mm,d.yy);
}
Output:
date=26 5 11
Enumerated Data Type:
The enumerated data type gives you an opportunity to invent your own data type and define
what value the variable of this data type can take. The format of the enum-definition is similar
to that of a structure.Here‟s how the example started above can be implemented.
syntax:
enum enumdata_type
{
variables
};
Ex:
enum c++
{
function,class,constructor,encapsulation
};
enum c++ f1,f2;
like structure,this declaration has two parts;
a) The first part declares the data types and specifies its possible values. These values are
called “enumetators”.
b) The Second part declares variables of this data type.
Now we can give values to these variables
class
person1=class;
person2=constructor;
Remember we can‟t use values that are not in the original declaration,thus, the following
expression would causes an error.
person1=unknown;
Internally the complier treats the enumerators as integers. Each value on the list of permissible
values corresponds to an integer, starting with 0.Thus in our example, function is stored as o,
and class is stored as 1,constructor is stored at 2,encapaulation is stored as 3 This way of
assigned numbers can be overridden by the programmer by initializing a the enumerators to
different integers value as shown below
enum c++

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
128 www.newgentech.in C LANGUAGE BY Mr.PRR

{
function=100,class=200,constructor=300,encapsulation=400
}
Advantages:
1. This can helps in making the program listing more readable. Which can be advantages when
a program gets complicated or when more than one programmer would be working on it.
2. Using this we can also reduce programming errors.
/* write a program to explain enumdata type */
#include<stdio.h>
#include<conio.h>
int main()
{
enum sample
{
x,y=10,z
};
enum sample s;
s=z;
clrscr();
printf("%d\n",x);
printf("%d\n",y);
printf("%d\n",z);
return(0);
getch(); }

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
129 www.newgentech.in C LANGUAGE BY Mr.PRR

FILES
 scanf( ) and printf( ) functions read and write data which always uses the terminal
(keyboard and screen) as the target.
 It becomes confusing and time consuming to use large volumes of data through terminals.
 The entire data is lost when either program terminates or computer is turned off.
 Sometimes it may be necessary to store data in a manner that can be later retrieved and
processed.
This leads to employ the concept of FILESto store data permanently in the system.
DEFINATION:
File is a set of records that can be accessed through the set of library functions.Record is
logical group of data fields that comprise a single row of information, which describes the
characteristics of an object. AFile is a place on disk where a group of related data (records )
can be stored.
File Operations:
1. Creating a new file
2. Opening an existing file
3. Reading from a file
4. Writing to a file
5. Moving to a specific location in a file (seek)
6. Closing a file
Q) What Exactly Is Program Input/Output?
C program keeps data in random access memory (RAM) while executing. This data is in the
form of variables, structures, and arrays that have been declared by the program. Where did
this data come from, and what can the program do with it? Data can come from some location
external to the program. Data moved from an external location into RAM, where the program
can access it, is called input. The keyboard and disk files are the most common sources of
program input. Data can also be sent to a location external to the program; this is called
output. The most common destinations for output are the screen, a printer, and disk files. Input
sources and output destinations are collectively referred to as devices. The keyboard is a
device, the screen is a device, and so on. Some devices (the keyboard) are for input only,
others (the screen) are for output only, and still others (disk files) are for both input and
output. Whatever the device, and whether it's performing input or output, C carries out all input
and outputoperations by means of streams.
Q) What Is a Stream?
A stream is a sequence of characters. More exactly, it is a sequence of bytes of data. A
sequence of bytes flowing into a program is an input stream; a sequence of bytes flowing out of
a program is an output stream. By focusing on streams, you don't have to worry as much about
where they're going or where they originated. The major advantage of streams, therefore, is
that input/output programming is deviceindependent. Programmers don't need to write special
input/output functions for each device (keyboard, disk, and so on). The program sees
input/output as a continuous stream of bytes no matter where the input is
coming from or going to.
Every C stream is connected to a file. In this context, the term file doesn't refer to a disk file.
Rather, it is anintermediate step between the stream that your program deals with and the
actual physical device being usedfor input or output. For the most part, the beginning C
programmer doesn't need to be concerned with these files, because the details of interactions
between streams, files, and devices are taken care of automatically
by the C library functions and the operating system.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
130 www.newgentech.in C LANGUAGE BY Mr.PRR

NOTE: Input and output can take place between your program and a variety of
external devices.

A Stream acts as an interface between a program and an input/output Device.

Text modes:
Mode meaning
r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.
W Opens the file for writing. If a file of the specified name doesn't exist, it is created. If
a file of the specified name does exist, it is deleted without warning, and a new,
empty file is created.
a Opens the file for appending. If a file of the specified name doesn't exist, it is
created. If the file does exist, new data is appended to the end of the file.
r+ Opens the file for reading and writing. If a file of the specified name doesn't exist, it
is created. If the file does exist, new data is added to the beginning of the file,
overwriting existing

w+ Opens the file for reading and writing. If a file of the specified name doesn't exist, it
is created. If the file does exist, it is overwritten.
a+ Opens a file for reading and appending. If a file of the specified name doesn't exist,
it is created. If the file does exist, new data is appended to the end of the file.

File input and output functions:


File input/output functions
fopen(fp, Open existing file / Create new file
mode)

fclose(fp) Closes a file associated with file pointer.

closeall ( ) Closes all opened files with fopen()

fgetc(ch, fp) Reads character from current position and advances the pointer
to next character.

fprintf( ) Writes all types of data values to the file.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
131 www.newgentech.in C LANGUAGE BY Mr.PRR

fscanf() Reads all types of data values from a file.

gets() Reads string from a file.

puts() Writes string to a file.

getw() Reads integer from a file.

putw() Writes integer to a file.

fread() Reads structured data written by fwrite() function

fwrite() Writes block of structured data to the file.

fseek() Sets the pointer position anywhere in the file

feof() Detects the end of file.

rewind() Sets the record pointer at the beginning of the file.

ferror() Reports error occurred while read/write operations

fflush() Clears buffer of input stream and writes buffer of output stream.

ftell() Returns the current pointer position.

Examples1:
/* write a program to open a file and #include<conio.h>
store information*/ void main()
#include<stdio.h> {
#include<conio.h> char ch;
void main() FILE *fp;
{ clrscr();
char ch; fp=fopen("ramesh","r");
FILE *fp; ch=getc(fp);
fp=fopen("ramesh","w"); while(ch!=EOF)
printf("enter data\n"); {
ch=getchar(); putchar(ch);
while(ch!=EOF) ch=getc(fp);
{ }
putc(ch,fp); fclose(fp);
ch=getchar(); }
} Q) Write a C program to count number
fclose(fp); of lines
} #include <stdio.h>
Example2: /* count lines in input */
/* write a program to open a file and main()
read the information*/ {
#include<stdio.h> int c, nl;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
132 www.newgentech.in C LANGUAGE BY Mr.PRR

nl = 0;
clrscr();
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
getch();
}
Q) Write a C program that copies its
input to its output one character at a
time

#include <stdio.h>
/* copy input to output; 1st version */
main()
{
int c;
clrscr();
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
Q) Write a program to counts
characters.
#include <stdio.h>
void main()
{
long nc;
clrscr();
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
getch();
}

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
133 www.newgentech.in C LANGUAGE BY Mr.PRR

COMMAND LINE ARGUMENTS


AND
The C Preprocessor
COMMAND LINE ARGUMENTS:
In C it is possible to accept command line arguments. Command-line arguments are given after
the name of a program in command-line operating systems like DOS or Linux, and are passed
in to the program from the operating system.
To use command line arguments in your program, you must first understand the full declaration
of the main function, which previously has accepted no arguments. In fact, main can actually
accept two arguments:
i) one argument is number of command line arguments,
ii) second argument is a full list of all of the command line arguments.
The full declaration of main looks like this:
int main ( int argc, char *argv[] )
The integer, argc is the argument count. It is the number of arguments passed into the
program from the command line, including the name of the program.
The array of character pointers is the listing of all the arguments. argv[0] is the name of the
program, or an empty string if the name is not available. After that, every element number less
than argc is a command line argument.
We can use each argv element just like a string, or use argv as a two dimensional array. The
argv[argc] is a null pointer.
Almost any program that wants its parameters to be set when it is executed would use this.
One common use is to write a function that takes the name of a file and outputs the entire text
of it onto the screen.
For example to create a directory, we execute at command line or prompt as follows,
mkdir dir_name
where actually, mkdir is the name of the program written by somebody and is used to
create a directory with a given name. The usage of that program would be as shown above.
So, we can also write such programs using arguments called command-line arguments.
Example: Program to illustrate command line arguments in C -program.
/*the cmdline.c is the name of the program. */
#include<stdio.h>
void main (int argc, char *argv[])
{
int i;
if(argc != 2)
{
printf("Too few arguments.\n");
exit(0);
}
printf("\nThe command-line arguments %d are:\n", argc);
for(i=0;i<argc; i++)
printf("argv[%d]: %s\n", i, argv[i]);
getch();
}
Output:
D:\cpds>cmdline Suresh Rahul Harikrishna Govardhan
The command-line arguments 5 are:
argv[0]: D:\CPDS\CMDLINE.EXE

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
134 www.newgentech.in C LANGUAGE BY Mr.PRR

argv[1]: Suresh
argv[2]: Rahul
argv[3]: Harikrishna
argv[4]: Govardhan
Explanation: How to execute this program,
i) Type program in file : cmdline.c
ii) Compile cmdline.c
iii) Identify the location of cmdline.exe. in my case, cmdline.exe is in D:\cpds directory. Or copy
cmdline.exe into require directory or drive. Then execute from there, as shown below.
iv) D:\cpds>cmdline Suresh Rahul Harikrishna Govardhan.
The C Preprocessor
C PREPROCESSOR DIRECTIVES:
 Before a C program is compiled in a compiler, source code is processed by
a program called preprocessor. This process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and they begin with “#”
symbol.
Below is the list of preprocessor directives that C programming languageoffers.

Preprocessor Syntax/Description

Macro Syntax: #define


This macro defines constant value and can be
any of the basic data types.

Header file Syntax: #include <file_name>


inclusion The source code of the file “file_name” is
included in the main program at the specified
place.

Conditional Syntax: #ifdef, #endif, #if, #else, #ifndef


compilation Set of commands are included or excluded in
source program before compilation with
respect to the condition.

Other directives Syntax: #undef, #pragma, #undef is used to


un define a defined macro variable. #Pragma is
used to call a function before and after main
function in a C program.

A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
135 www.newgentech.in C LANGUAGE BY Mr.PRR

There are 4 regions of memory which are created by a compiled C program. They are,
1. First region – This is the memory region which holds the executable code of the program.
2. 2nd region – In this memory region, global variables are stored.
3. 3rd region – stack
th
4. 4 region – heap
DO YOU KNOW DIFFERENCE BETWEEN STACK & HEAP MEMORY IN C LANGUAGE?

Stack Heap

Stack is a memory region where Heap is a memory region


“local variables”, “return addresses which is used by dynamic
of function calls” and “arguments memory allocation functions
to functions” are hold while at run time.
C program is executed.

CPU‟s current state is saved in Linked list is


stack memory an example which uses heap
memory.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
136 www.newgentech.in C LANGUAGE BY Mr.PRR

DO YOU KNOW DIFFERENCE BETWEEN COMPILERS VS INTERPRETERS IN


C LANGUAGE?

Compilers Interpreters

Compiler reads the entire source Interpreter reads the program


code of the program and source code one line at a time
converts it into binary code. This and executing that line. This
process is called compilation. process is called interpretation.
Binary code is also referred as
machine code, executable, and
object code.

Program speed is fast. Program speed is slow.

One time execution. Interpretation occurs at every


Example: C, C++ line of the program.
Example: BASIC

KEY POINTS TO REMEMBER:


1. Source program is converted into executable code through different processes like pre
compilation, compilation, assembling and linking.
2. Local variables uses stack memory.
3. Dynamic memory allocation functions use the heap memory.
EXAMPLE PROGRAM FOR #DEFINE, #INCLUDE PREPROCESSORS IN C LANGUAGE:
 #define – This macro defines constant value and can be any of the basic data types.
 #include <file_name> – The source code of the file “file_name” is included in the main
C program where “#include <file_name>” is mentioned.
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
137 www.newgentech.in C LANGUAGE BY Mr.PRR

printf("value of backslash_char : %c \n", backslash_char);


}
OUTPUT:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
EXAMPLE PROGRAM FOR CONDITIONAL COMPILATION DIRECTIVES:
A) EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:
 “#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If”
clause statements are included in source file.
 Otherwise, “else” clause statements are included in source file for compilation and
execution.
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}
OUTPUT:
RAJU is defined. So, this line will be added in this C file
B) EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN C:
 #ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, “If”
clause statements are included in source file.
 Otherwise, else clause statements are included in source file for compilation and execution.
#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
138 www.newgentech.in C LANGUAGE BY Mr.PRR

printf("SELVA is not defined. So, now we are going to " \


"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);
#endif
return 0;
}
OUTPUT:
SELVA is not defined. So, now we are going to define here
C) EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF IN C:
 “If” clause statement is included in source file if given condition is true.
 Otherwise, else clause statement is included in source file for compilation and execution.
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return 0;
}
OUTPUT:
This line will be added in this C file since a = 100
EXAMPLE PROGRAM FOR UNDEF IN C LANGUAGE:
This directive undefines existing macro in the program.
#include <stdio.h>
#define height 100
void main()
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new value

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
139 www.newgentech.in C LANGUAGE BY Mr.PRR

printf("value of height after undef \& redefine:%d",height);


}
OUTPUT:
First defined value for height : 100
value of height after undef & redefine : 600
EXAMPLE PROGRAM FOR PRAGMA IN C LANGUAGE:
Pragma is used to call a function before and after main function in a C program.
#include <stdio.h>
void function1( );
void function2( );
#pragma startup function1
#pragma exit function2
int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \
"main function" ) ;"
}
OUTPUT:
Function1 is called before main function call
Now we are in main function
Function2 is called just before end of main function
MORE ON PRAGMA DIRECTIVE IN C LANGUAGE:

Pragma command Description

#Pragma startup This directive executes function named


<function_name_1> “function_name_1” before

#Pragma exit This directive executes function named


<function_name_2> “function_name_2” just before

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
140 www.newgentech.in C LANGUAGE BY Mr.PRR

termination of the program.

#pragma warn – rvl If function doesn‟t return a value, then


warnings are suppressed by
this directivewhile compiling.

#pragma warn – par If function doesn‟t use passed function


parameter , then warnings are
suppressed

#pragma warn – rch If a non reachable code is written inside


a program, such warnings are
suppressed by this directive.

Header Files:
What are header files in c ?
Header files are the predefined files in c which consists the function definitions of the library
functions. These header files are must and should be included in the program inorder to use
inbuilt library functions in c. we can create our own header files in c to reduse code work.
What is the use of creating our own header files in c?
Header files are used to store the function definitions. So if your code is too large, then you can
put dome of your function definitions in a header file and include that header file into your
source code at the time of compilation. This reduces our coding work and increases code
readability.
If there is any function which is to be repeatedly used in all the programs, then it becomes
difficult to write the function definition in each and every program. for example if you want to
display author information at the end of a program for all the programs written by a particular
author, then it becomes hard to display it manually in each and every program.
So in that case you can store the author information in a function and save that function in a
header file. Now you need to just include that header file in each and every program to display
the author information.
How to create our own header files in c?
creating our own header files in c is very easy. If you want to store the function definition of a
particular function in a header file, then follow the below steps.
Step 1:
Write the function definition in a text file and save it as filename.h. remember to write only
function definition. you should not write function prototype and main function. remember the
function name you used in the header file.
void about_author()
{
printf("\n About Author");
printf("\n Author Name: Ramesh Reddy P");
printf("\n E-Mail: ramesh_java01@yahoo.com");
printf("\n Working: ngcsoftsolutions”);
}

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
141 www.newgentech.in C LANGUAGE BY Mr.PRR

Save this file name as author.h and palce “include” folder which is avilable in tc folder which is
our software instalation directory.
Step 2:
Write the program by including the created header file.
#include<stdio.h>
#include<conio.h>
#include<author.h>
void main()
{
int a=10,b=20,c;
c=a+b;
printf("Sum=%d",c);
about_author();
getch();
}
Output:
sum is 30
about author
name: Ramesh Reddy P
e-mail:ramesh_java01@yahoo.com
Working: ngcsoftsolutions
In the above program we are calling the function about_author() function which is in the header
file. we are not defining the function definition in the program. the compiler includes the
function definition of that function from the header file.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
142 www.newgentech.in C LANGUAGE BY Mr.PRR

ADDITIONAL PRACTICE PROGRAMS

/* My first C program */ {
#include <stdio.h> /* declarations */
int main (void) char letter1, letter2, letter3, letter4;
{
printf ("This is my first C program.\n"); printf ("Enter a name: ");
return (0); scanf ("%c%c%c%c", &letter1, &letter2,
} &letter3, &letter4);
/* Trying printf and scanf */ printf ("You entered: %c%c%c%c",
#include <stdio.h> letter1, letter2, letter3, letter4);
int main (void) printf (" / Backwards: %c%c%c%c\n",
{ letter4, letter3, letter2, letter1);
/* declarations */ return (0);
double x, y, z; }
/* executable statements */ /* The "circle" program (from
printf ("Enter two real numbers: "); keyboard) */
scanf ("%lf %lf", &x, &y); #include <stdio.h>
z = x + y; #define PI 3.1416
printf ("\nThe sum of %lf and %lf is %f.\n", int main (void)
x, y, z); {
printf ("\nThe product of %lf and %lf is /* declarations */
%lf.\n", x, y, x*y); double diam, area, circ, r;
return (0); /* get diameter from user */
} printf ("Enter a value for the diameter:
/* Numeric Placeholders */ ");
#include <stdio.h> scanf ("%lf", &diam);
int main (void) /* do the computations */
{ r = diam / 2;
/* declarations */ area = PI * r * r;
int a; circ = 2 * PI * r;
double x; /* display the report on the screen */
/* executable statements */ printf ("\nA circle with a diameter of %3.1lf
a = 1000; cm, ", diam);
x = 100.583665; printf ("has an area of %5.3lf cm2\n",
printf ("%d\n", a); area);
printf ("%3d\n", a); printf ("and a circumference of %4.2lf
printf ("%4d\n", a); cm.\n", circ);
printf ("%5d\n", a); return (0);
printf ("\n"); }
printf ("%lf\n", x); /* The "circle" program (using files) */
printf ("%15lf\n", x); #include <stdio.h>
printf ("%15.4lf\n", x); #define PI 3.1416
printf ("%18.2lf\n", x); int main (void)
printf ("%12.0lf\n", x); {
return (0); double diam, area, circ, r;
} FILE *in, *out;
/* This program reads four characters /* opening files */
*/ in = fopen ("diameter.data", "r");
#include <stdio.h> out = fopen ("report_circle.txt", "w");
int main (void) /* get diameter from file */

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
143 www.newgentech.in C LANGUAGE BY Mr.PRR

printf ("Reading data from file... "); int main (void)


fscanf (in, "%lf", &diam); {
printf ("Value read: %lf\n\n", diam); int a, b, c, d, e, total;
/* do the computations */ FILE *f1, *f2, *f3;
r = diam / 2; /* opening input files */
area = PI * r * r; f1 = fopen ("file1.dat", "r");
circ = 2 * PI * r; f2 = fopen ("file2.dat", "r");
/* send results to report file */ /* reading data */
fprintf (out, "%4.2lf %4.2lf\n", area, fscanf (f1, "%d%d%d", &a, &b, &c);
circ); fscanf (f2, "%d%d%, &d, &e);
printf ("Sending results to file /* adding the numbers */
report_circle.txt...\n\n"); total = a + b + c + d + e;
/* closing files */ /* closing input files */
fclose (in); fclose (f1);
fclose (out); fclose (f2);
printf ("Program completed."); /* opening output file */
return (0); f3 = fopen ("total.dat", "w");
} /* output report on both screen and file
/* The = operator puts the value on the */
right */ printf ("Read from first file: %d %d
/* into the variable on the left */ %d\n", a, b, c);
#include <stdio.h> printf ("Read from second file: %d
int main (void) %d\n", d, e);
{ printf ("The sum is: %d\n\n", total);
/* declarations */ fprintf ("f3, "%d", total);
int a, b, c, d, e; printf ("\nFILE total.dat CREATED.\n");
/* fill variable a */ /* check your directory for the new file!
a = 10; */
/* modify variable a few times*/ /* closing output file */
a = 20; fclose (f3);
a = 10 + a; return (0);
a = a + a + 2; }
a = 2 + a; /* Maximum Values */
/* a few more assignments */ #include <stdio.h>
b = a; #include <limits.h>
c = b = 5; #include <float.h>
c = 10 + a; int main (void)
d = a + a + 2; {
e = 20 + a; printf ("The largest integer is: %d\n",
a = a - b + c; INT_MAX);
/* the final values are... */ printf ("The largest double is: %e\n",
printf ("a:%4d\n b:%4d\n c:%4d\n DBL_MAX);
d:%4d\n e:%4d\n", a, b, c, d, e); return (0);
return (0); }
} /* The remainder (%) operator */
/* Working with multiple files */ #include <stdio.h>
/* (This program contains a few syntax int main (void)
errors. Try to correct them) */ {
#include <stdio.h> int a, b, c, d;
#define PI 3.1416 /* a few operations */

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
144 www.newgentech.in C LANGUAGE BY Mr.PRR

a = 10 % 3; before = -217.5;
b = -10 % 3; after = floor (before);
c = 10 % -3; printf ("The floor of %3.1lf is %3.1lf\n",
d = -10 % -3; before, after);
/* you need to double the % to display on /* the log function */
screen */ before = 200.0;
printf ("10 %% 3 is %d\n", a); after = log (before);
printf ("-10 %% 3 is %d\n", b); printf ("The ln of %3.1lf is %3.1lf\n",
printf ("10 %% -3 is %d\n", c); before, after);
printf ("-10 %% -3 is %d\n", d); /* the log10 function*/
return (0); before = 200.0;
} after = log10 (before);
/* Integer division */ printf ("The log of %3.1lf is %3.1lf\n",
#include <stdio.h> before, after);
int main (void) /* the sqrt function*/
{ before = 200.0;
int a, b, c; after = sqrt (before);
double x, y, z, w; printf ("The square root of %3.1lf is
a = 10; b = 20; %3.1lf\n", before, after);
/* dividing two integers */ /* the fabs function (for doubles)*/
z = a / b; before = -413.56;
c = a / b; after = fabs (before);
printf ("The value of z is %5.3lf ", z); printf ("The absolute value of %3.1lf is
printf ("and the value of c is %d\n", c); %3.1lf\n", before, after);
/* converting (casting) one operand /* the sin function */
before the division*/ before = 45.0;
x = (double)a / b; after = sin (before * PI / 180);
printf ("The value of x is %5.3lf\n", x); printf ("The sine of %3.1lf is %5.3lf\n",
/* casting the quotient after the division*/ before, after);
y = (double) (a / b); /* the cos function */
printf ("The value of y is %5.3lf\n", y); before = 45.0;
/* casting both operands before the after = cos (before * PI / 180);
division*/ printf ("The cosine of %3.1lf is %5.3lf\n",
w = (double)a / (double)b; before, after);
printf ("The value of w is %5.3lf\n", w); /* the tan function */
return (0); before = 45.0;
} after = tan (before * PI / 180);
/* Functions from the math library */ printf ("The tangent of %3.1lf is
#include <stdio.h> %5.3lf\n", before, after);
#include <math.h> /* the exp function */
#define PI 3.1416 before = 10.0;
int main (void) after = exp (before);
{ printf ("e to the power of %3.1lf is
double before, after, x, y, z; %5.3lf\n", before, after);
/* the ceil function */ /* the pow function */
before = -217.5; x = 9.0; y = 3.0;
after = ceil (before); z = pow (x, y);
printf ("The ceiling of %3.1lf is %3.1lf\n", printf ("%3.1lf to the power of %3.1lf is
before, after); %3.1lf\n", x, y, z);
/* the floor function */ return (0);

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
145 www.newgentech.in C LANGUAGE BY Mr.PRR

} b = a--;
/* The (-)unary operator */ printf ("After b=a--, a is now %d and b is
#include <stdio.h> %d\n", a, b);
int main (void) /* a is decremented and b gets the
{ decremented a */
int a, b, c; b = --a;
a = 10; b = 20; printf ("After b=++a, a is now %d and b
/* b is 20 so -b is -20 */ is %d\n", a, b);
b = -b + a; return (0);
/* with multiple similar unary operators, }
use parentheses */ /* The random [rand()] function */
/* do you understand why c is 30? */ #include <stdio.h>
c = -b - (-a) + -b; #include <time.h>
printf ("The value of b is %d ", b); #include <stdlib.h>
printf ("and the value of c is %d\n", c); int main (void)
return (0); {
} /* initialize random generator */
/* Increment (++) and decrement (--) srand (time(NULL));
*/ /* generate random numbers */
#include <stdio.h> printf("RAND_MAX = %d\n", RAND_MAX);
int main (void) printf ("A number between 0 and
{ RAND_MAX : %d\n", rand());
int a, b; printf ("A number between 0 and 99:
a = 5; %d\n", rand() % 100);
/* increment (++) */ printf ("A number between 0 and 9:
/* a is incremented by 1 */ %d\n", rand() % 10);
++a; printf ("A number between 1 and 6:
printf ("After ++a, a is now %d\n", a); %d\n", (rand() % 6) + 1);
/* a is once more incremented by 1 */ return (0);
a++; }
printf ("After a++, a is now %d\n", a); /* Problem: This program just
/* a is incremented but b gets the current demonstrates how to assign values
a */ to pointer variables. It serves no other
b = a++; purpose. */
printf ("After b=a++, a is now %d and b #include <stdio.h>
is %d\n", a, b); int main (void)
/* a is incremented and b gets the {
incremented a */ /* c and d are pointers to integers */
b = ++a; int a, b, *c, *d, e;
printf ("After b=++a, a is now %d and b
is %d\n", a, b); a = 10;
/* decrement (--) */ b = a * 3;
/* a is decremented by 1 */ c = &a; /* address of a goes into c
--a; */
printf ("After --a, a is now %d\n", a); d = &b; /* address of b goes into d
/* a is once more decremented by 1 */ */
a--; e = *c + *d; /* *c is a and *d is b
printf ("After a--, a is now %d\n", a); */
/* a is decremented but b gets the current *d = a;
a */ d = &a;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
146 www.newgentech.in C LANGUAGE BY Mr.PRR

*c = *d - a % b + *c; printf ("It is quite warm. \n");


printf ("Do you understand why\n"); }
printf ("a= %d, b= %d, e= %d ?\n", a, b, else
e); {
return (0); printf ("The temperature is %d degrees.
} \n", temp);
/* Problem: This is just a silly program printf ("It is quite cool. \n");
playing with pointers */ }
#include <stdio.h> return (0);
int main (void) }
{ /* The traffic light program (nested ifs)
/* a and e are integers */ */
int a, e; #include <stdio.h>
/* b is a pointer to an integer */ int main (void)
int* b; {
/* c is a pointer to a pointer to an integer char colour;
*/ /* ask user for colour */
int** c; printf ("Enter the colour of the light (R, G or
/* d is a pointer to a pointer to a pointer Y): ");
to an integer */ scanf ("%c", &colour);
int*** d; /* test if colour is red */
a = 25; /* a contains the integer 25 */ if (colour == 'r' || colour == 'R')
b = &a; /* b contains the address of a printf ("STOP! \n");
*/ else
c = &b; /* c contains the address of b */ if (colour == 'y' || colour == 'Y')
d = &c; /* d contains the address of c */ /* yellow colour test */
/* Do you understand that ***d is actually printf ("CAUTION! \n");
a? */ else
e = ***d * 2; if (colour == 'g' || colour == 'G')
printf ("%d", e); /* green colour test */
return (0); printf ("GO! \n");
} else
/* A simple if statement */ /* if not Y or G or R then invalid colour */
#include <stdio.h> printf ("INVALID COLOUR! \n");
int main (void) return (0);
{ }
int temp; /* The traffic light program (switch) */
printf ("What is the current temperature? #include <stdio.h>
"); int main (void)
scanf ("%d", &temp); {
printf ("------------------------------------ char colour;
\n"); /* ask user for colour */
/* this if statement contains a true and a printf ("Enter the colour of the light
false branch */ (R,G,Y,A): ");
/* with a compound statement in each scanf ("%c", &colour);
branch*/ /* test the alternatives */
if (temp >= 20) switch (colour)
{ {
printf ("The temperature is %d degrees. /* red light */
\n", temp); case 'R':

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
147 www.newgentech.in C LANGUAGE BY Mr.PRR

case 'r': printf ("Time = %4.1lf - %2d orbits


printf ("STOP! \n"); completed\n", time, orbit);
break; orbit = orbit + 1;
/* yellow or amber light */ }
case 'Y': /* back to Earth */
case 'y': time = time + transit;
case 'A': printf ("Time = %5.1lf - Mission
case 'a': complete.\n", time);
printf ("CAUTION! \n"); return (0);
break; }
/* green light */ /* The fuel tank program */
case 'G': #include <stdio.h>
case 'g': int main (void)
printf ("GO! \n"); {
break; double capacity, supply, pumped;
/* other colour */ /* in liters */
default: /* initialize capacity of tank */
printf ("The colour is not capacity = 5000.0;
valid.\n");
} /* ask user for initial supply already in
return (0); tank */
} printf ("Enter the the initial supply: ");
/* Mission to the Moon */ scanf ("%lf", &supply);
#include <stdio.h> /* the program loops until supply falls
int main (void){ below 10% */
double transit, period, time; while (supply > capacity * 0.10)
int n_orbits, orbit; {
/* 73 hours from Earth to Moon */ /* ask user for quantity removed or
transit = 72; delivered */
/* 1.5 hours per orbit around Moon */ printf ("\nEnter the amount
period = 1.5; delivered(+)/removed(-): ");
/* mission begins */ scanf ("%lf", &pumped);
printf ("Mission to the Moon - Times in supply = supply + pumped;
hours\n"); /* test so that you don't pump more
printf when tank is empty */
("========================== if (supply < 0.0)
==========\n"); supply = 0.0;
time = 0.0;
n_orbits = 10; /* mission is 10 orbits */ /* test so that you don't fill more when
printf ("Time - %4.1lf - Mission begins\n", tank is full */
time); if (supply > capacity)
/* we are at the moon */ supply = capacity;
time = time + transit; }
printf ("Time = %4.1lf - At the moon\n", printf ("\nSupply below 10%% (%.2lf l
time); remaining)\n", supply);
orbit = 1;
/* doing the orbits around the Moon */ return (0);
while (orbit <= n_orbits) }
{ /* Simple countdown using a for loop
time = time + period; */

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
148 www.newgentech.in C LANGUAGE BY Mr.PRR

#include <stdio.h> int main (void)


int main (void){ {
int time; FILE *birdfile;
/* the loop */ int birds, days, total, i, j;
for (time=60; time>=0; time=time-1) birdfile = fopen ("birds.txt", "r");
{ total = 0;
printf ("%d ", time); /* loop goes though all 12 months */
} for (i=1; i<=12; ++i)
printf ("\n\nLIFTOFF!\n\n"); {
return(0); /* reading the number of days of
} sightings */
/* sums and averages */ fscanf (birdfile, "%d", &days);
/* this program calculates the average /* loop varies with number of days of
of all the numbers in a file of integers sightings */
*/ for (j=1; j<=days; ++j)
#include <stdio.h> {
int main (void) /* reading the number of birds */
{ fscanf (birdfile, "%d", &birds);
int number, sum, count; total = total + birds;
double average; }
FILE *in; }
in = fopen ("numbers.data", "r"); fclose (birdfile);
/* sums and counts must always printf ("Total number of birds sighted:
be initialized to zero */ %d\n", total);
sum = 0; return(0);
count = 0; }
/* read number by number until /* Birdwatching program (EOF/file
the end of file */ input/feof) */
while (fscanf (in, "%d", &number) #include <stdio.h>
!= EOF) int main (void)
{ {
/* count and sum the FILE *birdfile;
numbers */ int birds, days, total, i, j;
sum = sum + number; birdfile = fopen ("birds.txt", "r");
count = count + 1; total = 0;
} fscanf (birdfile, "%d", &days); /* reads
fclose (in); first number in the file */
/* final report */ /* loop goes while there is data to read */
printf ("There are %d numbers in while (!(feof (birdfile)))
the file.\n", count); {
printf ("The sum of all the numbers /* loop varies with number of days of
is %d.\n", sum); sightings */
average = (double)sum / count; for (j=1; j<=days; ++j)
printf ("There average of all the {
numbers is %5.2lf.\n", average); fscanf (birdfile, "%d", &birds);
return (0); total = total + birds;
} }
/* Birdwatching program (fixed loop / /* update - reading again */
file input) */ fscanf (birdfile, "%d", &days);
#include <stdio.h> }

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
149 www.newgentech.in C LANGUAGE BY Mr.PRR

fclose (birdfile); for (j=1; j<=days; ++j)


printf ("Total number of birds sighted: {
%d\n", total); fscanf (birdfile, "%d", &birds);
return(0); total = total + birds;
} }
/* Birdwatching program (EOF/file }
input/status var) */ fclose (birdfile);
#include <stdio.h> printf ("Total number of birds sighted:
int main (void) %d\n", total);
{ return(0);
FILE *birdfile; }
int birds, days, total, i, j, status; /* Input validation loop (do-while) */
birdfile = fopen ("birds.txt", "r"); #include <stdio.h>
total = 0; int main (void)
/* initialization - reading 1st value */ {
status = fscanf (birdfile, "%d", &days); char colour;
while (status != EOF) /* loop goes while /* ask user for colour */
there is data */ do
{ {
/* loop varies with no of days of printf ("Enter the colour of the light
sightings */ (R,G,Y,A): ");
for (j=1; j<=days; ++j) scanf (" %c", &colour); /* very important
{ to leave space before %c here */
fscanf (birdfile, "%d", &birds); }while (colour!='R' && colour!='r' &&
total = total + birds; colour!='G' && colour!='g'
} && colour!='Y' && colour!='y' &&
colour!='A' && colour!='a');
/* update - reading again */ /* test the alternatives */
status = fscanf (birdfile, "%d", &days); switch (colour)
} {
fclose (birdfile); /* red light */
printf ("Total number of birds sighted: case 'R':
%d\n", total); case 'r':
return(0); printf ("STOP! \n");
} break;
/* Birdwatching program (EOF loop, no /* yellow or amber light */
status var) */ case 'Y':
#include <stdio.h> case 'y':
int main (void) case 'A':
{ case 'a':
FILE *birdfile; printf ("CAUTION! \n");
int birds, days, total, i, j; break;
birdfile = fopen ("birds.txt", "r"); /* green light */
total = 0; case 'G':
/* loop goes while there is data */ case 'g':
while (fscanf (birdfile, "%d", &days) != printf ("GO! \n");
EOF) break;
{ /* no default case necessary here */
/* loop varies with no of days of }
sightings */ return (0);

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
150 www.newgentech.in C LANGUAGE BY Mr.PRR

} /* *result in bigger2 uses the same


/* Problem: This program shows a memory cell as result in main */
function that generates two results. }
One result is returned (-), the other int main (void)
accessed from the main via an address {
(+). */ double x, y, result;
printf ("Enter a real number: ");
scanf ("%lf", &x);
printf ("Enter a real number: ");
scanf ("%lf", &y);
/* calling the function (3 arguments) */
#include <stdio.h> /* &result is the address where variable
#include <math.h> result is stored */
double quadratic (int a, int b, int c, bigger2 (x, y, &result);
double* xplus) /* printing the report */
{ printf ("The largest number is
double xminus; %f.\n", result);
xminus = (-b - sqrt (b * b-4*a *c))/(2 * return (0);
a); }
*xplus = (-b + sqrt (b *b - 4*a*c))/(2 * /* Problem: Write a function that
a); determines if a number is prime or not.
return (xminus); The function must return 1 if prime, 0 if
} not. In addition, the function must
"return" the value of one of the
int main (void) divisors. */
{ #include <stdio.h>
int a = 10, b = 40, c = 30; #include <math.h>
double xplus, xminus; /* function returns true if n is even. */
/* calling the function. the address of xplus /* it returns false if n is odd */
is sent as an argument */ int even (int n)
xminus = quadratic (a, b, c, {
&xplus); return (!(n%2));
printf ("Using +: %lf\n", xplus); }
printf ("Using -: %lf\n", xminus); /* function returns true if n is prime,
return (0); the pointer variable references the divisor
} value */
/* Problem: Write a void function that int prime2 (int n, int *divisor)
"returns" the largest value of two real {
numbers. */ int i, is_prime;
/* this function returns nothing but will /* looking for a divisor. if found, it
change the value of the variable in the is not a prime number */
calling *divisor = 0;
function's memory area */ /* eliminating even numbers
void bigger2 (double n1, double n2, except 2 */
double *result) if (even (n))
{ {
if (n1>n2) if (n==2)
*result = n1; *divisor=0;
else else
*result = n2; *divisor=2;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
151 www.newgentech.in C LANGUAGE BY Mr.PRR

} is not a prime number */


else divisor = 0;
{
if (n==1) /* eliminating even numbers except 2 */
*divisor=0; /* 1 is a prime number */ if (even (n))
else {
/* trying to divide number by 3,5,7,... */ if (n==2)
/* to find a divisor until sqrt(n) */ divisor=0;
for (i=3; i<=sqrt(n); i=i+2) else
{ divisor=1;
if (!(n%i)) }
*divisor=i; else
} {
} if (n==1)
is_prime = *divisor; divisor=0; /* 1 is a prime number
/* if there is a divisor then NOT prime */ */
return (!is_prime); else
} /* trying to divide number by 3,5,7,... */
int main (void) /* to find a divisor until sqrt(n) */
{ for (i=3; i<=sqrt(n); i=i+2)
int x, div; {
printf ("Enter a positive integer number: if (!(n%i))
"); }
scanf ("%d", &x); }
/* testing for prime and printing the /* if there is a divisor then NOT prime */
report */ return (!divisor);
if (prime2 (x, &div)) }
printf ("%d is a prime number.\n", x); /* This main program prints all prime
else numbers between 1 and 1000 */
printf ("%d not prime number. Divisible int main (void)
by %d.\n", x, div); {
return (0); int x;
} for (x=1; x<=1000; ++x)
/* Problem: Write a program that if (prime3 (x))
prints out all the prime numbers printf (" %d ", x);
between 1 and 1000. */ return (0);
#include <stdio.h> }
#include <math.h> /* Problem: Write a function that takes
/* function returns true if n is even. */ in an integer number and "returns"
/* it returns false if n is odd */ both twice the number and three times
int even (int n) the number. */
{ #include <stdio.h>
return (!(n%2)); /* double_triple function begins */
} int double_triple (int x, int *d)
/* function returns true if n is prime */ {
int int t;
prime3 (int n) *d=2*x; /* double "returned" via pointer */
{ t=3*x;
int divisor, i; return (t); /* triple returned the standard
/* looking for a divisor. if found, it way */

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
152 www.newgentech.in C LANGUAGE BY Mr.PRR

} /* the variables that will be filled by the


/* double_triple function ends */ function */
/* main program begins */ char sign;
int main(void) int whole;
{ double fraction;
int a,twice,thrice; printf ("Enter a real number: ");
a=10; scanf ("%lf", &n);
thrice = double_triple (a, &twice); /* calling the function */
printf("%d is two times %d.\n",twice,a); sign = separate (n, &whole, &fraction);
printf("%d is three times %d.\n",thrice,a); /* printing the report */
return(0); printf ("Parts of %f: \n", n);
} printf ("===============\n\n");
/* main program ends */ printf ("Sign is: %c \n", sign);
/* This function takes a real number and printf ("Whole part is %d \n", whole);
separates it */ printf ("Fraction part is %f \n", fraction);
/* into three parts: a sign (a character return (0);
value), a */ }
/* whole part (an integer) and a /* Problem: This is simple addition
fraction (double) */ reader/parser for 2 doubles. */
#include <stdio.h> #include <stdio.h>
#include <math.h> /* function to read expression */
/* the function returns the sign but the void readex (double *op1, double *op2)
pointer parameters */ {
/* will modifiy the corresponding variable char plus;
arguments in */ /* no & required in scanf because &*op1 is
/* main program the same thing as op1 */
*/ scanf ("%lf %c %lf", op1, &plus, op2);
char separate (double number, int *w, }
double *f) int main(void)
{ {
char s; double a, b, c;
double magnitude; /* the absolute value of printf ("Enter an addition expression (eg:
the number */ 4.5+3.5): ");
/* testing if positive or negative and /* the addresses of the two operands are
assignation of sign */ sent to the function */
if (number < 0) readex (&a, &b);
s = '-'; c = a + b;
else if (number == 0) printf("%lf + %lf is %lf.\n",a,b,c);
s = ' '; return(0);
else }
s = '+'; /* Problem: This program initializes an
magnitude = fabs (number); array with all cells filled with 0.0 */
*w = floor (magnitude); #include <stdio.h>
*f = magnitude - *w; int
return (s); main (void)
} {
int main (void) double x[100];
{ int i;
double n; /* the original number */ /* initializing the array with 0.0 */
for (i=0; i<100; ++i)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
153 www.newgentech.in C LANGUAGE BY Mr.PRR

x[i] = 0.0; /* computing the sum and sum of squares


/* printing the array for verification */ */
for (i=0; i<100; ++i) for (i=0; i<MAX; ++i)
printf ("%5.1lf", x[i]); {
return (0); sum = sum + x[i];
} sumsq = sumsq + x[i] *
/* Problem: This program asks the user x[i];
for a value and fills all 100 cells of an }
array with that value */ /* computing mean and standard deviation
#include <stdio.h> */
/* no size in array parameter */ mean = sum / MAX;
/* just a pointer to array in main */ sd = sqrt(sumsq / MAX - mean * mean);
void /* printing report */
fill_array (int list[], int n, int in_value) printf ("The mean is %lf. \n", mean);
{ printf ("The standard deviation is %lf. \n",
int i; sd);
for (i=0; i<n; ++i) return (0);
list[i] = in_value; }
} /* Problem: This program fills an array
from a file */
int #include <stdio.h>
main (void) int main (void)
{ {
int x[100], i, value; int numbers[10], i;
/* initializing the array with a user value */ FILE *input;
/* the 2nd argument must be the size of the input = fopen("numbers.txt", "r");
array */ /* reading file - filling array */
printf ("Enter a value: "); for (i=0; i<10; ++i)
scanf ("%d", &value); fscanf(input, "%d", &numbers[i]);
fill_array (x, 100, value);
/* printing the array for verification */
for (i=0; i<100; ++i) /* printing the content of array */
printf ("%d ", x[i]); printf("The numbers read are: ");
return (0); for (i=0; i<10; ++i)
} printf("%4d", numbers[i]);
/* This program computes the meand printf ("\n");
and standard deviations of the values fclose (input);
inside an array */ return (0);
#include <stdio.h> }
#include <math.h> /* Problem: This programs fills an
#define MAX 5 array with a value submitted by the
int main (void) user. */
{ #include <stdio.h>
double mean, sd, sum, sumsq; /* array parameter can be expressed as a
double x[] = {10.0, 15.0, 20.0, 10.0, pointer */
30.0}; /* *list is the same thing as list[] */
int i; void fill_array (int *list, int n, int in_value)
sum = 0; {
sumsq = 0; int i;
for (i=0; i<n; ++i)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
154 www.newgentech.in C LANGUAGE BY Mr.PRR

list[i] = in_value; printf ("\nThe array contains %d values ",


} actual_size);
int main (void) printf ("for a capacity of 100 cells.\n");
{ return (0);
int x[100]; }
int i; /* Problem: Add the corresponding
/* &x[0] is the address of the x[0] values from two arrays of the same
*/ size. */
/* which is the same thing as x */ #include <stdio.h>
fill_array (&x[0], 100, 5); /* the function that adds the two arrays a1
/* printing the array for verification and a2. it "returns" a3 back */
*/ void addarrays (int a1[], int a2[], int a3[],
for (i=0; i<100; ++i) int n)
printf ("%d ", x[i]); {
return (0); int i;
} /* do the adding of every corresponding
/* Problem: This program partially fills cells */
an array from a file until the end of file for (i=0; i<n; ++i)
(EOF). a3[i] = a1[i] + a2[i];
We get the actual number of data read }
*/ int main (void)
#include <stdio.h> {
int array_from_file (double a[], int size) int x[] = {1,2,3,4}, i;
{ int y[] = {10,20,30,40};
int i; int z[4];
FILE* in; /* call the function */
in = fopen ("data_array.dat", "r"); addarrays (x, y, z, 4);
i=0; /* the first cell */ /* print a report */
/* filling the array cell by cell */ for (i=0; i<4; ++i)
/* until it is full or until the EOF */ printf ("%3d", x[i]);
while (i < 100 && fscanf (in, "%lf", &a[i]) != printf ("\n + \n");
EOF) for (i=0; i<4; ++i)
{ printf ("%3d", y[i]);
i=i+1; printf ("\n-------------\n");
} for (i=0; i<4; ++i)
fclose (in); printf ("%3d", z[i]);
/* the actual number of values in the array return (0);
*/ }
return (i); /* THE BASIC SEARCH ALGORITHM FOR
} A 1-D ARRAY */
#include <stdio.h>
int search (int arraytosearch[], int
int main (void) valuetosearch, int size)
{ {
double array[100]; int i, found;
int actual_size, i;
actual_size = array_from_file (array, 100); /* initialize found at -1, if value not
for (i=0; i < actual_size; ++i) found, stays at -1 */
printf ("%3.1lf ", array[i]); found = -1;

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
155 www.newgentech.in C LANGUAGE BY Mr.PRR

/* search until found or until end of array */ printf("\n Enter a,b values:");
i = 0; scanf("%d%d",&a,&b);
while (found<0 && i<size) a=a-b;
{ b=a+b;
if (arraytosearch[i] == a=b-a;
valuetosearch) printf("\n values of a and b after
found = i; /* I have found it! */ swaping:%d \t %d",a,b);
else getch();
i = i + 1; }
} // write a program to print ASCII
return (found); number
} #include<stdio.h>
int main (void) #include<conio.h>
{ void main()
int x[] = {
{12,67,56,60,88,34,123}; int k ;
int value = 60; clrscr() ;
int pos, i; printf("\n\n");
pos = search (x, value, 7); for(k=0; k<=255; k++)
if (pos >= 0) {
printf ("%d was found at position %d.\n", printf("\t %d %c", k, k) ;
value, pos); }
else getch() ;
printf ("%d was not found in the array.\n", }
value); /* A dynamically-allocated 1-D array */
return (0);} #include <stdio.h>
// write a program to calculate int main (void)
perimeter of a circle {
#include<stdio.h> double* array; /* declare a pointer only */
#include<conio.h> int i, size;
void main() /* ask user for size of array */
{ printf ("How large do you want your array?
int r; ");
float p; scanf ("%d", &size);
clrscr(); /* allocate the array in the heap */
printf("\n Enter radius values:"); array = (double *) calloc (size,
scanf("%d",&r); sizeof(double));
p=2*3.14*r;
printf("\n Perimeter of the circle is = /* printing the array for verification
%f",p); surprise! a dynamic array is automatically
getch(); initialized with zeros! */
} for (i = 0; i < size; ++i)
// write a program to perform swaping printf ("%6.2lf", array[i]);
of two numbers without third variable /* freeing the memory allocation */
#include<stdio.h> free (array);
#include<conio.h> return (0);
void main() }
{
int a,b;
clrscr();

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
156 www.newgentech.in C LANGUAGE BY Mr.PRR

C&DS Interview Questions & Answers


1. What is an algorithm?
Ans: An algorithm is a step-by-step method of performing any task.
2. What is a flow chart?
Ans: A flowchart is a type of diagram that represents an algorithm or process, showing the steps as
boxes of various kinds, and their order by connecting these with arrows.
3. The C compiler translates source to assembly code in C Programming.
4. The assembler creates object code.
5. What are the stages of developing your C program?
Ans: There are four stages of developing C program
1. Creating the program
2. Compiling the program
3. Linking the program with functions that are needed from C Library
4. Running the program.
6. What is a C Preprocessor?
Ans: C Preprocessor is a program that processes our source program before it is passed to the
compiler.
7. What is the use of header files as used in C programming?
Ans: Header files are used to have declarations. It is simple to include a single header file than
writing all the needed functions prototypes.
8. What is the Structure of a C Program?
Ans:
1. Documentation Section.
2. Linking Section.
3. Definition Section.
4. Global declaration Section.
5. main function.
6. subprogram section.
9. Every statement in a C program must end with a Semicolon.
10. What is the use of main() function?
Ans: main() is the starting point of program execution.
11. How many main() functions can there be in a C Program?
Ans: Only one.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
157 www.newgentech.in C LANGUAGE BY Mr.PRR

12. What are Macros?


Ans: A macro is a fragment of code which has been given a name. Whenever the name is used, it is
replaced by the contents of the macro. Example: #define UPPER 25.
13. What are advantages and disadvantages of macros?
Ans: The advantage of macro is that it reduces the time taken for control transfer as in case of
Function. The disadvantage of it is here the entire code is substituted so the program becomes
Lengthy if a macro is called several times.
14. What are C Tokens?
Ans: Keywords, Identifiers, Constants, Strings, Special symbols and Operators.
15. What is a constant? What are types of Constants?
Ans: Constant is a fixed value, which never change throughout a program. There are two types of
constants: Numeric and Alpha Numeric Constants
16. What is a variable?
Ans: A variable is an identifier which is given for the memory location where we can store the data.
17. Main () function is a pre-defined function. True or False?
Ans: False.
18. What are the fundamental/Primary Data types in C?
Ans: integer (int), character (char), floating point (float) and double-precision floating point
(double).
19: What are user defined data types?
Ans: typedef and enum
20. What are the storage classes in C?
Ans: auto, static, extern and register.
21. What are the compile time operators?
Ans: only sizeof is a compile time operator.
22. What are the operators in C?
Ans: Arithmetic, Relational, Logical, Assignment, Increment and Decrement, Conditional, Bitwise,
Special
23. What are Relational Operators?
Ans: <, <=, >, >=, ==, !=
24. What are Logical Operators?
Ans: && meaning (logical AND), || meaning (logical OR) and ! meaning (logical NOT)
25. What are the special operators in C?
Ans: comma operator, sizeof operator, pointer operators (& and *) and member selection operators
(.and ->)

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
158 www.newgentech.in C LANGUAGE BY Mr.PRR

26. What is sizeof operator?


Ans: It returns the number of bytes the operand occupies.
27. What is type casting?
Ans: converting a variable of one type to another type.
28. What is the abbreviation of stdio.h?
Ans: standard input-output header file.
29. What is the format specifier for integer?
Ans: %d or %i
30. %x is a format specifier for hexadecimal integer.
31. %o is a format specifier for Octal integer.
32 What are control or decision making statements?
Ans: if, switch, conditional operator and goto statements.
33. Syntax of conditional operator?
Ans:
condition? result1: result2;
If the condition is true, result1 is returned else result2 is returned.
34. What is goto statement?
Ans: The goto statement is used for unconditional jump from one part of the program to another
part of the program.
35. What is the difference between while and do-while?
Ans: In case of while loop, the condition is first checked and then the loop is executed.
In case of do-while, the loop is first execute and then the condition is checked. Here in do-while the
loop is executed at least once irrespective of the condition.
36. Incase of for() loop, initialization is mandatory. True or false?
Ans: False.
37. Incase of for() loop, test-condition is mandatory. True or false?
Ans: True.
38. What is an array?
Ans: An array is a group of related data items that share a common name.
39: How do you declare an array?
Ans: type variable-name[size];
40. How do you initialize an array?
Ans: static type array-name [size]={list of values}
41. How do you declare a two-dimensional array?
Ans: type variable-name[row_size][column_size];

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
159 www.newgentech.in C LANGUAGE BY Mr.PRR

42. What is a string in C?


Ans: A string is a collection of characters or string is a one character array.
43. What are the string handling functions in C?
Ans: strcat()—concatenates two strings, strcmp() – compares two strings, strcpy() – copies one
string over another, strlen() – finds the length of the string.
44. What are the examples of library functions in C?
Ans: printf() ,scanf(), clrscr(), getch() and puts() etc…….
45. What is <ctype.h > used for?
Ans: Character testing and conversion functions
46. What does <stdio.h> contain?
Ans: It contains standard I/O library functions.
47. What does <stdlib.h> contain?
Ans: It contains Utility functions such as string conversion routines, memory allocation routines,
random number generator etc..
48. A main program can contain how many functions?
Ans: It can contain any number of functions.
49. What is a pointer?
Ans: A pointer is a variable, which contains the address of another variable.
50. What is NULL pointer?
Ans: A null pointer does not point to any object.
51. Explain the scope of static variables.
Ans: The scope of a static variable is local to the block in which the variable is defined.
52. C is High level Language or Low level language?
Ans: High-Level Language.
53. Who invented C?
Ans: Dennis Ritchie.
54. C follows Top down Approach.
55. C programming language is case sensitive?
Ans: Yes.
56. What is Break Statement in C?
Ans: The break statement terminates the execution of the current loop and the Control passes to
the statement that follows the terminated statement.
57. What is Continue Statement in C?
Ans: Whenever a keyword ‗continue‟ is encountered inside a loop, the control automatically passes
to the beginning of the loop.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
160 www.newgentech.in C LANGUAGE BY Mr.PRR

58. What is the difference between Break and Continue in C?


Ans: break statement is used to break any type of loop such as while, do while and for loop. Break
statement terminates the loop body immediately. Continue statement is used to break current
iteration.
After continue statement the control returns to the top of the loop test conditions.
59. What is a function?
Ans: A function is a self-contained block of statements that perform a coherent task of some kind.
60. Why use functions?
Ans: It increases the performance of the system. And it supports reusability.
61. Explain the use of fflush() function.
Ans: fflush() [returns 0 if buffer successfully deleted / returns EOF on an error] causes the system
to empty the buffer associated with the specified output stream.
62. Explain the difference between strcpy() and memcpy() function.
Ans: strcpy() copies a string until it comes across the termination character ‗\0‘. With memcopy(),
the programmer needs to specify the size of data to be copied.
63. Explain the difference between exit() and _exit() function.
Ans: exit() does cleanup work like closing file descriptor, file stream and so on, while _exit() does
not.
64. What are volatile variables?
Volatile variables are like other variables except that the values might be changed at any given
point of time only by ‗some external resources‘.
65. Define recursion in C.
Ans: A programming technique in which a function may call itself.
66. What does static variable mean in C?
Ans: static is an access qualifier that limits the scope but causes the variable to exist for the lifetime
of the program.
67. What is difference between call by value and call by reference in
Ans: In call by value the value to function interchange is passed by value. And in call by
reference the address is passed by using symbol ‗&‘ and the value is accessed by using
symbol ‗*‘.
68. What are the auto variables? Where are they stored?
Ans: The auto variables are stored in the memory of the system. The keyword ‗auto‘ is optional.
Many of the variables used by the program / application are ‗auto‘ variables, being the main
memory is faster. These variables are stored in the memory runtime stack.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
161 www.newgentech.in C LANGUAGE BY Mr.PRR

69. List out differences between arrays and linked list


Ans: The difference between arrays and linked lists are:
 Arrays are linear data structures. Linked lists are linear and non-linear data structures.
 Linked lists are linear for accessing, and non-linear for storing in memory
 Array has homogenous values. And each element is independent of each other positions.
Each node in the linked list is connected with its previous node which is a pointer to the
node.
 Array elements can be modified easily by identifying the index value. It is a complex process
for modifying the node in a linked list.
 Array elements cannot be added, deleted once it is declared. The nodes in the linked list can
be added and deleted from the list.
70. Explain the term enumerations in C
Ans: A set of named integer constants is known as an enumeration. The enumeration type
declaration includes the name of the enumeration tag and the definition of a set of named integers.
Ex: enum CITY {Mumbai, Bangalore, Chennai, New Delhi} metros;
71. Define register variables. What are the advantages of using register variables?
Ans: The variables of ‗register‘ type modifier will inform the compiler for storing the variables in a
register of CPU.
The advantage of this type modifier is the access optimization and speed of program execution. The
operations of these variables are faster by orders of magnitude.
72. What is the use of typedef?
Ans: The keyword typedef is used for defining user defined data types.
73. How to create user defined datatypes?
Ans: by using the keyword ―typedef‖
Syntax: typedef type identifier;
Example: typedef int units;
74. In header files whether functions are declared or defined?
Ans: Functions are declared within header file. That is function prototypes exist in a header file, not
function bodies. They are defined in library (lib).
75. What is static memory allocation?
Ans: Static Memory Allocation: Memory is allocated for the declared variable by the compiler.
76. What is dynamic memory allocation?
Ans: Dynamic Memory Allocation: Allocation of memory at the time of execution (run time) is
known as dynamic memory allocation.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
162 www.newgentech.in C LANGUAGE BY Mr.PRR

76.What functions are used to create dynamic memory allocation?


Ans: calloc() and malloc()
77. What is the difference between malloc() and calloc()?
Ans: malloc() is a one argument function while calloc() is two argument function. malloc() take
garbage value at initial time while calloc() take null values at initial time.
78. What is the purpose of main( ) function?
Ans: The function main() calls / invokes other functions within it. The execution of the program
always starts with main() function.
79. What is the difference between a string and an array?
The following are the differences:
 String can hold only char data. Whereas an array can hold any data type.
 An array size cannot be changed. Whereas a string size can be changed if it is a char pointer
 The last element of an array is an element of the specific type. The last character of a string
is a null – ‗\0‘ character.
 The length of an array is to specified in [ ] at the time of declaration (except char[ ]). The
length of the string is the number of characters + one (null character).
80. Difference between array and pointer?
Ans:
Array
1- Array allocates space automatically
2- It cannot be resized
3- It cannot be reassigned
4- sizeof (arrayname) gives the number of bytes occupied by the array.
Pointer
1- Explicitly assigned to point to an allocated space.
2-It can be sized using realloc()
3-pointer can be reassigned.
4-sizeof (p) returns the number of bytes used to store the pointer variable p
81. What will be printed as the result of the operation below?
main()
{
int x=10, y=15;
x = x++;
y = ++y;
printf(%d %d\n‖,x,y);
OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
163 www.newgentech.in C LANGUAGE BY Mr.PRR

}
Ans: 11, 16
82. What will be the result of the following code?
#define TRUE 0 // some code
while(TRUE)
{
// some code
}
Ans: This will not go into the loop as TRUE is defined as 0
83. What are the uses of a pointer?
Ans: Pointer is used in the following cases
i) It is used to access array elements
ii) It is used for dynamic memory allocation.
iii) It is used in Call by reference
iv) It is used in data structures like trees, graph, linked list etc.
84. What is a structure?
Ans: Structure constitutes a super data type which represents several different data types in a
single unit. A structure can be initialized if it is static or global.
85. What is a union?
Ans: Union is a collection of heterogeneous data type but it uses efficient memory utilization
technique by allocating enough memory to hold the largest member. Here a single area of memory
contains values of different types at different time. A union can never be initialized.
86. What are the differences between structures and union?
Ans: A structure variable contains each of the named members, and its size is large enough to hold
all the members. Structure elements are of same size.
A union contains one of the named members at a given time and is large enough to hold the largest
member. Union element can be of different sizes.
87. What are the differences between structures and arrays?
Ans: Structure is a collection of heterogeneous data type but array is a collection of homogeneous
data types.
Array
1-It is a collection of data items of same data type.
2-It has declaration only
3-.There is no keyword.
4- array name represent the address of the starting element.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
164 www.newgentech.in C LANGUAGE BY Mr.PRR

Structure
1-It is a collection of data items of different data type.
2- It has declaration and definition
3- keyword struct is used
4-Structure name is known as tag it is the short hand notation of the declaration.
88. What are enumerations?
Ans: They are a list of named integer-valued constants.
Example:
enum color { black , orange=4,yellow, green, blue, violet };
This declaration defines the symbols ―black‖, ―orange‖, ―yellow‖, etc. to have the values ―1,‖ ―4,‖ ―5,‖
… etc. The difference between an enumeration and a macro is that the enum actually declares a
type, and therefore can be type checked.
89. Out of fgets() and gets() which function is safe to use and why?
Ans: fgets() is safer than gets(), because we can specify a maximum input length. Neither one is
Completely safe, because the compiler can‘t prove that programmer won‘t overflow the buffer he
pass to fgets ().
90. Differentiate between for loop and a while loop? What are it uses?
Ans: For executing a set of statements fixed number of times we use for loop while when the
number of iterations to be performed is not known in advance we use while loop.
91. What the advantages of using Unions?
Ans: When the C compiler is allocating memory for unions it will always reserve enough room for
the largest member.
92. What is the difference between Strings and Arrays?
Ans: String is a sequence of characters ending with NULL .it can be treated as a one dimensional
array of characters terminated by a NULL character.
93. What is a far pointer? Where we use it?
Ans: In large data model (compact, large, huge) the address B0008000 is acceptable because in
these model all pointers to data are 32bits long. If we use small data model(tiny, small, medium) the
above address won‘t work since in these model each pointer is 16bits long. If we are working in a
small data model and want to access the address B0008000 then we use far pointer. Far pointer is
always treated as a 32bit pointer and contains a segment address and offset address both of 16bits
each. Thus the address is represented using segment: offset format B000h:8000h. For any given
memory address there are many possible far address segment: offset pair. The segment register
contains the address where the segment begins and offset register contains the offset of data/code
from where segment begins.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
165 www.newgentech.in C LANGUAGE BY Mr.PRR

94. What is a huge pointer?


Ans: Huge pointer is 32bit long containing segment address and offset address. Huge pointers are
normalized pointers so for any given memory address there is only one possible huge address
segment: offset pair. Huge pointer arithmetic is doe with calls to special subroutines so its
arithmetic slower than any other pointers.
95. What is a normalized pointer, how do we normalize a pointer?
Ans: It is a 32bit pointer, which has as much of its value in the segment register as possible. Since a
segment can start every 16bytes so the offset will have a value from 0 to F. for normalization
convert the address into 20bit address then use the 16bit for segment address and 4bit for the offset
address. Given a pointer 500D: 9407,we convert it to a 20bitabsolute address 549D7,Which then
normalized to 549D:0007.
96. What is near pointer?
Ans: A near pointer is 16 bits long. It uses the current content of the CS (code segment) register (if
the pointer is pointing to code) or current contents of DS (data segment) register (if the pointer is
pointing to data) for the segment part, the offset part is stored in a 16 bit near pointer. Using near
pointer limits the data/code to 64kb segment.
97. In C, why is the void pointer useful? When would you use it?
Ans: The void pointer is useful because it is a generic pointer that any pointer can be cast into and
back again without loss of information.
98. What is a NULL Pointer? Whether it is same as an uninitialized pointer?
Ans: Null pointer is a pointer which points to nothing but uninitialized pointer may point to
anywhere.
99. Are pointers integer?
Ans: No, pointers are not integers. A pointer is an address. It is a positive number.
100. Can a Structure contain a Pointer to itself?
Ans: Yes such structures are called self-referential structures.
101. . What do the „c‟ and „v‟ in argc and argv stand for?
Ans: The c in argc(argument count) stands for the number of command line argument the program
is invoked with and v in argv(argument vector) is a pointer to an array of character string that
contain the arguments.
102. Difference between syntax vs logical error?
Ans:
Syntax Error
1-These involves validation of syntax of language.
2-compiler prints diagnostic message.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
166 www.newgentech.in C LANGUAGE BY Mr.PRR

Logical Error
1-logical error are caused by an incorrect algorithm or by a statement mistyped in such a way
that it doesn‘t violet syntax of language.
2-difficult to find.
103. What is pre-increment and post-increment?
Ans: ++n (pre increment) increments n before its value is used in an assignment operation or any
expression containing it. n++ (post increment) does increment after the value of n is used.
104. What is a file?
Ans: A file is a region of storage in hard disks or in auxiliary storage devices.It contains bytes of
information .It is not a data type.
105. What are the types of file?
Ans: Files are of two types
1-high level files (stream oriented files) :These files are accessed using library functions
2-low level files(system oriented files) :These files are accessed using system calls
106. What is FILE?
Ans: FILE is a predefined data type. It is defined in stdio.h file.
107. What is a file pointer?
Ans: The pointer to a FILE data type is called as a stream pointer or a file pointer. A file pointer
points to the block of information of the stream that had just been opened.
108. Difference between an array of pointers and a pointer to an array?
Ans:
Array of pointers
1- Declaration is: data_type *array_name[size];
2-Size represents the row size.
3- The space for columns may be dynamically
Pointers to an array
1-Declaration is data_type ( *array_name)[size];
2-Size represents the column size.
109. Are the variables argc and argv are always local to main?
Ans: Yes they are local to main.
110. Can main () be called recursively?
Ans: Yes any function including main () can be called recursively.
111. What is a Data structure?
Ans: Data structure is a collection of organized data that are related to each other. Data structures
can be classified into two types:

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
167 www.newgentech.in C LANGUAGE BY Mr.PRR

1. Linear data structure.


2. Non linear data structure.
112. What are the goals of Data Structure?
Ans: It must rich be enough in structure to reflect the actual relationship of data in real world.
The structure should be simple enough for efficient processing of data.
113. What are linear data structures?
Ans: Arrays and Linked lists.
114. What are non linear data structures?
Ans: Trees and Graphs.
115. What does abstract Data Type Mean?
Ans: Data type is a collection of values and a set of operations on these values. Abstract data type
refer to the mathematical concept that define the data type.
It is a useful tool for specifying the logical properties of a data type.
ADT consists of two parts
1) Values definition
2) Operation definition
Example:-The value definition for the ADT RATIONAL states that RATIONAL value consists of
two
integers, second doesn‘t equal to zero.
The operator definition for ADT RATIONAL includes the operation of creation (make rational)
addition, multiplication and test for equality.
116. What is a stack?
Ans: A stack is a linear data structure in which item is inserted and deleted at one end. A stack is
called a Last in First out (LIFO) structure because the data item is inserted into the stack is the
first data item to be deleted from the stack.
117. What is the difference between a Stack and an Array?
Ans: STACK
i) Stack is a ordered collection of items
ii) Stack is a dynamic object whose size is constantly changing as items are pushed and popped .
iii) Stack may contain different data types
iv) Stack is declared as a structure containing an array to hold the element of the stack, and an
integer to indicate the current stack top within the array.
ARRAY
i) Array is an ordered collection of items
ii) Array is a static object i.e. no of item is fixed and is assigned by the declaration of the array

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
168 www.newgentech.in C LANGUAGE BY Mr.PRR

iii) It contains same data types.


iv) Array can be home of a stack i.e. array can be declared large enough for maximum size of the
stack.
118. What are the operations of stack?
Ans: Push and Pop.
119. What is a Queue?
Ans: A queue is an ordered collection of items from which items may be deleted at one end (front
end) and items inserted at the other end (rear end).
It obeys FIFO rule there is no limit to the number of elements a queue contains.
120. What do you mean by recursive definition?
Ans: The definition which defines an object in terms of simpler cases of itself is called recursive
definition.
121. What is sequential search?
Ans: In sequential search each item in the array is compared with the item being searched until a
match occurs. It is applicable to a table organized either as an array or as a linked list.
122. What actions are performed when a function is called?
Ans: When a function is called
i) arguments are passed
ii) local variables are allocated and initialized
ii) transferring control to the function.
123. What actions are performed when a function returns?
Ans:
i) Return address is retrieved
ii) Function‘s data area is freed
iii) Branch is taken to the return address.
124. What is a linked list?
Ans: A linked list is a linear collection of data elements, called nodes, where the linear order is
given by pointers. Each node has two parts first part contain the information of the element second
part contains the address of the next node in the list.
125. What are the advantages of linked list over array (static data structure)?
Ans:
The disadvantages of array are
i) unlike linked list it is expensive to insert and delete elements in the array
ii) One can‘t double or triple the size of array as it occupies block of memory space.In linked list

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
169 www.newgentech.in C LANGUAGE BY Mr.PRR

i) each element in list contains a field, called a link or pointer which contains the address of the next
element
ii) Successive element‘s need not occupy adjacent space in memory.
126. What is the pre-requisite of binary search?
Ans: The elements should be in sorted order.
127. Can we apply binary search algorithm to a sorted linked list, why?
Ans: No we cannot apply binary search algorithm to a sorted linked list, since there is no way of
indexing the middle element in the list. This is the drawback in using linked list as a data structure.
128. What do you mean by free pool?
Ans: Pool is a list consisting of unused memory cells which has its own pointer.
129. What do you mean by garbage collection?
Ans: It is a technique in which the operating system periodically collects all the deleted space onto
the free storage list.
It takes place when there is minimum amount of space left in storage list or when CPU is ideal.
The alternate method to this is to immediately reinsert the space into free storage list which is time
consuming.
130. What do you mean by overflow and underflow?
Ans: When new data is to be inserted into the data structure but there is no available space i.e. free
storage list is empty this situation is called overflow.
When we want to delete data from a data structure that is empty this situation is called underflow.
131. What are the disadvantages array implementations of linked list?
Ans:
i) The no of nodes needed can‘t be predicted when the program is written.
ii) The no of nodes declared must remain allocated throughout its execution.
132. What is a priority queue?
Ans: The priority queue is a data structure in which the intrinsic ordering of the elements (numeric
or alphabetic).
Determines the result of its basic operation. It is of two types
i) Ascending priority queue- Here smallest item can be removed (insertion is arbitrary)
ii) Descending priority queue- Here largest item can be removed (insertion is arbitrary)
133. What are the disadvantages of sequential storage?
Ans:
i) Fixed amount of storage remains allocated to the data structure even if it contains less element.
ii) No more than fixed amount of storage is allocated causing overflow.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
170 www.newgentech.in C LANGUAGE BY Mr.PRR

134. What are the disadvantages of representing a stack or queue by a linked list?
Ans:
i) A node in a linked list (info and next field) occupies more storage than a corresponding element
in an array.
ii) Additional time spent in managing the available list.
135. What is dangling pointer and how to avoid it?
Ans: After a call to free(p) makes a subsequent reference to *p illegal, i.e. though the storage top is
freed but the value of p(address) remain unchanged .so the object at that address may be used as the
value of *p (i.e. there is no way to detect the illegality).Here p is called dangling pointer.
To avoid this it is better to set p to NULL after executing free(p).The null pointer value doesn‘t
reference a storage location it is a pointer that doesn‘t point to anything.
136. What are the disadvantages of linear list?
Ans:
i) We cannot reach any of the nodes that precede node (p)
ii) If a list is traversed, the external pointer to the list must be persevered in order to reference the
list again.
137. Define circular list?
Ans: In linear list the next field of the last node contain a null pointer, when a next field in the last
node contain a pointer back to the first node it is called circular list.
Advantages – From any point in the list it is possible to reach at any other point.
138. What are the disadvantages of circular list?
Ans:
i) We can‘t traverse the list backward
ii) If a pointer to a node is given we cannot delete the node.
139. Define double linked list?
Ans: It is a collection of data elements called nodes, where each node is divided into three parts
i) An info field that contains the information stored in the node
ii) Left field that contain pointer to node on left side
iii) Right field that contain pointer to node on right side.
140. Is it necessary to sort a file before searching a particular item ?
Ans:
If less work is involved in searching a element than to sort and then extract, then we don‘t go for
sort If frequent use of the file is required for the purpose of retrieving specific element, it is more
efficient to sort the file.
Thus it depends on situation.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
171 www.newgentech.in C LANGUAGE BY Mr.PRR

141. What are the issues that hamper the efficiency in sorting a file?
Ans: The issues are
i) Length of time required by the programmer in coding a particular sorting program
ii) Amount of machine time necessary for running the particular program
iii) the amount of space necessary for the particular program.
142. Calculate the efficiency of sequential search?
Ans: The number of comparisons depends on where the record with the argument key appears in
the table
If it appears at first position then one comparison
If it appears at last position then n comparisons
Average=(n+1)/2 comparisons
Unsuccessful search n comparisons
Number of comparisons in any case is O (n).
143. Parenthesis is never required in Postfix or Prefix expressions, why?
Ans: Parenthesis is not required because the order of the operators in the postfix /prefix
expressions determines the actual order of operations in evaluating the expression.
144. List out the areas in which data structures are applied extensively?
Ans: Compiler Design, Operating System, Database Management System, Statistical analysis
package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation.
145. What are the major data structures used in the following areas: network data model &
Hierarchical data model.
Ans:
RDBMS – Array (i.e. Array of structures)
Network data model – Graph
Hierarchical data model – Trees
146. If you are using C language to implement the heterogeneous linked list, what pointer
type will
you use?
Ans: The heterogeneous linked list contains different data types in its nodes and we need a link,
pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void
pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.
147. Minimum number of queues needed to implement the priority queue?
Ans: Two. One queue is used for actual storing of data and another for storing priorities.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
172 www.newgentech.in C LANGUAGE BY Mr.PRR

148. What is the data structures used to perform recursion?


Ans: Stack. Because of its LIFO (Last In First Out) property it remembers its ‗caller‘ so knows
whom to return when the function has to return. Recursion makes use of system stack for storing
the return addresses of the function calls.
Every recursive function has its equivalent iterative (non-recursive) function. Even when such
equivalent iterative procedures are written, explicit stack is to be used.
149. What are the notations used in Evaluation of Arithmetic Expressions using prefix and
postfix forms?
Ans: Polish and Reverse Polish notations.
150. Convert the expression ((A + B) * C – (D – E) ^ (F + G)) to equivalent Prefix and
Postfix notations.
Ans: Prefix Notation:
^ – * +ABC – DE + FG
Postfix Notation:
AB + C * DE – – FG + ^
151. Sorting is not possible by using which of the following methods?
(a) Insertion
(b) Selection
(c) Exchange
(d) Deletion
Ans: (d) Deletion.
Using insertion we can perform insertion sort, using selection we can perform selection sort, using
exchange we can perform the bubble sort (and other similar sorting methods). But no sorting
method can be done just using deletion.
152. List out few of the Application of tree data-structure?
Ans:
The manipulation of Arithmetic expression,
Symbol Table construction,
Syntax analysis.
153. List out few of the applications that make use of Multilinked Structures?
Ans: Sparse matrix, Index generation.
154. in tree construction which is the suitable efficient data structure?
(A) Array (b) Linked list (c) Stack (d) Queue (e) none
Ans: (b) Linked list

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
173 www.newgentech.in C LANGUAGE BY Mr.PRR

155. What is the type of the algorithm used in solving the 8 Queens problem?
Ans: Backtracking
156. In an AVL tree, at what condition the balancing is to be done?
Ans: If the ‗pivotal value‘ (or the ‗Height factor‘) is greater than 1 or less than –1.
157. There are 8, 15, 13, 14 nodes were there in 4 different trees. Which of them could have
formed a
full binary tree?
Ans: 15
In general:
There are 2n-1 nodes in a full binary tree.
By the method of elimination:
Full binary trees contain odd number of nodes. So there cannot be full binary trees with 8 or 14
nodes, so rejected. With 13 nodes you can form a complete binary tree but not a full binary tree. So
the correct answer is 15.
Note: Full and Complete binary trees are different. All full binary trees are complete binary trees
but not vice versa.
158. In RDBMS, what is the efficient data structure used in the internal storage
representation?
Ans: B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching
easier.
This corresponds to the records that shall be stored in leaf nodes.
159. What is a spanning Tree?
Ans: A spanning tree is a tree associated with a network. All the nodes of the graph appear on the
tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight
between nodes is minimized.
160. Does the minimum spanning tree of a graph give the shortest distance between any 2
specified
nodes?
Ans: No.
Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it
doesn‘t mean that the distance between any two nodes involved in the minimum-spanning tree is
minimum.
161. What are the memory allocation functions in C?
Ans: Malloc: Allocates required size of bytes and returns a pointer to the first byte of the allocated
space.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
174 www.newgentech.in C LANGUAGE BY Mr.PRR

Calloc: Allocates space for an array of elements, initializes them to zero and then returns a pointer
to the memory.
free: Frees previously allocated space.
Realloc: Modifies the size of previously allocated space.
162. Local variables are stored in Stack area.
163. The free memory region is called the HEAP.
164. Malloc() returns a pointer.
165. What is the general form/syntax of malloc?
Ans: ptr=(cast-type*)malloc(byte-size);
166. What is the general form/syntax of calloc?
Ans: ptr=(cast-type*)malloc(n, elem-size);
167. What is the use of free() function?
Ans: It is used to release a block of memory which was earlier used to store some data.
168. What is a node?
Ans: A node is an abstract basic unit used to build linked data structures such as trees, linked lists.
169. What does a node contain?
Ans: A node contains two fields, one containing the item and the other containing the address of the
next item.
170. What is self-referential structure?
Ans: A structure which contains a member field that points to the same structure type is called self-
referential structure.
Ex: struct node
{
Int item;
Struct node *next;
};
171. What are the advantages of Linked List?
Ans: A linked list is a dynamic data structure and therefore the size of the linked list can grow or
shrink in size during execution of the program.
A linked list does not require any extra space therefore it does not waste extra memory.
It provides flexibility in rearranging the items efficiently.
172. What are the types of Linked Lists?
Ans: There are different kinds of linked lists they are:
Linear singly linked list
Circular singly linked list

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
175 www.newgentech.in C LANGUAGE BY Mr.PRR

Two way or doubly linked list


Circular doubly linked list.
173. What is singly linked list?
Ans: The singly-linked list is the most basic of all the linked data structures. A singly-linked list is
simply a sequence of dynamically allocated objects, each of which refers to its successor in the list.
174. What is doubly linked list?
Ans: A doubly linked list, also known as two-way linked list, consists of data as well as links to
the next item, as well as the previous item. In DLL each item has two links or pointers: one link
points to the next item in the list, whereas the second link points back to the previous item in the
list.
175. What are the operations of double linked list?
Ans:
Inserting an item
Deleting an item
Displaying all the items in the list
Searching for an item in the list
176. What does the right link of the last node in a doubly linked list point to?
Ans: It points to a null value.
177. A linked list is a dynamic data structure. True or false?
178. What does the left link of the first node in a doubly linked list point to?
Ans: It points to a null value.
179. What is circular double linked list?
Ans: A circular, doubly-linked list is a circular list is formed by making use of variables which
would otherwise be null: The last element of the list is made the predecessor of the first element;
the first element, the successor of the last.
180. What are the applications of linked list?
Ans: 1.Sparse matrix representation
2. Polynomial manipulation
3. Dyanamic memory storage
4. in symbol table
181. What is a tree?
Ans: A tree consists of one or more nodes (vertex) which are connected by branches (edges). Each
node can have key and associated information.
182. What is Binary tree?
Ans: A Binary tree is a tree in which each node can have at most two children, left and right child.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
176 www.newgentech.in C LANGUAGE BY Mr.PRR

183. What is the order of binary tree?


Ans: Two
184. What is Full Binary tree?
Ans: A full Binary tree is a Binary tree in which all the leaf nodes are terminated at the same level
and all the non-leaf nodes should have exactly two children.
185. What is complete Binary tree?
Ans:
1. A complete Binary tree is a binary tree in which all the leaf nodes be on level n or n-1
2. Every node on level 1 to n-1 should have exactly two children.
3. A right child should not be added before adding left child.
186. What are the different Binary tree traversal methods?
Ans: In-order tree traversal, Pre-order tree traversal and post order tree traversal.
187. What is In-order tree traversal?
Ans: In this type, the left sub-tree is traversed first, followed by the root, and finally by the right
sub tree.
188. What is Pre-order tree traversal?
Ans: In this traversal, the root is visited first, followed by the left sub-tree, followed by the right
subtree.
189. What is Post-order tree traversal?
Ans: In this traversal, the left sub-tree is traversed first, followed by the right sub-tree, followed by
the node.
190. What is a graph?
Ans: A graph is a set of nodes (also known as vertices) and a set of arcs (also known as edges).
191. What is sorting?
Ans: Sorting means rearranging a given list of elements in an orderly manner.
192. Mention the different types of sorting techniques.
Ans:
1. Bubble sort 4. Merge sort
2. Insertion sort 5. Quick sort
3. Selection sort 6. Heap sort etc..
193. Quick sort employees Divide and conquer technique.
194. Briefly explain Bubble sort.
Ans: This method takes two elements at a time. It compares these two elements. If the first element
is less than the second element, then they are left undisturbed. If the first element is greater than

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com
177 www.newgentech.in C LANGUAGE BY Mr.PRR

the second element, they are swapped. This procedure continues with the next two elements, goes
on and ends when all the elements are sorted.
195. What is the order of bubble sort?
Ans: O (n2)
196. What is the average case of quick sort is?
Ans: O (nlogn)
197. Briefly explain Selection sort.
Ans: In this, the first element in the list is selected. It is compared repeatedly with all the elements.
If any element is found to be lesser than the selected element, these two are swapped. This
procedure is repeated till the entire array is sorted.
198. What is the best case performance of selection sort?
Ans: O(n2)
199. What is merge sort?
Ans: The merge sort technique sorts a given set if values by combining two sorted arrays into one
larger sorted array.
200. What is binary search?
Ans: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly
check until the value is found or the interval is empty.

OPP BSNL OFFICE , BESIDE GOVT HIGH SCHOOL, L B NAGAR RING ROAD, L B NAGAR
PH: 9848293727, 040 6460 8727 www.newgentech.in Email: ngcomputershyd@gmail.com

Potrebbero piacerti anche