SlideShare una empresa de Scribd logo
1 de 47
Arrays:  Array notations and representations, manipulating array elements, using multidimensional arrays, arrays of unknown or varying size. Structure : Purpose and usage of structures, declaring structures, assigning of structures. Pointers to Objects : Pointer and address arithmetic, pointer operations and declarations, using pointers as function arguments, Dynamic memory allocation, defining and using stacks and linked lists. UNIT IV
Introduction ,[object Object],[object Object],[object Object]
6.2 Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Name of array (Note that all elements of this array have the same name,  c ) Position number of the element within array  c c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4]
6.2 Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object]
6.3 Declaring Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
6.4 Examples Using Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
1  /* Arrays Example  */ 2   /* Histogram printing program */ 3 #include  <stdio.h> 4 #define  SIZE 10 5 6 int  main() 7 { 8   int  n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 9   int  i, j; 10 11   printf( &quot;%s%13s%17s&quot;, &quot;Element&quot;, &quot;Value&quot;, &quot;Histogram&quot; ); 12 13   for  ( i = 0; i <= SIZE - 1; i++ ) { 14   printf( &quot;%7d%13d  &quot;, i, n[ i ]) ; 15 16   for  ( j = 1; j <= n[ i ]; j++ )  /* print one bar */ 17   printf( &quot;%c&quot;, '*' ); 18 19   printf( &quot;&quot; ); 20   } 21 22   return  0; 23 }
Element  Value  Histogram 0  19  ******************* 1  3  *** 2  15  *************** 3  7  ******* 4  11  *********** 5  9  ********* 6  13  ************* 7  5  ***** 8  17  ***************** 9  1  *
6.4 Examples Using Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Passing Arrays to Functions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
1 /*  2   Passing arrays and individual array elements to functions */ 3 #include  <stdio.h> 4 #define  SIZE 5 5 6 void  modifyArray(  int  [],  int  );  /* appears strange */ 7 void  modifyElement(  int  ); 8 9 int  main() 10 { 11   int  a[ SIZE ] = { 0, 1, 2, 3, 4 }, i;  12 13   printf( &quot;Effects of passing entire array call &quot; 14   &quot;by reference:The values of the &quot; 15   &quot;original array are:&quot; ); 16 17   for  ( i = 0; i <= SIZE - 1; i++ )  18   printf( &quot;%3d&quot;, a[ i ] ); 19 20   printf( &quot;&quot; ); 21   modifyArray( a, SIZE );  /* passed call by reference */ 22   printf( &quot;The values of the modified array are:&quot; ); 23 24   for  ( i = 0; i <= SIZE - 1; i++ ) 25   printf( &quot;%3d&quot;, a[ i ] ); 26 27   printf( &quot;Effects of passing array element call &quot; 28   &quot;by value:The value of a[3] is %d&quot;, a[ 3 ] ); 29   modifyElement( a[ 3 ] ); 30   printf( &quot;The value of a[ 3 ] is %d&quot;, a[ 3 ] ); 31   return  0; 32 } Entire arrays passed call-by-reference, and can be modified Array elements passed call-by-value, and cannot be modified
Effects of passing entire array call by reference: The values of the original array are: 0  1  2  3  4 The values of the modified array are: 0  2  4  6  8 Effects of passing array element call by value: The value of a[3] is 6 Value in modifyElement is 12 The value of a[3] is 6 33 34 void  modifyArray(  int  b[],  int  size ) 35 { 36   int  j; 37 38   for  ( j = 0; j <= size - 1; j++ ) 39   b[ j ] *= 2; 40 } 41 42 void  modifyElement(  int  e ) 43 { 44   printf( &quot;Value in modifyElement is %d&quot;, e *= 2 ); 45 }
/* Program to count the no of positive and negative numbers*/  #include< stdio.h >  void main( )  {    int a[50],n,count_neg=0,count_pos=0,I;    printf(“Enter the size of the array”);    scanf(“%d”,&n);    printf(“Enter the elements of the array”);    for(I=0;I < n;I++)    scanf(“%d”,&a[I]);    for(I=0;I < n;I++)    {    if(a[I] < 0)    count_neg++;    else    count_pos++;    }    printf(“There are %d negative numbers in the  array”,count_neg);    printf(“There are %d positive numbers in the  array”,count_pos);  }
Multiple-Dimensional Arrays ,[object Object],[object Object],[object Object],Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[   0   ][   0   ] a[   1   ][   0   ] a[   2   ][   0   ] a[   0   ][   1   ] a[   1   ][   1   ] a[   2   ][   1   ] a[   0   ][   2   ] a[   1   ][   2   ] a[   2   ][   2   ] a[   0   ][   3   ] a[   1   ][   3   ] a[   2   ][   3   ] Row subscript Array name Column subscript
Initialization of multidimensional arrays:  Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces  Example:  Initializes the elements of first row to zero and second row to 1.  int table[2][3]={{0,0,0},{1,1,1}}  By surrounding the elements of each row by braces.  C allows arrays of three or more dimensions. The compiler determines the maximum number of dimension. The general form of a multidimensional array declaration is:  date_type array_name[s1][s2][s3]…..[sn];  Where s is the size of the ith dimension. Some examples are:  int survey[3][5][12];  float table[5][4][5][3];  Survey is a 3 dimensional array declared to contain 180 integer elements. Similarly table is a four dimensional array containing 300 elements of floating point type.
example program to add two matrices & store the results in the 3rd matrix #include<stdio.h> #include<conio.h> void main()  {  int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;  clrscr();  printf(&quot;enter the order of first matrix:&quot;); scanf(&quot;%d %d&quot;,&m,&n); printf(&quot;enter the order of the second matrix&quot;); scanf(&quot;%d %d&quot;,&p,&q); if(m==p && n==q) {   printf(&quot;matrix can be added&quot;);   printf(&quot;enter the elements of the matrix a&quot;);   for(i=0;i < m;i++)   {   for(j=0;j < n;j++) scanf(&quot;%d&quot;,&a[i][j]); }   printf(&quot;enter the elements of the matrix b&quot;);   for(i=0;i < p;i++) {   for(j=0;j < q;j++)   scanf(&quot;%d&quot;,&b[i][j]); }
printf(&quot;the sum of the matrix a and b is&quot;); for(i=0;i < m;i++) { for(j=0;j < n;j++) c[i][j]=a[i][j]+b[i][j]; } for(i=0;i < m;i++) {   for(j=0;j < n;j++) printf(&quot;%d&quot;,c[i][j]);   printf(&quot;&quot;); } } }
Structure Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an  array  are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types.  G eneral format:  struct tag_name  {    data type member1;    data type member2;    …    …  }  Example:  struct lib_books  {    char title[20];    char author[15];    int pages;    float price;  };
the keyword struct declares a structure to holds the details of four fields namely title, author pages and price. These are members of the structures. Each member may belong to different or same data type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure.  We can declare structure  variables  using the tag name any where in the program. For example the statement,  struct lib_books book1, book2, book3;  declares book1,book2,book3 as  variables  of type struct lib_books each declaration has four elements of the structure lib_books. The complete structure declaration might look like this  struct lib_books  {    char title[20];    char author[15];    int pages;    float price;  };  struct lib_books, book1, book2, book3;  Structure Contd………
We can also combine both template declaration and variables declaration in one statement, the declaration  struct lib_books  {    char title[20];    char author[15];    int pages;    float price;  } book1,book2,book3;  is valid.  book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books but does not include a tag name for use in the declaration.  A structure is usually defines before main along with macro definitions. In such cases the structure assumes global status and all the functions can access the structure.  Structure Contd………
Giving values to members:  The link between a member and a structure variable is established using the member operator ‘.’ Which is known as dot operator or period operator.  For example:  Book1.price  Is the variable representing the price of book1 and can be treated like any other ordinary variable. We can use scanf statement to assign values like  scanf(“%s”,book1.file);  scanf(“%d”,&book1.pages);  book1.pages=250;  book1.price=28.50;
#include<stdio.h> struct student { int id_no; char name[20]; char address[20]; int age; }newstudent; void main() { printf(&quot;Enter the student information&quot;); printf(&quot;Now Enter the student id_no&quot;); scanf(&quot;%d&quot;,&newstudent.id_no); printf(&quot;Enter the name of the student&quot;); scanf(&quot;%s&quot;,&newstudent.name); printf(&quot;Enter the address of the student&quot;); scanf(&quot;%s&quot;,&newstudent.address); printf(&quot;Enter the age of the student&quot;); scanf(&quot;%d&quot;,&newstudent.age); printf(&quot;Student information&quot;); printf(&quot;student id_number=%d&quot;,newstudent.id_no); printf(&quot;student name=%s&quot;,newstudent.name); printf(&quot;student Address=%s&quot;,newstudent.address); printf(&quot;Age of student=%d&quot;,newstudent.age); } EXAMPLE OF STRUCTURE
Initializing structure:  Example:  Struct student newstudent  { 12345, “kapildev”, “Pes college”, 19; };  This initializes the id_no field to 12345,  the name field to “kapildev”, the address field to “pes college” and the age field to 19.
Functions and structures:  We can pass structures as arguments to functions. Unlike array names however, which always point to the start of the array, structure names are not pointers. As a result, when we change structure parameter inside a function, we don’t effect its corresponding argument.  Passing structure to elements to functions:  A structure may be passed into a function as individual member or a separate variable.  A program example to display the contents of a structure passing the individual elements to a function is shown below.  #include<stdio.h> struct emp {  int emp_id;  char name[25];  char department[10];  float salary;  };  void display(int,char []); void main() { static struct emp emp1={125,&quot;sampath&quot;,&quot;operator&quot;,7500.00}; display(emp1.emp_id,emp1.name); }  /* function to display structure variables*/  void display(int e_no,char e_name[]) { printf(&quot;%d %s&quot;,e_no,e_name); }
Arrays of structure:  It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables. We can define an array of structures as shown in the following example:  structure information  {    int id_no;    char name[20];    char address[20];    char combination[3];    int age;  }  student[100];
An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below.  #include<stdio.h> void main() { struct info { int id_no; char name[20]; char address[20]; int age; }std[100]; int I,n; printf(&quot;Enter the number of students&quot;); scanf(&quot;%d&quot;,&n); printf(&quot; Enter Id_no,name address combination age&quot;); for(I=0;I<n;I++) scanf (&quot;%d%s%s%d&quot;, &std[I].id_no,std[I].name,std [I].address,&std[I].age); printf(&quot; Student information&quot;); for (I=0;I< n;I++) printf(&quot;%d %s %s %d&quot;,std[I].id_no,std[I].name,std[I].address,std[I].age ); }
Structure within a structure:  A structure may be defined as a member of another structure. In such structures the declaration of the embedded structure must appear before the declarations of other structures.  struct date  {    int day;    int month;    int year;  };  struct student  {    int id_no;    char name[20];    char address[20];    int age;    struct date def;    struct date doa;  }oldstudent,newstudent;  the sturucture student constains another structure date as its one of its members.
Union  Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows:  union item  {    int m;    float p;    char c;  }  code;   this declares a variable code of type union item. The union contains three members each with a different data type. However we can use only one of them at a time. This is because if only one location is allocated for union variable irrespective of size. The compiler allocates a piece of storage that is large enough to access a union member we can use the same syntax that we use to access structure members. That is  code.m  code.p  code.c  are all valid member variables.
Pointers Pointer declaration:  A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the  compiler  that you are creating a pointer variable. Finally you give the name of the variable.  type *variable_name  Example:  int *ptr;    float *ptr1;  Address operator:  Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example:  ptr=&num;  This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.
/* A program to illustrate pointer declaration*/  #include<stdio.h> void main()  {    int *ptr;    int num;    num=45;    ptr=&num;    printf (“ num is %d”, num);    printf (“ The num pointer is %d”,ptr);  }   Output: num is 45 The num pointer is 45
/* Program to display the contents of the variable their address using pointer variable*/  #include<stdio.h> void main() {  int num, *intptr;  float x, *floptr;  char ch, *cptr;  num=123;  x=12.34;  ch='a'; intptr=&num; cptr=&ch; floptr=&x; printf(&quot;Num %d stored at address %u&quot;,*intptr,intptr);  printf(&quot;Value %f stored at address %u&quot;,*floptr,floptr);  printf(&quot;Character %c stored at address %u&quot;,*cptr,cptr);  }
Pointer expressions & pointer arithmetic Like other variables pointer variables can be used in expressions.  For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid.  y = *p1 * *p2;    sum = sum + *p1;    z = 5* - *p2/p1;    *p2 = *p2 + 10;  we can also compare pointers by using relational operators the expressions such as  p1 >p2 , p1==p2 and p1!=p2 are allowed.
/*Program to illustrate the pointer expression and pointer arithmetic*/  #include<stdio.h> #include<conio.h> void main() { int *ptr1,*ptr2; int a,b,x,y,z; clrscr(); a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2-6; y=6* (- *ptr1) / *ptr2 + 30; printf(&quot;Address of a %u&quot;,ptr1); printf(&quot;Address of b %u&quot;,ptr2); printf(&quot;a=%d, b=%d&quot;,a,b); printf(&quot;x=%d,y=%d&quot;,x,y); ptr1=ptr1 + 70; printf(&quot;a=%d, b=%d&quot;,a,b); printf(&quot;Adress of a %u&quot;,ptr1); getch(); }
 
