Documente Academic
Documente Profesional
Documente Cultură
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.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
\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
\? Question Mark
\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
2. User defined
3. Derived
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 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)
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
char
%c Character
unsigned char
short
unsigned short
%d Signed Integer
int
long
float
%e or %E Scientific notation of float values
double
float
%g or %G Similar as %e or %E
double
short
unsigned short
%i Signed Integer
int
long
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
unsigned int
%lu Unsigned integer
unsigned long
short
unsigned short
%o Octal representation of Integer. int
unsigned int
long
%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
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
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
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)
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
#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
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).
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
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
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
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
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
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
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
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
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
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
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); }
}
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
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
} 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
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.
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
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
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
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
Fun1() Fun2()
{ Values of arguments {
….. …..
….. …
No return 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
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
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.
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
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
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
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
Function Description
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
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
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
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
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
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,
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 cellsx[0] x[1] x[2] x[3] x[4] x[5] x[6]
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
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
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
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
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
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
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
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
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
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.
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.
fgetc(ch, fp) Reads character from current position and advances the pointer
to next 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
131 www.newgentech.in C LANGUAGE BY Mr.PRR
fflush() Clears buffer of input stream and writes buffer of output stream.
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
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
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
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
Compilers Interpreters
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
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
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
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
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
/* 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
}
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
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
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
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
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
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
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