bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_1 / practice-c / pc-ip-09.c

pc-ip-09.c (1258B)


      1 /*
      2  * Question 9:
      3  * Write a program to find the sum of n elements entered by the user. Use dynamic memory allocation (malloc() or calloc()).
      4  */
      5 
      6 #include <stdio.h>
      7 #include <stdlib.h>
      8 
      9 void inputArray(double[], int);
     10 void printArray(double[], int);
     11 double sum(double[], int);
     12 
     13 int main()
     14 {
     15     int n;
     16     double *arr = NULL;
     17     printf("Enter the number of element: ");
     18     scanf("%d", &n);
     19     arr = (double *)malloc(n * sizeof(double));
     20     if (arr == NULL)
     21     {
     22         printf("\nMemory allocation failed.");
     23         return 1;
     24     }
     25     inputArray(arr, n);
     26     printf("\nGiven Array: ");
     27     printArray(arr, n);
     28     printf("\nSum of the elements of the array: %g", sum(arr, n));
     29     free(arr);
     30     return 0;
     31 }
     32 
     33 void inputArray(double arr[], int n)
     34 {
     35     int i;
     36     for (i = 0; i < n; i++)
     37     {
     38         printf("Enter element %d: ", i + 1);
     39         scanf("%lf", &arr[i]);
     40     }
     41 }
     42 
     43 void printArray(double arr[], int n)
     44 {
     45     int i;
     46     printf("[");
     47     for (i = 0; i < n; i++)
     48     {
     49         printf("%g", arr[i]);
     50         if (i < n - 1)
     51         {
     52             printf(", ");
     53         }
     54     }
     55     printf("]");
     56 }
     57 
     58 double sum(double arr[], int n)
     59 {
     60     int i;
     61     double sum = 0;
     62     for (i = 0; i < n; i++)
     63     {
     64         sum += arr[i];
     65     }
     66     return sum;
     67 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror