Sunteți pe pagina 1din 127

ALGORITHM

An algorithm is any set of detailed instructions which results in a predictable end-


state from a known beginning. Algorithms are only as good as the instructions
given, however, and the result will be incorrect if the algorithm is not properly
defined.
To make a computer do anything, you have to write a computer program. To
write a computer program, you have to tell the computer, step by step, exactly
what you want it to do. The computer then "executes" the program, following
each step mechanically, to accomplish the end goal.
When you are telling the computer what to do, you also get to choose how it's
going to do it. That's where computer algorithms come in. The algorithm is the
basic technique used to get the job done. Let's follow an example to help get an
understanding of the algorithm concept.
Let's say that you have a friend arriving at the airport, and your friend needs to
get from the airport to your house. Here are four different algorithms that you
might give your friend for getting to your home:
The taxi algorithm:
Go to the taxi stand.
Get in a taxi.
Give the driver my address.
The call-me algorithm:
When your plane arrives, call my cell phone.
Meet me outside baggage claim.
The rent-a-car algorithm:
Take the shuttle to the rental car place.
Rent a car.
Follow the directions to get to my house.
The bus algorithm:
Outside baggage claim, catch bus number 70.
Transfer to bus 14 on Main Street.
Get off on Elm street.
Walk two blocks north to my house.
All four of these algorithms accomplish exactly the same goal, but each algorithm
does it in completely different way.
Each algorithm also has a different cost and a different travel time. Taking a taxi,
for example, is probably the fastest way, but also the most expensive. Taking the
bus is definitely less expensive, but a whole lot slower. You choose the algorithm
based on the circumstances.
n computer programming, there are often many different ways -- algorithms -- to
accomplish any given task. Each algorithm has advantages and disadvantages in
different situations.
PSE!O"O!E
An outline of a program, written in a form that can easily be converted into real
programming statements .
For example, the pseudocode
f student's grade is greater than or equal to 60
Print "passed"
else
Print "failed"
-----------------------------------------------
initialize passes to zero
initialize failures to zero
initialize student to one
while student counter is less than or equal to ten
input the next exam result
if the student passed
add one to passes
else
add one to failures
add one to student counter
print the number of passes
print the number of failures
if eight or more students passed
print "raise tuition"
------------------------------------------------
Some #e$%or&s that shoul& be use&
For looping and selection, The keywords that are to be used include Do
While...EndDo; Do Until...Enddo; Case...EndCase; f...Endif; Call ... with
(parameters); Call; Return ....; Return; When; Always use scope terminators for
loops and iteration.
As verbs, use the words Generate, Compute, Process, etc. Words such as set,
reset, increment, compute, calculate, add, sum, multiply, ... print, display, input,
output, edit, test , etc. with careful indentation tend to foster desirable
pseudocode.
Do not include data declarations in your pseudocode.
Pseudocode (pronounced SOO-doh-kohd) is a detailed yet readable description
of what a computer program or algorithm must do, expressed in a formally-styled
natural language rather than in a programming language. Pseudocode is
sometimes used as a detailed step in the process of developing a program. t
allows designers or lead programmers to express the design in great detail and
provides programmers a detailed template for the next step of writing code in a
specific programming language.
Pseudocode cannot be compiled nor executed, and there are no real formatting
or syntax rules. t is simply one step - an important one - in producing the final
code. The benefit of pseudocode is that it enables the programmer to
concentrate on the algorithms without worrying about all the syntactic details of a
particular programming language. n fact, you can write pseudocode without
even knowing what programming language
Because pseudocode is detailed yet readable, it can be inspected by the team of
designers and programmers as a way to ensure that actual programming is likely
to match design specifications. Catching errors at the pseudocode stage is less
costly than catching them later in the development process. Once the
pseudocode is accepted, it is rewritten using the vocabulary and syntax of a
programming language.
'LO("HART
The flowchart is a means of visually presenting the flow of data through an
information processing systems, the operations performed within the system and
the sequence in which they are performed.
The program flowchart can be likened to the blueprint of a building. As we know
a designer draws a blueprint before starting construction on a building. Similarly,
a programmer prefers to draw a flowchart prior to writing a computer program. As
in the case of the drawing of a blueprint, the flowchart is drawn according to
defined rules and using standard flowchart symbols
A flowchart is a diagrammatic representation that illustrates the sequence of
operations to be performed to get the solution of a problem. Flowcharts are
generally drawn in the early stages of formulating computer solutions. Flowcharts
facilitate communication between programmers and business people. These
flowcharts play a vital role in the programming of a problem and are quite helpful
in understanding the logic of complicated and lengthy problems. Once the
flowchart is drawn, it becomes easy to write the program in any high level
language. Often we see how flowcharts are helpful in explaining the program to
others. Hence, it is correct to say that a flowchart is a must for the better
documentation of a complex program.
Flowcharts are usually drawn using some standard symbols; however, some
special symbols can also be developed when required. Some standard symbols,
which are frequently required for flowcharting many computer programs are
shown in Fig. 25.1
Start or end of the program
Computational steps or processing function of a program
nput or output operation
Decision making and branching
Connector or joining of two parts of program
Magnetic Tape
Magnetic Disk
Off-page connector
Flow line
Annotation
Display
The following are some guidelines in flowcharting:
a. n drawing a proper flowchart, all necessary requirements should be listed
out in logical order.
b. The flowchart should be clear, neat and easy to follow. There should not
be any room for ambiguity in understanding the flowchart.
c. The usual direction of the flow of a procedure or system is from left to right
or top to bottom.
d. Only one flow line should come out from a process symbol.
or
e. Only one flow line should enter a decision symbol, but two or three flow
lines, one for each possible answer, should leave the decision symbol.

f. Only one flow line is used in conjunction with terminal symbol.

