bsc

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

pc-ip-09.c (1449B)


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