SlideShare a Scribd company logo
1 of 91
• Pointers
• Malloc
• Alloc
• Calloc
• Free
• Realloc
• Functions
• Strings
• Structures
• Sorting
• File handling
• ‘Pointer’ is a variable that
contains a memory address of
other variable (does not contain
a actual data).This is why we
call it “Pointer” since it is used
to POINT other variable.
What Is
pointer?
Some situations where pointers can be used are
 To return more than one value from a function
 To pass arrays and strings more conveniently from one function
to another
 To manipulate arrays easily by moving pointers to them
instead of moving the arrays itself
 To allocate memory and access it
 (Direct Memory Allocation)
5
int main ()
{
int a;
int b;
int c;
…
int* ptr;
a = 1000;
b = 2000;
c = 3000;
}
1000 2000 3000
int a int b int c
NUL
3004 3006
int* ptr
1004 1006 1008 1012
6
int main ()
{
int a;
int b;
int c;
int* ptr;
a = 1000;
b = 2000;
c = 3000;
ptr = &a;
}
1000 2000 3000
1004 1006 1008 1012
int a int b int c
1004
3004 3008
int* ptrmemory
address of ‘a’
int *
p;
int*
p;
int
*p;
• Thus, the character * can appear anywhere between the
data type name and the variable name.
• Syntax:
data_type *var_name;
7
C provides
two operators
to work with
pointers.
(&) the
address of
operator
(*) the
dereferencing
is a unary operator that
returns the address of its
operand.
For example, given the
statements:
int x;
int *p;
The statement:
p = &x;
assigns the address of x
to p. That is, x and the
value of p refer to the
same memory location
referred to as indirection
operator
refers to the object to which
its operand (that is, the
pointer) points.
For example, given the
statements:
int x=25,*p;
p=&x
25
Xp
• Consider the following statements.
1. num = 78;
2. p = #
3. *p = 24;
9
Assignment
• The value of one pointer variable can be assigned to another
pointer variable of the same type.
• Example:
• Note:
Any changes made to *p automatically change the value
of *q, and vice versa.
int *p,*q, i=5;
q=&i;
p=q;
comparison
• Two pointer variables of the same type can be compared
for equality, and so on.
• Example : int *p,*q, i=5;
q=&i;
p==q;
p!=q;
evaluates to true if p and q have
the same value that is, if they point
to the same memory location.evaluates to true if p and q
point to different memory
locations.
Decrement and increment
• Integer values can be added and subtracted from a
pointer variable.
• ++ increments the value of a pointer variable by the size
of the memory to which it is pointing.
• Similarly, -- the value of a pointer variable by the size of
the memory to which it is pointing.
• Example :
• Let us assume that var is stored at the address 1000
• Then ptr_var has the value 1000 stored in it. Since integers
are 2 bytes long, after the expression “ptr_var++;” ptr_var
will have the value as 1002 and not 1001
int var,*ptr_var;
ptr_var=&var;
var=500;
Ptr_var++;
a &a[0]
‘a’is a pointer only to the first element, not the whole array
same
#include<stdio.h>
void main()
{
static int ary[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9,10};
int i;
for (i = 0; i < 10; i ++)
{
printf(“ni=%d,ary[i]=%d,*(ary+i)=%d“,i,
ary[i],*(ary + i));
printf(“&ary[i]= %X,ary+i=%X”,&ary[i],ary+i);
/* %X gives unsigned hexadecimal */
}
}
• The malloc() function dynamically allocates memory
when required. This function allocates ‘size’ byte of
memory and returns a pointer to the first byte or NULL if
there is some kind of error.
• calloc is similar to malloc, but the main difference is
that the
• values stored in the allocated memory space is zero by
default
 calloc requires two arguments
 The first is the number of variables you'd like to allocate
memory for
 The second is the size of each variable
• You've allocated a certain number of bytes for an array
but later find that you want to add values to it.You could
copy everything into a larger array, which is inefficient, or
you can allocate more bytes using realloc, without losing
your data.
 realloc takes two arguments
 The first is the pointer referencing the memory
 The second is the total number of bytes you want to reallocate
