-
Notifications
You must be signed in to change notification settings - Fork 28
/
4dynmem.c
46 lines (35 loc) · 1.14 KB
/
4dynmem.c
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
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char * argv[]) {
int count = 0;
int * numbers = NULL;
printf("How many numbers would you like to enter: ");
scanf("%d", &count);
/***********************************
* Dynamic memory allocation
* malloc() to allocate memory.
* ********************************/
// int *p = new int[10];
numbers = malloc (count*sizeof(int)); // number of bytes
if (numbers==NULL){
printf("Error: Memory allocation failed\n");
return -1;
}
for (int i=0; i<count; i++){
printf("\nEnter number %d: ", i);
scanf("%d", &numbers[i]);
}
int sum = 0;
for (int i=0; i<count; i++){
sum += numbers[i];
}
printf("\nThe sum of numbers you entered is = %d: ", sum);
printf("\nThe average of numbers you entered is = %d: ", sum/count);
float avg = (float)sum/(float)count;
printf("\nAverage = %f: ", avg);
/***********************************
* free() to de-allocate memory.
* ********************************/
free (numbers); // Don't forget to free once your done!!
return 0;
}