0

I am trying to insert an integer if array position is equal to 3 but unfortunately when I am printing my array a I am getting absured results like this:

   0
   0
   2

whereas, the result expected is:

   0
   0
   128
   0
   0

My code is:

#include<stdio.h>
int substitute_and_sum(int *a, int len)
{

    int sum = 0, i;
    for (i = 0; i < 5; i++)
    {
        if (i == 3)
        {
            a[i] = 128;
        }
    }

    printf("%d\n", *a);
    return 0;
}

int main()
{

    int arr[] = { 0, 0, 2, 0, 0 };
    int j = 5, i;

    for (i = 0; i < 5; i++)
    {
        substitute_and_sum(&arr[i], j);
    }
}
1
  • The loop in substitute_and_sum goes outside the bounds of the array since you are giving it the array at various indices rather than the start of the array. Commented Sep 11, 2013 at 17:45

5 Answers 5

3

You have two for loops which don't play well together. Remove one or the other. For example:

int main()
{

    int arr[] = { 0, 0, 2, 0, 0 };
    int j = 5;

    substitute_and_sum(arr, j);
    for (int i = 0; i < 5; i++)
    {
        printf("%d\n", a[i]);
    }
}

Note that I moved the printf into main. Your existing program is pretty weird.

Sign up to request clarification or add additional context in comments.

Comments

3

You just need to call like following

int main(){

 int arr[]={0,0,2,0,0};
 int j=5,i;

 //for(i=0;i<5;i++)
 //{
  substitute_and_sum(arr,j);
 //}
}

Or use :-

void substitute_and_sum(int *a)
{   
    *a = 128;
}

And in main :

for (i = 0; i < 5; i++)
{
    if (i == 2) //Note its index 2, not 3
    substitute_and_sum(&arr[i]);
}

Comments

1

one for loop is enough

#include<stdio.h>
int substitute_and_sum(int* a, int len) {

int sum =0, i; 
for(i=0;i< len;i++)
{
 if(i==3)
        { 
     a[i] = 128;
    }
 printf("%d\n" , a[i]);  
}

 return 0;
}

 int main(){

 int arr[]={0,0,2,0,0};
 int j=5,i;
  substitute_and_sum(&arr[i],j);
}

replace 5 with len otherwise what is the point of the argument and the last printf() is pointless because it only prints the value of the first element;

Comments

1

You loop over your array in both functions, just do it in one of them.

Comments

1

this works, whenever you send individual value of the array make it an habit of sending its index, if required for example in case like yours.

 #include<stdio.h>
    int substitute_and_sum(int *a, int i)
    {

            if (i == 3)


 {
            *a = 128;
        }
    printf("%d\n", *a);
    return 0;
}

int main()
{

    int arr[] = { 0, 0, 2, 0, 0 };
    int  i;

    for (i = 0; i < 5; i++)
    {
        substitute_and_sum(&arr[i], i);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.