#include <stdio.h>
#include<stdlib.h>
/*
//Author Ekwegbalum Unachukwu
//Tech ID 15846083
//Lab 2 assignment 2
//Due date: January 31st, 2025

//Lab 2

//********ARRAY***************

//*** Array to store the muiptle variables in the single variables
//Syntax; Datatype arrayname[Length_of_the_ array]= (element1 and element2,....);

//***********POINTER***************
//*****POINTER is used to store the memory
A pointer is a variable that stores the memory address of another variable. 
Syntax to declare a pointer: datatype *ptr; 
Use & to get the address of a variable. 
Use * (dereference operator) to access the value stored at the pointer.




//***Dynamic Memory Allocation 

//**int arr[5]; not able to change the size of the array after ceration.

//A function malloc(), calloc(); free(), realloc()
//malloc( used to dynamically allcoate the single block of memory with the specific size.
//Syntax: datatype * pointerName = (cast_type*)mallo(size_int_bytes);


cast_type, 

calloc() – contiguous allocation is used to dynamically allocate the specified
number of blocks of memory with the specified type.
- Syntax: ptr = (cast_type*) calloc(n, element_size_in_bytes);

realloc() – re-allocation is used to dynamically change the memory allocation of a
previously allocated memory.
- Syntax: ptr = realloc(ptr, new_size);


 free() – delocate or releasing the memory, reduce the wastage of memory.
- Once memory is no longer needed, we must release it using free() function
- Syntax: free(ptr);





*/
#include <stdio.h>
#include <stdlib.h>

float calculateMean(int *arr, int size) {
    float sum = 0;
    int *ptr = arr;

    for (int i = 0; i < size; i++) {
        sum += *(ptr + i);  // Using pointer arithmetic
    }

    return sum / size;
}

    

int main() {

    int size;
    printf("Enter the size of the array: \n");
    scanf("%d", &size);
    printf("Size of the array: %d \n", size);

    // Dynamically allocate memory for the array
    int *arr = (int *)malloc(size * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed.\n");
        return 1;// determines if the size has been entered 
    }

    // Input values into the array
    printf("Enter %d numbers: \n", size);
    for (int i = 0; i < size; i++) {
        scanf("%d", (arr + i));  // Using pointer arithmetic
        printf("%d, ", *(arr + i)); // print out the array
    }

    // Calculate and display the mean
    float mean = calculateMean(arr, size);
    printf("\nMean of the numbers: %.2f\n", mean);

    // Free allocated memory
    free(arr);

    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: