Sunday 17 December 2017

Difference Between Array and Structure In C?

                                                            Array

An array is a collection of similar type of data elements

An array is a derived data type

Array element access takes less time than structure

Array allocates static memory and uses index/subscript for accessing elements of the array

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
   int i;
    clrscr();
   int arr[5] = {10,20,30,40,50};

   /* Above array can be initialized as below also
      arr[0] = 10;
      arr[1] = 20;
      arr[2] = 30;
      arr[3] = 40;
      arr[4] = 50; */

   for (i=0;i<5;i++)
   {
      // Accessing each variable
      printf("value of arr[%d] is %d \n", i, arr[i]);
   }
getch();
 }
Output
value of arr[0] is 10                                                                                                          
value of arr[1] is 20                                                                                                          
value of arr[2] is 30                                                                                                          
value of arr[3] is 40                                                                                                          
value of arr[4] is 50

                               Structure

Structure is a collection of different types of data elements

Structure is a user defined data type.



Structure element access takes more time.

Structure allocates dynamic memory and uses (.) operator for accessing elements of the Structure

Example:

#include<stdio.h>
#include<conio.h>
struct emp

{

int id;

char name[50];

float sal;

};

 void main()

{

struct emp e1;

clrscr();

printf("Enter employee Id, Name, Salary: ");

scanf("%d",&e1.id);

scanf("%s",&e1.name);

scanf("%f",&e1.sal);



printf("Id: %d\n",e1.id);

printf("Name: %s\n",e1.name);

printf("Salary: %f\n",e1.sal);

getch();

}

Output:

Enter employee Id, Name, Salary:                                                                                               
101                                                                                                                            
Dev                                                                                                                            
240000                                                                                                                         
Id: 101                                                                                                                        
Name: Dev   
Salary: 240000.000000                                                                                                          
                       


No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...