Computer Programming with C
Computer Programming with C
ANSI C standard emerged in the early 1980s, this book was split into two
titles: The original was still called Programming in C, and the title that covered
ANSI C was called Programming in ANSI C. This was done because it took
several years for the compiler vendors to release their ANSI C compilers and for
them to become ubiquitous. It was initially designed for programming UNIX
operating system. Now the software tool as well as the C compiler is written in C.
Major parts of popular operating systems like Windows, UNIX, Linux is still
written in C. This is because even today when it comes to performance (speed of
execution) nothing beats C. Moreover, if one is to extend the operating system to
work with new devices one needs to write device driver programs. These
programs are exclusively written in C. C seems so popular is because it is reliable,
simple and easy to use. often heard today is – “C has been already superceded
by languages like C++, C# and Java.
Program
Compiler and interpreter are used to convert the high level language into machine
level language. The program written in high level language is known as source
program and the corresponding machine level language program is called as object
program. Both compiler and interpreter perform the same task but there working is
different. Compiler read the program at-a-time and searches the error and lists
them. If the program is error free then it is converted into object program. When
program size is large then compiler is preferred. Whereas interpreter read only one
line of the source code and convert it to object code. If it check error, statement by
statement and hence of take more time.
Integrated Development Environments (IDE)
The process of editing, compiling, running, and debugging programs is often
managed by a single integrated application known as an Integrated Development
Environment, or IDE for short. An IDE is a windows-based program that allows us
Comment line
It indicates the purpose of the program. It is represented as
/*……………………………..*/
Comment line is used for increasing the readability of the program. It is useful in
explaining the program and generally used for documentation. It is enclosed within
the decimeters. Comment line can be single or multiple line but should not be
nested. It can be anywhere in the program except inside string constant &
character constant.
Preprocessor Directive:
main()
It is the user defined function and every function has one main() function from
where actually program is started and it is encloses within the pair of curly braces.
The main( ) function can be anywhere in the program but in general practice it is
placed in the first position.
Syntax : main()
{
……..
……..
……..
}
The main( ) function return value when it declared by data type as int main( )
{
return 0
Step 2: After the source program has been entered into a file, then proceed to
have it compiled. The compilation process is initiated by typing a special
command on the system. When this command is entered, the name of the file that
contains the source program must also be specified. For example, under Unix, the
command to initiate program compilation is called cc. If we are using the popular
GNU C compiler, the command we use is gcc.
Typing the line
gcc prog1.c or cc prog1.c
In the first step of the compilation process, the compiler examines each program
statement contained in the source program and checks it to ensure that it
conforms to the syntax and semantics of the language. If any mistakes are
discovered by the compiler during this phase, they are reported to the user and the
compilation process ends right there. The errors then have to be corrected in the
source program (with the use of an editor), and the compilation process must be
restarted. Typical errors reported during this phase of compilation might be due to
an expression that has unbalanced parentheses (syntactic error), or due to the use
of a variable that is not “defined” (semantic error).
Step 4: After the program has been translated the next step in the compilation
process is to translate the assembly language statements into actual machine
instructions. The assembler takes each assembly language statement and converts
it into a binary format known as object code, which is then written into another file
on the system. This file has the same name as the source file under Unix, with the
last letter an “o” (for object) instead of a “c”.
Step 5: After the program has been translated into object code, it is ready to be
linked. This process is once again performed automatically whenever the cc or gcc
command is issued under Unix. The purpose of the linking phase is to get the
program into a final form for execution on the computer.
If the program uses other programs that were previously processed by the
compiler, then during this phase the programs are linked together. Programs that
are used from the system’s program library are also searched and linked together
with the object program during this phase.
The process of compiling and linking a program is often called building.
The final linked file, which is in an executable object code format, is stored in
another file on the system, ready to be run or executed. Under Unix, this file is
called a.out by default. Under Windows, the executable file usually has the same
name as the source file, with the c extension replaced by an exe extension.
main (void)
int v1, v2, sum; //v1,v2,sum are variables and int is data type declared
v1 = 150;
v2 = 25;
sum = v1 + v2;
return 0;
Output:
The alphabets, numbers and special symbols when properly combined form
constants, variables and keywords.
Identifiers are user defined word used to name of entities like variables, arrays,
functions, structures etc. Rules for naming identifiers are:
1) name should only consists of alphabets (both upper and lower case), digits
and underscore (_) sign.
2) first characters should be alphabet or underscore
3) name should not be a keyword
4) since C is a case sensitive, the upper case and lower case considered
differently, for example code, Code, CODE etc. are different identifiers.
5) identifiers are generally given in some meaningful name such as value,
net_salary, age, data etc. An identifier name may be long, some implementation
recognizes only first eight characters, most recognize 31 characters. ANSI
standard compiler recognize 31 characters. Some invalid identifiers are 5cb, int,
res#, avg no etc.
Keyword
data types
Data types refer to an extensive system used for declaring variables or functions of
different types before its use. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted. The value of a
variable can be changed any time.
Constant is a any value that cannot be changed during program execution. In C, any
number, single character, or character string is known as a constant. A constantis an
entity that doesn’t change whereas a variable is an entity that may change.For
example, the number 50 represents a constant integer value. The character string
"Programming in C is fun.\n" is an example of a constant character string. C
constants can be divided into two major categories:
These constants are further categorized as
In decimal constant first digit should not be zero unlike octal constant first digit
must be zero(as 076, 0127) and in hexadecimal constant first two digit should be
0x/ 0X (such as 0x24, 0x87A). By default type of integer constant is integer but if
the value of integer constant is exceeds range then value represented by integer
type is taken to be unsigned integer or long integer. It can also be explicitly
mention integer and unsigned integer type by suffix l/L and u/U.
Real constant is also called floating point constant. To construct real constant we
must follow the rule of ,
-real constant must have at least one digit.
-It must have a decimal point.
-It could be either positive or negative.
-Default sign is positive.
-No commas or blanks are allowed within a real constant. Ex.: +325.34
426.0
-32.76
Character constant
String constant
Set of characters are called string and when sequence of characters are
enclosed within a double quote (it may be combination of all kind of symbols) is a
string constant. String constant has zero, one or more than one character and at the
end of the string null character(\0) is automatically placed by compiler. Some
examples are “,sarathina” , “908”, “3”,” ”, “A” etc. In C although same characters
are enclosed within single and double quotes it represents different meaning such
as “A” and ‘A’ are different because first one is string attached with null character
at the end but second one is character constant with its corresponding ASCII value
is 65.
Symbolic constant
Symbolic constant is a name that substitute for a sequence of characters and,
characters may be numeric, character or string constant. These constant are
generally defined at the beginning of the program as
#define CH ‘b’
Variables
Variable is a data name which is used to store some data value or symbolic names
for storing program
computations and results. The value of the variable can be change during the
execution. The rule for naming the variables is same as the naming identifier.
Before used in the program it must be declared. Declaration of variables specify its
name, data types and range of the value that variables can store depends upon its
data types.
Syntax:
int a;
char c;
float f;
Variable initialization
When we assign any initial value to variable during the declaration, is called
initialization of variables. When variable is declared but contain undefined value
then it is called garbage value. The variable is initialized with the assignment
operator such as
Or int a;
a=20;
Expressions
An expression is a combination of variables, constants, operators and function call.
It can be arithmetic, logical and relational for example:-
a>b //relational
a==b // logical
func(a, b) // function call
Expressions consisting entirely of constant values are called constant expressions.
So, the expression
121 + 17 - 110
is a constant expression because each of the terms of the expression is a constant
value. But if i were declared to be an integer variable, the expression
180 + 2 – j
would not represent a constant expression.
Operator
This is a symbol use to perform some operation on variables, operands or with the
constant. Some operator required 2 operand to perform operation or Some
required single operation.
Several operators are there those are, arithmetic operator, assignment, increment ,
decrement, logical, conditional, comma, size of , bitwise and others.
1. Arithmatic Operator
This operator used for numeric calculation. These are of either Unary arithmetic
operator, Binary arithmetic operator. Where Unary arithmetic operator required
Unary (+) and Unary (-) is different from addition and subtraction.
When both the operand are integer then it is called integer arithmetic and the result
is always integer. When both the operand are floating point then it is called floating
arithmetic and when operand is of integer and floating point then it is called mix
type or mixed mode arithmetic . And the result is in float type.
2.Assignment Operator
A value can be stored in a variable with the use of assignment operator. The
assignment operator(=) is used in assignment statement and assignment expression.
Operand on the left hand side should be variable and the operand on the right hand
side should be variable or constant or any expression. When variable on the left
hand side is occur on the right hand side then we can avoid by writing the
compound statement. For example,
int x= y;
int Sum=x+y+z;
The Unary operator ++, --, is used as increment and decrement which acts upon
single operand. Increment operator increases the value of variable by one
.Similarly decrement operator decrease the value of the variable by one. And these
operator can only used with the variable, but cann't use with expression and
constant as ++6 or ++(x+y+z).
EXAMPLE
let y=12;
z= ++y;
y= y+1;
z= y;
Similarly in the postfix increment and decrement operator is used in the operation .
And then increment and decrement is perform.
EXAMPLE
let x= 5;
y= x++;
y=x;
x= x+1;
4.Relational Operator
a.(a>=b) || (b>20)
c. 0(b!=7)
5. Conditional Operator
SYNTAX
Here exp1 is first evaluated. It is true then value return will be exp2 . If false then
exp3.
EXAMPLE
void main()
printf(“value is:%d”);
Output:
Value is:10
6. Comma Operator
EXAMPLE
int i, j, k, l;
for(i=1,j=2;i<=5;j<=10;i++;j++)
Size of operator is a Unary operator, which gives size of operand in terms of byte
that occupied in the memory. An operand may be variable, constant or data type
qualifier.
EXAMPLE
main( )
int sum;
float f;
Bitwise operator permit programmer to access and manipulate of data at bit level.
Various bitwise operator enlisted are
bitwise OR (|)
These operator can operate on integer and character value but not on float and
double. In bitwise operator the function showbits( ) function is used to display the
binary representation of any integer or character value.
In one's complement all 0 changes to 1 and all 1 changes to 0. In the bitwise OR its
value would obtaining by 0 to 2 bits.
It operate on 2operands and operands are compared on bit by bit basic. And hence
both the operands are of same type.
Operator used with one or more operand and return either value zero (for false) or
one (for true). The operand may be constant, variables or expressions. And the
expression that combines two or more expressions is termed as logical expression.
C has three logical operators :
&& AND
|| OR
! NOT
Where logical NOT is a unary operator and other two are binary
operator. Logical AND gives result true if both the conditions are
true, otherwise result is false. Andlogial OR gives result false if
both the condition false, otherwise result is true.
[] array subscript
arrow operator
. dot operator
+ addition 27
4 left to right
*
- subtraction
<< left shift 5 left to right
>> right shift
, comma operator 15
28 *
Loops
Aparajita Mukherjee
Assistant Professor
UEM, Kolkata
Loops in C
C has three loop statements: the while, the for, and the
do…while. The first two are pretest loops, and the
the third is a post-test loop. We can use all of them
for event-controlled and counter-controlled loops.
Function declaration:-
Function declaration is also known as function prototype. It
inform the compiler about three thing, those are name of the
function, number and type of argument received by the
function and the type of value returned by the function.
While declaring the name of the argument is optional and
the function prototype always terminated by the semicolon.
Function definition:-
Function definition consists of the whole description and
code of the function. It tells about what function is doing
what are its inputs and what are its out put It consists of two
parts function header and function body
Syntax:-
return type function(type 1 arg1, type2 arg2, type3 arg3)
/*function header*/
{
Local variable declaration;
Statement 1;
Statement 2;
{
int a,b;
printf(“enter two no”);
scanf(“%d%d”,&a,&b);
int S=sum(a,b);
printf(“summation is = %d”,s);
}
int sum(intx1,int y1)
{
int z=x1+y1;
Return z;
}
UEM, Kolkata
opasdfghjklzxcvbnmqwertyuiopasdfg
hjklzxcvbnmqwertyuiopasdfghjklzxc
vbnmqwertyuiopasdfghjklzxcvbnmq
wertyuiopasdfghjklzxcvbnmqwertyui
opasdfghjklzxcvbnmqwertyuiopasdfg
hjklzxcvbnmqwertyuiopasdfghjklzxc
vbnmqwertyuiopasdfghjklzxcvbnmq
wertyuiopasdfghjklzxcvbnmqwertyui
opasdfghjklzxcvbnmqwertyuiopasdfg
hjklzxcvbnmrtyuiopasdfghjklzxcvbn
mqwertyuiopasdfghjklzxcvbnmqwert
yuiopasdfghjklzxcvbnmqwertyuiopas
dfghjklzxcvbnmqwertyuiopasdfghjklz
xcvbnmqwertyuiopasdfghjklzxcvbnm
qwertyuiopasdfghjklzxcvbnmqwerty
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
How recursion works?
voidrecurse()
{
........
recurse();
........
}
intmain()
{
........
recurse();
........
}
Therecursioncontinuesuntilsomeconditionismettopreventit.
Topreventinfiniterecursion,if...elsestatement(orsimilarapproach)canbeusedwhereonebranch makes
the recursive call and other doesn't.
Example:SumofNaturalNumbersUsingRecursion
#include<stdio.h>
int sum(int n);
intmain()
{
intnumber,result;
printf("Enterapositiveinteger:"); scanf("%d",
&number);
result = sum(number);
printf("sum=%d",result);
}
intsum(intnum)
{
if (num!=0)
returnnum+sum(num-1);//sum()functioncallsitself
else
returnnum;
}
Output
Enterapositiveinteger:
3
6
value of num is 3 initially. During next function call, 2 is passed to the sum()
function.Thisprocesscontinuesuntilnumisequalto0.
Whennumisequalto0,theifconditionfailsandtheelsepartisexecutedreturningthesumof integers to the
main()function.
Example:FactorialofaNumberUsing Recursion
#include<stdio.h>
longintmultiplyNumbers(intn);
intmain()
{
int n;
printf("Enterapositiveinteger:"); scanf("%d",
&n);
printf("Factorialof%d=%ld",n,multiplyNumbers(n)); return 0;
}
longintmultiplyNumbers(intn)
{
if(n>=1)
returnn*multiplyNumbers(n-1);
else
return1;
}
Output
Enterapositiveinteger:6
Factorial of 6 = 720
Supposetheuserentered6.
Initially,themultiplyNumbers()iscalledfromthemain()functionwith6passedasan argument.
Then,5ispassedtothemultiplyNumbers()functionfromthesamefunction(recursivecall). In each
recursive call, the value of argument n is decreased by 1.
Whenthevalueofnislessthan1,thereisnorecursive call.
Example:GCDofTwoNumbersusingRecursion
#include<stdio.h>
inthcf(intn1,intn2); int
main()
{
intn1,n2;
printf("Entertwopositiveintegers:"); scanf("%d
%d", &n1, &n2);
printf("G.C.Dof%dand%dis%d.",n1,n2,hcf(n1,n2)); return 0;
}
inthcf(intn1,intn2)
{
if(n2!=0)
returnhcf(n2,n1%n2); else
returnn1;
}
AdvantagesandDisadvantagesofRecursion
Recursionmakesprogramelegantandcleaner.Allalgorithmscanbedefinedrecursivelywhich makes
it easier to visualize and prove.
Ifthespeedoftheprogramisvitalthen,youshouldavoidusingrecursion.Recursionsusemore memory and
are generally slow. Instead, you can use loop.
Array subscript always start from zero which is known as lower bound and
upper
value is known as upper bound and the last subscript value is one less than the
size
of array. Subscript can be an expression i.e. integer value. It can be any integer,
integer constant, integer variable, integer expression or return value from
functional call that yield integer value.
So if i & j are not variable then the valid subscript are
ar [i*7],ar[i*i],ar[i++],ar[3];
The array elements are standing in continuous memory locations and the
amount of storage required for hold the element depend in its size & type.
Total size in byte for 1D array is:
Total bytes=size of (data type) * size of array.
For example:-
int arr[5]={1,2,3,4,5,6,7,8};//error
we cannot copy all the elements of an array to another array by simply assigning
it
to the other array like, by initializing or declaring as
int a[5] ={1,2,3,4,5};
int b[5];
b=a;//not valid
(note:-here we will have to copy all the elements of array one by one, using for
loop.)
Single dimensional arrays and functions
/*program to pass array elements to a function*/
#include<stdio.h>
void main()
{
int arr[10],i;
printf(“enter the array elements\n”);
for(i=0;i<10;i++)
{
scanf(“%d”,&arr[i]);
check(arr[i]);
}
}
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
scanf(“%d”,&a[i][j]);
}
}
For displaying value:-
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
While initializing we can group the elements row wise using inner braces.
for example:-
int mat[4][3]={{11,12,13},{14,15,16},{17,18,19},{20,21,22}};
And while initializing , it is necessary to mention the 2nd dimension where 1st
dimension is optional.
int mat[][3];
int mat[2][3];
int mat[][];
int mat[2][]; invalid
If we initialize an array as
int mat[4][3]={{11},{12,13},{14,15,16},{17}};
Then the compiler will assume its all rest value as 0,which are not defined.
Mat[0][0]=11, Mat[1][0]=12, Mat[2][0]=14, Mat[3][0]=17
#define COLUMN 3;
int mat[ROW][COLUMN];
#preprocessordirectives
declarations
variables
functions
intmain (void){
declarations;
statements;
return value;
}
Aparajita Mukherjee Assistant Professor UEM, Kolkata
YourFirstCProgram
hello.c
/*WelcometoBBM101*/ #include
<stdio.h>
intmain(void)
{
printf(“Helloworld!\n”);
return 0;
}
Helloworld!
Helloworld!
Helloworld!
Helloworld!
Helloworld!
intmain(void)
{
printf(“Helloworld!\n”);
return 0;
}
Create/Edit
Compile Execute
Program
“Thecycleendsoncetheprogrammerissatisfiedwiththe
program, e.g., performance and correctness-wise.”
• Case-sensitive
– e.g.,firstNameandfirstnamearetwodifferentidentifiers.
• Identifiersareusedfor
– Variablenames
– Functionnames
– Macronames
■• Invalididentifiers
Invalididentifiers
–xyz.1
xyz.1
–gx^2
gx^2
–114West
114West
–int
intThisisakeyword
–pi*r*r
pi*r*r
• DataTypeModifiers
– signed/unsigned
– short/long
• Creservesabyteinmemorytostorea.
• Whereisthatmemory?Atanaddress.
• Underthehood,Chasbeenkeepingtrackofvariables and
their addresses.
• Apointerisavariablethatcontainstheaddressofa
variable.
• Pointersprovideapowerfulandflexiblemethodfor
manipulating data in your programs; but they are
difficult to master.
–Closerelationshipwitharraysandstrings
Aparajita Mukherjee Assistant Professor UEM, Kolkata
BenefitsofPointers
• Pointersallowyoutoreferencealargedatastructureina
compact way.
• Pointersfacilitatesharingdatabetweendifferentpartsof a
program.
– Call-by-Reference
• Dynamicmemoryallocation:Pointersmakeitpossibleto
reserve new memory during program execution.
– Pointerscontainaddressofavariablethathasaspecific
value (indirect reference)
– Indirection–referencingapointervalue
countPtr count
7
– Declaresapointertoanint(pointeroftypeint*)
– Multiplepointersrequireusinga*beforeeachvariable
declaration
int*myPtr1,*myPtr2;
– Candeclarepointerstoanydatatype
– Initializepointersto0,NULL,oranaddress
• 0orNULL–pointstonothing(NULLpreferred)
Addressofy
is value of
yptr
• *and&areinverses
- Theycanceleachotherout
rate = 500;
p_rate=&rate;
p_rate rate
/*Printthevalues*/
printf(“rate = %d\n”, rate); /* direct access */
printf(“rate=%d\n”,*p_rate);/*indirectaccess*/
<stdio.h> Theaddressofaisthevalue of
aPtr.
intmain()
{
inta; /*aisaninteger*/
The * operator returns an
int*aPtr; /*aPtrisapointertoaninteger*/
alias to what its operand
a=7; pointsto.aPtrpointstoa, so
aPtr=&a; /*aPtrsettoaddressofa*/ *aPtr returns a.
printf("Theaddressofais%p\nThevalueofaPtris%p",&a,aPtr);
printf("\n\nThevalueofais%d\nThevalueof*aPtris%d",a,*aPtr);
Noticehow *and&
printf("\n\nShowingthat*and&areinversesof areinverses
eachother.\n&*aPtr=%p\n*&aPtr=%p\n",&*aPtr,*&aPtr);
return0;
}
ProgramOutput
The address of a is 0012FF88
ThevalueofaPtris0012FF88
Thevalueofais7
Thevalueof*aPtris7
Showing that * and & are inverses of each other.
&*aPtr = 0012FF88
*&aPtr=0012FF88
= b = 7;
p=&a;
printf(“*p=%d\n”,*p);
*p=3;
printf(“a=%d\n”,a);
ProgramOutput
p=&b; *p= 7
*p=2**p –a; a=3
printf(“b= %d\n”, b); b=11
= 5;
y=7;
p=&x;
y=*p;
Thus,
y = *p;
y=*&x; y
= x;
Allequivalent
Declarationsandinitializations
int k=3, j=5, *p = &k, *q = &j, *r;
double x;
Expression EquivalentExpression Value
p == &k p == (&k) 1
p = k + 7 p = (k + 7) illegal
* * &p * ( * (&p)) 3
r = &x r = (&x) illegal
7 * * p/ *q +7 (( (7 * (*p) )) / (*q)) + 7 11
* (r = &j) *= *p ( * (r = (&j))) *= (*p) 15
Declarations
int*p;
float*q;
void*v;
Legalassignments Illegalassignments
p = 0; p= 1;
p = (int*)1; v= 1;
p = v= q; p= q;
p = (int*)q;
Aparajita Mukherjee Assistant Professor UEM, Kolkata
CallingFunctionsbyReference
• Callbyreferencewithpointerarguments
– Passaddressofargumentusing&operator
– Allowsyoutochangeactuallocationinmemory
– Arraysarenotpassedwith&becausethearrayname is
already a pointer
• * operator
– Usedasalias/nicknameforvariableinsideoffunction
voiddouble_it(int*number)
{
*number=2*(*number);
}
– *numberusedasnicknameforthevariablepassed
• Thisfunctionhasnoeffectwhatever.Instead,passapointer:
voidSetToZero(int*ip)
{
*ip=0;
}
Youwouldmakethefollowingcall:
SetToZero(&x);
Thisisreferredtoascall-by-reference.
voidchange_arg(int*y); int
main (void)
{
intx=5;
change_arg(&x);
printf(“%d\n”,x);
return 0;
}
voidchange_arg(int*y)
{
*y=*y+2;
}
InsidecubeByReference,*nPtris
return0;
used(*nPtrisnumber).
}
voidcubeByReference(int*nPtr)
{
*nPtr=*nPtr**nPtr**nPtr;/*cubenumberinmain*/
}
ProgramOutput
Theoriginalvalueofnumberis5 The
new value of number is 125
Aparajita Mukherjee Assistant Professor UEM, Kolkata
/*Cubeavariableusingcallbyvalue*/ #include
<stdio.h>
intCubeByValue(intn); int
main(void)
{
int number = 5;
printf(“Theoriginalvalueofnumberis%d\n”,number); number =
CubeByValue(number);
printf(“Thenewvalueofnumberis%d\n”,number); return
0;
}
tmp = p;
p = q;
q = tmp;
}
voidswap(int*p,int*q); int
main (void) p q
{
inta=3;
int b = 7; 3 7
printf(“%d%d\n”,a,b);
swap(&a, &b);
printf(“%d%d\n”,a,b); return
0; q
p
}
tmp = *p;
*p = *q;
*q = tmp;
}
voidseparate(doublenum,char*signp,int*wholep,double*fracp)
{
doublemagnitude;
if(num<0)
*signp=‘-‘; else
if (num == 0)
*signp=‘‘;
else
*signp=‘+’;
magnitude=fabs(num);
*wholep=floor(magnitude);
*fracp=magnitude-*wholep;
}
/* Gets data */
printf(“Enteravaluetoanalyze:”);
scanf(“%lf”, &value);
/*Separatesdatavalueinthreeparts*/
separate(value, &sn, &whl, &fr);
/* Prints results */
printf(“Partsof%.4f\nsign:%c\n”,value,sn);
printf(“whole number magnitude: %d\n”, whl);
printf(“fractional part : %.4f\n”, fr);
return 0;
}
#include<stdio.h>#def
ine SIZE 10
for(i=0;i<SIZE;i++)
printf("%4d",a[i]);
/*sortanarrayofintegersusingbubblesortalgorithm*/ void
bubbleSort( int *array, const int size )
{
intpass,j;
for(pass=0;pass<size-1;pass++) for ( j = 0;
j < size - 1; j++ )
/*swapadjacentelementsiftheyareoutoforder*/ if (
array[ j ] > array[ j + 1 ] )
swap(&array[j],&array[j+1]);
}/*endfunctionbubbleSort */
ProgramOutput
Data items in originalorder
2 6 4 810128968 45 37
Data items in ascendingorder
2 4 6 810123745 68 89
intmain(){
floatarray[20];/*createarray */
printf("Thenumberofbytesinthearrayis %d"
"\nThenumberofbytesreturnedbygetSizeis%d\n", sizeof(
array ), getSize( array ) );
return0;
}
size_tgetSize(float*ptr){
return sizeof( ptr );
}
ProgramOutput
The number of bytes in the array is 80
The number of bytes returned by getSize is 4
Aparajita Mukherjee Assistant Professor UEM, Kolkata
Example
/*Demonstratingthesizeofoperator*/
#include <stdio.h>
intmain()
{
charc; /*definec*/
shorts; /*defines*/
inti; /*definei*/
longl; /*definel*/
floatf; /*definef*/
double d; /* define d */
long double ld; /*defineld*/
intarray[20];/*initializearray */
int*ptr=array;/*createpointertoarray */
return0;
}
• Thefourdynamicmemorymanagementfunctionsare
malloc, calloc,realloc,andfree.
• Thesefunctionsareincludedintheheaderfile
<stdlib.h>.
• allocatesstorageforanobjectwhosesizeisspecifiedby
size:
– Itreturnsapointertotheallocatedstorage,
– NULLifitisnotpossibletoallocatethestoragerequested.
– Theallocatedstorageisnotinitializedinanyway.
• e.g. float*fp,fa[10];
fp = (float *) malloc(sizeof(fa));
allocatesthestoragetoholdanarrayof10floating-point
elements, and assigns the pointer to this storage to fp.
• allocatesthestorageforanarrayofnobjobjects,eachofsize
size.
– Itreturnsapointertotheallocatedstorage,
– NULLifitisnotpossibletoallocatethestoragerequested.
– Theallocatedstorageisinitializedtozeros.
• e.g.double*dp,da[10];
dp=(double *) calloc(10,sizeof(double));
allocatesthestoragetoholdanarrayof10doublevalues, and
assigns the pointer to this storage to dp.
• changesthesizeoftheobjectpointedtobyptosize.
– Itreturnsapointertothenewstorage,
– NULLifitisnotpossibletoresizetheobject,inwhichcase the
object (*p) remains unchanged.
– The new size may be larger (the original contents are
preservedandtheremainingspaceisunitialized)orsmaller
(the contents are unchanged upto the new size) than the
original size.
cp=(char*)realloc(cp,sizeof(“compute”));
discardsthetrailing‘\0’andmakescppointtoanarrayif8characterscontaining the
characters in computer
cp=(char*)realloc(cp,sizeof(“computerization”));
cp points to an array of 16 characters, the first 9 of which contain
thenull-terminatedstringcomputerandtheremaining7areuninitialized.
• deallocatesthestoragepointedtobyp,wherepisapointer to
the storage previously allocated by malloc, calloc, or
realloc.
• e.g.free(fp);
free(dp);
free(cp);
pointervariablevPtr
intmain(void){ int
*array, *p;
inti,no_elements;
printf("Enternumberofelements:"); scanf("%d",&no_elements);
printf("Entertheelements:");
array=(int*)malloc(no_elements*sizeof(int));
for(p=array,i=0; i<no_elements; i++, p++)
scanf("%d",p);
printf("Elements:");
for(p=array,i=0;i<no_elements;i++,p++)
printf("%d ",*p);
printf("\n");
printf("Elements:");
for(p=array,i=0;i<no_elements+2;i++,p++)
printf("%d ",*p);
printf("\n");
free(array);
return 0; ProgramOutput
} Enternumberofelements:4
Entertheelements:2345
Elements:2345
Entertwonewelements:67
Elements:234567
#include<stdio.h>#inc
lude<ctype.h>
voidconvertToUppercase(char*sPtr); int
main()
{
charstring[]="charactersand$32.98";/*initializechararray*/
printf("Thestringbeforeconversionis:%s",string);
convertToUppercase( string );
printf("\nThestringafterconversionis:%s\n",string); return 0;
ProgramOutput
Thestringbeforeconversionis:charactersand$32.98 The
string after conversion is: CHARACTERS AND $32.98
#include<stdio.h>
voidprintCharacters(constchar*sPtr); int
main()
{
/*initializechararray*/
charstring[]="printcharactersofastring";
printf("Thestringis:\n");
printCharacters( string );
printf( "\n" );
return0;
}
voidprintCharacters(constchar*sPtr)
{
/*loopthroughentirestring*/ for (
; *sPtr != '\0'; sPtr++ )
printf("%c",*sPtr);
}/*endfunctionprintCharacters */
ProgramOutput
The string is:
print characters of a string
voidf(constint*xPtr);/*prototype */
intmain()
{
inty; /*definey*/
f( &y ); /* f attempts illegal modification */
return 0; /*indicatessuccessfultermination*/
}/*endmain*/
/*xPtrcannotbeusedtomodifythevalueofthevariabletowhichit points */
voidf(constint*xPtr)
{
*xPtr=100;/*error:cannotmodifyaconstobject */
}/*endfunctionf*/
intmain()
{
intx;/*definex*/
inty;/*definey*/
Changing*ptrisallowed–xis
/*ptrisaconstantpointertoa not aconstant.
nintegerthatcanbemodifi ed
throughptr,butptralwayspointstothesamememorylocation*/ int *
const ptr = &x;
Changingptrisanerror–ptr
*ptr=7;/*allowed:*ptrisnotconst*/ isaconstantpointer.
ptr=&y;/*error:ptrisconst;cannotassignnewaddress */
return0;
}/*endmain*/
intmain() {
intx= 5;/*initializex*/
int y; /*definey*/
/*ptr isaconstantpointertoaconstantinteger.ptralwayspoints to
the samelocation;theintegeratthatlocationcannotbemodified */
constint*constptr=&x;
printf( "%d\n", *ptr );
return0;/*indicatessuccessfultermination*/
}/*endmain*/
i < 4; i++)
printf(“b[%d]=%d\n”,i,b[i]);
for(offset=0;offset<4;offset++)
printf(“*(b+%d)=%d\n”,offset,*(b+offset));
/*Pointersubscriptnotation*/ for
(i=0; i < 4; i++)
printf(“bPtr[%d]=%d\n”,i,bPtr[i]);
/*Pointeroffsetnotation*/
for (offset = 0; offset < 4; offset++)
printf(“*(bPtr+%d)=%d\n”,offset”
“*(bPtr+offset)”);
return0;
}
*( b + 0 )= 10
*( b + 1 )= 20
*( b + 2 )= 30
*( b + 3 )= 40
bPtr[ 0 ] = 10
bPtr[ 1 ] = 20
bPtr[ 2 ] = 30
bPtr[ 3 ] = 40
*( bPtr + 0 )= 10
*( bPtr + 1 )= 20
*( bPtr + 2 )= 30
*( bPtr + 3 )= 40
intmain()
{
charstring1[10 ]; /*createarraystring1*/
char *string2 = "Hello"; /*createapointertoastring*/ char
string3[ 10 ]; /* create array string3 */
charstring4[]="GoodBye";/*createapointertoastring */
copy1(string1,string2);
printf("string1=%s\n",string1); copy2(
string3, string4 );
printf("string3=%s\n",string3);
return0;
}
/*copys2tos1usingpointernotation*/ void
copy2( char *s1, const char *s2 )
{
/*loopthroughstrings*/
for(;(*s1=*s2)!='\0';s1++,s2++)
;
}/*endfunctioncopy2*/
ProgramOutput
string1 = Hello
string3=GoodBye
Aparajita Mukherjee Assistant Professor UEM, Kolkata
ArraysofPointers
• Arrayscancontainpointers
• Forexample:anarrayofstrings
char*suit[4]={"Hearts","Diamonds", "Clubs",
"Spades" };
– Stringsarepointerstothefirstcharacter
– char*–eachelementofsuitisapointertoachar
– Thestringsarenotactuallystoredinthearraysuit,only
pointers to the strings are stored
suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’
suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’
– suitarrayhasafixedsize,butstringscanbeofanysize
intmain(){
int order; /*1forascendingorderor2fordescendingorder*/ int
counter; /* counter */
/*initializearraya */
inta[SIZE]={2,6,4,8,10,12,89,68,45,37};
return0;
}
voidswap(int*element1Ptr,int*element2ptr); for (
pass = 1; pass < size; pass++ ) {
for(count=0;count<size-1;count++){
/* if adjacent elements are out of order, swap them */
if((*compare)(work[count],work[count+1])){
swap(&work[count],&work[count+1]);
}
}
}
}/*endfunctionbubble */
/*determinewhetherelementsareoutoforderforanascendingordersort*/ int
ascending( int a, int b ) {
returnb<a;
}/*endfunctionascending */
ProgramOutput
PGH,UEMK
• The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The character array or the
string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and
the last character must always be 0. The termination character ('\0') is important in a string since it is the only way to
identify where the string ends.
• There are two ways to declare a string in c language.
• By char array [char ch[3]={‘U', ‘E', ‘M', '\0'}; ]
• By string literal[char ch[]={‘UEM’};
PGH,UEMK
Traversing String_By using the length of string
#include<stdio.h>
void main ()
{
char s[5] = “INDIA";
int i = 0;
int count = 0;
while(i<5)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}
PGH,UEMK
Traversing String_Using the null character
• #include<stdio.h>
• void main ()
• {
• char s[5] = “INDIA";
• int i = 0;
• int count = 0;
• while(s[i] != NULL)
• {
• if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
• {
• count ++;
• }
• i++;
• }
PGH,UEMK
Pointers with strings
#include<stdio.h>
void main ()
{
char s[4] = “PUJO";
char *p = s; // pointer p is pointing to string s.
printf("%s",p); // the string javatpoint is printed if we print p.
}
PGH,UEMK
gets() function
• The gets() function enables the user to enter some characters followed by
the enter key. The gets() allows the user to enter the space-separated
strings. It returns the string entered by the user.
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
PGH,UEMK
fgets() function
• The fgets() makes sure that not more than the maximum limit of characters
are read.
#include<stdio.h>
void main()
{
char str[20];
printf("Enter the string? ");
fgets(str, 20, stdin);
printf("%s", str);
}
PGH,UEMK
puts() function
• The puts() function is very much similar to printf() function. The puts() function is used to
print the string on the console which is previously read by using gets() or scanf() function.
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
PGH,UEMK
• The strlen() function returns the length of the given string. It doesn't count
null character '\0'.
• The strcpy(destination, source) function copies the source string in
destination. [ strcpy(ch2,ch); ]
• The strcat(first_string, second_string) function concatenates two strings
and result is returned to first_string. [strcat(ch,ch2); ]
• The strcmp(first_string, second_string) function compares two string and
returns 0 if both strings are equal. [strcmp(str1,str2)==0]
• The strrev(string) function returns reverse of the given string.[strrev(str)]
• The strlwr(string) function returns string characters in lowercase. The
strupr(string) function returns string characters in uppercase.
PGH,UEMK
String strstr()
• The strstr() function returns pointer to the first occurrence of the matched string in the given string.
• char *strstr(const char *string, const char *match)
• string: It represents the full string from where substring will be searched. match: It represents the substring
to be searched in the full string.
• #include<stdio.h>
• #include <string.h>
• int main(){
• char str[100]="A is part of b part";
• char *sub;
• sub=strstr(str,"part");
• printf("\nSubstring is: %s",sub);
• return 0;
• }
PGH,UEMK
Structs,Unions and Enums
Aparajita Mukherjee
Assistant Professor
UEM,Kolkata
– Derived datatypes:
• pointers,arrays,functions...
• Today we will learn two new derived types
– Structs
– Unions
• And one “syntacticsugar” datatype
– Enums
Aparajita Mukherjee Assistant Professor UEM, Kolkata
Structs
• Struct: A derived type for a collection of
related variables under one name
– Much like classes in Java with no methods
– Members can be primitives or derived types
• Useful for...
– Readability of code through conceptual grouping
– FileI/Ooffixed length records into structs
– Designing recursive datastructures(e.g.linked lists,
trees, graphs) using pointers
• Canstructshavemembersofpointerstoowntype?
struct A {
intx;
structA*y;
};
Itislegal!(NowthinkofwhatthesizeofstructAwouldbe.)
• Word:(largest)unitofdatathatcanbeaccessedina
single memory operation
–Whatitmeanstobe a“32-bit” or“64-bit” system
– Usually,sizeofword==registersize
• Efficienttoload/storeregisterinasingleoperation
• Problem:whatifanaccessspansmultiplewords
(lands on the boundary between two words)?
– Wouldresultintwomemoryaccesses
• Imaginepatchingtogetheravaluefromtwoaccesses
• Imagineaccessestotwodifferentcachelines,pagesetc
• aligned(aggregatepointer):pointerpisaligned
– if pointer to each primitive member is aligned
(evenafterperformingpointerarithmeticonp)
– Forarray:onlyrequiresfirstelementtobealigned
– Forstruct:morecomplicated(membersdifferinsize)
struct{ struct{
longlongy; char longlongy; char
x; x;
}A; charpadding[7];
} A;
• Compilerinsertspaddingtopreventmisalignedaccesses
(Even when A is used in an array, hence 2nd case)
Aparajita Mukherjee Assistant Professor UEM, Kolkata
• Differentcompilersmayproducedifferentpadding
➔ Mustbecarefulwhenwriting/readingfileusingstruct
• Sizeofunionisatleastaslargeasthelargestmember.
#include<stdio.h>
#include<string.h>
voidmodify(structemp*);
struct emp
{
charname[20];
int age;
};
intmain()
{
structempe={"John",35};
modify(&e);
printf("%s%d",e.name,e.age);
return 0;
}
voidmodify(structemp*p)
{
p->age=p->age+2;
}
#include<stdio.h>in
t main()
{
structemp
{
charn[20];
int age;
};
structempe1={"Dravid",
23};
structempe2=e1; if(e1
== e2)
printf("Thestructure
are equal");
return0;
}
nt main()
{
structemp
{
charname[25];
intage;float
bs;
};
struct emp e;
e.name="Suresh";
e.age = 25;
printf("%s%d\n",e.name,
e.age);
return0;
}
Incompatibletypesinassignment.Wecannotassignastringtoastruct variable like
e.name = "Suresh"; in C.
Aparajita Mukherjee Assistant Professor UEM, Kolkata
Wehavetousestrcpy(e.name,"Suresh");toassignastring.
#include<stdio.h>
voidfun(inta[],intn); int
main()
{
inta[5]={1,2,3,4,5};
fun(a,5);
}
voidfun(inta[],intn)
{
int i;
for(i=0;i<=n-1;i++)
printf("value=%d\n",a[i]);
}
#include<stdio.h>struct
Point{
intstuff;
intmy_array[4];
};
voidprint_point(conststructPointppnt){
//...
}
intmain(intargc,char*argv[])
{
structxPoint={8,{1,2,3,4}};
print_point(pnt);
return0;
}
File: the file is a permanent storage medium in which we can store the data permanently.
Types of file can be handled we can handle three type of file as (1) sequential file (2) random
access file (3) binary file
opening a file:
Before performing any type of operation, a file must be opened and for this
fopen() function is used.
syntax:
FILE *fp=fopen(“ar.c”,”r”);
If fopen() unable to open a file than it will return NULL to the file pointer.
File-pointer: The file pointer is a pointer variable which can be store the address
of a special file that means it is based upon the file pointer a file gets opened.
Declaration of a file pointer:-
FILE* var;
Modes of open
Syntax:
character_variable=getc(file_ptr);
puts(character-var,file-ptr);
fclose(file-ptr);
If fopen() unable to open a file then it will return NULL to the file-pointer.
Syntax:
fputc(character,file_pointer);
#include<stdio.h>
void main()
FILE *fs,*fd;
char ch;
If(fs=fopen(“scr.txt”,”r”)==0)
return;
If(fd=fopen(“dest.txt”,”w”)==0)
while(ch=fgets(fs)!=EOF)
fputc(ch,fd);
fcloseall();
Syntax:
gets(file pointer);
fputs(integer,file_pointer);
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
int word;
/*place the word in a file*/
fp=fopen(“dgt.txt”,”wb”);
If(fp==NULL)
{
printf(“Error opening file”);
exit(1);
}
word=94;
putw(word,fp);
If(ferror(fp))
printf(“Error writing to file\n”);
else
printf(“Successful write\n”);
fclose(fp);
/*reopen the file*/
fp=fopen(“dgt.txt”,”rb”);If(fp==NULL)