-4

I am using a very simple code for subroutine but it is not printing right values. Please help me in this. My code is:

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

main(){
  int i, a, b=0.0, c=0.0;
  void sum(int a , int b);
  for ( i = 0; i < 2; i++ ) {   
    sum (a, b); c = c+b;
  }
  printf("%d\n", c);
}
void sum(int a , int b){
  int i;
  for ( i = 0; i <6; i++ )  {a = i*i;b = b+a;}
}
aland
  • 4,829
  • 2
  • 24
  • 42
user3132983
  • 65
  • 1
  • 5

5 Answers5

2

The effects of sum(int,int) are not visible to the caller, because a and b are passed by value. You need to use pointers to achieve the results that you want:

void sum(int *a , int *b){
    for (int i = 0; i <6; i++ ) {
        *a = i*i;
        *b += *a;
    }
}

Change the forward declaration to use pointers as well, and call sum (&a, &b) to pass the pointers.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

sum(a, b) is a NOP, you need to pass a pointer:

#include <stdio.h>

void sum(int *a, int *b)
{
    int i;

    for (i = 0; i < 6; i++) {
        *a = i * i;
        *b = *b + *a;
    }
}

int main(void)
{
    int i, a, b = 0.0, c = 0.0;

    for (i = 0; i < 2; i++) {   
        sum(&a, &b);
        c = c + b;
    }
    printf("%d\n", c);
    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

You are calling the function by values. You should call the function by reference that is using pointers or reference.

0

For adding in subroutines you need to use Call by reference Method. Then only the values are properly assigned to variables. But you are using Call by Value Method. so it will pass only the copy of the values to subroutine function. What are the changes made in subroutine that does not affect in main function. Try the following changes

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

main(){
int i, a, b=0, c=0; // fix 1
void sum(int *a , int *b); // fix 2
  for ( i = 0; i < 2; i++ ) {
  sum (&a, &b); c = c+b; // fix 3
  }
  printf("%d\n", c);
}
void sum(int *a , int *b){ // fix 4
  int i;
  for ( i = 0; i <6; i++ )  {*a = i*i;*b = *b+*a;}
}
Sathish
  • 3,740
  • 1
  • 17
  • 28
0
#include<stdio.h>


void sum(int *a , int *b);
int main() {
  int i, a, b=0.0, c=0.0;
  for ( i = 0; i < 2; i++ )
  {
        sum (&a, &b);
        c = c+b;
  }
  printf("%d\n", c);
}

void sum(int *a , int *b){
  int i;
  for ( i = 0; i <6; i++ )
  {
        *a = i*i;
        *b = (*b) + (*a);
  }
  return;
}

Output:

165

I have done required formating of your code and changes function arguments to pointer type.

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222