Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can someone help me with these C program problems? Thanks 1. Write a C program t

ID: 3684825 • Letter: C

Question

Can someone help me with these C program problems? Thanks

1. Write a C program that creates two arrays of integers, one on the stack and one on the heap. You will loop through these arrays and populate them with values (any value is fine). You will then loop through these arrays again and print each value. Your output should look something like “Value in index 1 is 100 from stack array and 100 from heap array.” Do not forget to print newlines. Do not forget to de-allocate any memory you allocate.

2. Write a program that allocates an array on the heap and then iterates through the heap using pointer arithmetic. Print the item as in part 2 at each iteration. Loop backwards through the array using pointer arithmetic and print as well.

Explanation / Answer

1.

#include<stdio.h>
#include<stdlib.h>

int main(){
  
   int size;
   printf("Enter size of array: ");
   scanf("%d", &size);
  
   //stack array
   int stack[size];
  
   //heap array
   int *heap = (int *)malloc(size*sizeof(int));
   int i;
  
   // getting user input for both Stack and Heap array
   for(i=0; i<size; i++){
       printf("Enter value for Stack array at index %d : ",i);
       scanf("%d", &stack[i]);
       printf("Enter value for Heap array at index %d : ",i);
       scanf("%d", (heap+i));
      
   }
  
   //printing
   for(i=0; i<size; i++){
       printf("Value in index %d is %d from stack array and %d from heap array. ",i,stack[i], heap[i]);
   }
  
   //deallocating heap array
   free(heap);
   return 0;
}

2.


#include<stdio.h>
#include<stdlib.h>

int main(){
  
   int size;
   printf("Enter size of array: ");
   scanf("%d", &size);
  
  
   //dynamic array creation
   int *heap = (int *)malloc(size*sizeof(int));
   int i;
  
   // getting user input for both Stack and Heap array
   for(i=0; i<size; i++){
       printf("Enter value at index %d : ",i);
       scanf("%d", (heap+i)); // pointer arithmetic
      
   }
  
   //printing forward
   printf(" Printing forward ");
   for(i=0; i<size-1; i++){
       printf("Value in index %d is %d ",i, *heap);
       heap++;
   }
   printf("Value in index %d is %d ",i, *heap); // last element
  
   printf(" Printing backward ");
   //printing backward
   for(i=size-1; i>0; i--){
       printf("Value in index %d is %d ",i, *heap);
       heap--;
   }
   printf("Value in index %d is %d ",i, *heap); // first element
  
   //deallocating heap array
   free(heap);
   return 0;
}