Tuesday, April 12, 2022

Assignment 2 :Dynamic memory allocation in C.

Assignment 2: Dynamic memory allocation in C.

  •  Dynamic Memory Allocation is manual allocation and freeing of memory according to your programming needs. 
  • Dynamic memory is managed and served with pointers that point to the newly allocated memory space in an area which we call the heap.
  • Now you can create and destroy an array of elements dynamically at runtime without any problems. To sum up, the automatic memory management uses the stack, and the C Dynamic Memory Allocation uses the heap.
  • The <stdlib.h> library has functions responsible for Dynamic Memory Management.
  1. malloc() :- Allocates the memory of requested size and returns the pointer to the first byte of allocated space.
            The syntax of malloc() function is given below:
            ptr=(cast-type*)malloc(byte-size)  

    2. calloc() :- Allocates the space for elements of an array. Initializes the elements to zero                                 and returns a pointer to the memory.

            The syntax of calloc() function is given below:
            ptr=(cast-type*)calloc(number, byte-size)  

    3.  realloc() :- It is used to modify the size of previously allocated memory space.

            The syntax of realloc() function.
            ptr=realloc(ptr, new-size) 


    4. Free() :- Frees or empties the previously allocated memory space.

            The syntax of free() function.
                free(ptr)  


Example:-
#include<stdio.h>  
#include<stdlib.h>  
int main(){  
  int n,i,*ptr,sum=0;    
    printf("Enter number of elements: ");    
    scanf("%d",&n);    
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using malloc    
    if(ptr==NULL)                         
    {    
        printf("Sorry! unable to allocate memory");    
        exit(0);    
    }    
    printf("Enter elements of array: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Sum=%d",sum);    
    free(ptr);     
return 0;  
}    

/*********************************************************/
Output

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
/*****************************************************/


1. Write a program to  accept N integers and store them dynamically and access them.
Program :-
#include<stdio.h>  
#include<stdlib.h>  
void main()
{
int *p, n,i;
printf(“How many elements :”);
scanf(“%d”,&n);
p = (int *)malloc(n*sizeof(int));
/* Accepting data */
for(i=0; i<n;i++)
scanf(”%d”,p+i);
/* Displaying data */
for(i=0; i<n;i++)
printf(”%d\t”,*(p+i));
}


2. Program :-
 #include<stdio.h>
#include<stdlib.h>
main()
{
 int *a[10],r,c,i,j;
printf("Enter the order of matrix\n");
scanf("%d%d",&r,&c);
printf("Enter matrix elements\n");
 for(i=0;i<r;i++)
 {
 /**** dynamically allocate memory for every row ****/
 a[i]=(int *)malloc(c*sizeof(int));
 for(j=0;j<c;j++)
 {
scanf("%d",a[i]+j);
 }
 }
 /****** Display Matrix ******/
printf("The matrix is as below\n");
 for(i=0;i<r;i++)
 {
 for(j=0;j<c;j++)
 {
printf("%d\t",*(*(a+i)+j));
 }
printf("\n");
 }
}


3. Write a program to accept N integers and store them dynamically display them in 
reverse order.
Program :-
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, max;
    int *ptr;

    // Input maximum elements of array
    printf("Enter total number of elements: ");
    scanf("%d", &max);
    
    // Allocate memory for 'max' integer elements and initialized to 0 
    ptr = (int *) calloc(max, sizeof(int));
    
    // If memory not allocated
    if(ptr == NULL)
    {
        printf("Memory is not created!!!");
        exit(0); // Exit from the program
    }
    
    // Input elements from user
    printf("Enter %d elements: \n", max);
    for (i = 0; i < max; i++)
        scanf("%d", (ptr + i));
    
    // Print all elements 
    printf("\nArray elements are:\n");
    for (i =max; i >=0; i--)
        printf("%d ", *(ptr + i));
    
    // Release allocated memory
    free(ptr);
    
    return 0;
}

4. Write a program to allocate memory dynamically for n integers such that the memory is 
initialized to 0. And display it.

