AndrewM
AndrewM

Reputation: 55

How can I manipulate an Array?

I have an array

arr[]={7,5,-8,3,4};

And I have to update the same array to

arr[]={7,12,4,7,11};

my code:

#define _CRT_SECURE_NO_WARNINGS

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

int sumArr(int *arr, int size);

void main()
{

    int arr[] = { 7,5,-8,3,4 };
    int i, size, res = 0;

    printf("Enter Size Of The Array:");
    scanf("%d", &size);

    res = sumArr(arr, size);

    for (i = 0; i < size; i++)
    {
        printf("%d\n", res);
    }

  }


int sumArr(int *arr, int size)
{

        int i;

    for (i = 0; i < size; i++)
    {
      arr[i+1]+= arr[i];

        printf("  %d  \n", arr[i + 1]);
    }

    return arr[i+1];
}

The output should be: 7,12,4,7,11 But in my code, the output is: 12,4,7,11,-858993449,58196502,58196502,58196502,58196502,58196502

Any hints? I can use auxiliary functions for input and output arrays, will it help?

Upvotes: 1

Views: 67

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You have several mistakes in your code:

  • You need to stop the summing loop once i+1 reaches the end of the array
  • Your code knows the size; there is no need to read it from end-user
  • You need to print the value of res once, rather than printing it in a loop
  • You should consider moving the printing portion of the program into main from sumArray.

The modifications are very straightforward:

int sumArr(int *arr, int size) {
    // Stop when i+1 reaches size; no printing
    for (int i = 0; i+1 < size; i++) {
        arr[i+1]+= arr[i];
    }
    return arr[size-1];
}

Printing in the main:

printf("sum=%d\n", res);
for (int i = 0; i < size; i++) {
    printf("arr[%d] = %d\n", i, arr[i]);
}

Demo.

Upvotes: 3

Related Questions