g. Write within standard symbols briefly. As necessary, you can use the
annotation symbol to describe data or computational steps more clearly.
h. f the flowchart becomes complex, it is better to use connector symbols to
reduce the number of flow lines. Avoid the intersection of flow lines if you
want to make it more effective and better way of communication.
i. Ensure that the flowchart has a logical start and finish.
j. t is useful to test the validity of the flowchart by passing through it with a
simple test data.
A!)A*TAGES O' SI*G 'LO("HARTS
The benefits of flowcharts are as follows:
1. Communication: Flowcharts are better way of communicating the logic of
a system to all concerned.
2. Effective analysis: With the help of flowchart, problem can be analysed in
more effective way.
3. Proper documentation: Program flowcharts serve as a good program
documentation, which is needed for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program
becomes easy with the help of flowchart. t helps the programmer to put
efforts more efficiently on that part
LIMITATIO*S O' SI*G 'LO("HARTS
1. Complex logic: Sometimes, the program logic is quite complicated. n that
case, flowchart becomes complex and clumsy.
2. Alterations and Modifications: f alterations are required the flowchart may
require re-drawing completely.
3. Reproduction: As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
4. The essentials of what is done can easily be lost in the technical details of
how it is done.
Examples+
!ra% a ,lo%chart to ,in& the sum o, ,irst -. natural numbers/
!ra% a ,lo%chart to ,in& the largest o, three numbers A010 an& "/
Example 2
!ra% a ,lo%chart ,or computing ,actorial * 3*45
Where N! = 1 2 3 .. N .
Assignment +
Algorithm and flowchart to find the roots of quadratic equation ax2+bx+c=0
for all cases
Algorithm and flowchart for finding maximum and minimum of given n
numbers
Algorithm and flowchart to generate Fibonacci numbers up to n
n mathematics, the 'ibonacci numbers are the numbers in the following
sequence:
By definition, the first two Fibonacci numbers are 0 and 1, and each remaining
number is the sum of the previous two.
"OMPILERS an& I*TERPRETERS
A compiler is a special program that processes statements written in a particular
programming language and turns them into machine language or "code" that a
computer's processor uses.
Typically, a programmer writes language statements in a language such as
Pascal or C one line at a time using an editor. The file that is created contains
what are called the source statements . The programmer then runs the
appropriate language compiler, specifying the name of the file that contains the
source statements.
When executing (running), the compiler first parses (or analyzes) all of the
language statements syntactically one after the other and then, in one or more
successive stages or "passes", builds the output code, making sure that
statements that refer to other statements are referred to correctly in the final
code.
Traditionally, the output of the compilation has been called object code or
sometimes an object module . (Note that the term "object" here is not related to
object-oriented programming .) The object code is machine code that the
processor can process or "execute" one instruction at a time.
More recently, the Java programming language, a language used in object-
oriented programming ,has introduced the possibility of compiling output
(called bytecode ) that can run on any computer system platform for which
a Java virtual machine or bytecode interpreter is provided to convert the
bytecode into instructions that can be executed by the actual hardware
processor. Using this virtual machine, the bytecode can optionally be
recompiled at the execution platform by a just-in-time compiler .
Thus, a compiler differs from an interpreter, which analyzes and executes each
line of source code in succession, without looking at the entire program. The
advantage of interpreters is that they can execute a program immediately.
Compilers require some time before an executable program emerges. However,
programs produced by compilers run much faster than the same programs
executed by an interpreter.
An interpreter translates high-level instructions into an intermediate form, which it
then executes. n contrast, a compiler translates high-level instructions directly
into machine language. Compiled programs generally run faster than interpreted
programs. The advantage of an interpreter, however, is that it does not need to
go through the compilation stage during which machine instructions are
generated. This process can be time-consuming if the program is long. The
interpreter, on the other hand, can immediately execute high-level programs.
For this reason, interpreters are sometimes used during the development of a
program, when a programmer wants to add small sections at a time and test
them quickly. n addition, interpreters are often used in education because they
allow students to program interactively.
C COMPILER
"ompiler (in&o%s
*I6-
li7e
Other OSs
License
t$pe
I!E8
AMPC Yes Yes Yes Proprietary Yes
Amsterdam
Compiler Kit
No Yes Yes
Open Source
(BSD)
No
Clang Yes Yes Yes
Open Source
(BSD)
No
GCC C Yes Yes
Yes BM
mainfraime,
AmigaOS,
VAX/VMS,
RTEMS
Open source No
LabWindows/CV Yes Yes Yes Proprietary Yes
lcc Yes Yes Yes
Proprietary
(open-source
freeware)
Windows
Nwcc Yes Yes Yes Open source No
Open64 Yes Yes Yes Open source No
Pelles C Yes No No Freeware Yes
Portable C
Compiler
Yes Yes Yes
Open source
(BSD)
No
SAS/C Yes Yes
Yes BM
mainframe,
AmigaOS, 68K,
88K, Unix
Proprietary Yes
Tiny C Compiler Yes Yes No Open source No
CCS C Compiler Yes Yes No Proprietary Yes
ups debugger [1]
(includes C
interpreter)
No Yes
Yes Solaris,
SunOS
Open source Yes
VBCC Yes Yes Yes Open Source No
C!C"" compilers
"ompiler (in&o%s *I6- Other License t$pe I!E8
li7e OSs
C++ Builder Yes No No Proprietary Yes
AMD x86
Open64
Compiler Suite
? ? ? ? ?
Turbo C++
Explorer
Yes No No Freeware Yes
C++ Compiler Yes No No Freeware No
Ch interpreter Yes Yes ? Freeware Yes
Code::Block[2] Yes Yes Yes Open-Source Yes
CNT Yes Yes
Yes Solaris,
BeBox, MS-
DOS,
Convex, etc.
X11/MT license Yes
Borland C++ Yes No DOS Proprietary Yes
Turbo C++ for
DOS
No No DOS Proprietary Yes
Clang Yes Yes Yes Open source No
CodeWarrior Yes Yes Yes ? Yes
Comeau C/C++ Yes Yes Yes Proprietary ?
CoSy compiler
development
system
Yes Yes No Proprietary No
Digital Mars Yes No DOS Proprietary Yes
Djgpp No No DOS Open source No
EDGE ARM
C/C++
Yes Yes Yes Proprietary Yes
MinGW Yes No No Open source No
GCC Yes Yes Yes Open source
Yes Apple
Xcode for
Mac OS X,
Eclipse
HP aC++ No Yes No Proprietary No
AR C/C++
Compilers
Yes No No Proprietary Yes
ntel C++
Compiler
Yes Yes Yes Proprietary Yes
KA C++
Compiler
? ? ? ? ?
Microtec Yes Yes Yes Proprietary Yes
MULT Yes Yes Yes Proprietary Yes
Open Watcom Yes No Yes Open source Yes
Open64 Yes Yes Yes Open source No
PathScale No Yes No
Proprietary/Open
source
No
PG Workstation Yes Yes No Proprietary Yes
ProDev
WorkShop
No No Yes Proprietary Yes
RealView C/C++
Compiler
(armcc)
Yes Yes ? Proprietary Yes
SAS/C C++ ? ?
BM
mainframe
Proprietary ?
Sun Studio No Yes Yes Proprietary Yes
TenDRA No Yes No Open source No
VectorC Yes No No Proprietary No
Visual C++ Yes No No Proprietary Yes
Visual C++
Express
Yes No No Freeware Yes
VisualAge C++ Yes AX OS/2 Proprietary Yes
XL C/C++ No Yes Yes Proprietary No
Wind River
(Diab) Compiler
Yes Yes Yes Proprietary Yes
Lin7er 3computing5
n computer science, a lin7er or lin7 e&itor is a program that takes one or more
objects generated by a compiler and combines them into a single executable
program.
Computer programs typically comprise several parts or modules; all these
parts/modules need not be contained within a single object file, and in such case
refer to each other by means of symbols. Typically, an object file can contain
three kinds of symbols:
defined symbols, which allow it to be called by other modules,
undefined symbols, which call the other modules where these symbols are
defined, and
local symbols, used internally within the object file to facilitate relocation.
When a program comprises multiple object files, the linker combines these files
into a unified executable program, resolving the symbols as it goes along.
Linkers can take objects from a collection called a library. Some linkers do not
include the whole library in the output; they only include its symbols that are
referenced from other object files or libraries. Libraries exist for diverse purposes,
and one or more system libraries are usually linked in by default.
The linker also takes care of arranging the objects in a program's address space.
This may involve relocating code that assumes a specific base address to
another base. Since a compiler seldom knows where an object will reside, it often
assumes a fixed base location (for example, zero). Relocating machine code
may involve re-targeting of absolute jumps, loads and stores.
The executable output by the linker may need another relocation pass when it is
finally loaded into memory (just before execution). This pass is usually omitted on
hardware offering virtual memory every program is put into its own address
space, so there is no conflict even if all programs load at the same base address.
This pass may also be omitted if the executable is a position independent
executable.
The G* "ompiler "ollection (usually shortened to G"") ,Originally named
the G* " "ompiler, because it only handled the C programming language,
GCC 1.0 was released in 1987, and the compiler was extended to compile C++
in December of that year
TR1O " "OMPILER
Turbo "99 was a C++ compiler and integrated development environment (DE)
originally from Borland. Most recently it was distributed by Embarcadero
Technologies, which acquired all of Borland's compiler tools
Turbo C++ v1.01 and Turbo C v2.0 can be downloaded, free of charge, from
Borland's Antique Software website
" PROGRAMMI*G LA*GAGE HISTOR:
The development of Unix in the C language made it uniquely portable and
improvable.
The first version of Unix was written in the low-level PDP-7 assembler language.
Soon after, a language called TMG was created for the PDP-7 by R. M. McClure.
Using TMG to develop a FORTRAN compiler, Ken Thompson instead ended up
developing a compiler for a new high-level language he called B, based on the
earlier BCPL language developed by Martin Richard.
When the PDP-11 computer arrived at Bell Labs, Dennis Ritchie built on B to
create a new language called C which inherited Thompson's taste for concise
syntax, and had a powerful mix of high-level functionality and the detailed
features required to program an operating system. Most of the components of
Unix were eventually rewritten in C, culminating with the kernel itself in 1973.
Because of its convenience and power, C went on to become the most popular
programming language in the world over the next quarter century.
This development of Unix in C had two important consequences:
Portability . t made it much easier to port Unix to newly developed
computers, because it eliminated the need to translate the entire operating
system to the new assemble language by hand:
o First, write a C-to-assembly language compiler for the new
machine.
o Then use the new compiler to automatically translate the Unix C
language source code into the new machine's assembly language.
o Finally, write only a small amount of new code where absolutely
required by hardware differences with the new machine.
mprovability . t made Unix easy to customize and improve by any
programmer that could learn the high-level C programming language.
Many did learn C, and went on to experiment with modifications to the
operating system, producing many useful new extensions and
enhancements.
(hat is the a&;antages o, c language8
Speed of the resulting application. C source code can be optimized much
more than higher-level languages because the language set is relatively
small and very efficient .t is about as close as you can get to
programming in assembly language, without programming in assembly
language .Heck you can even use assembly and C together!
That leads to a second advantage that C has which is its application in
Firmware programming (hardware). That is due to its ability to use/work
with assembly and communicate directly with controllers, processors and
other devices.
C is a building bock for many other currently known languages. Look up
the history of C and you will find that it has been around for some time .
Take a look at Python for example a fully Object-Oriented High-Level
programming language. t is written in C (perhaps C++ too). That tells you
if you ever want to know what is going on under the hood in other
languages; understanding C and how it works is essential.
C is a compiled language versus an interpreted language. Explained
simply, this means that the code is compacted into executable instruction
(in the case of windows anyway) rather than being "translated" on the fly
at run time. This feature also lends heavily to the speed of C programs.
!ISA!)A*TAGES O' " ARE+
1. There is no runtime checking.
2.There is no strict type checking(for ex:we can pass an integer value for the
floating data type).
3. As the program extends it is very difficult to fix the bugs.
'EATRES O' "
C has facilities for structured programming and allows lexical variable scope and
recursion, while a static type system prevents many unintended operations. n C,
all executable code is contained within functions. Function parameters are
always passed by value. Pass-by-reference is simulated in C by explicitly
passing pointer values. C also exhibits the following more specific characteristics:
variables may be hidden in nested blocks
partially weak typing; for instance, characters can be used as integers
low-level access to computer memory by converting machine addresses
to typed pointers
function and data pointers supporting ad hoc run-time polymorphism
array indexing as a secondary notion, defined in terms of pointer
arithmetic
a preprocessor for macro definition, source code file inclusion, and
conditional compilation
complex functionality such as /O, string manipulation, and mathematical
functions consistently delegated to library routines
A relatively small set of reserved keywords
o A lexical structure that resembles B more than ALGOL
Absent ,eatures
The relatively low-level nature of the language affords the programmer close
control over what the computer does, while allowing special tailoring and
aggressive optimization for a particular platform. This allows the code to run
efficiently on very limited hardware, such as embedded systems.
C does not have some features that are available in some other programming
languages:
No nested function definitions
No direct assignment of arrays or strings (copying can be done via
standard functions; assignment of objects having struct or union type is
supported)
No automatic garbage collection
No requirement for bounds checking of arrays
No operations on whole arrays
No syntax for ranges, such as the A..B notation used in several languages
Prior to C99, no separate Boolean type (zero/nonzero is used instead)
[6]

No formal closures or functions as parameters (only function and variable
pointers)
No generators or coroutines; intra-thread control flow consists of nested
function calls, except for the use of the longjmp or setcontext library
functions
No exception handling; standard library functions signify error conditions
with the global errno variable and/or special return values, and library
functions provide non-local gotos
Only rudimentary support for modular programming
No compile-time polymorphism in the form of function or operator
overloading
Very limited support for object-oriented programming with regard to
polymorphism and inheritance
Limited support for encapsulation
No native support for multithreading and networking
No standard libraries for computer graphics and several other application
programming needs
STR"TRE O' A " PROGRAM
Every C program consists of one or more functions. A function is nothing but a
group or sequence of C statements that are executed together. Each C program
function performs a specific task. The 'main35' function is the most important
function and must be present in every C program. The execution of a C program
begins in the main35 function.
Programmers are ,ree to name " program ,unctions 3except the main35
,unction5/
A C program basically has the following form:
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
1asic structure o, a " program is+
/* Documentation section */
/* Link section */
/* Definition section */
/* Global declaretion section */
/* Function section */
(return type) (function name) (arguments...)
void main()
{
Declaration part
Executable part (statements)
}
/* Sub-program section */
(return type) (function name 1) (arguments...)
(return type) (function name 2) (arguments...)
.
.
.
(return type) (function name n) (arguments...)
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
The following program is written in the C programming language. Open a text file
hello#c using vi editor and put the following lines inside that file.
=inclu&e >st&io/h?
int main35
@
AB M$ ,irst program BA
print,3CHello0 (orl&4 DnC5E

return .EAA return interger ;alue Fero
G
*OTE+ n computer programming, a return statement causes execution to leave
the current subroutine and resume at the point in the code immediately after
where the subroutine was called known as its return a&&ress/ Return
statements in many languages allow a function to specify a return ;alue to be
passed back to the code that called the function.
f a function does not have a return type (i.e., its return type is void), the return
statement can be used without a value, in which case the program just breaks
out of the current function and returns to the calling one.
exit(0)
This causes the program to exit with a successful termination.
exit(1)
This causes the program to exit with a system-specific meaning.
On many systems, exit(1) signals some sort of failure, however there
is no guarantee.
As recall, the C standard only recognizes three standard exit
values:
EXT_SUCCESS -- successful termination
EXT_FALURE -- unsuccessful termination
0 -- same as EXT_SUCCESS
_____________________________________________________________
Preprocessor "omman&s+ These commands tells the compiler to do
preprocessing before doing actual compilation. Like #include <stdio.h> is
a preprocessor command which tells a C compiler to include stdio.h file
before going to actual compilation. You will learn more about C
Preprocessors in C Preprocessors session.
'unctions+ are main building blocks of any C Program. Every C Program
will have one or more functions and there is one mandatory function which
is called main() function. This function is prefixed with keyword int which
means this function returns an integer value when it exits. This integer
value is retured using return statement.
The C Programming language provides a set of built-in functions. n the above
example printf() is a C built-in function which is used to print anything on the
screen.
)ariables+ are used to hold numbers, strings and complex data for
manipulation..
Statements H Expressions + Expressions combine variables and
constants to create new values. Statements are expressions,
assignments, function calls, or control flow statements which make up C
programs
"omments+ are used to give additional useful information inside a C
Program. All the comments will be put inside /*...*/ as given in the example
above. A comment can span through multiple lines.
$ote the %ollo&ings
C is a case sensitive programming language. t means in C printf and
Printf will have different meanings.
C has a free-form line structure. End of each C statement must be marked
with a semicolon.
Multiple statements can be one the same line.
White Spaces (ie tab space and space bar ) are ignored.
Statements can continue over multiple lines.
" Program "ompilation
To compile a C program you would have to Compiler name and program files
name. Assuming your compiler's name is cc and program file name is hello.c,
give following command at Unix prompt.
Icc hello/c
This will produce a binary file called a.out and an object file hello.o in your current
directory.
Here a.out is your first program which you will run at Unix prompt like any other
system program. f you don't like the name a.out then you can produce a binary
file with your own name by using -o option while compiling C program. See an
example below
Icc -o hello hello/c
Now you will get a binary with name hello. Execute this program at Unix prompt
but before executing / running this program make sure that it has execute
permission set. f you don't know what is execute permission then just follow
these two steps
Ichmo& J-- hello
I/Ahello
This will produce following result
Hello, World
The s7eleton o, a simple " program is gi;en belo% :
main35
@
statement K E
statement L E
G
,unctionK35
@
;ariable &eclarationsE
statement KE
statement LE
G
A C program is nothing but a collection of one or more functions. A
function name is always followed by a pair of parenthesis, as in case of
main().
Every program must have a special function named main(). The
program execution starts from this function.
The group of statements within main35 are executed sequentially. The
closing brace of the main35 function signals the end of the program. When
this brace is reached, the program execution stops and the control is
handed over to the operating system.
There should be a main35 function somewhere in the program so that
the computer can determine where to start the execution.
The main35 function can be located anywhere in the program, but the
general practice is to place it as the first function for better readability.
(RITI*G :OR 'IRST " PROGRAM
The following is a simple C program that prints a message 'Hello0 %orl&' on the
screen.
AB
Author+ M*T
!ate+ K2AK.AL..N
Purpose+ This program prints a message
BA
K/=inclu&e>st&io/h?
L/main35
2/@
O/ print,3PHello0 %orl&Q5E
-/G
Type this program in any text editor and then compile and run it using a C-
compiler. However, your task will become much easier if you are using an DE
such as Turbo C (available freely from
http://community.borland.com/downloads/). Download and install Turbo C on
your machine and follow the steps given below in order to type and run the
program given above:
K/ Go to the &irector$ %here $ou ha;e installe& Turbo "/
L/ T$pe T" at the !OS comman& prompt/
2/ In the e&it %in&o% that opens0 t$pe the mentione& program abo;e/
O/ Sa;e the program as hello/c b$ pressing 'L or Alt 9 RSS/
-/ Press Alt 9 R"S or Alt 9 'N to compile the program/
T/ Press Alt 9 RRS or "trl 9 'N to execute the program/
J/ Press Alt 9 '- to see the output/
I, $ou are using a Linux machine, you have to follow the steps mentioned
below:
1. Go to the Linux command prompt (# or $).
2. Type vi.
3. The vi editor will open.
4. Type the program in the editor.
5. Press 'Esc + Shift + ':'.
6. Type 'w' + 'q' followed by file name 'hello.c'.
7. At the command prompt type 'gcc hello.c'.
8. Type './a.out' to run the program.
*ote+ " is a case-sensitive language/ It ma7es a &istinction bet%een letters
%ritten in lo%er an& upper case/ 'or example0 RAS an& RaS %oul& be ta7en to
mean &i,,erent things/ Also0 remember that all " language 7e$%or&s shoul&
be t$pe& in lo%er case/
*!ERSTA*!I*G THE PROGRAM
In the program $ou sa% abo;e0 the in,ormation enclose& bet%een RAB BAS is
calle& a RcommentS and may appear anywhere in a C program. Comments are
optional and are used to increase the readability of the program.
The R=inclu&eS in the ,irst line o, the program is calle& a preprocessor
&irecti;e/ A preprocessor is a program that processes the " program
be,ore the compiler. All the lines in the " program beginning %ith a hash
3=5 sign are processe& b$ the preprocessor/
'stdio.h' refers to a file supplied along with the C compiler. t contains ordinary C
statements. These statements give information about many other functions that
perform input-output roles.
Thus, the statement R=inclu&e>st&io/h?S e,,ecti;el$ inserts the ,ile Rst&io/hS
into the ,ile hello/c ma7ing ,unctions containe& in the Rst&io/hS ,ile a;ailable
to the programmer/
For example, one of the statements in the file 'stdio.h' provides the information
that a function print,35 exists, and can accept a string (a set of characters
enclosed within the double quotes).
The next statement is the main35 function. As you already know, this is the place
where the execution of the C program begins. Without this function, your C
program cannot execute.
Next comes the opening brace '{', which indicates the beginning of the function.
The closing brace '}' indicates the end of the function.
The statement print,35 enclosed within the braces'{}' informs the compiler to print
(on the screen) the message enclosed between the pair of double quotes.
n this case, 'Hello0 %orl&' is printed. As mentioned earlier, the statement
print,35 is a built-in function shipped along with the C compiler. Many other built-
in functions are available that perform specific tasks. The power of C lies in these
functions.
1e cautious about errors4
Errors/bugs are very common while developing a program. f you don't detect
them and correct them, they cause a program to produce wrong results.
There are three t$pes o, errors U s$ntax0 logical0 an& run-time errors/ Let
us look at them:
1. S$ntax errors+ These errors occur because of wrongly typed statements,
which are not according to the syntax or grammatical rules of the
language. For example, in C, if you don't place a semi-colon after the
statement (as shown below), it results in a syntax error.
printf("Hello,world) error in syntax (semicolon missing)
printf("Hello,world"); - This statement is syntactically correct.
2. Logical errors+ These errors occur because of logically incorrect
instructions in the program. Let us assume that in a 1000 line program, if
there should be an instruction, which multiplies two numbers and is
wrongly written to perform addition. This logically incorrect instruction may
produce wrong results. Detecting such errors are difficult.
3. Runtime errors+ These errors occur during the execution of the programs
though the program is free from syntax and logical errors. Some of the
most common reasons for these errors are
a/ %hen $ou instruct $our computer to &i;i&e a number b$ Fero/
b/ %hen $ou instruct $our computer to ,in& logarithm o, a
negati;e number/
c/ %hen $ou instruct $our computer to ,in& the sVuare root o, a
negati;e integer/
Unless you run the program, there is no chance of detecting such errors.
Assignment
1. (rite a " program to print $our name an& a&&ress on the screen/
L/ (rite a " program to print the name o, $our ,a;orite cric7eter/
Every " program must contain a main function , since the main function is the
rst function called when you run your program at the command line.
n its simplest form, a " program is given by
int main3;oi&5 @
print,3RRHello %orl&4DnSS5E
G
The int stan&s ,or the Dreturn t$pe", which says that the main function returns
an integer if you tell it to do so. We will get into more detail with functions and
return types, but you can return a number to the command line with the return
function in ", as in
int main3;oi&5 @
print,3RRHello %orl&4DnSS5E
return LE
G
When you compile and run your program, it will return a 2 to the command line,
that you can access with the $? character, which stores the value returned by the
last command executed, as in
I /Aa/out
Hello %orl&4
I echo I8
L
Just as in shell scripts, you can specify exit codes in " as well, which perform the
same function as the return function in the previous example:
int main3;oi&5 @
print,3RRHello %orl&4DnSS5E
exit3L5E
G
Compiling and running this example yields the same result as the previous
example. The ;oi& statement in main3;oi&5 tells the main function that there
are no arguments being supplied to it at the command line.
*ote that all statements in " programs en& %ith the semicolon E except ,or
the prepro-cessor &irecti;es that begin %ith =/
Ho% " program %or7s
The jump to the object oriented C++ language becomes much easier. C++ is an
extension of C, and it is nearly impossible to learn C++ without learning C first.
(hat is "8
C is what is called a compile& language. This means that once you write your C
program, you must run it through a " compiler to turn your program into an
executable that the computer can run (execute).
The C program is the human-readable form, while the executable that comes out
of the compiler is the machine-readable and executable form. What this means is
that to write and run a C program, you must have access to a C compiler.
f you are using a UNX machine (for example, if you are writing CG scripts in C
on your host's UNX computer, or if you are a student working on a lab's UNX
machine), the C compiler is available for free. t is called either "cc" or "gcc" and
is available on the command line.
f you are a student, then the school will likely provide you with a compiler -- find
out what the school is using and learn about it. f you are working at home on a
Windows machine, you are going to need to download a free C compiler or
purchase a commercial compiler.
On a UNX machine, type gcc samp/c -o samp (if gcc does not work, try cc).
This line invokes the C compiler called gcc, asks it to compile samp.c and asks it
to place the executable file it creates under the name samp. To run the program,
type samp (or, on some UNX machines, /Asamp).

On a DOS or Windows machine using DJGPP, at an MS-DOS prompt


type gcc samp/c -o samp/exe. This line invokes the C compiler called gcc, asks
it to compile samp.c and asks it to place the executable file it creates under the
name samp/exe. To run the program, type samp.

f you are working with some other compiler or development system, read
and follow the directions for the compiler you are using to compile and execute
the program.
f you mistype the program, it either will not compile or it will not run. f the
program does not compile or does not run correctly, edit it again and see where
you went wrong in your typing. Fix the error and try again.
This C program starts with =inclu&e >st&io/h?. This line inclu&es the
"standard /O library" into your program. The standard /O library lets you read
input from the keyboard (called "standard in"), write output to the screen (called
"standard out"), process text files stored on the disk, and so on. t is an extremely
useful library. C has a large number of standard libraries like stdio, including
string, time and math libraries.

A librar$ is simply a package of code that someone else has written to


make your life easier (we'll discuss libraries a bit later).

The line int main35 declares the main function. Every C program must
have a function named main somewhere in the code. We will learn more about
functions shortly. At run time, program execution starts at the first line of the main
function.
n C, the @ and G symbols mark the beginning and end of a block of code.
n this case, the block of code making up the main function contains two lines.

The print, statement in C allows you to send output to standard out (for
us, the screen). The portion in quotes is called the ,ormat string and describes
how the data is to be formatted when printed. The format string can contain string
literals such as "This is output from my first program!," symbols for carriage
returns (\n), and operators as placeholders for variables (see below).

f you are using UNX, you can type man 2 print, to get complete
documentation for the printf function. f not, see the documentation included with
your compiler for details about the printf function.
The return .E line causes the function to return an error code of 0 (no
error) to the shell that started execution.
Hea&er ,ile
n computing, header files are a feature of some programming languages (most
famously C and C++) that allows programmers to separate certain elements of a
program's source code into reusable files.
Header files commonly contain forward declarations of classes, subroutines,
variables, and other identifiers. Programmers who wish to declare standardized
identifiers in more than one source file can place such identifiers in a single
header file, which other code can then include whenever the header contents are
required. The C standard library traditionally declare their standard functions in
header files.
Newer compiled languages (such as Java, C#) do not use forward declarations;
identifiers are recognized automatically from source files and read directly from
dynamic library symbols. This means header files are not needed.
n computer programming, a ,or%ar& &eclaration is a declaration of an identifier
(denoting an entity such as a type, a variable, or a function) for which the
programmer has not yet given a complete definition. but at some point the
programmer would still have to provide definitions for the declared entities.
struct personE

int elementsWXE

;oi& print3int5E
After processing these declarations, the compiler would allow the programmer to
refer to the entities person, elements and print in the rest of the program
struct person
@
const char BnameE
char sexE
int ageE
GE

int elementsWK.XE

;oi& print3int x5 @
print,3CY&DnC0 x5E
G
the ,ollo%ing are some o, the hea&er ,iles in c+
=inclu&e>st&io/h?
=inclu&e>string/h?
=inclu&e>math/h?
=inclu&e>st&lib/h?
=inclu&e>,loats/h?
=inclu&e>conio/h?
=inclu&e>time/h?
=inclu&e>limits/h?
=inclu&e>graphic/h?
=inclu&e>ct$pe/h?
=inclu&e>malloc/h?
=inclu&e>calloc/h?
=inclu&e>soun&/h?
there are about 32 header files in c
A header file is used to define constants, variables, macro's and functions that
may be common to several applications. When a system consists of multiple
applications that all access the same data it becomes essential that each
application uses identical definitions and it is safer for all of those applications to
use the same methods to read that data. updating data should only be performed
by a single function, from a single application, but reading data can be safely
performed by using the common defintions found in header files.
A header file is a file containing C declarations and macro definitions to be
shared between several source files. :ou reVuest the use o, a hea&er ,ile in
$our program b$ including it0 %ith the " preprocessing &irecti;e Z=inclu&e[/
Hea&er ,iles ser;e t%o purposes/
S$stem hea&er ,iles declare the interfaces to parts of the operating
system. You include them in your program to supply the definitions and
declarations you need to invoke system calls and libraries.
:our o%n hea&er ,iles contain declarations for interfaces between the
source files of your program. Each time you have a group of related
declarations and macro definitions all or most of which are needed in
several different source files, it is a good idea to create a header file for
them.
Inclu&ing a hea&er ,ile pro&uces the same results as cop$ing the hea&er
,ile into each source ,ile that nee&s it. Such copying would be time-consuming
and error-prone. (ith a hea&er ,ile0 the relate& &eclarations appear in onl$
one place/ I, the$ nee& to be change&0 the$ can be change& in one place,
an& programs that inclu&e the hea&er ,ile %ill automaticall$ use the ne%
;ersion %hen next recompile&/
The header file eliminates the labor of finding and changing all the copies as well
as the risk that a failure to find one copy will result in inconsistencies within a
program.
In "0 the usual con;ention is to gi;e hea&er ,iles names that en& %ith /h/ It
is most portable to use onl$ letters0 &igits0 &ashes0 an& un&erscores in
hea&er ,ile names0 an& at most one &ot/
1oth user an& s$stem hea&er ,iles are inclu&e& using the preprocessing
&irecti;e Z=inclu&e[/ t has two variants:
=inclu&e >%ile?
This ;ariant is use& ,or s$stem hea&er ,iles. t searches for a file
named file in a standard list of system directories. You can prepend
directories to this list with the - option.
=inclu&e C%ileC
This ;ariant is use& ,or hea&er ,iles o, $our o%n program. t searches
for a file named file first in the directory containing the current file, then in
the quote directories and then the same directories used for <file>. You
can prepend directories to the list of quote directories with the -iquote
option.
The argument o, Z=inclu&e[0 %hether &elimite& %ith Vuote mar7s or angle
brac7ets0 beha;es li7e a string constant in that comments are not
recogniFe&0 an& macro names are not expan&e&. Thus, #include <x/*y>
specifies inclusion of a system header file named x/*y.
" librar$ hea&ers
*ame !escription
<assert.h>
Contains the assert macro, used to assist with detecting logical
errors and other types of bug in debugging versions of a program.
<complex.h> A set of functions for manipulating complex numbers.
<ctype.h>
Contains functions used to classify characters by their types or to
convert between upper and lower case in a way that is independent
of the used character set (typically ASC or one of its extensions,
although implementations utilizing EBCDC are also known).
<errno.h> For testing error codes reported by library functions.
<fenv.h> For controlling floating-point environment.
<float.h>
Contains defined constants specifying the implementation-specific
properties of the floating-point library, such as the minimum
difference between two different floating-point numbers
(_EPSLON), the maximum number of digits of accuracy (_DG) and
the range of numbers which can be represented (_MN, _MAX).
<inttypes.h> For precise conversion between integer types.
<iso646.h> For programming in SO 646 variant character sets.
<limits.h>
Contains defined constants specifying the implementation-specific
properties of the integer types, such as the range of numbers which
can be represented (_MN, _MAX).
<locale.h>
For setlocale and related constants. This is used to choose an
appropriate locale.
<math.h> For computing common mathematical functions.
<setjmp.h>
Declares the macros setjmp and longjmp, which are used for non-
local exits.
<signal.h> For controlling various exceptional conditions.
<stdarg.h> For accessing a varying number of arguments passed to functions.
<stdbool.h> For a boolean data type.
<stdint.h> For defining various integer types.
<stddef.h> For defining several useful types and macros.
<stdio.h>
Provides the core input and output capabilities of the C language.
This file includes the venerable printf function.
<stdlib.h>
For performing a variety of operations, including conversion,
pseudo-random numbers, memory allocation, process control,
environment, signalling, searching, and sorting.
<string.h> For manipulating several kinds of strings.
<tgmath.h> For type-generic mathematical functions.
<time.h> For converting between various time and date formats.
<wchar.h>
For manipulating wide streams and several kinds of strings using
wide characters - key to supporting a range of languages.
<wctype.h> For classifying wide characters.
" stan&ar& librar$
The " stan&ar& librar$ consists of a set of sections of the SO C standard which
describe a collection of header files and library routines used to implement
common operations, such as input/output and string handling, in the C
programming language.
The C standard library is an interface standard described by a document; it is not
an actual library of software routines available for linkage to C programs. No
such implementation is properly called C standard library.
The term C runtime library is used on some platforms to refer to a set of base
libraries, which may be distributed in dynamically linkable form with an operating
system (with or without header files), or distributed with a C compiler.
Another term sometimes used is libc. Not just any library is called the run-time
library; run time in this context means the run-time support package associated
with a compiler which is understood to make a language complete. The run-time
support provides not only the C standard library functions, but possibly other
material needed to create an environment for the C program, such as
initialization prior to the invocation of the main function, or subroutines to provide
arithmetic operations missing from the CPU that are needed by code generated
by the C compiler.
(HAT IS A GLO1AL !E"LARATIO*8
A global declaration of a function or variable is a declaration that is at the global
scope of the program, not inside another function. This means that the name will
be visible within all functions in the program.
THE MAI* '*"TIO* A*! PROGRAM E6E"TIO*
Every C program has a primary (main) function that must be named main. f your
code adheres to the Unicode programming model, you can use the wide-
character version of main, %main. The main function serves as the starting point
for program execution. t usually controls program execution by directing the calls
to other functions in the program. A program usually stops executing at the end
of main, although it can terminate at other points in the program for a variety of
reasons. At times, perhaps when a certain error is detected, you may want to
force the termination of a program. To do so, use the exit function.
MAI* '*"TIO* I* " IS A SER-!E'I*E! '*"TIO*. No doubt it is a rule
that without main function C program can not be compiled means that Main
function is just to inform compiler about starting of program which is pre-defined
in C.
DON'T BE CONFUSED BETWEEN THE PRE-!E'I*E! STATEME*T A*!
PRE-!E'I*E! '*"TIO*/
PRE-DEFNED STATEMENT S PROGRAM STARTS WTH MAN FUNCTON
AND PRE-DEFNED FUNCTONS ARE THE FUNCTONS WHCH ARE
TOTALLY DEFNED N LBRARY/HEADER FLE.
Functions within the source program perform one or more specific tasks. The
main function can call these functions to perform their respective tasks. When
main calls another function, it passes execution control to the function, so that
execution begins at the first statement in the function. A function returns control
to main when a return statement is executed or when the end of the function is
reached.
You can declare any function, including main, to have parameters. The term
"parameter" or "formal parameter" refers to the identifier that receives a value
passed to a function. When one function calls another, the called function
receives values for its parameters from the calling function. These values are
called "arguments." You can declare formal parameters to main so that it can
receive arguments from the command line using this format
When you want to pass information to the main function, the parameters are
traditionally named argc and argv, although the C compiler does not require
these names. The types for argc and argv are defined by the C language.
Traditionally, if a third parameter is passed to main, that parameter is named
envp.
BBBBBBIn "0 main35 cannot return an$thing other than an int/Something li7e
;oi& main35 is illegal/ There are onl$ three ;ali& return ;alues ,rom main35 -
.0 E6IT<S""ESS0 an& E6IT<'AILRE
The " preprocessor (cpp) is the preprocessor for the C programming language.
n many C implementations, it is a separate program invoked by the compiler as
the first part of translation. The preprocessor handles directives for source file
inclusion (#include), macro definitions (#define), and conditional inclusion (#if).
(HAT ARE MA"ROS8
Macros, which are special lines/fragments of code, differ from any other code
written in the source files in the aspect that it's not passed to the compiler (either
for the purpose of encoding into machine instructions, or some intermediate form
instructions). nstead, macros perform textual manipulations on the source code
before passing it to the compiler, where this process preliminary to compiling the
source files is called "preprocessing", and the software component responsible of
doing it is called the "preprocessor". Henceforth, macros are usually defined as
"preprocessor directives", where a segment of code is replaced by the results of
the macro processing before passing the source code to the compiler. A very
valuable technique to gain a thorough understanding of the operation of macros
in any environment is to learn how to obtained the preprocessed source code,
and see how the macro directives are expanded.
n C and C++, a Macro is a piece of text that is expanded by the preprocessor
part of the compiler. This is used in to expand text before compiling.
=&e,ine )ALE K.
E;er$%here that )ALE is use& the number o, K. %ill be use& instea&/
int ,re&W)ALEXE
=&e,ine A L
=&e,ine 1 2
=&e,ine " A 9 1
It is better to use constants %ith const instea& o, the #define macro/
*ESTE! "OMME*TS
n the following program, the second printf() is a comment:
#include <stdio.h>

int main(void)
{
printf("This program has a comment.\n");
/* printf("This is a comment line and will not print.\n"); */
return 0;
}
Because the second printf() is equivalent to a space, the output of this program
is:
This program has a comment.
Because the comment delimiters are inside a string literal, printf() in the following
program is not a comment.
#include <stdio.h>

int main(void)
{
printf("This program does not have \
/* NOT A COMMENT */ a comment.\n");
return 0;
}
The output of the program is:
This program does not have
/* NOT A COMMENT */ a comment.
You can nest single line comments within C-style comments. For example, the
following program will not output anything:
#include <stdio.h>

int main(void)
{
/*
printf("This line will not print.\n");
// This is a single line comment
// This is another single line comment
printf("This line will also not print.\n");
*/
return 0;
\\ }
RLES I* " PROGRAMMI*G LA*GAGE
Here are some of the syntax rules in C Programming
that must be familiarize:
a. Put semicolon at the end of variable declaration.
b. Commas should be used to separate variables.
c. Variables should be declared first before it can be used.
d. An identifier must not begin with a digit.
e. An identifier must consist only of letters, digits, or underscores.
f. An identifier defined in a C standard library must not be redefined.
g. C reserved words cannot be used as an identifier.
h. n using the scanf function the order of the placeholders must correspond to
the order of the variables in the input list.
" PROGRAM "OMPILATIO* STEPS8
There are 6 steps
1. Pre-processor - which replaces macros
2. Code will be separated from comments
3. syntax error will be given - types of parsing
4. compilation - will convert high level language to assembly
5. assembler - will convert assembly to machine language
6. linker - will generate final executable.
THE " "HARA"TER SET
The character set in C Language can be grouped into the following categories.
1. Letters
2. Digits
3. Special Characters
4. White Spaces
White Spaces are ignored by the compiler until they are a part of string constant.
White Space may be used to separate words, but are strictly prohibited while
using between characters of keywords or identifiers.
" "haracter-Set Table
Letters !igits
Upper Case A to Z 0 to 9
Lower Case a to z
.
A character denotes any alphabet ,digit or symbols to represent
information.The following are the valid alphabets, numbers and special
symbols permitted in C
*umerals+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Alphabets+ a, b, ..z
A, B, .....Z
Arithmetic Operations: +, -, *, /, %(Mod)
Special "haracters+

( ) { } [ ] < >
= ! $ ? . , : ;
' " & | ^ ~ ` #
\ blank - _ / * % @

"O*STA*TS0 )ARIA1LES A*! #E:(OR!S
A 'constant' is an entity that does not change, but a 'variable' as the name
suggests may change.
We do a number of calculations in a computer and the computed values are
stored in some memory spaces. norder to retrieve and re-use those values
from the computer's memory locations they are given names. Since the
value stored in each location may change, the names given to these
locations are called as ';ariable namesS/
"onstants+
There are mainly three t$pes o, constants namel$+ integer0 real an&
character constants/
Integer "onstants+
The integer constants
Whole Numbers
Eg. 25, 35, -25, -46
Computer allocates only 2 bytes in memory.
16
th
bit is sign bit. (if 0 then +ve value, if 1 then ve value)

3i5 !ecimal Integer "onstant+
0 to 9
E.g: 49, 58, -62, . (40000 cannot come bcoz it is > 32767)
3ii5 Octal Integer "onstant+
0 to 7
Add "0 before the value.
Eg.: 045, 056, 067
3iii5 Hexa&ecimal Integer+
0 to 9 and A to F
Add 0x before the value
E.g: 0x42, 0x56, 0x67
REAL "O*STA*TS+
The real or floating point constants are in two forms namely fractional form
and the exponential form.
A real constant in fractional form must:
Have at least one digit
t must have a decimal point
Could have positive or negative sign(default sign is positive)
Must not have commas or spaces within it
Allots 4 bytes in memory
Ex: +867.9, -26.9876, 654.0
n exponential form, the real constant is represented as two parts. The part
lying before the 'e' is the 'mantissa', and the one following 'e' is the
'exponent'.
The real constant in exponential form must follow the following rules:
The mantissa part and the exponential part should be separated by
the letter 'e'
The mantissa may have a positive or negative sign(default sign is
positive)
The exponent must have at least one digit
The exponent must be a positive or negative integer(default sign is
positive)
The range of real constants in exponential form is -3.4e38 and
-3.4e38
Ex: +3.2e-4, 4.1e8, -0.2e+4, -3.2e-4
"HARA"TER "O*STA*TS
A character constant is an alphabet, a single digit or a single special symbol
enclosed within inverted commas. The maximum length of a character
constant can be 1 character. Allots 1 byte of memory
Ex: 'B', 'l', '#'
STRI*G "O*STA*TS
Strings in C are represented by arrays of characters. The end of the string is
marked with a special character, the null character, which is simply the character
with the value 0. The null or string-terminating character is represented by
another character escape sequence, \0.
n fact, C's only truly built-in string-handling is that it allows us to use string
constants (also called string literals) in our code. Whenever we write a string,
enclosed in double quotes, C automatically creates an array of characters for us,
containing that string, terminated by the \0 character. For example, we can
declare and define an array of characters, and initialize it with a string constant:
char string[] = "Hello, world!";
To do anything else with strings, we must typically call functions. The C library
contains a few basic string manipulation functions, and to learn more about
strings, we'll be looking at how these functions might be implemented.
Since C never lets us assign entire arrays, we use the strcpy function to copy
one string to another:
#include <string.h>
char string1[] = "Hello, world!";
char string2[20];
strcpy(string2, string1);
TO#E*S I* "
n a C source program, the basic element recognized by the compiler is the
"token." A token is source-program text that the compiler does not break down
into component elements.
There are 6 types of Tokens in C which are as follows:-
1. Keyword
2. dentifier
3. Constants/Literals
4. Variable
5. Operator
6. Punctuator
T:PES O' " )ARIA1LES
Variable names are names given to locations in the memory. These
locations can contain integer, real or character constants. An integer variable
can hold only an integer constant, a real variable can hold only a real
constant and a character variable can hold only a character constant.
Rules ,or "onstructing )ariable *ames
A variable name is any combination of 1 to 31 alphabets, digits or
underscores. Some compilers allow variable names whose length could be
up to 247 characters.
The first character in the variable name must be an alphabet
No commas or blanks are allowed within a variable name.
No special symbol other than an underscore (as in net<sal) can be
used in a variable name.
Ex.: si_int
e_hra
pod_e_81
C compiler makes it compulsory for the user to declare the type of any
variable name that he wishes to use in a program. This type declaration is
done at the beginning of the program. Following are the examples of type
declaration statements:
Ex.: int si, e_hra ;
float bas_sal ;
char code ;
Since, the maximum allo%able length o, a ;ariable name is 2K
characters, an enormous number of variable names can be constructed
using the above-mentioned rules. t is a good practice to exploit this
enormous choice in naming variables by using meaningful variable names.
" #e$%or&s
C makes use of only 32 keywords or reserved words which combine with the
formal syntax to the form the C programming language. Note that all
keywords in C are written in lower case. A keyword may not be used as a
variable name.
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while


As a programmer, you will frequently want your program to "remember" a value.
For example, if your program requests a value from the user, or if it calculates a
value, you will want to remember it somewhere so you can use it later. The way
your program remembers things is by using ;ariables. For example:
int b;
This line says, " want to create a space called b that is able to hold one integer
value." A variable has a name (in this case, b) and a t$pe (in this case, int, an
integer). You can store a value in b by saying something like:
b = 5;
You can use the value in b by saying something like:
printf("%d", b);
n C, there are several standard types for variables:
int - integer (whole number) values
,loat - floating point values
char - single character values (such as "m" or "Z")
A variable is just a named area of storage that can hold a single value (numeric
or character). The " language &eman&s that $ou &eclare the name o, each
;ariable that $ou are going to use an& its t$pe0 or class0 be,ore $ou actuall$
tr$ to &o an$thing %ith it/
The Programming language " has t%o main ;ariable t$pes
LO"AL )ARIA1LES
GLO1AL )ARIA1LES
Local 'ariables
Local variables scope is confined within the block or function where it is
defined. Local variables must always be defined at the top of a block.
When a local variable is defined - it is not initalised by the system, you
must initalise it yourself.
When execution of the block starts the variable is available, and when the
block ends the variable 'dies'.
Check following example's output
main()
{
int i=4;
int j=10;

i++;

if (j > 0)
{
/* i defined in 'main' can be seen */
printf("i is %d\n",i);
}

if (j > 0)
{
/* 'i' is defined and so local to this block */
int i=100;
printf("i is %d\n",i);
}/* 'i' (value 100) dies here */

printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/
}

This will generate following output
i is 5
i is 100
i is 5
Here 99 is called incremental operator and it increase the value of any integer
variable by 1. Thus i99 is equivalent to i = i + !
You will see -- operator also which is called decremental operator and it
decreases the value of any integer variable by 1. Thus i-- is equivalent to i = i " !
(lobal 'ariables
Global variable is defined at the top of the program file and it can be visible and
modified by any function that may reference it.
Global variables are initalised automatically by the system when you define them!
!ata T$pe Initialser
int 0
char '\0'
float 0
pointer NULL
f same variable name is being used for global and local variable then local
variable takes preference in its scope. But it is not a good practice to use global
variables and local variables with the same name.
int i=4; /* Global definition */

main()
{
i++; /* Global variable */
func();
printf( "Value of i = %d -- main function\n", i );
}
func()
{
int i=10; /* Local definition */
i++; /* Local variable */
printf( "Value of i = %d -- func() function\n", i );
}
This will produce following result
Value of i = 11 -- func() function
Value of i = 5 -- main function
i in main function is global and will be incremented to 5. i in ,unc is internal and
will be incremented to 11. When control returns to main the internal variable will
die and and any reference to i will be to the global.
!ATA T:PES I* "
A programming language is proposed to help programmer to process certain
kinds of data and to provide useful output. The task of data processing is
accomplished by executing series of commands called program. A program
usually contains different types of data types (integer, float, character etc.) and
need to store the values being used in the program. C language is rich of data
types. A C programmer has to employ proper data type as per his requirement.
C has different data types for different types of data and can be broadly classified
as :
1. Primary data types
2. Secondary data types
Primar$ &ata t$pes consist ,ollo%ing &ata t$pes/
!ata T$pes in "
Integer t$pes+
ntegers are whole numbers with a range of values, range of values are machine
dependent. Generally an integer occupies 2 bytes memory space and its value
range limited to -32768 to +32768 (that is, -2
15
to +2
15
-1). A signed integer use
one bit for storing sign and rest 15 bits for number.
To control the range of numbers and storage space, " has three classes o,
integer storage namel$ short int0 int an& long int/ All three &ata t$pes ha;e
signe& an& unsigne& ,orms/ A short int requires half the amount of storage
than normal integer. Unlike signed integer, unsigned integers are always positive
and use all the bits for the magnitude of the number. Therefore the range of an
unsigned integer will be from 0 to 65535. The long integers are used to declare a
longer range of values and it occupies 4 bytes of storage space.
S$ntax+ int <variable name>; like
int num1;
short int num2;
long int num3;
Example+ 5, 6, 100, 2500.
Integer !ata T$pe Memor$ Allocation
'loating Point T$pes+
The float data type is used to store fractional numbers (real numbers) with 6
digits of precision. Floating point numbers are denoted by the keyword float.
When the accuracy of the floating point number is insufficient, we can use the
double to define the number. The double is same as float but with longer
precision and takes double space (8 bytes) than float. To extend the precision
further we can use long double which occupies 10 bytes of memory space.
S$ntax+ float <variable name>; like
float num1;
double num2;
long double num3;
Example+ 9.125, 3.1254.
'loating Point !ata T$pe Memor$ Allocation
"haracter T$pe+
Character type variable can hold a single character. As there are singed and
unsigned int (either short or long), in the same way there are signed and
unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned
characters have values between 0 and 255, signed characters have values from
128 to 127.
S$ntax+ char <variable name>; like
char ch = 'a';
Example+ a, b, g, S, j.
)OI! T:PE+
The void type has no values therefore we cannot declare it as variable as we did
in case of integer and float.
The void data type is usually used with function to specify its type. Like in our first
C program we declared "main() as void type because it does not return any
value.
ser &e,ine& t$pe &eclaration
C language supports a feature where user can define an identifier that
characterizes an existing data type. This user defined data type identifier can
later be used to declare variables. n short its purpose is to redefine the name of
an existing data type.
S$ntax+ typedef <type> <identifier>; like
typedef int number;
Now we can use number in lieu of int to declare integer variable. For example:
"int x1 or "number x1 both statements declaring an integer variable. We have
just changed the default keyword "int to declare integer variable to "number.
!I''ERE*"E 1ET(EE* THE !E'I*ITIO* A*! !E"LARATIO* O' A
)ARIA1LE I* "8
definition defines the memory area ( allocates the memory ) for the variable and
the declaration tells about the signature of the variable ( type and size to be
considered). definition occures once through the program( memory is allocated
once ), but the declaration can occur many times.
OR For a variable, the definition is the statement that actually allocates memory.
For example, the statement:
long int ;arE
is a definition. On the other hand, an extern reference to the same variable:
extern long int ;arE
is a declaration, since this statement doesn?t cause any memory to be allocated.
Here?s another example of a declaration:
t$pe&e, M$T$pe shortE
I*ITIALI\E )ARIA1LES I* "
C does not initialize variables automatically, so if you do not initialize them
properly, you can get unexpected results. Fortunately, C makes it easy to
initialize variables when you declare them.
InitialiFe )ariables at !eclaration
nitialize a variable in C to assign it a starting value. Without this, you
will get whatever happened to be in memory at that moment, which
leads to inconsistent behavior and irreproducible bugs that can be
exceedingly difficult to track down.
Add an initialization to the declaration. Just tack on an assignment
right to the end of the declaration, like so:
int x = 5;
Know that initializing arrays works similarly, save that you must put
multiple comma-separated values inside curly brackets. When doing
this, you can leave off the array's size, and it will be filled in
automatically:
int month_lengths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
Take advantage of character strings. Character strings, which are
really arrays of characters, also support a simpler format for
initialization:
char title[] = "My Program";
Express either kind of array initialization in pointer format (since arrays
are really pointers):
int *month_lengths = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
char *title = "My Program";
Remember that structures in C are initialized in the same way as
arrays:
struct role = { "Hamlet", 7, FALSE, "Prince of Denmark", "Kenneth Branagh"};
InitialiFe )ariables Manuall$
Wait to initialize a variable at another place in the program if this will be
clearer. For instance, a variable that will be the index of a for loop is
usually best initialized in the for loop. This makes it easier for another
programmer to read, since the initialization is near where it will be
used.
nitialize the data structure at the right time. f a data structure is going
to be dynamically allocated with malloc() or a similar function, you can't
initialize it until after it's allocated. However, in this case, what you're
declaring is actually a pointer, which should still be initialized to NULL
as a matter of course.
T:PE "O*)ERSIO*
type conversion or typecasting re,ers to changing an entit$ o, one &ata t$pe
into another/ This is &one to ta7e a&;antage o, certain ,eatures o, t$pe
hierarchies
There are two types of conversion: implicit and explicit. The term for implicit type
conversion is coercion. The most common form of explicit type conversion is
known as casting. Explicit type conversion can also be achieved with separately
defined conversion routines such as an overloaded object constructor.
Implicit con;ersion
mplicit conversions do not require any operator. They are automatically
performed when a value is copied to a compatible type. For example:
1
2
3
short a]L...E
int bE
b]aE
Here, the value of a has been promoted from short to int and we have not had
to specify any type-casting operator. This is known as a standard conversion.
Standard conversions affect fundamental data types, and allow conversions
such as the conversions between numerical types (short to int, int to
float, double to int...), to or from bool, and some pointer conversions.
Some of these conversions may imply a loss of precision, which the compiler
can signal with a warning. This can be avoided with an explicit conversion.
Explicit con;ersion
C++ is a strong-typed language. Many conversions, specially those that imply a
different interpretation of the value, require an explicit conversion. We have
already seen two notations for explicit type conversion: functional and c-like
casting:
1
2
3
4
short a]L...E
int bE
b ] 3int5 aE AA c-li7e cast notation
b ] int 3a5E AA ,unctional notation
"O*STA*T A*! )OLATILE )ARIA1LE
)olatile is a Vuali,ier that is applied to a variable when it is declared. t tells the
compiler that the value of the variable may change at any time-without any action
being taken by the nearby code. The implications of this are quite serious. Let's
take a look at the syntax.
A variable should be declared volatile whenever its value could change
unexpectedly. n practice, only three types of variables could change:
Memory-mapped peripheral registers
Global variables modified by an interrupt service routine
Global variables within a multi-threaded application
f we do not use volatile qualifier the following problems may arise:
Code that works fine-until you turn optimization on
Code that works fine-as long as interrupts are disabled
Flaky hardware drivers
Tasks that work fine in isolation-yet crash when another task is enabled
Example:
static int var;
void test(void)
{
var = 0;
while (var != 255)
continue;
}
The above code sets the value in var to 0. t then starts to poll that value in a loop
until the value of var becomes 255.
An optimizing compiler will notice that no other code can possibly change the
value stored in 'var', and therefore assume that it will remain equal to 0 at all
times. The compiler will then replace the function body with an infinite
loop, similar to this:
void test_opt(void)
{
var = 0;
while (TRUE)
continue;
}
)eclaration o% 'olatile variable
nclude the keyword volatile before or after the data type in the
variable.
volatile int var;
int volatile var;
Pointer to a ;olatile ;ariable
;olatile int * var;
int volatile * var;
Above statements implicate 'var' is a pointer to a volatile integer.
"O*STA*T )ARIA1LE
const
const is used with a datatype declaration or definition to specify an
unchanging value
Examples:
const int five = 5;
const double pi = 3.141593;
const objects may not be changed
The following are illegal:
const int five = 5;
const double pi = 3.141593;
pi = 3.2;
five = 6;
E6TER*AL )ARIA1LES
Where a global variable is declared in one file, but used by functions from
another, then the variable is called an external variable in these functions, and
must be declared as such. The declaration must be preceeded by the word
extern. The declaration is required so the compiler can find the type of the
variable without having to search through several source files for the declaration.
Global and external variables can be of any legal type. They can be initialised,
but the initialisation takes place when the program starts up, before entry to the
main function.
STATI" )ARIA1LES
Another class of local variable is the static type. A static can only be accessed
from the function in which it was declared, like a local variable. The static variable
is not destroyed on exit from the function, instead its value is preserved, and
becomes available again when the function is next called. Static variables are
declared as local variables, but the declaration is preceeded by the word static.
static int counter;
Static ;ariables can be initialise& as normal0 the initialisation is per,orme&
once onl$0 %hen the program starts up/
Can a variable be both const and #olatile?
Yes. The const modifier means that this code cannot change the value of the
variable, but that does not mean that the value cannot be changed by means
outside this code. For instance, the timer structure was accessed through a
volatile const pointer. The function itself did not change the value of the timer, so
it was declared const. However, the value was changed by hardware on the
computer, so it was declared volatile. f a variable is both const and volatile, the
two modifiers can appear in either order.
(RITE A " PROGRAM TO 'I*! THE SM O' T(O *M1ERS A*! THEIR
A)ERAGE8
#include <stdio.h>
int main (void) // main()
{
int x=3, y=5; //int x,y,ave; x=10;y=20;ave=(x+y)/2;
printf ("sum=%d, average=%d\n", x+y, (x+y)/2);
//printf("Average of two numbers %dand %d=%d/n,x,y,ave);
return 0; // no need if no return type
}
SER !E'I*E! !ATA T:PES I* "
user can create his o%n &ata t$pe ,or han&ling &ata that &oes not ,it in one
o, the existing &ata t$pes
SI*G T:PE!E'
The type definition statement is used to allow user &e,ine& &ata t$pes to be
&e,ine& using other already available &ata t$pes.
1asic 'ormat+
typedef existing_data_type new_user_define_data_type;
Examples+
typedef int nteger;
The example above simply creates an alternative &ata type name or "alias
called nteger for the built in &ata type called "int. This is generally not a
recommended use of the typedef statement.
typedef char Characters [ WORDSZE ]; /* #define WORDSZE 20 */
The example above creates a user &e,ine& &ata type called Characters.
Characters is a &ata type that supports a list of "char values. The fact that this
user &e,ine& &ata type is an array of WORDSZE is now built into the &ata type.
Characters One_String;
/* [ ] and WORDSZE are not specified *//* this also applies to argument list use
*/
The first keyword we shall explore is typedef. With this keyword we can define a
new type, and give it a user-friendly name. For example:
typedef int Boolean;
This code tells the compiler that we want to define a type Boolean, that is
equivalent to an integer. n order to use this new type, we could use code similar
to:
Boolean bResult;
// ... Some code ...
if (bResult == 0) { printf ("False\n"); }
This is not, however, very user friendly, but can be made more so by using the
#define keyword to define values for true and false:
#define FALSE 0;
#define TRUE 1;
// ... Some code ...
Boolean bResult;
// ... Some code ...
if (bResult == FALSE) { printf ("False\n"); }
This is fine, but there is en even more elegant way to achieve this.
E*MERATE! T:PES 3E*M5
Enumerated &ata t$pes are a user &e,ine& ordinal &ata type. The main purpose
of the enumerated &ata type is to allow numbers to be replaced by words. This is
intended to improve the readability of programs.
1asic 'ormat+
enum data_type_name { word1, word2, ., word(n-1), word(n) };
OR
enum data_type_name { word1 = integer1, word2 = integer2, etc. };
Examples+
enum Boolean { FALSE, TRUE };
n the example above a user &e,ine& &ata type called Boolean has been
&e,ine&.The new &ata type has two values: FALSE and TRUE. The word FALSE
has the integer value of 0. The word TRUE has the integer value of 1.
I, no integer ;alues are speci,ie& then the le,t most %or& has integer ;alue
. an& each one a,ter that is incremente& b$ one ,rom that point/ 3.0 K0 L0 20
etc^5 This also means that the left-most word is generally the smallest and the
right-most word is generally the largest.
enum 1oolean @ 'ALSE ] .0 TRE ] K GE
enum (ee7&a$s @ Mon&a$ ] K0 Tues&a$0 (e&nes&a$0 Thurs&a$0 'ri&a$ GE
n the example above a user &e,ine& &ata type called Weekdays has been
&e,ine&.
The ne% &ata t$pe has ,i;e ;alues+ Mon&a$0 Tues&a$0 (e&nes&a$0
Thurs&a$0 an& 'ri&a$/ Mon&a$ is K0 Tues&a$ is L0 (e&nes&a$ is 20
Thurs&a$ is O0 an& 'ri&a$ is -/*otice that the starting ;alue is K in this
example instea& o, ./
enum Boolean Positive;
/* uninitialized variable declaration */
enum Weekdays Day = Wednesday;
/* initialized variable declaration */
if ( Number > 0 )
Positive = TRUE;
else
Positive = FALSE;
for ( Day = Monday; Day <= Friday; ++ Day )
{
/* execute the body of loop */
}
The &isa&;antage o, enumerate& &ata t$pes is that normal input an& output
operations are not supporte&/
scanf ( "%d%c, &Day, &Enter_Key );/* integer based */
The &e,ine& values for the variable Day are: Monday, Tuesday, Wednesday,
Thursday, and Friday. None of these values can be type in from the keyboard.
Any integer value can be typed in even though the only &e,ine& values are 1
through 5.
print, 3 PY&DnQ0 Mon&a$ 5E AB integer base& BA
The %or& Mon&a$ %ill not be &ispla$e& on the screen ,or output/ Instea&
the integer ;alue K %ill be &ispla$e&/
An enumerated data type is a list of possible values, each of which is assigned a
sequential number. This allo%s us to %rite co&e that can compare ;alues
easil$/ So, for our Boolean example:
t$pe&e, enum @'ALSE0 TREG 1ooleanE
This tells the compiler that we would like a Boolean type that evaluates to
FALSE, or TRUE. The compiler will assign the values 0 and 1 to these new
types, enabling comparisons such as:
Boolean bResult;
// ... Some code ...
if (bResult == FALSE) { printf ("False\n"); }
(e can also &e,ine more complex lists+
typedef enum {Mon, Tue, Wed, Thu, Fri} Workdays;
Workdays Today;
// ... Some code ...
if (Today == Mon) { printf("Monday\n"); }
However, in order to define complex data types which can contain data beyond
the basic types, we need two more keywords.
ENUM is closely related to the #define preprocessor.
t allows you to define a list of aliases which represent integer numbers. For
example if you find yourself coding something like:
#define MON 1
#define TUE 2
#define WED 3
You could use enum as below.
enum week { Mon=1, Tue, Wed, Thu, Fri Sat, Sun} days;
or
enum escapes { BELL = '\a', BACKSPACE = '\b', HTAB = '\t',
RETURN = '\r', NEWLNE = '\n', VTAB = '\v' };

or
enum boolean { FALSE = 0, TRUE };

An advantage of enum over =&e,ine is that it has scope This means that the
variable (just like any other) is only visable within the block it was declared within.
$otes*
f a variable is defined with enum it is considered by the compiler to be an
integer, and can have ANY integer value assigned to it, it is not restericted
to the values in the enum statement.
STRI*G "O*STA*TS
String constants are seVuences o, characters enclose& in &ouble Vuotes/
The same backslash sequences that are used in character constants can be
used in string constants. $.g., "hello there", "a newline: \n", "a
string\nwith mltiple\nlines". f a string is long and you want to break
it up across several lines of code, $ou can put a bac7slash _ust be,ore a 3real5
ne%line an& the " compiler %ill thro% a%a$ both the bac7slash an& the
ne%line, e.g.,
print,3CA ;er$ long help messageDn
that is more rea&able i, it is bro7en up o;erDnDse;eral lines/DnC5E
this string contains one real newline (the \n).
Character constants are usually just the character enclosed in single quotes; 'a',
'b', 'c'. Some characters can't be represented in this way, so we use a 2 character
sequence as follows.
[Dn[ ne%line
[Dt[ tab
[DD[ bac7slash
[D[[ single Vuote
[D.[ null 3 se&automaticall$ to terminate character string 5
OPERATORS I* "
(hat is Operator8 Simple answer can be given using expression % + & is e'ual
to (. Here 4 and 5 are called operands and + is called operator.
C language supports following type of operators.
Arithmetic Operators
Logical 3or Relational5 Operators
1it%ise Operators
Assignment Operators
Misc Operators
+rithmetic Operators*
There are following arithmetic operators supported by C language:
Assume variable A holds 10 and variable holds 20 then:
Operator !escription Example
+ Adds two operands A + B will give 30
-
Subtracts second operand from
the first
A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denominator B / A will give 2
%
Modulus Operator and remainder
of after an integer division
B % A will give 0
++
ncrement operator, increases
integer value by one
A++ will give 11
--
Decrement operator, decreases
integer value by one
A-- will give 9
Tr$ ,ollo%ing example to un&erstan& all the arithmetic operators/
"op$ an& paste ,ollo%ing " program in test/c ,ile an& compile an&
run this program.
main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
This will produce following result
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Logical ,or Relational- Operators*
There are following logical operators supported by C language
Assume variable A holds 10 and variable holds 20 then:
Operator !escription Example
==
Checks if the value of two
operands is equal or not, if yes
then condition becomes true.
(A == B) is not true.
!=
Checks if the value of two
operands is equal or not, if values
are not equal then condition
becomes true.
(A != B) is true.
>
Checks if the value of left operand
is greater than the value of right
operand, if yes then condition
becomes true.
(A > B) is not true.
< Checks if the value of left operand (A < B) is true.
is less than the value of right
operand, if yes then condition
becomes true.
>=
Checks if the value of left operand
is greater than or equal to the
value of right operand, if yes then
condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand
is less than or equal to the value
of right operand, if yes then
condition becomes true.
(A <= B) is true.
&&
Called Logical AND operator. I,
both the operan&s are non Fero
then then con&ition becomes
true.
(A && B) is true.
||
Called Logical OR Operator. I,
an$ o, the t%o operan&s is non
Fero then then con&ition
becomes true/
(A || B) is true.
!
Called Logical NOT Operator. Use
to reverses the logical state of its
operand. I, a con&ition is true
then Logical *OT operator %ill
ma7e ,alse/
!(A && B) is false.
Tr$ ,ollo%ing example to un&erstan& all the Logical operators/ "op$ an&
paste ,ollo%ing " program in test/c ,ile an& compile an& run this program/
main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
printf("Line 1 - a is equal to b\n" );
}
else
{
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b )
{
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
AB Lets change ;alue o, a an& b BA
a ] -E
b ] L.E
if ( a <= b )
{
printf("Line 4 - a is either less than or euqal to b\n" );
}
if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
if ( a && b )
{
printf("Line 6 - Condition is true\n" );
}
if ( a || b )
{
printf("Line 7 - Condition is true\n" );
}
/* Again lets change the value of a and b */
a = 0;
b = 10;
if ( a && b )
{
printf("Line 8 - Condition is true\n" );
}
else
{
printf("Line 8 - Condition is not true\n" );
}
if ( !(a && b) )
{
printf("Line 9 - Condition is true\n" );
}
}
This will produce following result
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Line 6 - Condition is true
Line 7 - Condition is true
Line 8 - Condition is not true
Line 9 - Condition is true
.it&ise Operators*
Bitwise operator works on bits and perform bit by bit operation.
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1000
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
*ote+
con;ert &ecimal ON to binar$+
ONAL ] LO r K
LOAL ] KL r .
KLAL ] T r .
TAL ] 2 r .
2AL ] K r K
KAL ] . r K
*o% rea& the remain&ers ,rom bottom to top+ the binar$ eVui;alent is
KK...K
con;ert binar$ KK.K..K to &ecimal+
K 9 ` 9 2L 9 TO ] K.-
con;ert &ecimal ./J to binar$+
./J B L ] K/O
./O B L ] ./`
./` B L ] K/T
./T B L ] K/L
./L B L ] ./O
./O B L ] ./`
./` B L ] K/T
./T B L ] K/L etc/ *ote that %e ha;e starte& to repeat pre;ious
results/ *o% rea& the integer parts occurring on
the right si&e0 ,rom the top &o%n+ the binar$
representation o, &ecimal ./J is ./K.KK..KK..///
%here the CKK..C repeats ,ore;er/
The bit on the far right, in this case a ., is known as the Least signi,icant bit
3LS15.
The bit on the far left, in this case a K, is known as the Most signi,icant bit
3MS15
There are following Bitwise operators supported by C language
Operator !escription Example
&
Binary AND Operator copies a bit
to the result if it exists in both
operands.
(A & B) will give 12 which is 0000
1100
|
Binary OR Operator copies a bit if
it exists in either operand.
(A | B) will give 61 which is 0011
1101
^
Binary XOR Operator copies the
bit if it is set in one operand but
not both.
(A ^ B) will give 49 which is 0011
0001
~ Binary Ones Complement
Operator is unary and has the
(~A ) will give -60 which is 1100
0011
efect of 'flipping' bits.
<<
Binary Left Shift Operator. The left
operands value is moved left by
the number of bits specified by the
right operand.
A << 2 will give 240 which is 1111
0000
>>
Binary Right Shift Operator. The
left operands value is moved right
by the number of bits specified by
the right operand.
A >> 2 will give 15 which is 0000
1111
Try following example to understand all the Bitwise operators. Copy and paste
following C program in test.c file and compile and run this program.
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
unsigned int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}
This will produce following result
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
+ssignment Operators*
There are following assignment operators supported by C language:
Operator !escription Example
=
Simple assignment operator,
Assigns values from right side
operands to left side operand
C = A + B will assign value of A + B
into C
+=
Add AND assignment
operator, t adds right
operand to the left operand
and assign the result to left
operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment
operator, t subtracts right
operand from the left operand
and assign the result to left
operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment
operator, t multiplies right
operand with the left operand
and assign the result to left
operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment
operator, t divides left
operand with the right
operand and assign the result
to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment
operator, t takes modulus
using two operands and
assign the result to left
operand
C %= A is equivalent to C = C % A
<<=
Left shift AND assignment
operator
C <<= 2 is same as C = C << 2
>>=
Right shift AND assignment
operator
C >>= 2 is same as C = C >> 2
&=
Bitwise AND assignment
operator
C &= 2 is same as C = C & 2
^=
bitwise exclusive OR and
assignment operator
C ^= 2 is same as C = C ^ 2
|=
bitwise inclusive OR and
assignment operator
C |= 2 is same as C = C | 2
Try following example to understand all the Assignment Operators. Copy and
paste following C program in test.c file and compile and run this program.
main()
{
int a = 21;
int c ;
c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c );
c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );
c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
}
This will produce following result
Line 1 - = Operator Example, Value of c = 21
Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - %= Operator Example, Value of c = 11
Line 7 - <<= Operator Example, Value of c = 44
Line 8 - >>= Operator Example, Value of c = 11
Line 9 - &= Operator Example, Value of c = 2
Line 10 - ^= Operator Example, Value of c = 0
Line 11 - |= Operator Example, Value of c = 2
hort $otes on L-'+L/E and R-'+L/E*
x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced
by x. Here x and 1 are known as L-VALUES and R-VALUES respectively L-
values can be on either side of the assignment operator where as R-values only
appear on the right.
So x is an L-value because it can appear on the left as we've just seen, or on the
right like this: y = x; However, constants like 1 are R-values because 1 could
appear on the right, but 1 = x; is invalid.
Misc Operators
There are few other operators supported by C Language.
Operator !escription Example
sizeof()
Returns the size of an
variable.
sizeof(a), where a is interger, will
return 4.
&
Returns the address of an
variable.
&a; will give actaul address of the
variable.
* Pointer to a variable. *a; will pointer to a variable.
? : Conditional Expression
f Condition is true? Then value X :
Otherwise value Y
si0eo% Operator*
Try following example to understand sizeof operators. Copy and paste following
C program in test.c file and compile and run this program.
main()
{
int a;
short b;
double double c;
char d[10];
printf("Line 1 - Size of variable a = %d\n", sizeof(a) );
printf("Line 2 - Size of variable b = %d\n", sizeof(b) );
printf("Line 3 - Size of variable c= %d\n", sizeof(c) );
printf("Line 4 - Size of variable d= %d\n", sizeof(d) );
/* For character string strlen should be used instead of sizeof */
printf("Line 5 - Size of variable d= %d\n", strlen(d) );
}
This will produce following result
Line 1 - Size of variable a = 4
Line 2 - Size of variable b = 2
Line 3 - Size of variable c= 8
Line 4 - Size of variable d= 10
Line 5 - Size of variable d= 10
1 and 2 Operators*
Try following example to understand & operators. Copy and paste following C
program in test.c file and compile and run this program.
main()
{
int i=4; /* variable declaration */
int* ptr; /* int pointer */
ptr = &i; /* 'ptr' now contains the
address of 'i' */
printf(" i is %d.\n", i);
printf("*ptr is %d.\n", *ptr);
}
This will produce following result
i is 4.
*ptr is 4.
3 * Operator
Try following example to understand ? : operators. Copy and paste following C
program in test.c file and compile and run this program.
main()
{
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
printf( "Value of b is %d\n", b );
b = (a == 10) ? 20: 30;
printf( "Value of b is %d\n", b );
}
This will produce following result
Value of b is 30
Value of b is 20
*ote + K[s an& L[s complement
Generally negative numbers can be represented using
either 1's complement or 2's complement representation.
1's complement ---reverse all the bits
2's complement ---reverse all the bits + 1
i.e 1's complement of 2 ( 0000 0010 ) is -2 ( 1111 1101 )
2's complement of 2 ( 0000 0010 ) is -2 ( 1111 1110 )
Binary numbers do not have signs. So 2's complement is used to represent a
negative nos. 2's complement is found in following way :
Step )
f we have a binary no 00001100(decimal 12) then we have
to invert it by replacing all the 1s by 0 and 0s by 1.
So we get 00001100 ---> 11110011
Step )
Now we have to add 1 to the no which we found in ()
So we get ,
11110011 + 00000001 = 11110100
So the no 11110100 represents -12 .
Operators Categories*
All the operators we have discussed above can be categorised into following
categories:
Postfix operators, which follow a single operand.
Unary prefix operators, which precede a single operand.
Binary operators, which take two operands and perform a variety of
arithmetic and logical operations.
The conditional operator (a ternary operator), which takes three
operands and evaluates either the second or third expression,
depending on the evaluation of the first expression.
Assignment operators, which assign a value to a variable.
The comma operator, which guarantees left-to-right evaluation of
comma-separated expressions.
" Operator Prece&ence an& Associati;it$
C operators in order of precedence (highest to lowest). Their associati#ity
indicates in what order operators of equal precedence in an expression are
applied.
Operator !escription Associati;it$
()
[]
.
->
++ --
Parentheses (function call) (see Note 1)
Brackets (array subscript)
Member selection via object name
Member selection via pointer
Postfix increment/decrement (see Note 2)
left-to-right
++ --
+ -
! ~
(type)
*
&
sizeof
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (change type)
Dereference/pointer
Address
Determine size in bytes
right-to-left
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <=
> >=
Relational less than/less than or equal to
Relational greater than/greater than or
equal to
left-to-right
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
=
+= -=
*= /=
%= &=
^= |=
Assignment
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
right-to-left
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
*ote K+
Parentheses are also used to group sub-expressions to
force a different precedence; such parenthetical
expressions can be nested and are evaluated from inner to
outer.
*ote L+
Postfix increment/decrement have high precedence, but the
actual increment or decrement of the operand is delayed
(to be accomplished sometime before the statement
completes execution). So in the statement $ ] x B F99E the
current value of F is used to evaluate the expression (i.e.)
F99 evaluates to F) and F only incremented after all else is
done.
" Ternar$ Operator
C ternary operator is a shorthand of combination of if and return statement.
Syntax of ternary operator are as follows:
3expressionK 5 8 expressionL+ expression2
f expression1 is true it returns expression2 otherwise it returns expression3. This
operator is a shorthand version of this if and return statement:
if(expression1)
return expression2;
else
return expression3;
Increment operator 99
Prefix: the value is incremented/decremented first and then
applied.
Postfix: the value is applied and the value is incremented/decremented.
#include<stdio.h>
main( )
{
int i = 3,j = 4,k;
k = i++ + --j;
printf("i = %d, j = %d, k = %d",i,j,k);
}
Out put + i ] O0 _ ] 20 7 ] T
The &ecrement operator+ --
#include <stdio.h>
#include <stdlib.h>

int main()
{
char weight[4];
int w;

printf("Enter your weight:");
gets(weight);
w=atoi(weight);

printf("Here is what you weigh now: %i\n",w);
w--;
printf("w++: %i\n",w);
w--;
printf("w++: %i\n",w);
return(0);
}
Enter your weight:123
Here is what you weigh now: 123
w++: 122
K[s complement an& L[s complement
Generall$ negati;e numbers can be represente& using
either K[s complement or L[s complement representation/
K[s complement ---re;erse all the bits
L[s complement ---re;erse all the bits 9 K
i/e K[s complement o, L 3 .... ..K. 5 is -L 3 KKKK KK.K 5
Examples
Original number+ .KKK.KK
K[s complement+ K...K..
L[s complement+ K...K.K
Original number+ KKKKKKK
K[s complement+ .......
L[s complement+ ......K
Original number+ KKKK...
K[s complement+ ....KKK
L[s complement+ ...K...
se o, clrscr
Usually you want to clear the screen prior to writng to the terminal.
Use;
#include < conio.h> /* as in console /O */
...
main()
{
...
clrscr();
*ote that as this is a comman&0 it must appear a,ter $our ;ariable
&eclarations.
requires the header file conio.h i.e #include <conio.h>
clrscr35E :- This is use to clear the output screen i.e console
suppose you run a program and then alter it and run it again you may find that
the previous output is still stucked there itself, at this time clrscr(); would clean
the previous screen.
One more thing to remember always use clrscr(); after the declaration like
int a,b,c;
float total;
clrscr();
getch35A getche35
getch35E :- getch is used to hold the screen in simple language, if u dont write this
the screen
will just flash and go away....
getch35 ta7es one char ,rom 7e$boar& but it %ill be in;isible to us/ in other
%or&s %e can sa$ that it %aits until press an$ 7e$ ,rom 7e$boar&/
getch() is a function which has its protype defined in conio.h header file.
it is basically used to take input a single characterfrom keyboard. and this char is
not displayed at the screen.
it waits untill itn gets a input thats why it can be used as a screen stopper.
getch35 returns to the program after hitting any key.
getche35 waits for the character, read it and then returns
to the program
getch35 waits for the user to input a character and
displays the output till the user enters a character.As
soon as the user enters a character it transfers the
control back to the main function, without displaying what
character was entered.
getche35 does the same thin but it displays the chacter
entered.here e stands for echo.
se o, getch350getche35 an& getchar35 in "
Most of the program is ending with getch(),and so we think that getch() is used to
display the output...but it is wrong.t is used to get a single character from the
console.
Just see the behaviors o% various single character input %unctions in c#
getchar()
getche()
getch()
getchar() is used to get or read the input (i.e a single character) at run time.
Library:
<CONO.H>
Example Declaration:
char ch;
ch = getchar();
This function return the character read from the keyboard.
Example Program:
void main()
{
char ch;
ch = getchar();
printf("nput Char s :%c",ch);
}
Here,declare the variable ch as char data type, and then get a value through
getchar,- library function and store it in the variable ch.And then,print the value
of variable ch.
During the program execution, a single character is get or read through the
getchar,-. The given value is displayed on the screen and the compiler wait for
another character to be typed. f you press the enter key/any other characters
and then only the given character is printed through the print, function.
getche() is used to get a character from console, and echoes to the screen.
Library:
<CONO.H>
Example Declaration:
char ch;
ch = getche();
getche reads a single character from the keyboard and echoes it to the current
text window, using direct video or BOS.
This function return the character read from the keyboard.
Example Program:
void main()
{
char ch;
ch = getche();
printf("nput Char s :%c",ch);
}
Here,declare the variable ch as char data type, and then get a value through
getche,- library function and store it in the variable ch.And then,print the value of
variable ch.
During the program execution, a single character is get or read through the
getche,-. The given value is displayed on the screen and the compiler does not
wait for another character to be typed. Then,after wards the character is printed
through the print, function.
getch() is used to get a character from console but does not echo to the screen.
Library:
<CONO.H>
Example Declaration:
char ch;
ch = getch(); (or ) getch();
getch reads a single character directly from the keyboard, without echoing to the
screen.
This function return the character read from the keyboard.
Example Program:
void main()
{
char ch;
ch = getch();
printf("nput Char s :%c",ch);
}
Here,declare the variable ch as char data type, and then get a value through
getch,- library function and store it in the variable ch.And then,print the value of
variable ch.
During the program execution, a single character is get or read through the
getch,-. The given value is not displayed on the screen and the compiler does
not wait for another character to be typed.And then,the given character is printed
through the print, function.
= " Tips+
2?L 8 print,3PTrueQ5+print,3P'alseQ5E AA prints True
F]xB99$ AA it %ill increment ,irst then multiplies
The siFeo, Operator
The siFeo, operator gives the amount of storage, in bytes, required to store an
object of the type of the operand. This operator allows you to avoid specifying
machine-dependent data sizes in your programs.
The sizeof program uses the " sizeof() call to &ispla$ the siFe 3in b$tes5
o, the stan&ar& " &ata t$pes 3char0 int0 long0///5/
Int x]KLE,loat $]LE
Print,3siFeo,3x55E AA prints L 3b$tes5
Print,3siFeo,3$55E AA prints O3b$tes5
H operator
Prints the a&&ress o, the ;ariable in the memor$
#include <stdio.h>
int main() {
int x = 0;
printf("Address of x ");
printf("= 0x%p \n", &x);
return 0;
}
Output: A&&ress o, x ] .x..T-'!'O
int a; /* a is an integer */
printf( "The address of a is %p, &a )//prints address of variable a -8907
TIP
print,3PDnK.]]K. +Y-&Q0K.]]K.5EAA prints K ,or true
print,3PDnK.]]K. +Y-&Q0K.?]K.5E AA prints K
print,3PDnK.]]K. +Y-&Q0K.4]K.5EAAprints .
b]3a]]- 8 2+O5E AA prints ;alue o, b
TIP
print,3PY-&Q0-?2 HH ->K. 5E AAprints K ,or true
print,3PY-&Q0`?- aa `>L5E AA prints . ,or ,alse
$]3x?]T- HH x>]N.8 K+.5E AA is correct
" - STORAGE "LASSES
A storage class defines the scope 3;isibilit$5 an& li,e time o, ;ariables an&Aor
,unctions within a C Program.
There are following storage classes which can be used in a C Program
auto
register
static
extern
auto - torage Class
auto is the default storage class for all local variables.
{
int Count;
auto int Month;
}
The example above defines two variables with the same storage class.
auto can onl$ be use& %ithin ,unctions0 i/e/ local ;ariables/
register - torage Class
register is used to &e,ine local ;ariables that shoul& be store& in a register
instea& o, RAM/ This means that the variable has a maximum size equal to the
register size (usually one word) and cant have the unary '&' operator applied to it
(as it does not have a memory location).
{
register int Miles;
}
Register shoul& onl$ be use& ,or ;ariables that reVuire Vuic7 access - such
as counters/ t should also be noted that defining 'register' does not mean that
the variable will be stored in a register. It means that it MIGHT be store& in a
register - &epen&ing on har&%are an& implementation restrictions/
static - torage Class
static is the &e,ault storage class ,or global ;ariables. The two variables
below (count and road) both have a static storage class.
static int Count;
int Road;
{
printf("%d\n", Road);
}
static ;ariables can be [seen[ %ithin all ,unctions in this source ,ile. At lin7
time0 the static ;ariables &e,ine& here %ill not be seen b$ the ob_ect
mo&ules that are brought in/
static can also be &e,ine& %ithin a ,unction. I, this is &one the ;ariable is
initialiFe& at run time but is not reinitialiFe& %hen the ,unction is calle&.
This inside a ,unction static ;ariable retains its ;alue during various calls.
void func(void);

static count=10; /* Global ;ariable - static is the &e,ault */

main()
{
while (count--)
{
func();
}

}

void func( void )
{
static i ] -E
i++;
printf("i is %d and count is %d\n", i, count);
}

This will produce following result

i is T an& count is N
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
*OTE + Here keyword #oid means function does not return anything and it does
not take any parameter. You can memorizes void as nothing. static ;ariables
are initialiFe& to . automaticall$/
!e,inition ;s !eclaration + Before proceeding, let us understand the difference
between de%intion an& declaration of a variable or function. !e,inition means
%here a ;ariable or ,unction is &e,ine& in realit$ an& actual memor$ is
allocate& ,or ;ariable or ,unction/ !eclaration means _ust gi;ing a re,erence
o, a ;ariable an& ,unction/ Through &eclaration %e assure to the complier
that this ;ariable or ,unction has been &e,ine& some%here else in the
program and will be provided at the time of linking. n the above examples char
*func(#oid) has been put at the top which is a declaration of this function where
as this function has been defined below to main() function.
There is one more very important use for 'static'. Consider this bit of code.
char *func(void);
main()
{
char *Text1;
Text1 = func();
}
char *func(void)
{
char Text2[10]="martin";
return(Text2);
}
Now, 'func' returns a pointer to the memory location where 'text2' starts BUT
text2 has a storage class of 'auto' and will disappear when we exit the function
and could be overwritten but something else. The answer is to specify
static char Text[10]="martin";
The storage assigned to 'text2' will remain reserved for the duration if the
program.
e4tern - torage Class
extern is used to gi;e a re,erence o, a global ;ariable that is ;isible to ALL
the program ,iles. (hen $ou use [extern[ the ;ariable cannot be initialiFe&
as all it &oes is point the ;ariable name at a storage location that has been
pre;iousl$ &e,ine&/
When you have multiple files and $ou &e,ine a global ;ariable or ,unction
%hich %ill be use& in other ,iles also0 then e4tern %ill be use& in another
,ile to gi;e re,erence o, &e,ine& ;ariable or ,unction. Just for understanding
e4tern is use& to &eclare a global ;ariable or ,unction in another ,iles.
File 1: main.c
int count=5;
main()
{
write_extern();
}
File 2: write.c
void write_extern(void);
extern int count;
void write_extern(void)
{
printf("count is %i\n", count);
}
Here e+tern keyword is being used to declare count in another file.
Now compile these two files as follows
gcc main.c write.c -o write
This fill produce write program which can be executed to produce result.
Count in 'main.c' will have a value of 5. f main.c changes the value of count -
write.c will see the new value
" - I*PT A*! OTPT
Input + n any programming language input means to feed some data into
program. This can be given in the form of file or from command line. C
programming language provides a set of built-in functions to read given input and
feed it to the program as per requirement.
Output + n any programming language output means to display some data on
screen, printer or in any file. C programming language provides a set of built-in
functions to output required data.
Here we will discuss only one input function and one output function just to
understand the meaning of input and output. Rest of the functions are given into
C - Built-in Functions
print%,- %unction
This is one of the most frequently used functions in C for output. Try following
program to understand print,35 function.
#include <stdio.h>
main()
{
int dec = 5;
char str[] = "abc";
char ch = 's';
float pi = 3.14;
printf("%d %s %f %c\n", dec, str, pi, ch);
}
The output of the above would be:
5 abc 3.140000 c
Here Y& is being use& to print an integer0 Ys is being use& to print a
string0 Y, is being use& to print a ,loat an& Yc is being use& to print a
character/
scan%,- %unction
This is the function which can be used to to read an input from the command line.
Try following program to understand scan,35 function.
#include <stdio.h>
main()
{
int x;
int args;
printf("Enter an integer: ");
if (( args = scanf("%d", &x)) == 0) {
printf("Error: not an integer\n");
} else {
printf("Read in %d\n", x);
}
}
Here Y& is being use& to rea& an integer ;alue an& %e are passing Hx to
store the ;alue rea& input/ Here Hin&icates the a&&ress o, ;ariable x/
This program %ill prompt $ou to enter a ;alue/ (hate;er ;alue $ou %ill
enter at comman& prompt that %ill be output at the screen using print,35
,unction. I, $ou enter a non-integer ;alue then it %ill &ispla$ an error
message/
Enter an integer+ L.
Rea& in L.
Here is another program that %ill help $ou learn more about print,+
#include <stdio.h>
int main()
{
int a, b, c;
a = 5;
b = 7;
c = a + b;
printf("%d + %d = %d\n", a, b, c);
return 0;
}
You will see the line "5 + 7 = 12" as output.
The computer adds the value in a (5) to the value in b (7) to form the result 12,
and then places that new value (12) into the variable c. The variable c is
assigned the value 12. 'or this reason0 the ] in this line is calle& Cthe
assignment operator/C
The print, statement then prints the line "5 + 7 = 12." The Y&
placehol&ers in the print, statement act as placehol&ers ,or ;alues. There
are three %d placeholders, and at the end of the printf line there are the three
variable names: a, b and c. C matches up the first %d with a and substitutes 5
there. t matches the second %d with b and substitutes 7. t matches the third %d
with c and substitutes 12. Then it prints the completed line to the screen: 5 + 7 =
12. The 9, the ] and the spacing are a part of the format line and get embedded
automatically between the %d operators as specified by the programmer.
" Errors to A;oi&+
Using the wrong character case - Case matters in C, so you cannot type
Print, or PRI*T'. t must be print,.
'orgetting to use the H in scan,
Too man$ or too ,e% parameters ,ollo%ing the ,ormat statement in print,
or scan,
'orgetting to &eclare a ;ariable name be,ore using it
The pre;ious program is goo&0 but it %oul& be better i, it rea& in the ;alues
- an& J ,rom the user instea& o, using constants. Try this program instead:
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter the first value:");
scanf("%d", &a);
printf("Enter the second value:");
scanf("%d", &b);
c = a + b;
printf("%d + %d = %d\n", a, b, c);
return 0;
}
Here's how this program works when you execute it:
Make the changes, then compile and run the program to make sure it works.
Note that scanf uses the same sort of format string as printf (type man scan, for
more info).
Also note the & in front of a and b. This is the a&&ress operator in ": It returns
the a&&ress o, the ;ariable (this will not make sense until we discuss pointers).
:ou must use the H operator in scan, on an$ ;ariable o, t$pe char0 int0 or
,loat0 as %ell as structure t$pes 3%hich %e %ill get to shortl$5/ I, $ou lea;e
out the H operator0 $ou %ill get an error %hen $ou run the program. Try it so
that you can see what that sort of run-time error looks like.
Let[s loo7 at some ;ariations to un&erstan& print, completel$. Here is the
simplest printf statement:
printf("Hello");
This call to print, has a ,ormat string that tells print, to sen& the %or&
CHelloC to stan&ar& out/ Contrast it with this:
printf("Hello\n");
The &i,,erence bet%een the t%o is that the second version sends the word
"Hello" ,ollo%e& b$ a carriage return to stan&ar& out/
The following line shows how to output the ;alue o, a ;ariable using print,.
printf("%d", b);
The Y& is a placehol&er that %ill be replace& b$ the ;alue o, the ;ariable b
%hen the print, statement is execute&. Often, you will want to embed the value
within some other words. One way to accomplish that is like this:
print,3CThe temperature is C5E
print,3CY&C0 b5E
print,3C &egreesDnC5E
An easier %a$ is to sa$ this+
print,3CThe temperature is Y& &egreesDnC0 b5E
You can also use multiple Y& placehol&ers in one print, statement:
print,3CY& 9 Y& ] Y&DnC0 a0 b0 c5E
n the printf statement, it is extremel$ important that the number o, operators
in the ,ormat string correspon&s exactl$ %ith the number an& t$pe o, the
;ariables ,ollo%ing it . For example, if the format string contains three %d
operators, then it must be followed by exactly three parameters and they must
have the same types in the same order as those specified by the operators.
You can print all o, the normal " t$pes %ith print, by using different
placeholders:
int 3integer ;alues5 uses Y&
,loat 3,loating point ;alues5 uses Y,
char 3single character ;alues5 uses Yc
character strings 3arra$s o, characters0 &iscusse& later5 use Ys
You can learn more about the nuances of printf on a UNX machine by typing
man 2 print,. Any other C compiler you are using will probably come with a
manual or a help file that contains a description of printf.
Scan,
Mo&i,$ this program so that it accepts three ;alues instea& o, t%o an&
a&&s all three together+
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter the first value:");
scanf("%d", &a);
printf("Enter the second value:");
scanf("%d", &b);
c = a + b;
printf("%d + %d = %d\n", a, b, c);
return 0;
}

The scan, ,unction allo%s $ou to accept input ,rom stan&ar& in, %hich ,or
us is generall$ the 7e$boar&/ The scanf function can do a lot of different things,
but it is generally unreliable unless used in the simplest ways. It is unreliable
because it &oes not han&le human errors ;er$ %ell. But for simple programs
it is good enough and easy-to-use.
The simplest application of scan, looks like this:
scan,3CY&C0 Hb5E
The program %ill rea& in an integer ;alue that the user enters on the
7e$boar& 3Y& is ,or integers0 as is print,0 so b must be &eclare& as an int5
an& place that ;alue into b/
The scan, ,unction uses the same placehol&ers as print,+
int uses Y&
,loat uses Y,
char uses Yc
character strings (discussed later) use Ys
:ou MST put H in ,ront o, the ;ariable use& in scan,/ The reason %h$ %ill
become clear once $ou learn about pointers/ It is eas$ to ,orget the H sign0
an& %hen $ou ,orget it $our program %ill almost al%a$s crash %hen $ou
run it/
n general, it is best to use scanf as shown here -- to rea& a single ;alue ,rom
the 7e$boar&/ se multiple calls to scan, to rea& multiple ;alues/ In an$ real
program0 $ou %ill use the gets or ,gets ,unctions instea& to rea& text a line
at a time/ Then $ou %ill CparseC the line to rea& its ;alues. The reason that
you do that is so you can detect errors in the input and handle them as you see
fit.
Char a;
Printf("enter value for a);
Scanf("%d,&a);
Printf("%d,a); // prints 255 if entered 255
// prints 0 if entered 256 coz char range is from 0 to 255
so after that range it considers as beginning so 0 is printed.
The print, an& scan, ,unctions will take a bit of practice to be completely
understood, but once mastered they are extremely useful.
To use a placehol&er0 $ou %rite Ydatatype replacing datatype %ith a ;alue
correspon&ing to the t$pe o, the ;ariable to be &ispla$e&. Finally, the name
of the variable to be displayed is added after the last quotation mark, but before
the semi-colon.
The values for ;ariable placehol&ers are as follows:
,ormat string input t$pe
Yc character
Y& &igit 3integer5
Y, ,loat
Yl, &ouble
Yu unsigne&
Ys string
printf("The value of my variable is %d",integer_var);
printf("Here is an integer: %d, a float: %f, and a character: %c",int_var,
float_var, char_var);
One commonl$ use& escape co&e is 5n0 %hich is use& to a&& a line ,ee& to
the output/ Escape characters al%a$s start %ith a bac7slash CDC/
printf("the number is %d\n\n",number);
%ill output+
the number is , (,ollo%e& b$ t%o blan7 lines5/
ES"APE SEbE*"ES
Escape SeVuence !escription
\' Single quote
\" Double quote
\\ Backslash
\nnn Octal number (nnn)
\0 Null character (really just the octal number zero)
\a Audible bell
\b Backspace
\f Formfeed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\xnnn Hexadecimal number (nnn)
\? Question mark
" has no built-in statements ,or input or output/

A librar$ o, ,unctions is supplie& to per,orm these operations/ The
IAO librar$ ,unctions are liste& the Phea&erQ ,ile >st&io/h?/

All input an& output is per,orme& %ith streams/

A CstreamC is a seVuence o, characters organiFe& into lines/

Each line consists o, Fero or more characters an& en&s %ith the
Cne%lineC character/
A*SI " stan&ar&s speci,$ that the s$stem must support lines that are
at least L-O characters in length 3inclu&ing the ne%line character5/
T$pes o, Streams in "
Stan&ar& input stream is calle& Cst&inC an& is normall$ connecte& to
the 7e$boar&

Stan&ar& output stream is calle& Cst&outC an& is normall$ connecte&
to the &ispla$ screen/

Stan&ar& error stream is calle& Cst&errC an& is also normall$
connecte& to the screen/
'ormatte& Output %ith print,
print, 3 5 E
This ,unction pro;i&es ,or ,ormatte& output to the screen/ The
s$ntax is+
print, 3 P,ormatQ0 ;arK0 ;arL0 ^ 5 E
The P,ormatQ inclu&es a listing o, the &ata t$pes o, the ;ariables to
be output an&0 optionall$0 some text an& control character3s5/
Example+
,loat a E int b E
scan, 3 PY,Y&Q0 Ha0 Hb 5 E
print, 3 P:ou entere& Y, an& Y& DnQ0 a0 b 5 E
getchar 3 5 E
This ,unction pro;i&es ,or getting exactl$ one character ,rom the
7e$boar&/
Example+
char chE
ch ] getchar 3 5 E
putchar 3char5 E
This ,unction pro;i&es ,or printing exactl$ one character to the
screen/
Example+
char chE
ch ] getchar 3 5 E AB input a character ,rom 7b&BA
putchar 3ch5 E AB &ispla$ it on the screen BA
getc 3 B,ile 5 E
This ,unction is similar to getchar3 5 except the input can be ,rom the
7e$boar& or a ,ile/
Example+
char chE
ch ] getc 3st&in5 E AB input ,rom 7e$boar& BA
ch ] getc 3,ileptr5 E AB input ,rom a ,ile BA
putc 3 char0 B,ile 5 E
This ,unction is similar to putchar 3 5 except the output can be to the
screen or a ,ile/
Example+
char chE
ch ] getc 3st&in5 E AB input ,rom 7e$boar& BA
putc 3ch0 st&out5 E AB output to the screen BA
putc 3ch0 out,ileptr5 E ABoutput to a ,ile BA
'ORMATTE! A*! *'ORMATTE! '*"TIO*S
-here are numerous library functions a#ailable for ./0. -hese can be classified
into three broad categories1
a. Console /O functions - functions to receive input from keyboard and write
output to VDU.
b. Disk /O functions - functions to perform /O operations on a floppy disk or
hard disk.
c. Port /O functions - functions to perform /O operations on various ports.
"onsole IAO 'unctions+
Console /O functions can be further classified.
"onsole InputAOutput ,unctions

Formatted functions Unformatted functions
6ype Input
Outpu
t
6ype Input Output
char scanf() printf() char getch() putch()
getchar() putchar()
getche( )
int scanf() printf() int - -
float scanf() printf() float - -
string scanf() printf() string gets() puts()
The basic di%%erence bet&een %ormatted and un%ormatted I!O %unctions is
that the %ormatted %unctions allo& the input read %rom the 7eyboard or the
output displayed on the ')/ to be %ormatted as per our re8uirements. 2or
e+ample) if #alues of a#erage mar3s and percentage mar3s are to be displayed
on the screen) then the details li3e where this output would appear on the
screen) how many spaces would be present between the two #alues) the number
of places after the decimal points etc.) can be controlled using formatted
functions.
-he library implements a simple model of te+t input and output. 4 te+t consists of
a se'uence of lines) each ending with a newline character. .f the system doesn5t
operate that way) the library does whate#er is necessary to ma3e it appear as if it
does. 2or instance) the library might con#ert carriage return and linefeed to
newline on input and back again on output.
getchar3 5+
The simplest input mechanism is to read one character at a time from the
standard input, normally the keyboard, with getchar( ).
int getchar3;oi&5E
getchar( ) returns the next input character each time it is called, or EOF when it
encounters, end of file. The symbolic constant EOF is defined in . The value is
typically -1, but tests should be written in terms of EOF so as to be independent
of the specific value.
putchar3 5+
The function :
int putchar3;oi&5E
is used for output. Putchar(c) puts the character c on the standard output, which
is by default, the screen. Putchar() returns the character written, or EOF if an
error occurs.
=inclu&e >st&io/h?
=inclu&e>ct$pe/h?
main35
AB "on;ert input to lo%er case BA
@
int cE
%hile 33c ] getchar355 4] EO'5
putchar3tolo%er3c 55E
return .E
G
print,3 5+
The output function printf() translates internal values to character.
print,3char ,ormat0 argK0 argL0 /// 5
The format string can contain:
Characters that are simply printed as they are.
Conversion specification that begins with a % sign.
Escape sequences that begins with a \ sign.
Printf() converts, formats, and prints its arguments on the standard output under
the control of the format. t returns the number of characters printed. The format
string contains two types of objects - ordinary characters, which are copied to the
output stream, and conversion specifications, each of which causes conversion
and printing of the next successive argument to printf(). Each conversion
specification begins with % and ends with a conversion character. Between the
% and the conversion character there may be, in order:
A minus sign, which specifies left adjustment of the converted argument.
A number that specifies the minimum field width. The converted
arguments will be printed in a field at least as wide as the specified
minimum. f necessary, it will be padded on the left (or right, if left
adjustment is called for) to make up the field width.
A period (.) separates the field width from the precision.
A number, i.e., the precision that specifies the maximum number of
characters to be printed from a string, or the number of digits after the
decimal point of a floating-point value, or the minimum number of digits for
an integer.
f the character after the % is not a conversion specification, the behavior is
undefined.
sprint,3 5+
This function works similar to the print,3 5 ,unction except ,or one small
&i,,erence/ Instea& o, sen&ing the output to the screen as print,3 5 &oes0 this
,unction %rites the output to an arra$ o, characters/ For example, look at the
following problem:
=inclu&e>st&io/h?
main3 5
@
int i ] K. E
char ch ] [A[ E
,loat a ] 2/KO E
char strWL.X E AB Arra$ o, characters BA
print, 3 CY& Yc Y,C0 i0 ch0 a5 E
sprint, 3 str0 CY& Yc Y,C0 i0 ch0 a5 E
print, 3 CYsC0 str 5 E
G
n this program, the print,3 5 prints out the ;alues o, i0 ch an& a on the screen,
whereas sprint,3 5 stores these ;alues in the character arra$ str. Since the
string str is present in memor$0 %hat is %ritten into str using sprint,3 5
&oesn[t get &ispla$e& on the screen/ Once str has been built0 its contents
can be &ispla$e& on the screen/ n our program this is achieved by the second
printf( ) statement.
scan,3 5+
scanf( ) allows us to enter data from the keyboard that will be formatted in a
certain way. The general form of scanf( ) statement is as follows:
scan,3CY& Y, YcC0Hc0Ha0Hch5E
Note that %e are sen&ing the a&&resses o, ;ariables 3a&&resses are
obtaine& b$ using H - [a&&ress o,[ operator5 to scan,3 5 ,unction. This is
necessary because the values received from keyboard must be dropped into
variables corresponding to these addresses. The values that are supplied
through the keyboard must be separated by either blank(s), tab(s), or newline(s).
Do not include these escape sequences in the format string.
Following is the list of conversion characters that can used with printf( ) and
scanf( ) function.
!ata t$pe
"on;ersion
character
nteger short signed %d or %i

short
unsigned
%u
long signed %ld

long
unsigned
%lu

unsigned
hexadecimal
%x

unsigned
octal
%o
Real float %f or %g
double %lf
Characters signed char %c

unsigned
char
%c
string %s
Aborts program with error -
%n
Hexadecimal
number is
small case
%hx
Hexadecimal number is upper
case %p
po%35 ,unction c inclu&e >math/h?
int x]L0$]2E
print,3x0$0po%3x0$55EAA gi;es thir& po%er o, t%o
main3;oi&5 @ G AAcorrect
;oi& main35 AAcorrect
gets3 5+
The gets3 5 ,unction recei;es a string ,rom the 7e$boar&/ The scan,3 5
,unction has some limitations %hile recei;ing a string o, characters
because the moment a blan7 character is t$pe&0 scan,3 5 assumes that the
en& o, the &ata is being entere&. So it is possible to enter onl$ one %or&
string using scan,3 5/ To enter multiple %or&s in to the string0 the gets3 5
,unction can be use&/ Spaces and tabs are perfectly accepted as part of the
string. t is terminated when the enter key is hit.
gets3;ariable name5E
For example:
gets3name5E
puts3 5+
The puts3 5 ,unction %or7s exactl$ opposite to gets3 5 ,unction. It outputs a
string to the screen/ Puts( ) can output a single string at a time.
puts3;ariable name5E
For example :
=inclu&e>st&io/h?
main3 5
@
char nameWO.XE
puts3CEnter $our nameC5E
gets3name5E
puts3C:our name isC5E
puts3name5E
G
Useful functions include:
print,35 Print a ,ormatte& string to st&out/
scan,35 Rea& ,ormatte& &ata ,rom st&in/
putchar35 Print a single character to st&out/
getchar35 Rea& a single character ,rom st&in/
puts35 Print a string to st&out/
gets35 Rea& a line ,rom st&in/
The three most useful PC console /O functions are:
getch35 Get a character ,rom the 7e$boar& 3no nee& to press
Enter5/
getche35 Get a character ,rom the 7e$boar& an& echo it/
7bhit35 "hec7 to see i, a 7e$ has been presse&/
Using the wrong format code for a particular data type can lead to bizarre output.
Further control can be obtained with modifier codes; for example, a numeric
prefix can be included to specify the minimum field width:
YK.&
This speci,ies a minimum ,iel& %i&th o, ten characters. f the field width is too
small, a wider field will be used. Adding a minus sign:
Y-K.&
- causes the text to be le,t-_usti,ie&. A numeric precision can also be specified:
YT/2,
This speci,ies three &igits o, precision in a ,iel& six characters %i&e. A string
precision can be specified as well, to indicate the maximum number of characters
to be printed. For example:
AB prtint/c BA
=inclu&e >st&io/h?
;oi& main35
@
print,3 C>Y&?DnC0 22T 5E
print,3 C>YL&?DnC0 22T 5E
print,3 C>YK.&?DnC0 22T 5E
print,3 C>Y-K.&?DnC0 22T 5E
G
This prints:
>22T?
>22T?
> 22T?
>22T ?
Similarly:
AB pr,loat/c BA
=inclu&e >st&io/h?
;oi& main35
@
print,3 C>Y,?DnC0 KL2O/-T 5E
print,3 C>Ye?DnC0 KL2O/-T 5E
print,3 C>YO/L,?DnC0 KL2O/-T 5E
print,3 C>Y2/K,?DnC0 KL2O/-T 5E
print,3 C>YK./2,?DnC0 KL2O/-T 5E
print,3 C>YK./2e?DnC0 KL2O/-T 5E
G
-- prints:
>KL2O/-T....?
>K/L2O-T.e9.2?
>KL2O/-T?
>KL2O/T?
> KL2O/-T.?
> K/L2Oe9.2?
And finally:
AB prtstr/c BA
=inclu&e >st&io/h?
;oi& main35
@
print,3 C>YLs?DnC0 C1arne$ must &ie4C 5E
print,3 C>YLLs?DnC0 C1arne$ must &ie4C 5E
print,3 C>YLL/-s?DnC0 C1arne$ must &ie4C 5E
print,3 C>Y-LL/-s?DnC0 C1arne$ must &ie4C 5E
G
-- prints:
>1arne$ must &ie4?
> 1arne$ must &ie4?
> 1arne?
<Barne >
" - 1ILT-I* LI1RAR: '*"TIO*S
String Manipulation 'unctions
char Bstrcp$ 3char B&est0 char Bsrc5E
Copy src string into dest string.

char Bstrncp$3char BstringK0 char BstringL0 int n5E


Copy first n characters of string2 to stringl .

int strcmp3char BstringK0 char BstringL5E


Compare string1 and string2 to determine alphabetic order.

int strncmp3char BstringK0 char BstringL0 int n5E


Compare first n characters of two strings.

int strlen3char Bstring5E


Determine the length of a string.

char Bstrcat3char B&est0 const char Bsrc5E


Concatenate string src to the string dest.

char Bstrncat3char B&est0 const char Bsrc0 int n5E


Concatenate n chracters from string src to the string dest.

char Bstrchr3char Bstring0 int c5E


Find first occurrence of character c in string.

char Bstrrchr3char Bstring0 int c5E


Find last occurrence of character c in string.

char Bstrstr3char BstringL0 char stringBK5E


Find first occurrence of string string1 in string2.

char Bstrto73char Bs0 const char B&elim5 E


Parse the string s into tokens using delim as delimiter.
Memor$ Management 'unctions
;oi& Bcalloc3int num elems0 int elem<siFe5E
Allocate an array and initialise all elements to zero .

;oi& ,ree3;oi& Bmem a&&ress5E


Free a block of memory.

;oi& Bmalloc3int num b$tes5E


Allocate a block of memory.

;oi& Brealloc3;oi& Bmem a&&ress0 int ne%siFe5E


Reallocate (adjust size) a block of memory.
1u,,er Manipulation
;oi&B memcp$3;oi&B s0 const ;oi&B ct0 int n5E
Copies n characters from ct to s and returns s. s may be corrupted if
objects overlap.

int memcmp3const ;oi&B cs0 const ;oi&B ct0 int n5E


Compares at most (the first) n characters of cs and ct, returning negative
value if cs<ct, zero if cs==ct, positive value if cs>ct.

;oi&B memchr3const ;oi&B cs0 int c0 int n5E


Returns pointer to first occurrence of c in first n characters of cs, or NULL
if not found.

;oi&B memset3;oi&B s0 int c0 int n5E


Replaces each of the first n characters of s by c and returns s.

;oi&B memmo;e3;oi&B s0 const ;oi&B ct0 int n5E


Copies n characters from ct to s and returns s. s will not be corrupted if
objects overlap.
"haracter 'unctions
int isalnum3int c5E
The function returns nonzero if c is alphanumeric

int isalpha3int c5E


The function returns nonzero if c is alphabetic only

int iscntrl3int c5E


The function returns nonzero if c is a control chracter

int is&igit3int c5E


The function returns nonzero if c is a numeric digit

int isgraph3int c5E


The function returns nonzero if c is any character for which either isalnum
or ispunct returns nonzero.

int islo%er3int c5E


The function returns nonzero if c is a lower case character.

int isprint3int c5E


The function returns nonzero if c is space or a character for which isgraph
returns nonzero.

int ispunct3int c5E


The function returns nonzero if c is punctuation

int isspace3int c5E


The function returns nonzero if c is space character

int isupper3int c5E


The function returns nonzero if c is upper case character

int isx&igit3int c5E


The function returns nonzero if c is hexa digit

int tolo%er3int c5E


The function returns the corresponding lowercase letter if one exists and if
isupper(c); otherwise, it returns c.

int toupper3int c5E


The function returns the corresponding uppercase letter if one exists and if
islower(c); otherwise, it returns c.
Error Han&ling 'unctions
;oi& perror3const char Bs5E
produces a message on standard error output describing the last error
encountered.

char Bstrerror3int errnum 5E


returns a string describing the error code passed in the argument errnum.
" LI1RAR: '*"TIO*S +
" MATH LI1RAR:
* The math library requires the declaration:
=inclu&e >math/h?
The math functions consist of:
sin3 x 5 Sine o, x/
cos3 x 5 "osine o, x/
tan3 x 5 Tangent o, x/
asin3 x 5 In;erse sine o, x/
acos3 x 5 In;erse cosine o, x/
atan3 x 5 In;erse tangent o, x/
sinh3 x 5 H$perbolic sine o, x/
cosh3 x 5 H$perbolic cosine o, x/
tanh3 x 5 H$perbolic tangent o, x/
exp3 x 5 Exponential ,unction -- edx/
log3 x 5 *atural log o, x/
logK.3 x 5 1ase K. log o, x/
po%3 x0 $ 5 Po%er ,unction -- xd$/
sVrt3 x 5 SVuare root o, x/
ceil3 x 5 Smallest integer not less than x0 returne& as &ouble/
,loor3 x 5 Greatest integer not greater than x0 returne& as &ouble/
,abs3 x 5 Absolute ;alue o, x/
All values are "doubles", and trig values are expressed in radians.
" STA*!AR! TILIT: LI1RAR: H TIME LI1RAR:
* The utility functions library features a grab-bag of functions. t requires the
declaration:
=inclu&e >st&lib/h?
Useful functions include:
ato,3 >string? 5 "on;ert numeric string to &ouble ;alue/
atoi3 >string? 5 "on;ert numeric string to int ;alue/
atol3 >string? 5 "on;ert numeric string to long ;alue/
ran&35 Generates pseu&oran&om integer/
sran&3 >see&? 5 See& ran&om-number generator -- Csee&C is an CintC/
exit3 >status? 5 Exits program -- CstatusC is an CintC/
s$stem3 >string? 5 Tells s$stem to execute program gi;en b$ the see&/
abs3 n 5 Absolute ;alue o, CintC argument/
labs3 n 5 Absolute ;alue o, long-int argument/
The functions "atof()", "atoi()", and "atol()" will return 0 if they can't convert the
string given them into a value.
The time and date library includes a wide variety of functions, some of them
obscure and nonstandard. This library requires the declaration:
=inclu&e >time/h?
The most essential function is "time()", which returns the number of seconds
since some long-ago date. t returns a value as "time_t" (a "long") as defined in
the header file.
The ,ollo%ing ,unction uses Ctime35C to implement a program &ela$ %ith
resolution in secon&s+
AB &ela$/c BA
=inclu&e >st&io/h?
=inclu&e >time/h?
;oi& sleep3 time<t &ela$ 5E
;oi& main35
@
puts3 C!ela$ing ,or 2 secon&s/C 5E
sleep3 2 5E
puts3 C!one4C 5E
G
;oi& sleep3 time<t &ela$ 5
@
time<t t.0 tKE
time3 Ht. 5E
&o
@
time3 HtK 5E
G
%hile 33 tK - t. 5 > &ela$ 5E
G
The "ctime()" function converts the time value returned by "time()" into a time-
and-date string. The following little program prints the current time and date:
AB time/c BA
=inclu&e >st&io/h?
=inclu&e >time/h?
;oi& main35
@
time<t BtE
time3 t 5E
puts3 ctime3 t 55E
G
This program prints a string of the form:
Tue !ec LJ K-+K`+KT KNNO
69E C :PRI$6;,-: ;/$C6IO$
* The "sprint,C ,unction creates strings %ith ,ormatte& &ata. Technically
speaking, this is part of the standard-/O library, and requires the declaration:
=inclu&e >st&io/h?
However, it is really a string function and needs to be discussed along with the
other string functions. The s$ntax o, Csprint,35C is exactl$ the same as it is ,or
Cprint,35C0 %ith the notable exception that the ,irst parameter is a pointer to
a string/ For example:
AB csprnt,/c BA
=inclu&e >st&io/h?
;oi& main35
@
char bWK..XE
int i ] OLE
,loat , ] K/KL2O,E
sprint,3 b0 C'ormatte& &ata+ Y& A Y,C0 i0 , 5E
puts3 b 5E
G
-- prints the string:
'ormatte& &ata+ OL A K/KL2O
There is also an "sscan,35C ,unction that similarl$ mirrors Cscan,35C
,unctionalit$.
C 6RI$( ;/$C6IO$ LI.R+R<
* The string-function library requires the declaration:
=inclu&e >string/h?
The most important string functions are as follows:
strlen35 Get length o, a string/
strcp$35 "op$ one string to another/
strcat35 Lin7 together 3concatenate5 t%o strings/
strcmp35 "ompare t%o strings/
strchr35 'in& character in string/
strstr35 'in& string in string/
strl%r35 "on;ert string to lo%ercase/
strupr35 "on;ert string to uppercase/
* The "strlen()" function gives the length of a string, not including the NULL
character at the end:
#include <stdio.h>
#include <string.h>
void main()
{
char *t = "XXX";
printf( "Length of <%s> is %d.\n", t, strlen( t ));
}
This prints:
Length o, >666? is 2/
* The "strcp$C ,unction copies one string ,rom another. For example:
#include <stdio.h>
#include <string.h>
void main()
{
char s1[100],
s2[100];
strcpy( s1, "string 2" );
strcpy( s2, "string 1" );
puts( "Original strings: " );
puts( "" );
puts( s1 );
puts( s2 );
puts( "" );
strcpy( s2, s1 );
puts( "New strings: " );
puts( "" );
puts( s1 );
puts( s2 );
}
This will print:
Original strings+
string K
string L
*e% strings+
string K
string K
Please be aware of two features of this program:
This program assumes that "s1" has enough space to store the final
string. The Cstrcp$35C ,unction %on[t bother to chec70 an& %ill gi;e
erroneous results i, that is not the case/
A string constant can be use& as the source string instea& o, a string
;ariable/ Using a string constant for the destination, of course, makes no
sense.
These comments are applicable to most of the other string functions.
There is a variant form of "strcp$C name& Cstrncp$C that %ill cop$ CnC
characters o, the source string to the &estination string0 presuming there
are that man$ characters a;ailable in the source string. For example, if the
following change is made in the example program:
strncp$3 sL0 sK0 - 5E
-- then the results change to:
*e% strings+
string K
string
Notice that the parameter "n" is declared "size_t", which is defined in "string.h".
* The "strcat35C ,unction _oins t%o strings+
#include <stdio.h>
#include <string.h>
void main()
{
char s1[50],
s2[50];
strcpy( s1, "Tweedledee " );
strcpy( s2, "Tweedledum" );
strcat( s1, s2 );
puts( s1 );
}
This prints:
T%ee&le&ee T%ee&le&um
There is a variant version of "strcat()" named "strncat()" that will append "n"
characters of the source string to the destination string. f the example above
used "strncat()" with a length of 7:
strncat3 sK0 sL0 J 5E
-- the result would be:
T%ee&le&ee T%ee&le
Again, the length parameter is of type "size_t".
* The Cstrcmp35C ,unction compares t%o strings+
#include <stdio.h>
#include <string.h>
#define ANSWER "blue"
void main()
{
char t[100];
puts( "What is the secret color?" );
gets( t );
while ( strcmp( t, ANSWER ) != 0 )
{
puts( "Wrong, try again." );
gets( t );
}
puts( "Right!" );
}
The "strcmp()" function returns a 0 for a successful comparison, and nonzero
otherwise. The comparison is case-sensitive, so answering "BLUE" or "Blue"
won't work.
There are three alternate forms for "strcmp()":
A "strncmp()" function which, as might be guessed, compares "n"
characters in the source string with the destination string: "strncmp( s1, s2,
6 )".
A "stricmp()" function that ignores case in comparisons.
A case-insensitive version of "strncmp" called "strnicmp".
* The CstrchrC ,unction ,in&s the ,irst occurrence o, a character in a string. t
returns a pointer to the character if it finds it, and null if not. For example:
#include <stdio.h>
#include <string.h>
void main()
{
char *t = "MEAS:VOLT:DC?";
char *p;
p = t;
puts( p );
while(( p = strchr( p, ':' )) != NULL )
{
puts( ++p );
}
}
This prints:
MEAS+)OLT+!"8
)OLT+!"8
!"8
The character is defined as a character constant, which C regards as an "int".
Notice how the example program increments the pointer before using it ("++p")
so that it doesn't point to the ":" but to the character following it.
The "strrchr()" function is almost the same as "strchr()", except that it searches
for the last occurrence of the character in the string.
* The Cstrstr35C ,unction is similar to Cstrchr35C except that it searches ,or a
string0 instea& o, a character/ It also returns a pointer+
char Bs ] C1lac7 (hite 1ro%n 1lue GreenCE
///
puts3 strstr3 s0 C1lueC 5 5E
* The "strlwr()" and "strupr()" functions simply perform lowercase or uppercase
conversion on the source string. For example:
#include <stdio.h>
#include <string.h>
void main()
{
char *t = "Die Barney die!";
puts( strlwr( t ) );
puts( strupr( t ) );
}
-- prints:
&ie barne$ &ie4
!IE 1AR*E: !IE4
These two functions only implemented in some compilers and are not part of
ANS C.
C C9+R+C6ER CL+ 6E6 LI.R+R<
* These functions perform various tests on characters. They require the
declaration:
=inclu&e >ct$pe/h?
The character is represented as an "int" and the functions return an "int". They
return 0 if the test is false and non-0 if the test is true:
isalnum3 c 5 "haracter is alpha or &igit/
isalpha3 c 5 "haracter is alpha/
iscntrl3 c 5 "haracter is control character/
is&igit3 c 5 "haracter is &ecimal &igit/
isgraph3 c 5 "haracter is printing character 3except space5/
islo%er3 c 5 "haracter is lo%er-case/
isprint3 c 5 "haracter is printing character 3inclu&ing space5/
ispunct3 c 5 "haracter is printing character but not spaceAalpha-&igit/
isspace3 c 5 "haracter is space0 ''0 L'0 "R0 HT0 )T/
isupper3 c 5 "haracter is upper-case/
isx&igit3 c 5 "haracter is hex &igit/
The library also contains two conversion functions that also accept and return an
"int":
tolo%er3 c 5 "on;ert to lo%er case/
toupper3 c 5 "on;ert to upper case/
C COMM+$) LI$E +R(/ME$6
* C allows a program to obtain the command line arguments provided when the
executable is called, using two optional parameters of "main()" named "argc
(argument count)" and "argv (argument vector)".
The "argc" variable gives the count of the number of command-line parameters
provided to the program. This count includes the name of the program itself, so it
will always have a value of at least one. The "argv" variable is a pointer to an
array of strings, with each element containing one of the command-line
arguments.
The following example program demonstrates:
AB cm&line/c BA
=inclu&e >st&io/h?
;oi& main3 int argc0 char Barg;WX 5
@
int ctrE
,or3 ctr].E ctr > argcE ctr99 5
@
puts3 arg;WctrX 5E
G
G
f this program is run from the command line as follows:
stooges moe larr$ curle$
-- the output is:
stooges
moe
larr$
curle$
n practice, the command line will probably take a number of arguments, some of
which will indicate options or switches, designated by a leading "-" or "/". Some of
the switches may be specified separately or together, and some may accept an
associated parameter. Other arguments will be text strings, giving numbers, file
names, or other data.
The following example program demonstrates parsing the command-line
arguments for an arbitrary program. t assumes that the legal option characters
are "A", "B", "C", and "S", in either upper- or lower-case. The "S" option must be
followed by some string representing a parameter.
AB cparse/c BA

=inclu&e >st&io/h?
=inclu&e >st&lib/h?
=inclu&e >string/h?

main3 int argc0 char Barg;WX 5
@
int m0 n0 AB Loop counters/ BA
l0 AB String length/ BA
x0 AB Exit co&e/ BA
chE AB "haracter bu,,er/ BA
char sWL-TXE AB String bu,,er/ BA

,or3 n ] KE n > argcE n99 5 AB Scan through args/ BA
@
s%itch3 3int5arg;WnXW.X 5 AB "hec7 ,or option character/ BA
@
case [-[+
case [A[+ x ] .E AB 1ail out i, K/ BA
l ] strlen3 arg;WnX 5E
,or3 m ] KE m > lE 99m 5 AB Scan through options/ BA
@
ch ] 3int5arg;WnXWmXE
s%itch3 ch 5
@
case [a[+ AB Legal options/ BA
case [A[+
case [b[+
case [1[+
case ["[+
case [&[+
case [![+ print,3 COption co&e ] YcDnC0 ch 5E
brea7E
case [s[+ AB String parameter/ BA
case [S[+ i,3 m 9 K ?] l 5
@
puts3 CIllegal s$ntax -- no string4C 5E
exit3 K 5E
G
else
@
strcp$3 s0 Harg;WnXWm9KX 5E
print,3 CString ] YsDnC0 s 5E
G
x ] KE
brea7E
&e,ault+ print,3 CIllegal option co&e ] YcDnC0 ch 5E
x ] KE AB *ot legal option/ BA
exit3 K 5E
brea7E
G
i,3 x ]] K 5
@
brea7E
G
G
brea7E
&e,ault+ print,3 CText ] YsDnC0 arg;WnX 5E AB *ot option -- text/ BA
brea7E
G
G
puts3 C!O*E4C 5E
G
For a more practical example, here's a simple program, based on an example
from the previous chapter, that attempts to read the names of an input and output
file from the command line. f no files are present, it uses standard input and
standard output instead. f one file is present, it is assumed to be the input file
and opens up standard output. This is a useful template for simple file-processing
programs.
AB cp,ile/c BA
=inclu&e >st&io/h?
=inclu&e >st&lib/h?
=&e,ine MA6 L-T
;oi& main3 unsigne& int argc0 unsigne& char Barg;WX 5
@

'ILE Bsrc0 B&stE
char bWMA6XE

AB Tr$ to open source an& &estination ,iles/ BA

s%itch 3argc5
@
case K+ AB *o parameters0 use st&in-st&out/ BA
src ] st&inE
&st ] st&outE
brea7E
case L+ AB One parameter -- use input ,ile H st&out/ BA
i, 3 3 src ] ,open3 arg;WKX0 CrC 55 ]] *LL 5
@
puts3 C"an[t open input ,ile/DnC 5E
exit3 . 5E
G
&st ] st&outE
brea7E
case 2+ AB T%o parameters -- use input an& output ,iles/ BA
i, 3 3 src ] ,open3 arg;WKX0 CrC 55 ]] *LL 5
@
puts3 C"an[t open input ,ile/DnC 5E
exit3 . 5E
G
i, 3 3 &st ] ,open3 arg;WLX0 C%C 55 ]] *LL 5
@
puts3 C"an[t open output ,ile/DnC 5E
exit3 . 5E
G
brea7E
&e,ault+ AB Too man$ parameters/ BA
puts3 C(rong parameters/DnC 5E
exit3 . 5E
G

AB "op$ one ,ile to the next/ BA

%hile3 3 ,gets3 b0 MA60 src 5 5 4] *LL 5
@
,puts3 b0 &st 5E
G

