English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn how to find the largest number entered by the user in dynamically allocated memory.
To understand this example, you should be familiar with the followingC Programming LanguageTopic:
#include <stdio.h> #include <stdlib.h> int main() { int num; float *data; printf("Enter the total number of elements: "); scanf("%d", &num); //Allocate memory for num elements data = (float *)calloc(num, sizeof(float)); if (data == NULL) { printf("Error!!! Memory allocation."); exit(0); } //Store the user's input numbers. for (int i = 0; i < num; ++i) { printf("Enter number %d: ", i + 1); scanf("%f", data + i); } //Find the largest number for (int i = 1; i < num; ++i) { if (*data < *(data + i)) *data = *(data + i); } printf("The largest number = %.2f", *data); return 0; }
Output result
Enter the total number of elements: 5 Enter a number 1: 3.4 Enter a number 2: 2.4 Enter a number 3: -5 Enter a number 4: 24.2 Enter a number 5: 6.7 The largest number = 24.20
In the program, ask the user to input the number of elements, which is stored in the variable num. We will allocate memory for num floating-point values.
Then, ask the user to input num. These numbers are stored in dynamically allocated memory.
Finally, determine the largest number among these numbers and print it on the screen.