Pointers and function:  The pointer are very much used in a function declaration. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function definition may be classified into two groups.  1. Call by reference  2. Call by value.  Call by value:  We have seen that a function is invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the called function. The current value of corresponding actual parameter becomes the initial value of formal parameter. The value of formal parameter may be changed in the body of the actual parameter. The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters.
#include<stdio.h> void swap(int,int); void main() { int x,y; x=20; y=30; printf(&quot; Value of x and y before function call =%d %d&quot;,x,y); swap(x,y); printf(&quot; Value of x and y after function call =%d %d&quot;,x,y); } void swap(int p,int q) { int temp; temp=p; p=q; q=temp;  } Output: Value of x and y before function call = 20 30 Value of x and y after function call =  20 30 Example of Call by Value
Call by Reference When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call.  /* example of call by reference*?  #include<stdio.h> void Swap(int *,int *); void main() { int x,y; x=20; y=30; printf(&quot; Value of x and y before function call =%d %d&quot;,x,y); Swap(&x,&y); printf(&quot; Value of x and y after function call =%d %d&quot;,x,y); } void Swap(int *p,int *q) { int temp; temp=*p; *p=*q; *q=temp; }
 
Dynamic memory allocation:  The process of allocating memory at run time is known as  dynamic memory allocation . Although c does not inherently have this facility there are four library routines which allow this function.  Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But c inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in c for purpose of memory management.  Function Task malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space calloc Allocates space for an array of elements initializes them to zero and returns a pointer to the memory free Frees previously allocated space realloc Modifies the size of previously allocated space.
Allocating a block of memory A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form:    ptr=(cast_type *)malloc(byte-size);  ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size.  Example:  x=(int *)malloc(100*sizeof(int));  On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int.
Allocating multiple blocks of memory Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is:    ptr=(cast_type *) calloc(n,elem_size);  The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.
Releasing the used space Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function.  free(ptr);  ptr is a pointer that has been created by using malloc or calloc.
To Alter the size of allocated memory The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is :  ptr=realloc(ptr,newsize);  This function allocates new memory space of size newsize to the pointer variable ptr and returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.
#include<stdio.h> #include<stdlib.h> #define NULL 0 void main() { char *buffer; /*Allocating memory*/ if((buffer=(char *)malloc(10))==NULL) {  printf(&quot;Malloc failed&quot;); exit(1); } strcpy(buffer,&quot;Bangalore&quot;); printf(&quot;Buffer contains:%s&quot;,buffer); /*Reallocation*/ if((buffer=(char *)realloc(buffer,15))==NULL) { printf(&quot;Reallocation failed&quot;); exit(1); } printf(&quot;Buffer size modified.&quot;); printf(&quot;Buffer still contains: %s&quot;,buffer); strcpy(buffer,&quot;Mysore&quot;); printf(&quot;Buffer now contains:%s&quot;,buffer); /*freeing memory*/ free(buffer); }
Linked List A linked list is called so because each of items in the list is a part of a structure, which is linked to the structure containing the next item. This type of list is called a linked list since it can be considered as a list whose order is given by links from one item to the next.  Structure Each item has a node consisting two fields one containing the variable and another consisting of address of the next item(i.e.,  pointer  to the next item) in the list. A linked list is therefore a collection of structures ordered by logical links that are stored as the part of data. Consider the following example to illustrator the concept of linking. Suppose we define a structure as follows struct linked_list    {    float age;    struct linked_list *next;    }    struct linked_list node1,node2;  Item  Item 
Advantages of Linked List A linked list is a dynamic data structure and therefore the size of the linked list can grow or shrink in size during execution of the program. A linked list does not require any extra space therefore it does not waste extra memory. It provides flexibility in rearranging the items efficiently.  The limitation of linked list is that it consumes extra space when compared to a array since each node must also contain the address of the next item in the list to search for a single item in a linked list is cumbersome and time consuming.
#include<stdio.h> #include<conio.h> #include<alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; }; void append(struct node **,int ); void display(struct node * ); void main( ) { struct node *p; p = NULL ; append ( &p, 14 ) ; append ( &p, 30 ) ; append ( &p, 25 ) ; append ( &p, 42 ) ; append ( &p, 17 ) ; display ( p ) ; } /* adds a node at the end of a linked list */ void append ( struct node **q, int num ) { struct node *temp, *r ; if (*q == NULL) {   temp = malloc(sizeof(struct node)) ; temp -> data = num ; temp -> link = NULL ; *q = temp ; } else { temp = *q ; /* go to last node */ while ( temp -> link != NULL ) temp = temp -> link; /* add node at the end */ r = malloc ( sizeof ( struct node ) ) ; r -> data = num ; r -> link = NULL ; temp -> link = r ; } } void display ( struct node *q ) { printf ( &quot;&quot; ) ; /* traverse the entire linked list */ while ( q != NULL ) { printf (&quot; %d &quot;, q -> data ) ; q = q -> link ; } } Example of Linked List

