C Language Examples - Find the Maximum Value

C Language Examples

Use the numerical value specified by user input to determine the maximum value.

Example - Find the Maximum Value

#include <stdio.h> #include <stdlib.h> int main() { int i, num; float *data; printf("Enter the number of elements (1 ~ 100):"); scanf("%d", &num); // Allocate memory for 'num' elements data = (float*) calloc(num, sizeof(float)); if(data == NULL) { printf("Error!!! Memory not allocated."); exit(0); } printf("\n"); // User input for(i = 0; i < num; ++i) { printf("Enter number %d:", i + 1); scanf("%f", data + i); } // Loop to find the maximum value for(i = 1; i < num; ++i) { // If you need to find the minimum value, change < to > if(*data < *(data + i)) *data = *(data + i); } printf("Maximum element = %.2f", *data); return 0; }

The output result is:

输入元素个数(1 ~ 100): 5

输入数字 1: 12
输入数字 2: 32
输入数字 3: 6
输入数字 4: 56
输入数字 5: 21
最大元素 = 56.00

C Language Examples

other extensions