Syntax:
void *realloc( void *ptr, size_t size );
• free() function can be used to de-allocates (frees) memory
• when it is no longer needed.
Syntax:
void free(void *ptr );
• This function de allocates the space pointed to by ptr,
• freeing it up for future use.
• ptr must have been used in a previous call to malloc(),
• calloc(), or realloc().
A function in C can have a value, a side
effect, or both
• The side effect occurs before the value is returned.
• The function’s value is the value of the expression in the
return statement.
• A function can be called for its value, its side effect, or both.
• The general syntax of a function in C is :
• The type_specifier specifies the data type of the value, which
the function will return.
• A valid function name is to be assigned to identify the
function
• Arguments appearing in parentheses are also termed as
formal parameters.
//Prototype declaration
void greeting();
int main()
{
greeting();
return 0;
} // main
Void greeting()
{
printf(“HELLO WORLD”);
return ;
} //greeting()
Declaration
is coded
first
Definition is
after the call
Call is in the
statement
sections
The type of the expression in the return
statement must match the return type in the
function header.
. Only one value can be returned by a
function
• Formal parameters are variables that are declared in the header of
the function definition.
• Actual parameters are the expressions in the calling statement.
• The formal and actual parameters must match exactly in type, order,
and number. Their names, however, do not need to be the same.
int square(int x);
Int main()
{
Int I
For(i=1;i<10; i++)
{
printf(“n square of %d is %d:”, i, square(i));
}
int square(int x)
{
int j;
j=x*x;
return(j);
}
Actual
argument
Formal
argument
• Local Variables
• Declared inside a function
• Created upon entry into a block and destroyed upon exit from the
block
• Formal Parameters
• Declared in the definition of function as parameters
• Act like any local variable inside a function
• Global Variables
• Declared outside all functions
• Holds value throughout the execution of the program
float pi=3.1415;
void area( int rad);
int main()
{
float radius;
printf("nEnter the radius of Circle : ");
scanf("%d", &radius);
area(radius);
Return 0;
}
Void area( int rad)
{
int area;
area=pi*rad*rad;
}
Global variable
Formal parameter
Local variable
 Every C variable has a characteristic called as a storage class
 The storage class defines two characteristics of the variable:
• Lifetime – The lifetime of a variable is the length of
time it retains a particular value
• Visibility – The visibility of a variable defines the parts of a
program that will be able to recognize the variable
• automatic
• external
• static
• register
• Scope Rules - Rules that govern whether one piece of
code knows about or has access to another piece of
code or data
• The code within a function is private or local to that
function
• Two functions have different scopes
• One function cannot be defined within another function
 Call by value
 Call by reference
 When arguments are
passed to the called
function, the values
are passed through
temporary variables
• In call by
reference, the
function is
allowed access
to the actual
memory
location of the
argument and
therefore can
change the
value of the
arguments of
the calling
routine
main()
{
.
.
palindrome();
.
.
}
palindrome()
{
.
.
getstr();
reverse();
cmp();
.
.
}
• A pointer variable can be passed as a parameter to a function
either by value or by reference.
• In the function pointerParameters, both p and q are pointers.
The parameter p is a reference parameter; the parameter q is
a value parameter.
• Furthermore, the function pointerParameters can change the
value of *q, but not the value of q. However, the function
pointerParameters can change the value of both p and *p.
 The string is any sequence of characters surrounded by
double quotes.
• Strings are arrays of characters terminated by the NULL
(‘0’) character.
• The ‘0’ null character is automatically added in the
internal representation of a string.
 A typical string variable declaration is:.
char str[10];
 str is a character array variable that can hold a maximum
of 10 characters including the null terminator.
 String I/O operations are carried out using functions from the
standard I/O library called stdio.h
 The gets() function is the simplest method of accepting a
string through standard input
 Input characters are accepted till the Enter key is pressed
 The gets() function replaces the terminating ‘n’ new line
character with the ‘0’ character
 Syntax :
gets(str);
 The puts() function is used to display a string on the standard output
device.
 Syntax :
puts(str);
 The scanf() and printf() functions are used to accept and display mixed
data types with a single statement.
 The syntax to accept a string is as follows:
scanf(“%s”, str);
 The syntax to display a string is as follows:
printf(“%s”, str);
Functions for handling strings are found in the standard
header file string.h. Few of the operations performed by
these functions are:
• Concatenating strings
• Comparing strings
• Locating a character in a string
• Copying one string to another
• Calculating the length of a string
 Joins two string values into
one.
 Syntax:
strcat(str1, str2);
 Concatenates the str2 at the
end of str1
 The function returns str1
 Compares two strings and returns an integer value based
on the results of the comparison.
 Syntax:
strcmp(str1, str2);
 The function returns a value:
• Less than zero if str1<str2
• Zero if str1 is same as str2
• Greater than zero if str1>str2
 Determines the occurrence of a character in a string.
 Syntax:
strchr(str, chr);
 The function returns a value:
• Pointer to the first occurrence of the character
(pointed by chr) in the string, str
• NULL if it is not present
 Copies the value in one
string onto another
 Syntax:
strcpy(str1, str2);
 The value of str2 is copied
onto str1
 The function returns str1
 Determines the length of a
string
 Syntax:
strlen(str);
 The function returns an
integer value for the
length of str
 When an array is passed as an argument to a function,
only the address of the array is passed
 The array name without the subscripts refers to the
address of the array
void main()
{
int array[10];
.
.
fn_ary(array);
.
.
}
#include<stdio.h>
void main()
{
int num[5], ctr, sum=0;
int sum_arr(int num_arr[]); /* Function declaration */
clrscr();
for(ctr=0;ctr<5;ctr++) /* Accepts numbers into the array */
{
printf("nEnter number %d: ", ctr+1);
scanf("%d", &num[ctr]);
}
sum=sum_arr(num); /* Invokes the function */
printf("nThe sum of the array is %d", sum);
getch();
}
int sum_arr(int num_arr[]) /* Function definition */
{
int i, total;
for(i=0,total=0;i<5;i++) /* Calculates the sum */
total+=num_arr[i];
return total; /* Returns the sum to main() */
}
Sample output of the
program
Enter number 1: 5
Enter number 2: 10
Enter number 3: 13
Enter number 4: 26
Enter number 5: 21
The sum of the array
is 75
#include<stdio.h>
#include<string.h>
void main()
{
char lines[5][20];
int ctr, longctr=0;
int longest(char lines_arr[][20]);
/* Function declaration */
clrscr();
for(ctr=0;ctr<5;ctr++)
/* Accepts string values into the array */
{
printf("nEnter string %d: ", ctr+1);
scanf("%s", lines[ctr]);
}
longctr=longest(lines);
/* Passes the array to the function */
printf("nThe longest string is %s", lines[longctr]);
getch();
}
int longest(char lines_arr[][20]) /* Function definition */
{
int i=0, l_ctr=0, prev_len, new_len;
prev_len=strlen(lines_arr[i]);
/* Determines the length of the first element */
for(i++;i<5;i++)
{
new_len=strlen(lines_arr[i]);
/* Determines the length of the next element */
if(new_len>prev_len)
l_ctr=i;
/* Stores the subscript of the longer string */
prev_len=new_len;
}
return l_ctr;
/* Returns the subscript of the longest string */
}
Sample output of the program
Enter string 1: The
Enter string 2: Sigma
Enter string 3: Protocol
Enter string 4: Robert
Enter string 5: Ludlum
The longest string is Protocol
• Structure is another user defined data type which allows
you to combine data items of different kinds.
• The variables in a structure can be of different types:
Some can be int, some can be float, and so on.
• The data items in a structure are called the members of
the structure.
• struct part part1;
• defines a variable, called part1, of type structure part.
• This definition reserves space in memory for part1.
Model no part no cost
10031001 1007 1011
part1
• Other ways of declaring structures variables:
struct stud
{
char name[10];
int age;
};
main()
{
struct stud s1, s2;
}
struct stud
{
char name[10];
int age;
} s1, s2;
main()
{
}
struct
{
char name[10];
int age;
} s1 s2;
main()
{
}
• Members can be accessed using something called the
dot operator. syntax is
Structure_var_name.element_name;
• Here’s how the first member is given a value:
part1.modelnumber = 6244;
• .Is called member access operator
• Initializer lists
part part1= { 6244, 373, 217.55 };
• Assignment statements
part part1;
part1.modelnumber = 6244;
part1.partnumber = 373;
Part1.cost = 217.55;
part part2; //define variable
part2 = part1;
Structures can also be nested in such a way that an element
of a structure is itself another structure:
struct subject
{
char name[20];
float marks;
};
struct friend
{
char name[10];
int age;
subject fsub;
}
Int main()
{
friend frnd1,frnd2;
frnd1.name=“amir”;
frnd2.name=areeb;
frnd1.fsub.name=“computer”;
frnd2.fsub.name=“maths”;
frnd1.fsub.marks=85;
frnd2.fsub.marks=80;
}
• A structure variable can be passed as an argument to a
function
• This facility is used to pass groups of logically related
data items together instead of passing them one by one
• The type of the argument should match the type of the
parameter
 A common use of structures is in arrays of structures
 A structure is first defined, and then an array variable of
that type is declared
 Example:
struct student class_a[50];
 To the access the variable author of the fourth element of
the array books:
class_a[4].marks;
• Structure arrays are initialized by enclosing the list of values of its
elements within a pair of braces
• Example
struct unit
{ char ch;
int i;
};
struct unit series [3] =
{ {‘a’, 100}
{‘b’, 200}
{‘c’, 300}
};
• Memory representation of arrays of structure
1001 1004 1007 1010
0 1 2
series
Ch i Ch i Ch i
1002 1004 1005 1007 1008 1010
• Sorting involves arranging the array data in a specified
order such as ascending or descending
• Data in an array is easier to search when the array is
sorted
• There are two methods to sort arrays – Selection Sort
and Bubble Sort
• In the selection sort method, the value present in each
element is compared with the subsequent elements in
the array to obtain the least/greatest value
main()
{
int arr[] = {15,2,20,10,1};
int temp=0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
} }
}
I J arr[j] > arr[j+1] Temp=arr[j] arr[j]=arr[j+1] arr[j+1]=temp
0 0 arr[0]>arr[1]
15 > 2 true
Temp=arr[0]
Temp=15
0 1 arr[1]>arr[2]
15 > 20 false
0 2 arr[2]>arr[3]
20 > 10 true
Temp=arr[2]
Temp=20
0 3 arr[3]>arr[4]
20 > 1 true
Temp=arr[3]
Temp=20
1 0 arr[0]>arr[1]
2 > 15 false
1 1 arr[0]>arr[1]
15 > 10 true
Temp=arr[1]
Temp=15
15 2 20 10 1
0 1 2 3 4
arr
main()
{
int arr[] = {15,2,20,10,1};
int temp=0;
for (int i = 1; i < max; i++)
{
int j = i;
while (j > 0)
{
if (arr[j - 1] > arr[j])
{
int temp = arr[j - 1];
arr [j - 1] = arr[j];
arr[j] = temp;
j--;
}
else
break;
}
}
}
I J=i J>0 arr[j - 1] > arr[j] Temp=arr[j-1] arr[j-1]=arr[j] arr[j]=temp J--
1 1 1>0 true arr[0]>arr[1]
15 > 2 true
Temp=15 0
1 0>0
false
2 2 2>0
true
arr[1]>arr[2]
15>20 false
While loop
terminate
3 3 3>0
true
arr[2]>arr[3]
20>15 true
temp=arr[2]
temp=20
2
2>0
true
arr[1]>arr[2]
15>10 true
temp=arr[1]
temp=15
1
1>0
true
arr[0]>arr[1]
2>15 false
While loop
terminate
15 2 20 10 1
0 1 2 3 4
arr
 All I/O operations in C are carried out using functions