AB All &one0 close up shop/ BA

,close3 src 5E
,close3 &st 5E
G
POI$6ER 6O C ;/$C6IO$
* This document has explained how to declare pointers to variables, arrays, and
structures in C. t is also possible to define pointers to functions. This feature
allows functions to be passed as arguments to other functions. This is useful for,
say, building a function that determines solutions to a range of math functions.
The syntax for declaring pointers to functions is obscure, and so let's start with an
idiot example: declaring a pointer to the standard library function "printf()":
AB ptrprt/c BA
=inclu&e >st&io/h?
;oi& main35
@
int 3B,unc<ptr5 35E AB !eclare the pointer/ BA
,unc<ptr ] print,E AB Assign it a ,unction/ BA
3B,unc<ptr5 3 CPrint, is here4DnC 5E AB Execute the ,unction/ BA
G
The function pointer has to be declared as the same type ("int" in this case) as
the function it represents.
Next, let's pass function pointers to another function. This function will assume
the functions passed to it are math functions that accept double and return
double values:
AB ptrroot/c BA
=inclu&e >st&io/h?
=inclu&e >math/h?

;oi& test,unc 3 char Bname0 &ouble 3B,unc<ptr5 35 5E

;oi& main35
@
test,unc3 CsVuare rootC0 sVrt 5E
G

