user3727944
user3727944

Reputation: 15

Calling a function within a loop

I am trying to a simple addition function that will take a number x from an array an and add a variable i to it, which is the iteration variable inside the for loop. Instead of adding each variable individually and producing the output of :

3, 2, 7

it produces values of

3, 5, 13.

#include <stdio.h>
int add(int x[], int y);
int main(void) {
    int i;
    int a[3] = {3, 1, 5};
    for(i=0; i<3; i++)
    {
        printf("%d \t", i);
        printf("%d, %d, equals %d \n", a[i], i,  add(a[i], i));
    }
    return 0;
}
int add(int x[], int y){
    return x+y;
}

Upvotes: 0

Views: 100

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

In your function definition,

int add(int x[], int y){

int x[] expects an array to be passed as the argument. By calling that with

      add(a[i], i)

you're making multiple mistakes, like

  • passing an int value where int * is expected, so a wrong and implicit conversion from int to int * is talking place.
  • Inside add(), x is of type int *. So, by saying return x+y;, you're essentially again (wrongly) converting a pointer to int type.

Here, it seems, you need only one int variable. not an array. Change it (both declaration and definition) to

int add(int x, int y){

Suggestion: Turn up the compiler warnings and pay heed to them. For example, with the -Wall option enabled, you would have received a warning saying

warning: passing argument 1 of ‘add’ makes pointer from integer without a cast

printf("%d, %d, equals %d \n", a[i], i,  add(a[i], i));
                                             ^

and

expected int * but argument is of type int

int add(int x[], int y);

and,

warning: return makes integer from pointer without a cast

  return x+y;
  ^

Upvotes: 2

Sushil Nagpal
Sushil Nagpal

Reputation: 29

You are using array as an argument. Please try below code:

#include <stdio.h>
int add(int x, int y);
int main(void) {
    int i;
    int a[3] = {3, 1, 5};
    for(i=0; i<3; i++)
    {
        printf("%d \t", i);
        printf("%d, %d, equals %d \n", a[i], i,  add(a[i], i));
    }
    return 0;
}
int add(int x, int y){
    return x+y;
}

Upvotes: 1

BM123
BM123

Reputation: 61

Try

int add(int x, int y){
    return x+y;
}

Upvotes: 6

Related Questions