-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_num_using_dynalloc.c
More file actions
52 lines (35 loc) · 1.03 KB
/
max_num_using_dynalloc.c
File metadata and controls
52 lines (35 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/** Find the max element from a dynamically allocated array using pointers **/
#include <stdio.h>
#include <stdlib.h>
int main() {
int arr_len;
printf("Enter number of elements in the array: ");
if (scanf("%d", &arr_len) != 1) {
printf("\nERROR: Wrong input given\n");
return -1;
}
int *arr = (int *)malloc(sizeof(int) * arr_len);
if (arr == NULL) {
printf("\nERROR: Failed allocating array\n");
return -1;
}
// Input the elements
for (int i = 0; i < arr_len; i++) {
printf("Enter element for position (%d) -> ", i);
if (scanf("%d", (arr + i)) != 1) {
printf("\nERROR: Wrong input given\n");
return -1;
}
}
// Get the max element
int largest = *arr; // Assumed to the first element at the beginning
for (int i = 1; i < arr_len; i++) {
if (*(arr + i) > largest) {
largest = *(arr + i); // Another max is found
}
}
printf("\nThe larget element is : %d\n", largest);
// Free the dynamically allocated memory
free(arr);
return 0;
}