;oi& test,unc 3 char Bname0 &ouble 3B,unc<ptr5 35 5
@
&ouble x0 xincE
int cE

print,3 CTesting ,unction Ys+DnDnC0 name 5E
,or3 c].E c > L.E 99c 5
@
print,3 CY&+ Y,DnC0 c03B,unc<ptr53 3&ouble5c 55E
G
G
t is obvious that not all functions can be passed to "testfunc()". The function
being passed must agree with the expected number and type of parameters, as
well as with the value returned.
C )<$+MIC MEMOR< +LLOC+6IO$ 1 )E+LLOC+6IO$
* For simple programs, it is OK to just declare an array of a given size:
char bu,,erWK.LOX
n more sophisticated programs, this leads to trouble. There may be no way of
knowing how big an array needs to be for the specific task the program is
performing, and so allocating an array in a fixed size will either result in wasted
memory or in not having enough to do the job.
The answer to this problem is to have the program allocate the memory at
runtime, and that's what the "malloc()" library function does. For example, let's
use "malloc()" to allocate an array of "char":
AB malloc/c BA
=inclu&e >malloc/h?
=inclu&e >st&io/h?
=inclu&e >st&lib/h? AB 'or CexitC ,unction/ BA
;oi& main35
@
char BpE AB Pointer to arra$/ BA
unsigne& countE AB SiFe o, arra$/ BA