Más contenido relacionado

La actualidad más candente

Character Array and String
Character Array and StringCharacter Array and String
Character Array and StringTasnima Hamid
 
Managing I/O & String function in C
Managing I/O & String function in CManaging I/O & String function in C
Managing I/O & String function in CAbinaya B
 
Multidimensional arrays in C++
Multidimensional arrays in C++Multidimensional arrays in C++
Multidimensional arrays in C++Ilio Catallo
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++Ilio Catallo
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiSowmya Jyothi
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programmingnmahi96
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Unionnikshaikh786
 
Module 4- Arrays and Strings
Module 4- Arrays and StringsModule 4- Arrays and Strings
Module 4- Arrays and Stringsnikshaikh786
 
Module 1:Introduction
Module 1:IntroductionModule 1:Introduction
Module 1:Introductionnikshaikh786
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotesSowri Rajan
 

La actualidad más candente (20)

Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
Managing I/O & String function in C
Managing I/O & String function in CManaging I/O & String function in C
Managing I/O & String function in C
 
Multidimensional arrays in C++
Multidimensional arrays in C++Multidimensional arrays in C++
Multidimensional arrays in C++
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
 
C++ string
C++ stringC++ string
C++ string
 
Module 4- Arrays and Strings
Module 4- Arrays and StringsModule 4- Arrays and Strings
Module 4- Arrays and Strings
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
Strings
StringsStrings
Strings
 
