Write a program in C to find the largest element using Dynamic Memory Allocation

Previous
Next

Solution:

  • We use calloc() function to allocate memory dynamically to arrays in C programming.
  • We scan the elements into array using “data+i” expression into consecutive memory locations.
  • We consider the first element as largest element in the array and compare with other elements.
  • If we found index element is greater than large element, we store the index element into large
#include <stdio.h>
#include <stdlib.h>
int main() 
{
	int n, i, large;
	int *data;
	printf("Enter the total number of elements: ");
	scanf("%d", &n);
	
	data = (int*)calloc(n, sizeof(int));
	if(data==NULL) 
	{
		printf("Couldn't allocate memory.");
		exit(0);
	}
	for (i=0; i<n; ++i) 
	{
		printf("Enter Number %d : ", i+1);
		scanf("%d", data+i);
	}	
	large=*data;
	for (i=1; i<n; ++i) 
	{
		if (large < *(data+i))
			large = *(data + i);
	}
	printf("Largest number = %d\n", large);
	return 0;
}
Previous
Next

Courses Enquiry Form