user227666
user227666

Reputation: 784

unexpected result in array element with C

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);
    }
}

Upvotes: 0

Views: 90

Answers (5)

Megharaj
Megharaj

Reputation: 1619

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);
    }
}

Upvotes: 1

P0W
P0W

Reputation: 47854

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]);
}

Upvotes: 3

Farouq Jouti
Farouq Jouti

Reputation: 1667

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;

Upvotes: 1

Crowman
Crowman

Reputation: 25936

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

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225242

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.

Upvotes: 3

Related Questions