Module 1:Introduction
Module 1:IntroductionModule 1:Introduction
Module 1:Introduction
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
String C Programming
String C ProgrammingString C Programming
String C Programming
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
Array and string
Array and stringArray and string
Array and string
 
String notes
String notesString notes
String notes
 

Destacado

C language UPTU Unit3 Slides
C language UPTU Unit3 SlidesC language UPTU Unit3 Slides
C language UPTU Unit3 SlidesRakesh Roshan
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageRakesh Roshan
 
Mechanics of materials
Mechanics of materialsMechanics of materials
Mechanics of materialsSelf-employed
 
differential equations Boyce & Diprima Solution manual
differential equations Boyce & Diprima Solution manualdifferential equations Boyce & Diprima Solution manual
differential equations Boyce & Diprima Solution manualshayangreen
 
2 axial loading- Mechanics of Materials - 4th - Beer
2 axial loading- Mechanics of Materials - 4th - Beer2 axial loading- Mechanics of Materials - 4th - Beer
2 axial loading- Mechanics of Materials - 4th - BeerNhan Tran
 
3 torsion- Mechanics of Materials - 4th - Beer
3 torsion- Mechanics of Materials - 4th - Beer3 torsion- Mechanics of Materials - 4th - Beer
3 torsion- Mechanics of Materials - 4th - BeerNhan Tran
 
