[C] Lab question. (Pass by reference)

  • Thread starter Thread starter ccky
  • Start date Start date
  • Tags Tags
    Lab Reference
AI Thread Summary
The discussion revolves around creating a function in C that accumulates a sum of float numbers using pass by reference. The initial code provided does not meet the requirements, as the function does not ask for user input or update the cumulative sum correctly. Participants emphasize the need for the function to take a reference to a variable declared in main and to prompt the user for input within the function itself. A static variable is suggested as a potential solution for retaining the cumulative sum across multiple calls, but it is clarified that the passed variable should suffice. The conversation also touches on multiple-choice questions related to C programming syntax and function calls.
ccky
Messages
15
Reaction score
0
a)Write a function,named getNumSum(),for accumulating(summing)float numbers;
-The function has no return value
-The function has 1 input argument named aSum:the current accumulative sum to be "updated" inside this function(Hint:use pass by reference)
-The function asks user for a float input,then updates the accumulative sum
*No code for input validation needed


My answner:

#include <stdio.h>

void getNumSum();
int main()
{

getNumSum();
return 0;
}

void getNumSum()
{
float aSum;
float *aSumAddr;

printf("type the floating point number :");
scanf(" %f", &aSum);

aSumAddr=&aSum; /*Pass to reference*/

printf("the current accumulative sum is %f",*aSumAddr);/*Use reference show the answer*/
}

I am so confused about above question.
Above the program,i want to ask which part i should modify?
Thanks!
 
Physics news on Phys.org
aSum must be a variable declared in main(), not in getNumSum().

You must pass its address to the getNumSum - you are not passing anything now.

Do you understand the difference between passing a value and a reference as a parameter?
 
To add to what Borek said, your getNumSum function needs to have a parameter (aSum). This parameter should be passed by reference rather than be passed by value. This means that what is being passed is the address of a variable rather than the value of the variable.
 
Borek said:
aSum must be a variable declared in main(), not in getNumSum().

You must pass its address to the getNumSum - you are not passing anything now.

Do you understand the difference between passing a value and a reference as a parameter?

I modify the program.Is it that?
My thought is that pass an reference is to use a address to store the variable...
#include <stdio.h>

void getNumSum(float *);
int main()
{
float aSum;

printf("type the floating point number :");
scanf(" %f", &aSum);

getNumSum(&aSum);
return 0;
}

void getNumSum(float *aSumAddr)
{

printf("the current accumulative sum is %f",*aSumAddr);
}
 
You are using pass-by-reference correctly, but you function is not updating a cumulative total. All that getNumSum is doing is printing the value that it was sent when it was called. You need another variable declared inside getNumSum. This variable will be incremented by the value at the address pointed to by aSumAddr.

You need a variable that doesn't lose its value between calls to getNumSum. It can't be a variable that is local to getNumSum and it shouldn't be a global variable declared outside all of the functions.
 
Mark44 said:
You need a variable that doesn't lose its value between calls to getNumSum. It can't be a variable that is local to getNumSum and it shouldn't be a global variable declared outside all of the functions.
A static variable in getNumSum would work, assuming it's not explicitly initialized, in which case, it's initialized to zero. The static variable would have local scope, but otherwise be similar to a global variable.
 
That's what I was hinting at, but I wanted the OP to come up with it on his own...
 
Somehow I doubt static variables are something that OP is aware of at this stage.
 
Borek said:
Somehow I doubt static variables are something that OP is aware of at this stage.
Or should be using. The variable that retains value between calls is the one passed to the function, by reference. There is no need for a static variable here.
ccky said:
I modify the program.Is it that?
My thought is that pass an reference is to use a address to store the variable...
Code:
#include <stdio.h>

void getNumSum(float *);
int main()
{
	float aSum;
	  	
    printf("type the floating point number :"); 
	scanf(" %f", &aSum);
	
	getNumSum(&aSum);
	return 0;
}

void getNumSum(float *aSumAddr)
{	

	printf("the current accumulative sum is %f",*aSumAddr);
}
There are a number of things wrong here.

One is how your post looks. Notice how different the code looks above versus in your post. Please place your code between a markers that start and end a block of code.

The posted code has a number of problems. One is that you aren't updating that pointer in your function getNumSum. That is the purpose of this assignment.

Another is that you did not follow the instructions given to you. "The function asks the user for a float input, then updates the accumulative sum." You are asking for the input in main. It's the function that is supposed to ask for (and receive) a floating point value. Follow directions!
 
  • #10
You are correct, D H. The cumulative sum should be passed to getNumSum by reference. This function should ask for input and increment the cumulative sum by that amount.

Borek, you are right as well, about there not being a need for a static variable. In retrospect, the requirements were clear, but I misinterpreted them.
 
  • #11
Mark44 said:
You are correct, D H. The cumulative sum should be passed to getNumSum by reference. This function should ask for input and increment the cumulative sum by that amount.

Borek, you are right as well, about there not being a need for a static variable. In retrospect, the requirements were clear, but I misinterpreted them.
Thank all for helping me!
I modify the another part.
void getNumSum(float *aSumAddr)
{
float Total;
Total=0.01;
*aSumAddr+=Total;
printf("the current accumulative sum is %f",*aSumAddr);
}

and,some Multiple choice questions.
I hope you can help me confirm the answer.Thank!.

1)Given the following C program code fragment with a valid variable count,which of the following answers is correct?
for( ; count<=30 ; );
A)It is syntactically incorrect B)It must be an infinite loop.
C)It must be a finite loop. D)It is syntactically correct.
My answer is D.