puts3 CSiFe o, arra$8C 5E
scan,3 CY&C0 count 5E AB Get siFe in b$tes/ BA
p ] 3char B5malloc3 3siFe<t5count 5E AB Allocate arra$/ BA
i,3 p ]] *LL 5 AB "hec7 ,or ,ailure/ BA
@
puts3 C"an[t allocate memor$4C 5E
exit3 . 5E
G
puts3 CAllocate& arra$4C 5E
,ree3 p 5E AB Release memor$/ BA
G
The header file "malloc.h" must be included, and a pointer to the memory block
to be allocated must be declared. The "malloc()" function sets the pointer to the
allocated memory block with:
p ] 3char B5malloc3 3siFe<t5count 5E
The count is in bytes and it is "cast" to the type of "size_t", which is defined in
"malloc.h". The pointer returned by "malloc()" is "cast" to type "char *", that is, a
pointer to type "char". By default, in ANS C, "malloc()" returns a pointer of type
"void", which allows the pointer to be cast to any other type.
f the "malloc()" fails because it can't allocate the memory, it returns the value null
(as defined in "stdio.h").
t is simple to allocate other data types by changing the "cast" operations:
int Bbu,E
///
bu, ] 3int B5malloc3 3siFe<t5siFeo,3 int 5 B count 5E
The "sizeof()" function is used to determine the number of bytes in the "int" data
type.
When the programs finished using the memory block, it get rids of it using the
"free" function:
,ree3 p 5E
C also contains two other memory-allocation functions closely related to
"malloc()": the "calloc()" function, which performs the same function as "malloc()"
but allows the block allocated to be specified in terms of number of elements:
;oi& Bcalloc3 siFe<t >number<elements?0 siFe<t >siFeo,<element<t$pe? 5E
-- and the "realloc()" function, which reallocates the size of an array that's already
been allocated:
;oi& Brealloc3 ;oi& B>bloc7<pointer?0 siFe<t >siFe<in<b$tes? 5E
COMMO$ PRO(R+MMI$( PRO.LEM I$ C
* There are a number of common programming pitfalls in C that even trap
experienced programmers:
1: Confusing "=" (assignment operator) with "==" (equality operator). For
example:
i, 3 x ] K 5
@
G
-- is bogus, and so is:
,or 3 x ]] KE ///
2: Confusing precedence of operations in expressions. When in doubt, use
parentheses to enforce precedence.
3: Confusing structure-member operators. f "struct_val" is a structure and
"struct_ptr" is a pointer to a structure, then:
struct<;al-?m$name
-- is wrong and so is:
struct<ptr/m$name
4: Using incorrect formatting codes for "printf()" and "scanf()". Using a "%f" to
print an "int", for example, can lead to bizarre output.
5: Remember that the actual base index of an array is 0, and the final index is 1
less than the declared size. For example:
int &ataWL.XE
///
,or 3 x ] KE x >] L.E 99x 5
@
print,3 CY&DnC0 &ataWxX 5E
G
-- will give invalid results when "x" is 20. Since C does not do bounds checking,
this one might be hard to catch.
6: Muddling syntax for multidimensional arrays. f:
&ataWK.XWK.X
-- is a two-dimensional array, then:
&ataWLXWJX
-- will select an element in that array. However:
&ataW L0 J X
-- will give invalid results but not be flagged as an error by C.
7: Confusing strings and character constants. The following is a string:
C:C
-- as opposed to the character constant:
[:[
This can cause troubles in comparisons of strings against character constants.
8: Forgetting that strings end in a null character ('\0'). This means that a string will
always be one character bigger than the text it stores. t can also cause trouble if
a string is being created on a character-by-character basis, and the program
doesn't tack the null character onto the end of it.
9: Failing to allocate enough memory for a string -- or, if pointers are declared, to
allocate any memory for it at all.
10: Declaring a string with a fixed size and then assigning it to a string literal:
char aWL-TX ] CThis &oesn[t %or74CE
11: Failing to check return values from library functions. Most library functions
return an error code; while it may not be desireable to check every invocation of
"printf()", be careful not to ignore error codes in critical operations.
Of course, forgetting to store the value returned by a function when that's the
only way to get the value out of it is a bonehead move, but people do things like
that every now and then.
12: Having duplicate library-function names. The compiler will not always catch
such bugs.
13: Forgetting to specify header files for library functions.
14: Specifying variables as parameters to functions when pointers are supposed
to be specified, and the reverse. f the function returns a value through a
parameter, that means it must be specified as a pointer:
m$,unc3 Hm$;ar 5E
The following will not do the job:
m$,unc3 m$;ar 5E
Remember that a function may require a pointer as a parameter even if it doesn't
return a value, though as a rule this is not a good programming practice.
15: Getting mixed up when using nested "if" and "else" statements. The best way
to avoid problems with this is to always use brackets. Avoiding complicated "if"
constructs is also a good idea; use "switch" if there's any choice in the matter.
Using "switch" is also useful even for simple "if" statements, since it makes it
easier to expand the construct if that is necessary.
16: Forgetting semicolons -- though the compiler usually catches this -- or adding
one where it isn't supposed to be -- which it usually doesn't. For example:
,or3 x ] KE x > K.E 99x 5E
@
print,3 CY&DnC0 x 5
G
-- never prints anything.
17: Forgetting "break" statements in "switch" constructs. As commented earlier,
doing so will simply cause execution to flow from one clause of the "switch" to the
next.
18: Careless mixing and misuse of signed and unsigned values, or of different
data types. This can lead to some insanely subtle bugs. One particular problem
to watch out for is declaring single character variables as "unsigned char". Many
/O functions will expect values of "unsigned int" and fail to properly flag EOF. t
is recommended to cast function arguments to the proper type even if it appears
that type conversion will take care of it on its own.
19: Confusion of variable names. t is recommended that such identifiers be
unique in the first 6 characters to ensure portability of code.
20: n general, excessively tricky and clever code. Programs are nasty beasts
and even if it works, it will have to be modified and even ported to different
languages. Maintain a clean structure and do the simple straightforward thing,
unless it imposes an unacceptable penalty.
ST!IO/H
st&io/h, which stands for "standard input/output header", is the header in the C
standard library that contains macro definitions, constants, and declarations of
functions and types used for various standard input and output operations.
Functions declared in stdio.h are extremely popular, since as a part of the C
standard library, they are guaranteed to work on any platform that supports C
Functions declared in stdio.h can generally be divided into two categories: the
functions for file manipulation and the functions for input-output manipulation.
*ame *otes
'ile manipulation ,unctions
fclose closes a file associated with the FLE * value passed to it
fopen, freopen opens a file for certain types of reading or writing
remove removes a file (deletes it)
rename renames a file
rewind
acts as if fseek(stream, 0L, SEEK_SET) was called for the stream
passed, and then its error indicator cleared
tmpfile
creates and open a temporary file, which is deleted when closed
with fclose()
Input-output manipulation ,unctions
clearerr clears end-of-file and error indicators for a given stream
feof
checks whether an end-of-file indicator has been set for a given
stream
ferror checks whether an error indicator has been set for a given stream
fflush
forces any pending buffered output to be written to the file
associated with a given stream
fgetpos
stores the file position indicator of the stream associated by its
first argument (a FLE *) to its second argument (a fpos_t *)
fgetc returns one character from a file
fgets gets a string from the file (ending at newline or end-of-file)
fputc writes one character to a file
fputs writes a string to a file
ftell returns a file-position indicator which can then be passed to fseek
fseek seeks through a file
fsetpos
sets the file position indicator of a stream associated by its first
argument (a FLE *) as stored in its second argument (a fpos_t *)
fread reads data from a file
fwrite writes data to a file
getc
reads and returns a character from a given stream and advances
the file position indicator; it is allowed to be a macro with the
same effects as fgetc, except that it may evaluate the stream
more than once
getchar has the same effects as getc(stdin)
gets
reads characters from stdin until a newline is encountered and
stores them in its only argument
printf, vprintf used to print to the standard output stream
fprintf, vfprintf used to print to a file
sprintf,
snprintf,
vsprintf,
vsnprintf
used to print to a char array (C string)
perror writes an error message to stderr
putc
writes and returns a character to a stream and advances the file
position indicator for it; equivalent to fputc, except that a macro
version may evaluate the stream more than once
putchar,
fputchar
has the same effects as putc(stdout)
scanf, vscanf used to input from the standard input stream
fscanf, vfscanf used to input from a file
sscanf,
vsscanf
used to input from a char array (e.g., a C string)
setbuf, setvbuf sets the buffering mode for a given stream
tmpnam creates a temporary filename
ungetc pushes a character back onto a stream
puts outputs a character string to stdout
conio/h
conio/h is a C header file used in old MS-DOS compilers to create text user
interfaces. t is not described in -he 6 Programming 7anguage book , and it is not
part of the C standard library, SO C nor is it required by POSX.
Member %unctions
int kbhit(void) Determines if a keyboard key was pressed.
int getch(void)
Reads a character directly from the console
without buffer, and without echo.
int getche(void)
Reads a character directly from the console
without buffer, but with echo.
int ungetch(int c) Puts the character c back into the keyboard buffer.
char *cgets(char *buffer) Reads a string directly from the console.
int cscanf(char *format,
arg0,... argn)
Reads formated values directly from the console.
int putch(int c) Writes a character directly to the console.
int cputs(const char *string) Writes a string directly to the console.
int cprintf(const char *format,
arg0,... argn)
Formats values and writes them directly to the
console.
string/h
string/h is the header in the C standard library for the C programming language
which contains macro definitions, constants, and declarations of functions and
types used not only for string handling but also various memory handling
functions; the name is thus something of a misnomer.
Functions declared in string.h are extremely popular, since as a part of the C
standard library, they are guaranteed to work on any platform which supports C.
However, some security issues exist with these functions, such as buffer
overflows, leading programmers to prefer safer, possibly less portable variants.
;unctions
*ame *otes
void *memcpy(void *dest,
const void *src, size_t n);
copies n bytes between two memory areas, which
must not overlap
void *memmove(void *dest,
const void *src, size_t n);
copies n bytes between two memory areas; unlike
with memcpy the areas may overlap
void *memchr(const void *s,
char c, size_t n);
returns a pointer to the first occurrence of c in the
first n bytes of s, or NULL if not found
int memcmp(const void *s1,
const void *s2, size_t n);
compares the first n characters of two memory
areas
void *memset(void *, int,
size_t);
overwrites a memory area with a byte pattern
char *strcat(char *dest, const
char *src);
appends the string src to dest
char *strncat(char *, const char
*, size_t);
appends at most n characters of the string src to
dest
char *strchr(const char *, int);
locates a character in a string, searching from the
beginning
char *strrchr(const char *, int);
locates a character in a string, searching from the
end
int strcmp(const char *, const
char *);
compares two strings lexicographically
int strncmp(const char *, const
char *, size_t);
compares up to the first n bytes of two strings
lexicographically
int strcoll(const char *, const
char *);
compares two strings using the current locale's
collating order
char *strcpy(char *toHere,
const char *fromHere);
copies a string from one location to another
char *strncpy(char *toHere,
const char *fromHere, size_t);
copies up to n bytes of a string from one location to
another
char *strerror(int);
returns the string representation of an error number
e.g. errno (not thread-safe)
size_t strlen(const char *); finds the length of a C string
size_t strspn(const char *s,
const char *accept);
determines the length of the maximal initial
substring of s consisting entirely of characters in
accept
size_t strcspn(const char *s,
const char *reject);
determines the length of the maximal initial
substring of s consisting entirely of characters not in
reject
char *strpbrk(const char *s,
const char *accept);
finds the first occurrence of any character in accept
in s
char *strstr(const char
*haystack, const char *needle);
finds the first occurrence of the string "needle" in the
longer string "haystack".
char *strtok(char *, const char
*);
parses a string into a sequence of tokens; non-
thread safe in the spec, non-reentrant
si!e"t strxfrm#char
*dest$ const char *src$
si!e"t n%;
transforms src into a collating form, such that the
numerical sort order of the transformed string is
equivalent to the collating order of src.

S-ar putea să vă placă și