Higher Differential Equation
Higher Differential EquationHigher Differential Equation
Higher Differential Equationgtuautonomous
 
02 first order differential equations
02 first order differential equations02 first order differential equations
02 first order differential equationsvansi007
 
Mechanics of materials lecture 01, Engr. Abdullah Khan
Mechanics of materials lecture 01, Engr. Abdullah KhanMechanics of materials lecture 01, Engr. Abdullah Khan
Mechanics of materials lecture 01, Engr. Abdullah KhanAbdullah Khan
 
Higher Differential Equation
Higher Differential Equation Higher Differential Equation
Higher Differential Equation Abdul Hannan
 

Destacado (14)

C language UPTU Unit3 Slides
C language UPTU Unit3 SlidesC language UPTU Unit3 Slides
C language UPTU Unit3 Slides
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
Mechanics of materials
Mechanics of materialsMechanics of materials
Mechanics of materials
 
differential equations Boyce & Diprima Solution manual
differential equations Boyce & Diprima Solution manualdifferential equations Boyce & Diprima Solution manual
differential equations Boyce & Diprima Solution manual
 
Higher order differential equations
Higher order differential equationsHigher order differential equations
Higher order differential equations
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
 
CO By Rakesh Roshan
CO By Rakesh RoshanCO By Rakesh Roshan
CO By Rakesh Roshan
 
Unit 2 stresses in composite sections
Unit 2  stresses in composite sectionsUnit 2  stresses in composite sections
Unit 2 stresses in composite sections
 
2 axial loading- Mechanics of Materials - 4th - Beer
2 axial loading- Mechanics of Materials - 4th - Beer2 axial loading- Mechanics of Materials - 4th - Beer
2 axial loading- Mechanics of Materials - 4th - Beer
 
3 torsion- Mechanics of Materials - 4th - Beer
3 torsion- Mechanics of Materials - 4th - Beer3 torsion- Mechanics of Materials - 4th - Beer
3 torsion- Mechanics of Materials - 4th - Beer
 
Higher Differential Equation
Higher Differential EquationHigher Differential Equation
Higher Differential Equation
 
02 first order differential equations
02 first order differential equations02 first order differential equations
02 first order differential equations
 
Mechanics of materials lecture 01, Engr. Abdullah Khan
Mechanics of materials lecture 01, Engr. Abdullah KhanMechanics of materials lecture 01, Engr. Abdullah Khan
Mechanics of materials lecture 01, Engr. Abdullah Khan
 
Higher Differential Equation
Higher Differential Equation Higher Differential Equation
Higher Differential Equation
 

Similar a Unit4 Slides

Similar a Unit4 Slides (20)

Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
 
Arrays
ArraysArrays
Arrays
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Arrays
ArraysArrays
Arrays
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Array
ArrayArray
Array
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays
ArraysArrays
Arrays
 
array-191103180006.pdf
array-191103180006.pdfarray-191103180006.pdf
array-191103180006.pdf
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Array in C full basic explanation
Array in C full basic explanationArray in C full basic explanation
Array in C full basic explanation
 

Último

Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Último (20)

Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