Program :-
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, max;
    int *ptr;

    // Input maximum elements of array
    printf("Enter total number of elements: ");
    scanf("%d", &max);
    
    // Allocate memory for 'max' integer elements and initialized to 0 
    ptr = (int *) calloc(max, sizeof(int));
    
    // If memory not allocated
    if(ptr == NULL)
    {
        printf("Memory is not created!!!");
        exit(0); // Exit from the program
    }
    
    // Input elements from user
    printf("Enter %d elements: \n", max);
    for (i = 0; i < max; i++)
        scanf("%d", (ptr + i));
    
    // Print all elements 
    printf("\nArray elements are:\n");
    for (i = 0; i < max; i++)
        printf("%d  ", *(ptr + i));
    
    // Release allocated memory
    free(ptr);
    
    return 0;
}



1. Accept N integers in an array using dynamic memory allocation. Find maximum from them
and display.
Program:-
#include <stdio.h>
#include <stdlib.h>

int main() {
  int n;
  double *data;
  printf("Enter the total number of elements: ");
  scanf("%d", &n);

  // Allocating memory for n elements
  data = (double *)calloc(n, sizeof(double));
  if (data == NULL) {
  printf("Error!!! memory not allocated.");
  exit(0);
  }

  // Storing numbers entered by the user.
  for (int i = 0; i < n; ++i) {
  printf("Enter number%d: ", i + 1);
  scanf("%lf", data + i);
  }

  // Finding the largest number
  for (int i = 1; i < n; ++i) {
    if (*data < *(data + i)) {
      *data = *(data + i);
    }
  }
  printf("Largest number = %.2lf", *data);

  free(data);

  return 0;
}

2. Accept n integers in an array. Copy only the non-zero elements to another array 
(allocated using dynamic memory allocation). Calculate the sum and average of non zero elements.
Program:-
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    int count;
    int *arr ,*arr1;
    int sum = 0;
    float avg=0.0;

    printf("Enter the total number of elements you want to enter : ");
    scanf("%d", &count);

    arr = (int *)malloc(count * sizeof(int));

for (i = 0; i < count; i++)
    {
        printf("Enter element %d : ", (i + 1));
        scanf("%d", arr + i);
    }

for (i = 0; i < count; i++)
    {
       if(*(arr+i)!=0)
*(arr1+i)=*(arr+i);
    }

    for (i = 0; i < count; i++)
    {
           sum += *(arr1 + i);
    }
    printf("sum is %d \n", sum);
    avg=sum/count;
     printf("Avg is %d \n", avg);
    free(arr);
    return 0;
}

3. Accept a matrix of order mXn (Use dynamic memory allocation and array of pointers
concept). Display trace of the matrix.
Program:-
#include<stdio.h>
#include<stdlib.h>
int main()
{
      int **a, row,col,i,j,t=0;
      printf("Enter Limit for Rows : ");
      scanf("%d",&row);
      printf("\nEnter Limit for Columns : ");
      scanf("%d",&col);
      a=(int **)malloc(row*sizeof(int*));
      for(i=0;i<row;i++)
      {
            a[i]=(int *)malloc(col*sizeof(int));
      }
      printf("\nEnter Elements for Matrix of Size %d*%d:\n\n",row,col);
      for(i=0;i<row;i++)
      {
            for(j=0;j<col;j++)
            {
                  scanf("%d",&a[i][j]);
            }
      }
      printf("\n%d*%d Matrix : \n\n",row,col);
      for(i=0;i<row;i++)
      {
            for(j=0;j<col;j++)
            {
                  printf("%3d ",a[i][j]);
            }
      printf("\n");
      }
      for(i=0;i<row;i++)
      {
            for(j=0;j<col;j++)
            {
if (i == j)
                   t=t+a[i][j];
            }
      }
      printf("\nTrace of Matrix = %d",t);
      return 0;
}


4. Accept a matrix of order mXn (Use dynamic memory allocation and array of pointers 
concept). Display Column wise sum of elements.
Program:-

