BCA

C AND LINEAR DATA STRUCURE

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6

PART C

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6 PROGRAM 7 . .

4.Program to create a dynamic array of n elements and find their sum and print in reverse order using functions with pointers(sum(int *,int)and rev_print(int *,int))

 

 /*Program to create a dynamic array of n elements and find their sum and print in reverse order
using functions with pointers(sum(int *,int)and rev_print(int *,int))*/


 
#include < stdio.h > 
#include < stdlib.h > 
  
int  sum_calculate(int *ptr,int n)
{
int sum=0,i=0;
   for (i = 0; i <  n; ++i) { 
           sum=sum+ ptr[i]; 
        } 
return sum;
}

void rev_print(int *ptr,int n)
{
int i ;
  printf("\nThe print in reverse order: "); 
 for (i = n-1; i >=0; i--) { 
            printf("%d, ", ptr[i]); 
        } 

}
void main() 
{ 
  
    // This pointer will hold the 
    // base address of the block created 
    int* ptr; 
    int n, i,sum; 
  
    // Get the number of elements for the array 
    n = 5; 
    printf("Enter number of elements: \n"); 
    scanf("%d",&n);
    // Dynamically allocate memory using malloc() 
    ptr = (int*)malloc(n * sizeof(int)); 
  
    // Check if the memory has been successfully 
    // allocated by malloc or not 
    if (ptr == NULL) { 
        printf("Memory not allocated.\n"); 
        exit(0); 
    } 
    else { 
  
        // Memory has been successfully allocated 
        printf("Memory successfully allocated using malloc.\n"); 
  
        // Get the elements of the array 
        for (i = 0; i < n; ++i) { 
            ptr[i] = i + 1; 
        } 
  
        // Print the elements of the array 
        printf("The elements of the array are: "); 
        for (i = 0; i < n; ++i) { 
            printf("%d, ", ptr[i]); 
        } 

        sum=sum_calculate(ptr, n);
        printf("\nThe sum fo elemets =: %d",sum); 
        rev_print( ptr,  n);

    } 
  
     
}