Unit4 Slides

  • 1. Arrays: Array notations and representations, manipulating array elements, using multidimensional arrays, arrays of unknown or varying size. Structure : Purpose and usage of structures, declaring structures, assigning of structures. Pointers to Objects : Pointer and address arithmetic, pointer operations and declarations, using pointers as function arguments, Dynamic memory allocation, defining and using stacks and linked lists. UNIT IV
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7. 1 /* Arrays Example */ 2 /* Histogram printing program */ 3 #include <stdio.h> 4 #define SIZE 10 5 6 int main() 7 { 8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 9 int i, j; 10 11 printf( &quot;%s%13s%17s&quot;, &quot;Element&quot;, &quot;Value&quot;, &quot;Histogram&quot; ); 12 13 for ( i = 0; i <= SIZE - 1; i++ ) { 14 printf( &quot;%7d%13d &quot;, i, n[ i ]) ; 15 16 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */ 17 printf( &quot;%c&quot;, '*' ); 18 19 printf( &quot;&quot; ); 20 } 21 22 return 0; 23 }
  • 8. Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *
  • 9.
  • 10.
  • 11. 1 /* 2 Passing arrays and individual array elements to functions */ 3 #include <stdio.h> 4 #define SIZE 5 5 6 void modifyArray( int [], int ); /* appears strange */ 7 void modifyElement( int ); 8 9 int main() 10 { 11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i; 12 13 printf( &quot;Effects of passing entire array call &quot; 14 &quot;by reference:The values of the &quot; 15 &quot;original array are:&quot; ); 16 17 for ( i = 0; i <= SIZE - 1; i++ ) 18 printf( &quot;%3d&quot;, a[ i ] ); 19 20 printf( &quot;&quot; ); 21 modifyArray( a, SIZE ); /* passed call by reference */ 22 printf( &quot;The values of the modified array are:&quot; ); 23 24 for ( i = 0; i <= SIZE - 1; i++ ) 25 printf( &quot;%3d&quot;, a[ i ] ); 26 27 printf( &quot;Effects of passing array element call &quot; 28 &quot;by value:The value of a[3] is %d&quot;, a[ 3 ] ); 29 modifyElement( a[ 3 ] ); 30 printf( &quot;The value of a[ 3 ] is %d&quot;, a[ 3 ] ); 31 return 0; 32 } Entire arrays passed call-by-reference, and can be modified Array elements passed call-by-value, and cannot be modified
  • 12. Effects of passing entire array call by reference: The values of the original array are: 0 1 2 3 4 The values of the modified array are: 0 2 4 6 8 Effects of passing array element call by value: The value of a[3] is 6 Value in modifyElement is 12 The value of a[3] is 6 33 34 void modifyArray( int b[], int size ) 35 { 36 int j; 37 38 for ( j = 0; j <= size - 1; j++ ) 39 b[ j ] *= 2; 40 } 41 42 void modifyElement( int e ) 43 { 44 printf( &quot;Value in modifyElement is %d&quot;, e *= 2 ); 45 }
  • 13. /* Program to count the no of positive and negative numbers*/ #include< stdio.h > void main( ) { int a[50],n,count_neg=0,count_pos=0,I; printf(“Enter the size of the array”); scanf(“%d”,&n); printf(“Enter the elements of the array”); for(I=0;I < n;I++) scanf(“%d”,&a[I]); for(I=0;I < n;I++) { if(a[I] < 0) count_neg++; else count_pos++; } printf(“There are %d negative numbers in the array”,count_neg); printf(“There are %d positive numbers in the array”,count_pos); }
  • 14.
  • 15. Initialization of multidimensional arrays: Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces Example: Initializes the elements of first row to zero and second row to 1. int table[2][3]={{0,0,0},{1,1,1}} By surrounding the elements of each row by braces. C allows arrays of three or more dimensions. The compiler determines the maximum number of dimension. The general form of a multidimensional array declaration is: date_type array_name[s1][s2][s3]…..[sn]; Where s is the size of the ith dimension. Some examples are: int survey[3][5][12]; float table[5][4][5][3]; Survey is a 3 dimensional array declared to contain 180 integer elements. Similarly table is a four dimensional array containing 300 elements of floating point type.
  • 16. example program to add two matrices & store the results in the 3rd matrix #include<stdio.h> #include<conio.h> void main() { int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q; clrscr(); printf(&quot;enter the order of first matrix:&quot;); scanf(&quot;%d %d&quot;,&m,&n); printf(&quot;enter the order of the second matrix&quot;); scanf(&quot;%d %d&quot;,&p,&q); if(m==p && n==q) { printf(&quot;matrix can be added&quot;); printf(&quot;enter the elements of the matrix a&quot;); for(i=0;i < m;i++) { for(j=0;j < n;j++) scanf(&quot;%d&quot;,&a[i][j]); } printf(&quot;enter the elements of the matrix b&quot;); for(i=0;i < p;i++) { for(j=0;j < q;j++) scanf(&quot;%d&quot;,&b[i][j]); }
  • 17. printf(&quot;the sum of the matrix a and b is&quot;); for(i=0;i < m;i++) { for(j=0;j < n;j++) c[i][j]=a[i][j]+b[i][j]; } for(i=0;i < m;i++) { for(j=0;j < n;j++) printf(&quot;%d&quot;,c[i][j]); printf(&quot;&quot;); } } }
  • 18. Structure Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types. G eneral format: struct tag_name { data type member1; data type member2; … … } Example: struct lib_books { char title[20]; char author[15]; int pages; float price; };
  • 19. the keyword struct declares a structure to holds the details of four fields namely title, author pages and price. These are members of the structures. Each member may belong to different or same data type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure. We can declare structure variables using the tag name any where in the program. For example the statement, struct lib_books book1, book2, book3; declares book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books. The complete structure declaration might look like this struct lib_books { char title[20]; char author[15]; int pages; float price; }; struct lib_books, book1, book2, book3; Structure Contd………
  • 20. We can also combine both template declaration and variables declaration in one statement, the declaration struct lib_books { char title[20]; char author[15]; int pages; float price; } book1,book2,book3; is valid. book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books but does not include a tag name for use in the declaration. A structure is usually defines before main along with macro definitions. In such cases the structure assumes global status and all the functions can access the structure. Structure Contd………
  • 21. Giving values to members: The link between a member and a structure variable is established using the member operator ‘.’ Which is known as dot operator or period operator. For example: Book1.price Is the variable representing the price of book1 and can be treated like any other ordinary variable. We can use scanf statement to assign values like scanf(“%s”,book1.file); scanf(“%d”,&book1.pages); book1.pages=250; book1.price=28.50;
  • 22. #include<stdio.h> struct student { int id_no; char name[20]; char address[20]; int age; }newstudent; void main() { printf(&quot;Enter the student information&quot;); printf(&quot;Now Enter the student id_no&quot;); scanf(&quot;%d&quot;,&newstudent.id_no); printf(&quot;Enter the name of the student&quot;); scanf(&quot;%s&quot;,&newstudent.name); printf(&quot;Enter the address of the student&quot;); scanf(&quot;%s&quot;,&newstudent.address); printf(&quot;Enter the age of the student&quot;); scanf(&quot;%d&quot;,&newstudent.age); printf(&quot;Student information&quot;); printf(&quot;student id_number=%d&quot;,newstudent.id_no); printf(&quot;student name=%s&quot;,newstudent.name); printf(&quot;student Address=%s&quot;,newstudent.address); printf(&quot;Age of student=%d&quot;,newstudent.age); } EXAMPLE OF STRUCTURE
  • 23. Initializing structure: Example: Struct student newstudent { 12345, “kapildev”, “Pes college”, 19; }; This initializes the id_no field to 12345, the name field to “kapildev”, the address field to “pes college” and the age field to 19.
  • 24. Functions and structures: We can pass structures as arguments to functions. Unlike array names however, which always point to the start of the array, structure names are not pointers. As a result, when we change structure parameter inside a function, we don’t effect its corresponding argument. Passing structure to elements to functions: A structure may be passed into a function as individual member or a separate variable. A program example to display the contents of a structure passing the individual elements to a function is shown below. #include<stdio.h> struct emp { int emp_id; char name[25]; char department[10]; float salary; }; void display(int,char []); void main() { static struct emp emp1={125,&quot;sampath&quot;,&quot;operator&quot;,7500.00}; display(emp1.emp_id,emp1.name); } /* function to display structure variables*/ void display(int e_no,char e_name[]) { printf(&quot;%d %s&quot;,e_no,e_name); }
  • 25. Arrays of structure: It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables. We can define an array of structures as shown in the following example: structure information { int id_no; char name[20]; char address[20]; char combination[3]; int age; } student[100];
  • 26. An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below. #include<stdio.h> void main() { struct info { int id_no; char name[20]; char address[20]; int age; }std[100]; int I,n; printf(&quot;Enter the number of students&quot;); scanf(&quot;%d&quot;,&n); printf(&quot; Enter Id_no,name address combination age&quot;); for(I=0;I<n;I++) scanf (&quot;%d%s%s%d&quot;, &std[I].id_no,std[I].name,std [I].address,&std[I].age); printf(&quot; Student information&quot;); for (I=0;I< n;I++) printf(&quot;%d %s %s %d&quot;,std[I].id_no,std[I].name,std[I].address,std[I].age ); }
  • 27. Structure within a structure: A structure may be defined as a member of another structure. In such structures the declaration of the embedded structure must appear before the declarations of other structures. struct date { int day; int month; int year; }; struct student { int id_no; char name[20]; char address[20]; int age; struct date def; struct date doa; }oldstudent,newstudent; the sturucture student constains another structure date as its one of its members.
  • 28. Union Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows: union item { int m; float p; char c; } code; this declares a variable code of type union item. The union contains three members each with a different data type. However we can use only one of them at a time. This is because if only one location is allocated for union variable irrespective of size. The compiler allocates a piece of storage that is large enough to access a union member we can use the same syntax that we use to access structure members. That is code.m code.p code.c are all valid member variables.
  • 29. Pointers Pointer declaration: A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. type *variable_name Example: int *ptr; float *ptr1; Address operator: Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=&num; This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.
  • 30. /* A program to illustrate pointer declaration*/ #include<stdio.h> void main() { int *ptr; int num; num=45; ptr=&num; printf (“ num is %d”, num); printf (“ The num pointer is %d”,ptr); } Output: num is 45 The num pointer is 45
  • 31. /* Program to display the contents of the variable their address using pointer variable*/ #include<stdio.h> void main() { int num, *intptr; float x, *floptr; char ch, *cptr; num=123; x=12.34; ch='a'; intptr=&num; cptr=&ch; floptr=&x; printf(&quot;Num %d stored at address %u&quot;,*intptr,intptr); printf(&quot;Value %f stored at address %u&quot;,*floptr,floptr); printf(&quot;Character %c stored at address %u&quot;,*cptr,cptr); }
  • 32. Pointer expressions & pointer arithmetic Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid. y = *p1 * *p2; sum = sum + *p1; z = 5* - *p2/p1; *p2 = *p2 + 10; we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.
  • 33. /*Program to illustrate the pointer expression and pointer arithmetic*/ #include<stdio.h> #include<conio.h> void main() { int *ptr1,*ptr2; int a,b,x,y,z; clrscr(); a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2-6; y=6* (- *ptr1) / *ptr2 + 30; printf(&quot;Address of a %u&quot;,ptr1); printf(&quot;Address of b %u&quot;,ptr2); printf(&quot;a=%d, b=%d&quot;,a,b); printf(&quot;x=%d,y=%d&quot;,x,y); ptr1=ptr1 + 70; printf(&quot;a=%d, b=%d&quot;,a,b); printf(&quot;Adress of a %u&quot;,ptr1); getch(); }
  • 34.  
  • 35. Pointers and function: The pointer are very much used in a function declaration. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function definition may be classified into two groups. 1. Call by reference 2. Call by value. Call by value: We have seen that a function is invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the called function. The current value of corresponding actual parameter becomes the initial value of formal parameter. The value of formal parameter may be changed in the body of the actual parameter. The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters.
  • 36. #include<stdio.h> void swap(int,int); void main() { int x,y; x=20; y=30; printf(&quot; Value of x and y before function call =%d %d&quot;,x,y); swap(x,y); printf(&quot; Value of x and y after function call =%d %d&quot;,x,y); } void swap(int p,int q) { int temp; temp=p; p=q; q=temp; } Output: Value of x and y before function call = 20 30 Value of x and y after function call = 20 30 Example of Call by Value
  • 37. Call by Reference When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call. /* example of call by reference*? #include<stdio.h> void Swap(int *,int *); void main() { int x,y; x=20; y=30; printf(&quot; Value of x and y before function call =%d %d&quot;,x,y); Swap(&x,&y); printf(&quot; Value of x and y after function call =%d %d&quot;,x,y); } void Swap(int *p,int *q) { int temp; temp=*p; *p=*q; *q=temp; }
  • 38.  
  • 39. Dynamic memory allocation: The process of allocating memory at run time is known as dynamic memory allocation . Although c does not inherently have this facility there are four library routines which allow this function. Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But c inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in c for purpose of memory management. Function Task malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space calloc Allocates space for an array of elements initializes them to zero and returns a pointer to the memory free Frees previously allocated space realloc Modifies the size of previously allocated space.
  • 40. Allocating a block of memory A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form: ptr=(cast_type *)malloc(byte-size); ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size. Example: x=(int *)malloc(100*sizeof(int)); On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int.
  • 41. Allocating multiple blocks of memory Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is: ptr=(cast_type *) calloc(n,elem_size); The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.
  • 42. Releasing the used space Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function. free(ptr); ptr is a pointer that has been created by using malloc or calloc.
  • 43. To Alter the size of allocated memory The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is : ptr=realloc(ptr,newsize); This function allocates new memory space of size newsize to the pointer variable ptr and returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.
  • 44. #include<stdio.h> #include<stdlib.h> #define NULL 0 void main() { char *buffer; /*Allocating memory*/ if((buffer=(char *)malloc(10))==NULL) { printf(&quot;Malloc failed&quot;); exit(1); } strcpy(buffer,&quot;Bangalore&quot;); printf(&quot;Buffer contains:%s&quot;,buffer); /*Reallocation*/ if((buffer=(char *)realloc(buffer,15))==NULL) { printf(&quot;Reallocation failed&quot;); exit(1); } printf(&quot;Buffer size modified.&quot;); printf(&quot;Buffer still contains: %s&quot;,buffer); strcpy(buffer,&quot;Mysore&quot;); printf(&quot;Buffer now contains:%s&quot;,buffer); /*freeing memory*/ free(buffer); }
  • 45. Linked List A linked list is called so because each of items in the list is a part of a structure, which is linked to the structure containing the next item. This type of list is called a linked list since it can be considered as a list whose order is given by links from one item to the next. Structure Each item has a node consisting two fields one containing the variable and another consisting of address of the next item(i.e., pointer to the next item) in the list. A linked list is therefore a collection of structures ordered by logical links that are stored as the part of data. Consider the following example to illustrator the concept of linking. Suppose we define a structure as follows struct linked_list { float age; struct linked_list *next; } struct linked_list node1,node2; Item  Item 
  • 46. Advantages of Linked List A linked list is a dynamic data structure and therefore the size of the linked list can grow or shrink in size during execution of the program. A linked list does not require any extra space therefore it does not waste extra memory. It provides flexibility in rearranging the items efficiently. The limitation of linked list is that it consumes extra space when compared to a array since each node must also contain the address of the next item in the list to search for a single item in a linked list is cumbersome and time consuming.
  • 47. #include<stdio.h> #include<conio.h> #include<alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; }; void append(struct node **,int ); void display(struct node * ); void main( ) { struct node *p; p = NULL ; append ( &p, 14 ) ; append ( &p, 30 ) ; append ( &p, 25 ) ; append ( &p, 42 ) ; append ( &p, 17 ) ; display ( p ) ; } /* adds a node at the end of a linked list */ void append ( struct node **q, int num ) { struct node *temp, *r ; if (*q == NULL) { temp = malloc(sizeof(struct node)) ; temp -> data = num ; temp -> link = NULL ; *q = temp ; } else { temp = *q ; /* go to last node */ while ( temp -> link != NULL ) temp = temp -> link; /* add node at the end */ r = malloc ( sizeof ( struct node ) ) ; r -> data = num ; r -> link = NULL ; temp -> link = r ; } } void display ( struct node *q ) { printf ( &quot;&quot; ) ; /* traverse the entire linked list */ while ( q != NULL ) { printf (&quot; %d &quot;, q -> data ) ; q = q -> link ; } } Example of Linked List