Program to Find Largest Number Using Dynamic Memory Allocation - (C Programs)
In this tutorial, we'll discuss how to write a C program that finds the largest number using dynamic memory allocation. Dynamic memory allocation allows the program to allocate memory dynamically during runtime, which is useful when the size of the data is unknown or changes frequently.
Syntax
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array;
int size;
int largest;
printf("Enter the size of the array: ");
scanf("%d", &size);
// Allocate memory dynamically
array = (int*) malloc(size * sizeof(int));
if (array == NULL) {
printf("Error: out of memory.");
return 1;
}
printf("Enter %d integers: ", size);
for (int i = 0; i < size; i++) {
scanf("%d", &array[i]);
}
// Find the largest number
largest = array[0];
for (int i = 1; i < size; i++) {
if (array[i > largest) {
largest = array[i];
}
}
printf("The largest number is: %d", largest);
// Deallocate memory
free(array);
return 0;
}
Example
Suppose that we have to find the largest number from a list of integers using dynamic memory allocation. Here's how we could do it:
Enter the size of the array: 5
Enter 5 integers: 2 6 1 8 5
The largest number is: 8
Output
Enter the size of the array: 10
Enter 10 integers: 53 23 1 87 43 65 29 10 72 43
The largest number is: 87
Explanation
This program uses dynamic memory allocation to allocate memory for an integer array. It prompts the user to enter the size of the array, allocates memory for the array using malloc()
, and reads in the integers from the user. It then finds the largest number from the integers and prints it out. Finally, it deallocates the memory using free()
.
Use
This program can be used to find the largest number from a list of integers provided by the user using dynamic memory allocation. It demonstrates how to allocate and deallocate memory dynamically in C.
Summary
In this tutorial, we discussed how to write a C program that finds the largest number using dynamic memory allocation. Dynamic memory allocation is useful when the size of the data is unknown or changes frequently. The program allocate memory for an integer array, finds the largest number from the integers, and deallocates the memory.