StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Program #37 (U4): malloc — Dynamic Array and Mean
Download
  1. C Programming
  2. C Programming Practice
Program #36 (U4): Pointer Basics & Array Sum via Pointer Traversal : Program #38 (U4): realloc — Grow/Shrink a Dynamic Array
C Programming Practice

Task: Read N, allocate an int array with malloc, input elements, compute the average, print it, and free the memory.

 
#include <stdio.h>

#include <stdlib.h>

 
int main(void){

    int N, *a;

    long long sum=0;

 
    printf("Enter N (>0): ");

    if(scanf("%d", &N)!=1 || N<=0){ printf("Invalid N.\n"); return 0; }

 
    a = (int*)malloc(N * sizeof(int));

    if(!a){ printf("Allocation failed.\n"); return 0; }

 
    printf("Enter %d integers: ", N);

    for(int i=0;i<N;++i){ scanf("%d", &a[i]); sum += a[i]; }

 
    printf("Mean = %.2f\n", (N? sum/(double)N : 0.0));

 
    free(a);

    return 0;

}

 

 

Program #36 (U4): Pointer Basics & Array Sum via Pointer Traversal Program #38 (U4): realloc — Grow/Shrink a Dynamic Array
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website