Program 1 : 

  1. /*

  2.  * C Program to Find Sum of Array Elements using Loops and Variables

  3.  */

  4.  

  5. #\nclude <stdio.h>

  6.  

  7. int main()

  8. {

  9.    int size;

  10.    printf("Enter size of the array: ");

  11.    scanf("%d",&size);

  12.  

  13.    //Declaring array

  14.    int arr[size];

  15.    printf("Enter array elements\n");

  16.  

  17.    // Input array elements

  18.    for(int i=0;i<size;i++)

  19.    scanf("%d",&arr[i]);

  20.    int sum=0;

  21.  

  22.    // Loop to find sum

  23.    for(int i=0;i<size;i++)

  24.    sum+=arr[i];

  25.  

  26.    //Print sum

  27.    printf("Sum of the array is: %d",sum);

  28.  

  29.    return 0;

  30. }



Using Pointers the same program :-

  1. /*

  2.  * C Program to Find Sum of Array Elements using Pointers

  3.  */

  4.  

  5. #include <stdio.h>

  6.  

  7. int main()

  8. {

  9.    int size;

  10.    printf("Enter size of the array: ");

  11.    scanf("%d",&size);

  12.    int arr[size];

  13.    printf("Enter array elements\n");

  14.    for(int i=0;i<size;i++)

  15.    scanf("%d",&arr[i]);

  16.    int sum=0;

  17.  

  18.    // pointer ptr points at the first element

  19.    int *ptr=&arr[0];

  20.    for(int i=0;i<size;i++)

  21.    {

  22.        sum+=*ptr;

  23.  

  24.        //Incrementing pointer to next element

  25.        ptr++;

  26.    }

  27.    printf("Sum of the array is: %d",sum);

  28.  

  29.    return 0;

  30. }







Comments

Popular posts from this blog

Solutions for Questions in Practical Slips from 1 to 5

Classical Problems of Synchronization in OS

SEMESTER IV : Assignment #1 NETWORKING