[C] Lab question. (Pass by reference)

In summary, getNumSum() updates a cumulative total by receiving a float input and adding it to a sum passed as a reference.2)What is the purpose of a static variable in a function?A static variable is used to store a value between calls to the function.
  • #1
ccky
15
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
  • #2
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?
 
  • #3
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.
 
  • #4
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);
}
 
  • #5
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.
 
  • #6
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.
 
  • #7
That's what I was hinting at, but I wanted the OP to come up with it on his own...
 
  • #8
Somehow I doubt static variables are something that OP is aware of at this stage.
 
  • #9
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.
 

Related to [C] Lab question. (Pass by reference)

1. What is pass by reference in the context of a lab question?

Pass by reference is a programming mechanism where the memory address of a variable is passed to a function or subroutine, allowing the function to directly access and modify the value of the variable.

2. How is pass by reference different from pass by value?

In pass by value, a copy of the variable's value is passed to the function, so any changes made to the value within the function are not reflected in the original variable. In pass by reference, the original variable is directly modified.

3. Why is pass by reference commonly used in lab questions?

Pass by reference is often used in lab questions because it allows for more efficient memory usage and can also simplify the code by avoiding the need for multiple return statements.

4. Are there any drawbacks to using pass by reference?

One potential drawback of pass by reference is that it can make the code more prone to unintended side effects, as the original variable is directly modified. Additionally, it may be more difficult to track and debug code that uses pass by reference.

5. How can I ensure that pass by reference is used correctly in my lab question?

To use pass by reference correctly, make sure to properly declare and pass the variables to the function. It is also important to keep track of which variables are being modified within the function and to use proper naming conventions to avoid confusion. Additionally, testing and debugging can help identify any issues with pass by reference in your code.

Similar threads

  • Programming and Computer Science
Replies
4
Views
857
  • Engineering and Comp Sci Homework Help
Replies
1
Views
9K
  • Engineering and Comp Sci Homework Help
Replies
17
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
25
Views
14K
  • Programming and Computer Science
Replies
34
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
14
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
12
Views
2K
Back
Top