C Lecture 1
C Lecture 1
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.
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.