#include<stdio.h>
#include<stdlib.h>
int main()
{
      int **a, row,col,i,j,t=0;
int rsum=0,csum=0;
      printf("Enter Limit for Rows : ");
      scanf("%d",&row);
      printf("\nEnter Limit for Columns : ");
      scanf("%d",&col);
      a=(int **)malloc(row*sizeof(int*));
      for(i=0;i<row;i++)
      {
            a[i]=(int *)malloc(col*sizeof(int));
      }
      printf("\nEnter Elements for Matrix of Size %d*%d:\n\n",row,col);
      for(i=0;i<row;i++)
      {
            for(j=0;j<col;j++)
            {
                  scanf("%d",&a[i][j]);
            }
      }
      printf("\n%d*%d Matrix : \n\n",row,col);
      for(i=0;i<row;i++)
      {
            for(j=0;j<col;j++)
            {
                  printf("%3d ",a[i][j]);
            }
      printf("\n");
      }

    printf("\nRow Sum....\n");
    for(i=0;i<row;i++)   
    {
        
        for(j=0;j<col;j++)
        {
            rsum=rsum+a[i][j];
        }
        printf("\nSum of all the elements in row %d is %d\n",i,rsum);
    }
    printf("\nColumn Sum....\n");
    for(i=0;i<row;i++)
    {
        
        for(j=0;j<col;j++)
        {
            csum=csum+a[j][i];
        }
        printf("\nSum of all the elements in column %d is %d\n",i,csum);
    }


}


Set A . Write C programs for the following problems.

1. Write a program to allocate memory dynamically for n integers such that the memory is initialized to 0. Accept the data from the user and find the range of the data elements.

 

#include <stdio.h>

#include <stdlib.h>

int main()

{

 int i, max;

 int *ptr;

 // Input maximum elements of array

 printf("Enter total number of elements: ");

 scanf("%d", &max);

 // Allocate memory for 'max' integer elements and initialized to 0

 ptr = (int *) calloc(max, sizeof(int));

 // If memory not allocated

 if(ptr == NULL)

 {

 printf("Memory is not created!!!");

 exit(0); // Exit from the program

 }

 // Input elements from user

 printf("Enter %d elements: \n", max);

 for (i = 0; i < max; i++)

 scanf("%d", (ptr + i));

 // Print all elements

 printf("\nArray elements are:\n");

 for (i = 0; i < max; i++)

 printf("%d ", *(ptr + i));

 // Release allocated memory

 free(ptr);

 return 0;

}

 

 

2. Accept n integers in an array. Copy only the non-zero elements to another array (allocated using dynamic memory allocation). Calculate the sum and average of non-zero elements.

#include <stdio.h>

#include <stdlib.h>

int main()

{

 int i;

 int count;

 int *arr ,*arr1;

 int sum = 0;

 float avg=0.0;

 printf("Enter the total number of elements you want to enter : ");

 scanf("%d", &count);

 arr = (int *)malloc(count * sizeof(int));

for (i = 0; i < count; i++)

 {

 printf("Enter element %d : ", (i + 1));

 scanf("%d", arr + i);

 }

for (i = 0; i < count; i++)

 {

if(*(arr+i)!=0)

*(arr1+i)=*(arr+i);

}

 for (i = 0; i < count; i++)

 {

sum += *(arr1 + i);

 }

 printf("sum is %d \n", sum);

 avg=sum/count;

printf("Avg is %d \n", avg);

 free(arr);

 return 0;

}

Set B . Write C programs for the following problems.

1. Accept the number of rows (m) and columns (n) for a matrix and dynamically allocate memory for the matrix. Accept and display the matrix using pointers. (Hint: Use an array of pointers.)

#include<stdio.h>

#include<stdlib.h>

int main()

{

 int **a, row,col,i,j,t=0;

 printf("Enter Limit for Rows : ");

 scanf("%d",&row);

 printf("\nEnter Limit for Columns : ");

 scanf("%d",&col);

 a=(int **)malloc(row*sizeof(int*));

 for(i=0;i<row;i++)

 {

 a[i]=(int *)malloc(col*sizeof(int));

 }

 printf("\nEnter Elements for Matrix of Size %d*%d:\n\n",row,col);

 for(i=0;i<row;i++)

 {

 for(j=0;j<col;j++)

 {

 scanf("%d",&a[i][j]);

 }

 }

 printf("\n%d*%d Matrix : \n\n",row,col);

 for(i=0;i<row;i++)

 {

 for(j=0;j<col;j++)

 {

 printf("%3d ",a[i][j]);

 }

 printf("\n");

 }

return 0;

} 







No comments:

Post a Comment