from the standard library
 This approach makes the C file system very powerful
and flexible
 I/O in C is unique because data may be transferred in its
internal binary representation or in a human-readable
text format
• When the program is terminated, the entire data is lost in
C programming. If you want to keep large volume of
data, it is time consuming to enter the entire data. But, if
file is created, these information can be accessed using
few commands.
• Stream is not a hardware it is linear queue which
connect file to program and passes block of data in both
direction .So it is independent of devices which we are
using. We can also define stream as source of data. This
source can be
•
• (a) A file
• (b) Hard disk or CD, DVD etc.
• (c) I/O devices etc.
• In c programming language there are two type of stream.
(a) Text streams
(b) Binary streams
• A text stream is a sequence of characters that can be
organized into lines terminated by a new line character
 Binary streams are a flat sequence of bytes, which do
not have any flags to indicate the end of file or end of
record
 The end of file is determined by the size of the file
 A file can refer to anything from a disk file to a terminal or
a printer
 A file is associated with a stream by performing an open
operation and disassociated by a close operation
 When a program terminates normally, all files are
automatically closed
 When a program crashes, the files remain open

More Related Content

What's hot (20)

Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointers
PointersPointers
Pointers
 
Pointer
PointerPointer
Pointer
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
C pointer
C pointerC pointer
C pointer
 