2)If the C program code fragment below is valid,how many functions are included?
varX("%d (%d) in fun()\n", notFn(varY()),(xyz*(abc)));
2 3 4 5 you can choose
My answer is 4.
 
  • #12
As D H already asked, please use code tags ([ code ] at the top and [ /code ] at the bottom, without the extra spaces I have) so that your indentation is preserved.
ccky said:
Thank all for helping me!
I modify the another part.
void getNumSum(float *aSumAddr)
{
float Total;
Total=0.01;
*aSumAddr+=Total;
printf("the current accumulative sum is %f",*aSumAddr);
}
This is close, but doesn't meet the requirements, which I copied below.
  • The function has 1 input argument named aSum:the current accumulative sum to be "updated" inside this function(Hint:use pass by reference)
  • The function asks user for a float input,then updates the accumulative sum

The name of the parameter should be aSum, not aSumAddr.
The function should ask for input of a (float) number, not hard-code it to the value 0.01. Also, I would advise using a different name for the variable. The name Total is misleading, as it's not being used for the cumulative sum. That's the role of aSum.

ccky said:
and,some Multiple choice questions.
I hope you can help me confirm the answer.Thank!.

1)Given the following C program code fragment with a valid variable count,which of the following answers is correct?
for( ; count<=30 ; );
A)It is syntactically incorrect B)It must be an infinite loop.
C)It must be a finite loop. D)It is syntactically correct.
My answer is D.
I think that multiple answers are possible.
ccky said:
2)If the C program code fragment below is valid,how many functions are included?
varX("%d (%d) in fun()\n", notFn(varY()),(xyz*(abc)));
2 3 4 5 you can choose
My answer is 4.
 
  • #13
ccky said:
1)Given the following C program code fragment with a valid variable count,which of the following answers is correct?
for( ; count<=30 ; );
A)It is syntactically incorrect B)It must be an infinite loop.
C)It must be a finite loop. D)It is syntactically correct.
My answer is D.
The generic form of a for loop is for (init; condition; increment) statement. Your loop omits the init and increment clauses, but that's OK because each of the init, condition, and increment clauses is optional (i.e., can be empty). The condition is a valid integer expression, so no problem there. The statement is the null statement (semicolon only), and that's OK, too. The statement is syntactically correct. And that is all you can say. It will loop infinitely if count is less than or equal to 30, but it will do nothing if count is greater than 30.

In short, D is the correct answer.


2)If the C program code fragment below is valid,how many functions are included?
varX("%d (%d) in fun()\n", notFn(varY()),(xyz*(abc)));
2 3 4 5 you can choose
My answer is 4.
Count carefully. There's no function call in "%d (%d) in fun()\n". This is just a string. There's no function call in (xyz*(abc)) either.
 
  • #14
Mark44 said:
As D H already asked, please use code tags ([ code ] at the top and [ /code ] at the bottom, without the extra spaces I have) so that your indentation is preserved. This is close, but doesn't meet the requirements, which I copied below.
  • The function has 1 input argument named aSum:the current accumulative sum to be "updated" inside this function(Hint:use pass by reference)
  • The function asks user for a float input,then updates the accumulative sum

The name of the parameter should be aSum, not aSumAddr.
The function should ask for input of a (float) number, not hard-code it to the value 0.01. Also, I would advise using a different name for the variable. The name Total is misleading, as it's not being used for the cumulative sum. That's the role of aSum.

I think that multiple answers are possible.
I have modified the part you say.Thanks!
I want to ask another question.
I am doing a lab regarding 'guess number game'
Actually,the answer should be the random number,but I set the exact number to 88,because it is easy for me to test other requirement.
I need to printf("Best Score so far [X]")
I want to ask how to set the number of guess of previous game?
Code:
#include <stdio.h>
int main()

{
	int GusNum,TotalNum,BesSor,a;
	char again;
	
	do
	{   TotalNum=0;
	do
	{	 
	    printf("Guess what the lucky number is <between 1 and 100>,then <Enter>:");
		scanf("%d",&GusNum);
	
		
		if(GusNum>=89&&GusNum<=100)
		printf("The number you typed is [%d] -Too LARGE,guess the lucky number again!\n\n",GusNum);
		else if (GusNum<=87&&GusNum>=1)
		printf("The number you typed is [%d] -Too SMALL,guess the lucky number again!\n\n",GusNum);	
		else if(GusNum==88)
		printf("OK This is your LUCKY NUMBER [88] Well Done!\n");	
		else 
		printf("OUT OF THE RANGE \n");
        
	    TotalNum++;

    }while(GusNum!=88);
        
       if(GusNum==88)
       {
        printf("Number of attempt [%d]\n\n",TotalNum);
        /*
       	if(a>TotalNum)
       	{
       		printf("Best score so far [%d]\n",TotalNum);
       		
       	}else printf("Best score so far [%d]\n",a);
        the wrong part i want to set the best socre*/
       
       printf("Play again Type 'y' for YES; all other characters for NO:");
       scanf(" %c", &again);

       }
    }while(again=='y');
 
  • #15
While it's okay to use a known, fixed value for testing, you should not have that 88 hard coded all over the place like that. (Six different places in your code!) You should be using a variable with a known, fixed value instead. Then, when you are satisfied that it works, switching to a random variable will be a piece of cake.
 
Back
Top