-
Help on using a funtion
Repeat Project 3 with the modification to write a separate function to accept k, m, n (in that order) and return the sum specified in the problem from the text. (A single, well-defined task)
This is that original project that works...
Code:
#include <stdio.h>
main()
{
int i,k,m,n,sum,e,ctr;
ctr=0;
FILE *payInFile, *payOutFile;
payInFile=fopen("data3.txt","r");
payOutFile=fopen("Pro3Out.txt","w");
e=fscanf(payInFile, "%d %d %d", &k, &m, &n);
fprintf(payOutFile," K M N Sum\n");
while(e==3)
{
sum=0;
ctr=ctr+1;
for(i=m;i<=n;i++)
{
if((i%k)==0)
{
sum=sum+i;
i++;
}
}
fprintf(payOutFile,"%6d %6d %6d %6d\n", k, m, n, sum);
e=fscanf(payInFile,"%d %d %d", &k, &m, &n);
}
fprintf(payOutFile,"\n\nEnd of Program, it processed %d sets of data", ctr);
fclose(payInFile);
fclose(payOutFile);
system("Pause");
}
This is the data it pulls in
Code:
13 22 054
7 8 045
013 023 032
2 2 014
5 15 59
15 48 56
7 248 267
4 2 16
19 234 735
2 3 4
11 456 957
9 2 66
7 39 0216
3 75 106
017 129 317
Now this is the code Ive tried to modify using a function and I just cant seem to get it working right.
Code:
#include <stdio.h>
int calcSum(int k, int m, int n);
main()
{
int i,k,m,n,sum,e,ctr;
ctr=0;
FILE *payInFile, *payOutFile;
payInFile=fopen("data3.txt","r");
payOutFile=fopen("Pro4Out.txt","w");
e=fscanf(payInFile, "%d %d %d", &k, &m, &n);
fprintf(payOutFile," K M N Sum\n");
while(e==3)
{
sum=calcSum(k,m,n);
ctr++;
fprintf(payOutFile,"%6d %6d %6d %6d\n", k, m, n, sum);
e=fscanf(payInFile,"%d %d %d", &k, &m, &n);
}
fprintf(payOutFile,"\n\nEnd of Program, it processed %d sets of data", ctr);
fclose(payInFile);
fclose(payOutFile);
system("Pause");
}
int calcSum(int k, int m, int n)
{
int sum,i;
for(i=m;i<=n;i++)
{
if((i%k)==0)
{
sum=sum+i;
return sum;
}
}
}
Any help would be appreciated. Thanks
-
You don't initialize sum in your function.
-
So something like this?
Code:
int calcSum(int k, int m, int n)
{
int sum,i;
for(i=m;i<=n;i++)
{
sum=0; //sum
if((i%k)==0)
{
sum=sum+i;
return sum;
}
}
}
I've tried this already to no avail. I know I'm missing sum=0; somewhere in this code.
I know I'm close to but at this point I'm stumped.
-
You need to return sum at the end of the function, not inside a loop.
-
You need to initialize sum before the loop, not inside it. Right now, every time through the loop, you reset sum to zero.
You need to think and trace through your code by hand, so you can envision what your code does as it runs. It may help to get some scratch paper to track the state of each variable after each individual instruction.
-
Thanks for your help. Finally got it and it took way longer than it should have haha