Used of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingUsed of Pointer in C++ Programming
Used of Pointer in C++ Programming
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
C pointer basics
C pointer basicsC pointer basics
C pointer basics
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Introduction to pointers and memory management in C
Introduction to pointers and memory management in CIntroduction to pointers and memory management in C
Introduction to pointers and memory management in C
 
Pointers in C/C++ Programming
Pointers in C/C++ ProgrammingPointers in C/C++ Programming
Pointers in C/C++ Programming
 
ppt on pointers
ppt on pointersppt on pointers
ppt on pointers
 
Double pointer (pointer to pointer)
Double pointer (pointer to pointer)Double pointer (pointer to pointer)
Double pointer (pointer to pointer)
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 

Viewers also liked

C standard library functions
C standard library functionsC standard library functions
C standard library functionsVaishnavee Sharma
 
OS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and MonitorsOS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and Monitorssgpraju
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationWayne Jones Jnr
 
2013 Mitsubishi Outlander at Jerry's Mitsubishi in Baltimore, Maryland
2013 Mitsubishi Outlander at Jerry's Mitsubishi in Baltimore, Maryland2013 Mitsubishi Outlander at Jerry's Mitsubishi in Baltimore, Maryland
2013 Mitsubishi Outlander at Jerry's Mitsubishi in Baltimore, MarylandJerry's Mitsubishi
 
Concept note jmdi eurocities - milano-tampere worksop
Concept note jmdi   eurocities - milano-tampere worksopConcept note jmdi   eurocities - milano-tampere worksop
Concept note jmdi eurocities - milano-tampere worksopThomas Jézéquel
 
Oakwood Premier Mumbai
Oakwood Premier MumbaiOakwood Premier Mumbai
Oakwood Premier Mumbaianil-chavan
 
Vrije opdracht ICT 2: Sanne Vanhaverbeke: Marrakech
Vrije opdracht ICT 2: Sanne Vanhaverbeke: MarrakechVrije opdracht ICT 2: Sanne Vanhaverbeke: Marrakech
Vrije opdracht ICT 2: Sanne Vanhaverbeke: MarrakechSanneVanhaverbeke
 
SenchaCon: DJing with Sencha Touch
SenchaCon: DJing with Sencha Touch SenchaCon: DJing with Sencha Touch
SenchaCon: DJing with Sencha Touch Patrick Sheridan
 
The China Analyst March 2011
The China Analyst   March 2011The China Analyst   March 2011
The China Analyst March 2011Barryvanwyk
 
Charter reporting sanahuja final
Charter reporting sanahuja finalCharter reporting sanahuja final
Charter reporting sanahuja finalThomas Jézéquel
 

Viewers also liked (20)

functions in C
functions in Cfunctions in C
functions in C
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
 
OS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and MonitorsOS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and Monitors
 
Memory Organization
Memory OrganizationMemory Organization
Memory Organization
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process Synchronization
 
