1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[C] Lab question. (Pass by reference)

  1. Oct 30, 2013 #1
    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!
     
  2. jcsd
  3. Oct 30, 2013 #2

    Borek

    User Avatar

    Staff: Mentor

    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?
     
  4. Oct 30, 2013 #3

    Mark44

    Staff: Mentor

    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.
     
  5. Oct 30, 2013 #4
    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);
    }
     
  6. Oct 30, 2013 #5

    Mark44

    Staff: Mentor

    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.
     
  7. Oct 30, 2013 #6

    rcgldr

    User Avatar
    Homework Helper

    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.
     
  8. Oct 31, 2013 #7

    Mark44

    Staff: Mentor

    That's what I was hinting at, but I wanted the OP to come up with it on his own...
     
  9. Oct 31, 2013 #8

    Borek

    User Avatar

    Staff: Mentor

    Somehow I doubt static variables are something that OP is aware of at this stage.
     
  10. Oct 31, 2013 #9

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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.


    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!
     
  11. Oct 31, 2013 #10

    Mark44

    Staff: Mentor

    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.
     
  12. Oct 31, 2013 #11
    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.
     
  13. Oct 31, 2013 #12

    Mark44

    Staff: Mentor

    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.
     
  14. Oct 31, 2013 #13

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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.


    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.
     
  15. Nov 3, 2013 #14
    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 (Text):
    #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');
     
  16. Nov 3, 2013 #15

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: [C] Lab question. (Pass by reference)
  1. C/C++ hw question! (Replies: 3)

Loading...