Rvrsit
RvrsitRvrsit
Rvrsit
 
2013 Mitsubishi Outlander at Jerry's Mitsubishi in Baltimore, Maryland
2013 Mitsubishi Outlander at Jerry's Mitsubishi in Baltimore, Maryland2013 Mitsubishi Outlander at Jerry's Mitsubishi in Baltimore, Maryland
2013 Mitsubishi Outlander at Jerry's Mitsubishi in Baltimore, Maryland
 
Portfolio
PortfolioPortfolio
Portfolio
 
Inforln.com ERP LN 10.3 & 10.4 Configurable Contract Deliverables Enhancements
Inforln.com ERP LN 10.3 & 10.4 Configurable Contract Deliverables EnhancementsInforln.com ERP LN 10.3 & 10.4 Configurable Contract Deliverables Enhancements
Inforln.com ERP LN 10.3 & 10.4 Configurable Contract Deliverables Enhancements
 
ITALIANI
ITALIANIITALIANI
ITALIANI
 
Incoming
IncomingIncoming
Incoming
 
HTML5 and Sencha Touch
HTML5 and Sencha TouchHTML5 and Sencha Touch
HTML5 and Sencha Touch
 
Monopolis
MonopolisMonopolis
Monopolis
 
Concept note jmdi eurocities - milano-tampere worksop
Concept note jmdi   eurocities - milano-tampere worksopConcept note jmdi   eurocities - milano-tampere worksop
Concept note jmdi eurocities - milano-tampere worksop
 
Oakwood Premier Mumbai
Oakwood Premier MumbaiOakwood Premier Mumbai
Oakwood Premier Mumbai
 
Vrije opdracht ICT 2: Sanne Vanhaverbeke: Marrakech
Vrije opdracht ICT 2: Sanne Vanhaverbeke: MarrakechVrije opdracht ICT 2: Sanne Vanhaverbeke: Marrakech
Vrije opdracht ICT 2: Sanne Vanhaverbeke: Marrakech
 
SenchaCon: DJing with Sencha Touch
SenchaCon: DJing with Sencha Touch SenchaCon: DJing with Sencha Touch
SenchaCon: DJing with Sencha Touch
 
The China Analyst March 2011
The China Analyst   March 2011The China Analyst   March 2011
The China Analyst March 2011
 
Concept note fv
Concept note fvConcept note fv
Concept note fv
 
Charter reporting sanahuja final
Charter reporting sanahuja finalCharter reporting sanahuja final
Charter reporting sanahuja final
 

Similar to Advance topics of C language

CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxsangeeta borde
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxsangeeta borde
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1AmIt Prasad
 
C language presentation
C language presentationC language presentation
C language presentationbainspreet
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it outrajatryadav22
 
User Defined Functions in C
User Defined Functions in CUser Defined Functions in C
User Defined Functions in CRAJ KUMAR
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handlingRai University
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 

Similar to Advance topics of C language (20)

Pointers
PointersPointers
Pointers
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Session 5
Session 5Session 5
Session 5
 
Functions
FunctionsFunctions
Functions
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
C
CC
C
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
C language
C languageC language
C language
 
C language presentation
C language presentationC language presentation
C language presentation
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
 
Function (rule in programming)
Function (rule in programming)Function (rule in programming)
Function (rule in programming)
 
User Defined Functions in C
User Defined Functions in CUser Defined Functions in C
User Defined Functions in C
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 

Recently uploaded

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 

Recently uploaded (20)

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 

Advance topics of C language

  • 1.
  • 2. • Pointers • Malloc • Alloc • Calloc • Free • Realloc • Functions • Strings • Structures • Sorting • File handling
  • 3. • ‘Pointer’ is a variable that contains a memory address of other variable (does not contain a actual data).This is why we call it “Pointer” since it is used to POINT other variable. What Is pointer?
  • 4. Some situations where pointers can be used are  To return more than one value from a function  To pass arrays and strings more conveniently from one function to another  To manipulate arrays easily by moving pointers to them instead of moving the arrays itself  To allocate memory and access it  (Direct Memory Allocation)
  • 5. 5 int main () { int a; int b; int c; … int* ptr; a = 1000; b = 2000; c = 3000; } 1000 2000 3000 int a int b int c NUL 3004 3006 int* ptr 1004 1006 1008 1012
  • 6. 6 int main () { int a; int b; int c; int* ptr; a = 1000; b = 2000; c = 3000; ptr = &a; } 1000 2000 3000 1004 1006 1008 1012 int a int b int c 1004 3004 3008 int* ptrmemory address of ‘a’
  • 7. int * p; int* p; int *p; • Thus, the character * can appear anywhere between the data type name and the variable name. • Syntax: data_type *var_name; 7
  • 8. C provides two operators to work with pointers. (&) the address of operator (*) the dereferencing is a unary operator that returns the address of its operand. For example, given the statements: int x; int *p; The statement: p = &x; assigns the address of x to p. That is, x and the value of p refer to the same memory location referred to as indirection operator refers to the object to which its operand (that is, the pointer) points. For example, given the statements: int x=25,*p; p=&x 25 Xp
  • 9. • Consider the following statements. 1. num = 78; 2. p = &num; 3. *p = 24; 9
  • 10. Assignment • The value of one pointer variable can be assigned to another pointer variable of the same type. • Example: • Note: Any changes made to *p automatically change the value of *q, and vice versa. int *p,*q, i=5; q=&i; p=q;
  • 11. comparison • Two pointer variables of the same type can be compared for equality, and so on. • Example : int *p,*q, i=5; q=&i; p==q; p!=q; evaluates to true if p and q have the same value that is, if they point to the same memory location.evaluates to true if p and q point to different memory locations.
  • 12. Decrement and increment • Integer values can be added and subtracted from a pointer variable. • ++ increments the value of a pointer variable by the size of the memory to which it is pointing. • Similarly, -- the value of a pointer variable by the size of the memory to which it is pointing.
  • 13. • Example : • Let us assume that var is stored at the address 1000 • Then ptr_var has the value 1000 stored in it. Since integers are 2 bytes long, after the expression “ptr_var++;” ptr_var will have the value as 1002 and not 1001 int var,*ptr_var; ptr_var=&var; var=500; Ptr_var++;
  • 14. a &a[0] ‘a’is a pointer only to the first element, not the whole array same
  • 15.
  • 16. #include<stdio.h> void main() { static int ary[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9,10}; int i; for (i = 0; i < 10; i ++) { printf(“ni=%d,ary[i]=%d,*(ary+i)=%d“,i, ary[i],*(ary + i)); printf(“&ary[i]= %X,ary+i=%X”,&ary[i],ary+i); /* %X gives unsigned hexadecimal */ } }
  • 17.
  • 18.
  • 19. • The malloc() function dynamically allocates memory when required. This function allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error.
  • 20.
  • 21. • calloc is similar to malloc, but the main difference is that the • values stored in the allocated memory space is zero by default  calloc requires two arguments  The first is the number of variables you'd like to allocate memory for  The second is the size of each variable
  • 22.
  • 23. • You've allocated a certain number of bytes for an array but later find that you want to add values to it.You could copy everything into a larger array, which is inefficient, or you can allocate more bytes using realloc, without losing your data.  realloc takes two arguments  The first is the pointer referencing the memory  The second is the total number of bytes you want to reallocate
  • 24. Syntax: void *realloc( void *ptr, size_t size );
  • 25.
  • 26.
  • 27. • free() function can be used to de-allocates (frees) memory • when it is no longer needed. Syntax: void free(void *ptr ); • This function de allocates the space pointed to by ptr, • freeing it up for future use. • ptr must have been used in a previous call to malloc(), • calloc(), or realloc().
  • 28.
  • 29. A function in C can have a value, a side effect, or both • The side effect occurs before the value is returned. • The function’s value is the value of the expression in the return statement. • A function can be called for its value, its side effect, or both.
  • 30.
  • 31. • The general syntax of a function in C is : • The type_specifier specifies the data type of the value, which the function will return. • A valid function name is to be assigned to identify the function • Arguments appearing in parentheses are also termed as formal parameters.
  • 32. //Prototype declaration void greeting(); int main() { greeting(); return 0; } // main Void greeting() { printf(“HELLO WORLD”); return ; } //greeting() Declaration is coded first Definition is after the call Call is in the statement sections
  • 33.
  • 34. The type of the expression in the return statement must match the return type in the function header. . Only one value can be returned by a function
  • 35. • Formal parameters are variables that are declared in the header of the function definition. • Actual parameters are the expressions in the calling statement. • The formal and actual parameters must match exactly in type, order, and number. Their names, however, do not need to be the same.
  • 36. int square(int x); Int main() { Int I For(i=1;i<10; i++) { printf(“n square of %d is %d:”, i, square(i)); } int square(int x) { int j; j=x*x; return(j); } Actual argument Formal argument
  • 37. • Local Variables • Declared inside a function • Created upon entry into a block and destroyed upon exit from the block • Formal Parameters • Declared in the definition of function as parameters • Act like any local variable inside a function • Global Variables • Declared outside all functions • Holds value throughout the execution of the program
  • 38. float pi=3.1415; void area( int rad); int main() { float radius; printf("nEnter the radius of Circle : "); scanf("%d", &radius); area(radius); Return 0; } Void area( int rad) { int area; area=pi*rad*rad; } Global variable Formal parameter Local variable
  • 39.  Every C variable has a characteristic called as a storage class  The storage class defines two characteristics of the variable: • Lifetime – The lifetime of a variable is the length of time it retains a particular value • Visibility – The visibility of a variable defines the parts of a program that will be able to recognize the variable
  • 40. • automatic • external • static • register
  • 41. • Scope Rules - Rules that govern whether one piece of code knows about or has access to another piece of code or data • The code within a function is private or local to that function • Two functions have different scopes • One function cannot be defined within another function
  • 42.  Call by value  Call by reference
  • 43.  When arguments are passed to the called function, the values are passed through temporary variables
  • 44. • In call by reference, the function is allowed access to the actual memory location of the argument and therefore can change the value of the arguments of the calling routine
  • 46. • A pointer variable can be passed as a parameter to a function either by value or by reference. • In the function pointerParameters, both p and q are pointers. The parameter p is a reference parameter; the parameter q is a value parameter. • Furthermore, the function pointerParameters can change the value of *q, but not the value of q. However, the function pointerParameters can change the value of both p and *p.
  • 47.
  • 48.  The string is any sequence of characters surrounded by double quotes. • Strings are arrays of characters terminated by the NULL (‘0’) character. • The ‘0’ null character is automatically added in the internal representation of a string.
  • 49.  A typical string variable declaration is:. char str[10];  str is a character array variable that can hold a maximum of 10 characters including the null terminator.
  • 50.  String I/O operations are carried out using functions from the standard I/O library called stdio.h  The gets() function is the simplest method of accepting a string through standard input  Input characters are accepted till the Enter key is pressed  The gets() function replaces the terminating ‘n’ new line character with the ‘0’ character  Syntax : gets(str);
  • 51.  The puts() function is used to display a string on the standard output device.  Syntax : puts(str);  The scanf() and printf() functions are used to accept and display mixed data types with a single statement.  The syntax to accept a string is as follows: scanf(“%s”, str);  The syntax to display a string is as follows: printf(“%s”, str);
  • 52. Functions for handling strings are found in the standard header file string.h. Few of the operations performed by these functions are: • Concatenating strings • Comparing strings • Locating a character in a string • Copying one string to another • Calculating the length of a string
  • 53.  Joins two string values into one.  Syntax: strcat(str1, str2);  Concatenates the str2 at the end of str1  The function returns str1
  • 54.  Compares two strings and returns an integer value based on the results of the comparison.  Syntax: strcmp(str1, str2);  The function returns a value: • Less than zero if str1<str2 • Zero if str1 is same as str2 • Greater than zero if str1>str2
  • 55.
  • 56.  Determines the occurrence of a character in a string.  Syntax: strchr(str, chr);  The function returns a value: • Pointer to the first occurrence of the character (pointed by chr) in the string, str • NULL if it is not present
  • 57.
  • 58.  Copies the value in one string onto another  Syntax: strcpy(str1, str2);  The value of str2 is copied onto str1  The function returns str1
  • 59.  Determines the length of a string  Syntax: strlen(str);  The function returns an integer value for the length of str
  • 60.  When an array is passed as an argument to a function, only the address of the array is passed  The array name without the subscripts refers to the address of the array void main() { int array[10]; . . fn_ary(array); . . }
  • 61. #include<stdio.h> void main() { int num[5], ctr, sum=0; int sum_arr(int num_arr[]); /* Function declaration */ clrscr(); for(ctr=0;ctr<5;ctr++) /* Accepts numbers into the array */ { printf("nEnter number %d: ", ctr+1); scanf("%d", &num[ctr]); }
  • 62. sum=sum_arr(num); /* Invokes the function */ printf("nThe sum of the array is %d", sum); getch(); } int sum_arr(int num_arr[]) /* Function definition */ { int i, total; for(i=0,total=0;i<5;i++) /* Calculates the sum */ total+=num_arr[i]; return total; /* Returns the sum to main() */ } Sample output of the program Enter number 1: 5 Enter number 2: 10 Enter number 3: 13 Enter number 4: 26 Enter number 5: 21 The sum of the array is 75
  • 63. #include<stdio.h> #include<string.h> void main() { char lines[5][20]; int ctr, longctr=0; int longest(char lines_arr[][20]); /* Function declaration */ clrscr(); for(ctr=0;ctr<5;ctr++) /* Accepts string values into the array */ { printf("nEnter string %d: ", ctr+1); scanf("%s", lines[ctr]); }
  • 64. longctr=longest(lines); /* Passes the array to the function */ printf("nThe longest string is %s", lines[longctr]); getch(); } int longest(char lines_arr[][20]) /* Function definition */ { int i=0, l_ctr=0, prev_len, new_len; prev_len=strlen(lines_arr[i]); /* Determines the length of the first element */
  • 65. for(i++;i<5;i++) { new_len=strlen(lines_arr[i]); /* Determines the length of the next element */ if(new_len>prev_len) l_ctr=i; /* Stores the subscript of the longer string */ prev_len=new_len; } return l_ctr; /* Returns the subscript of the longest string */ } Sample output of the program Enter string 1: The Enter string 2: Sigma Enter string 3: Protocol Enter string 4: Robert Enter string 5: Ludlum The longest string is Protocol
  • 66. • Structure is another user defined data type which allows you to combine data items of different kinds. • The variables in a structure can be of different types: Some can be int, some can be float, and so on. • The data items in a structure are called the members of the structure.
  • 67.
  • 68. • struct part part1; • defines a variable, called part1, of type structure part. • This definition reserves space in memory for part1. Model no part no cost 10031001 1007 1011 part1
  • 69. • Other ways of declaring structures variables: struct stud { char name[10]; int age; }; main() { struct stud s1, s2; } struct stud { char name[10]; int age; } s1, s2; main() { } struct { char name[10]; int age; } s1 s2; main() { }
  • 70. • Members can be accessed using something called the dot operator. syntax is Structure_var_name.element_name; • Here’s how the first member is given a value: part1.modelnumber = 6244; • .Is called member access operator
  • 71. • Initializer lists part part1= { 6244, 373, 217.55 }; • Assignment statements part part1; part1.modelnumber = 6244; part1.partnumber = 373; Part1.cost = 217.55; part part2; //define variable part2 = part1;
  • 72.
  • 73. Structures can also be nested in such a way that an element of a structure is itself another structure: struct subject { char name[20]; float marks; }; struct friend { char name[10]; int age; subject fsub; } Int main() { friend frnd1,frnd2; frnd1.name=“amir”; frnd2.name=areeb; frnd1.fsub.name=“computer”; frnd2.fsub.name=“maths”; frnd1.fsub.marks=85; frnd2.fsub.marks=80; }
  • 74. • A structure variable can be passed as an argument to a function • This facility is used to pass groups of logically related data items together instead of passing them one by one • The type of the argument should match the type of the parameter
  • 75.
  • 76.  A common use of structures is in arrays of structures  A structure is first defined, and then an array variable of that type is declared  Example: struct student class_a[50];  To the access the variable author of the fourth element of the array books: class_a[4].marks;
  • 77. • Structure arrays are initialized by enclosing the list of values of its elements within a pair of braces • Example struct unit { char ch; int i; }; struct unit series [3] = { {‘a’, 100} {‘b’, 200} {‘c’, 300} };
  • 78. • Memory representation of arrays of structure 1001 1004 1007 1010 0 1 2 series Ch i Ch i Ch i 1002 1004 1005 1007 1008 1010
  • 79. • Sorting involves arranging the array data in a specified order such as ascending or descending • Data in an array is easier to search when the array is sorted • There are two methods to sort arrays – Selection Sort and Bubble Sort • In the selection sort method, the value present in each element is compared with the subsequent elements in the array to obtain the least/greatest value
  • 80.
  • 81. main() { int arr[] = {15,2,20,10,1}; int temp=0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } }
  • 82. I J arr[j] > arr[j+1] Temp=arr[j] arr[j]=arr[j+1] arr[j+1]=temp 0 0 arr[0]>arr[1] 15 > 2 true Temp=arr[0] Temp=15 0 1 arr[1]>arr[2] 15 > 20 false 0 2 arr[2]>arr[3] 20 > 10 true Temp=arr[2] Temp=20 0 3 arr[3]>arr[4] 20 > 1 true Temp=arr[3] Temp=20 1 0 arr[0]>arr[1] 2 > 15 false 1 1 arr[0]>arr[1] 15 > 10 true Temp=arr[1] Temp=15 15 2 20 10 1 0 1 2 3 4 arr
  • 83.
  • 84. main() { int arr[] = {15,2,20,10,1}; int temp=0; for (int i = 1; i < max; i++) { int j = i; while (j > 0) { if (arr[j - 1] > arr[j]) { int temp = arr[j - 1]; arr [j - 1] = arr[j]; arr[j] = temp; j--; } else break; } } }
  • 85. I J=i J>0 arr[j - 1] > arr[j] Temp=arr[j-1] arr[j-1]=arr[j] arr[j]=temp J-- 1 1 1>0 true arr[0]>arr[1] 15 > 2 true Temp=15 0 1 0>0 false 2 2 2>0 true arr[1]>arr[2] 15>20 false While loop terminate 3 3 3>0 true arr[2]>arr[3] 20>15 true temp=arr[2] temp=20 2 2>0 true arr[1]>arr[2] 15>10 true temp=arr[1] temp=15 1 1>0 true arr[0]>arr[1] 2>15 false While loop terminate 15 2 20 10 1 0 1 2 3 4 arr
  • 86.  All I/O operations in C are carried out using functions from the standard library  This approach makes the C file system very powerful and flexible  I/O in C is unique because data may be transferred in its internal binary representation or in a human-readable text format
  • 87. • When the program is terminated, the entire data is lost in C programming. If you want to keep large volume of data, it is time consuming to enter the entire data. But, if file is created, these information can be accessed using few commands.
  • 88. • Stream is not a hardware it is linear queue which connect file to program and passes block of data in both direction .So it is independent of devices which we are using. We can also define stream as source of data. This source can be • • (a) A file • (b) Hard disk or CD, DVD etc. • (c) I/O devices etc.
  • 89. • In c programming language there are two type of stream. (a) Text streams (b) Binary streams
  • 90. • A text stream is a sequence of characters that can be organized into lines terminated by a new line character  Binary streams are a flat sequence of bytes, which do not have any flags to indicate the end of file or end of record  The end of file is determined by the size of the file
  • 91.  A file can refer to anything from a disk file to a terminal or a printer  A file is associated with a stream by performing an open operation and disassociated by a close operation  When a program terminates normally, all files are automatically closed  When a program crashes, the files remain open