Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C question

  1. Nov 18, 2004 #1
    Ok I am working on making a gambling program, that plays craps. Anyways, I have a question dealing with the basic structure of C. I thought that if you where going to return values, the function had to be something other than void. Well i'm looking through some of my professor past class activites, and he has values being returned but under void: See example



    Code (Text):
    void  get_d_array( double array[], int *pnumgot )
    /*
        purpose: get series of type double numbers from user
        goal state: return series of numbers in array[]
                    ruturn number of values entered in *pnumgot
    */
    { // begin get_d_array
      // variable declaration
        int  i;   // loop index

      // ask user for number of lengths
        printf( "\nHow many values do you have to enter? ");
        printf( "\nNumber of values must be less than %d", MAXSIZE );
        printf( "\n    Number of values ==> " );
        scanf( "%d", pnumgot );

      // get values
        for( i = 0; i < *pnumgot; i = i+1 )
        { // begin for
            array[i] = 2.0*i+5;
        } // end for

    } // end get_d_array
    So.... I mean values are being returned are they not? Yet this is under a void deceleration. Plus I thought that only one value can be returned.
     
    Last edited: Nov 18, 2004
  2. jcsd
  3. Nov 18, 2004 #2

    NateTG

    User Avatar
    Science Advisor
    Homework Helper

    The function get_d_array is not returning anything. The return value of a function is the value that you get when you do something like:

    foo=bar(biz);

    Passing by reference is something different that a return value.
     
  4. Nov 18, 2004 #3
    It depends on what you mean by returned.

    Normally that term refers to the single value passed by the return statement.

    If you want to 'return' more than one value you do it the way your professor did. Instead of passing values TO the function by value, you pass them by reference.

    That is what the * in front of pnumgot means. pnumgot is a pointer to a value, so if the function changes the data referenced by the pointer, the changed data is available to the calling routine when the function returns.

    As the pointer can be indexed past any arbitary number of individual values, this allows a function to return an arbitary number of results.

    When a value is passed to a function in the normal way, the function gets a fresh copy of the value, and even if it changes that value, the change is not available to the calling routine. But when you pass a value by reference, any changes made by the function are available to the caller.

    The array is passed by reference too, as in C:

    double array[]

    means exactly the same as

    double *array

    which also means the same as

    double* array
     
    Last edited: Nov 18, 2004
  5. Nov 18, 2004 #4
    Ahhh I see....So it's just passing reference. So for instance if i perfermed a calculation liek 2+2 and have sum = 2+2 then sume would be returned. Sum would alos fall into the catagory of not being declared also, correct?
     
  6. Nov 19, 2004 #5
    you have to specify what you want to return like this:

    Code (Text):
    int sum(int a, int b)
    {
      int answer;

      answer = a + b;

      return answer;
    }
    another function could use sum like this:
    Code (Text):
    void main()
    {
      int s;

      s = sum(2, 3);
    }
    the way to do the same without "returning" values but by passing values "by reference", would be like this:
    Code (Text):
    // the * means that v is a pointer
    // a pointer is a variable that contains the address of another variable
    void sum(int a, int b, int *v)
    {
      int answer;

      answer =  a + b;

      // write answer at the location in memory that  v "points to" :
      *v = answer;
    }
    another function could use sum like this:
    Code (Text):
    void main()
    {
      int s;
     
      // you pass a pointer that tells sum where in memory s is
      // (&s means: the address of s):
      sum(2, 3, &s);
    }
     
  7. Nov 19, 2004 #6
    AH Ok yeah i was talking to my CS(com Sci) friend and he explained it all to me, but your explination further clairfies it. Also... for instance what your returing, can it be called by another function. EX:

    Sum = 2+2

    and i have a display function and I want it to display sum down in it. do i just have it in the main parameters of the function?
     
  8. Nov 19, 2004 #7
    I do not know what you mean exactly. You can call a function and a function can return a value. You do not call a return value. When you want a function to have some value you pass it to the function via the function's arguments.

    if you want to pass the sum of 2 and 2 to another function you simply do:

    Code (Text):
    // this calls the function called sum
    //and assign the value that sum returns to a:
    a = sum(2, 2);

    // this passes the value of a to the function called other_function
    // via other_function's first argument:
    other_function(a, some_other_argument, and_a_third_perhaps);

    You can call the sum function from anywhere you want and assign the value it returns to a local variable.

    Code (Text):
    display_function(argument1, argument2)
    {
       int x;

       x = sum(34, 56);
       etc.
    }
     
  9. Nov 22, 2004 #8
    Well when i said call I mean like, if i have sum = 2+2 in one function. and then Sum needs to be displayed in the next function, then can i just have sum defined up in the parameters.
     
  10. Nov 25, 2004 #9
    if you have a variable sum in one function like this:

    Code (Text):
    void functionA(int a, int b)
    {
       int sum;

       sum =  2 + 2;
       
       etc.
    }
    then the variable sum is only available within that function (it is only known between the { and }).

    so if you need it in another function you will have to pass the value of the variable sum to the other function. Let's say that the other function, that needs sum, is called Display. Then you would pass the value of sum to Display like this:

    Code (Text):
    void functionA(int a, int b)
    {
       int sum;

       sum =  2 + 2;
       
       Display(sum);

       etc.
    }
     
  11. Nov 29, 2004 #10
    Ok i keep getting this error when I try to build my program:

    C:\Documents and Settings\jcs51.UPITT-USERS\Desktop\jcs51.cpp(128) : error C2061: syntax error : identifier 'total'


    and it bring me to this line

    Code (Text):
    if total = 2 && total = 3
        {
            game_state = 1;
            point = 0;
        }
        else if ptotal = 7 && ptotal = 11
        {
            game_state = 2;
            point = 0;

    This I assume total is getting the approate value that it needs and there a problem witht he passing of it from my first function to this one. If anyone has any ideas I'd appericate them greatly.


    this my my main function:

    Code (Text):
    isplayheader();

      // algorithm
        // while loop for new game
        run_again = 'y';
        while (run_again == 'y' || run_again ==  'Y');
        {

            toss_dice(die_1,die_2,&total);
            result_one(total, point);
            display_toss_1(die_1, die_2, total, game_state);

            // while loop for the point comparison
            while (point != 0)
            {
                toss_dice(die_1,die_2, &total);
                result_two(total, point);
                display_toss_2(die_1, die_2,total, game_state, point);
            }
            // ask user to play again
            printf( "\nWould you like to play another round?  (Y or N)"  );
            scanf("%c", run_again);
     
  12. Nov 29, 2004 #11
    these lines
    Code (Text):
    if total = 2 && total = 3  
    ...
    else if ptotal = 7 && ptotal = 11
    should be
    Code (Text):
    if total == 2 && total == 3  
    ...
    else if ptotal == 7 && ptotal == 11
    I also think there is something wrong here:
    Code (Text):
    while (point != 0)
            {  
                toss_dice(die_1,die_2, &total);
                result_two(total, point);
                display_toss_2(die_1, die_2,total, game_state, point);
            }
     
    this loop will never end if point is not already zero when you enter the loop, because no value is assigned to point (i.e the value of point does not change within this while loop)
     
  13. Nov 29, 2004 #12
    hmmm but point gets assigned a value from the previous alagorithm.
     
  14. Nov 29, 2004 #13
    You know that when you write something like

    result_two(total, point);

    then although the result_two() function can do what it wants with its copies of total and point, that's what they are - copies.

    So if the value of total was say 5, then whatever result_two() does, the value will still be 5 when control returns to the line that follows the function call.

    if you want the result_two() function to affect something local to the function call (say total) , you either have to do something like:

    total = result_two(total, point);

    or

    result_two(&total, point);
     
  15. Nov 29, 2004 #14
    Yeah I know, that function is just taking that "total" and evaluating in a if/else statment.. total dosn't need to change at that current point in time.
     
  16. Nov 29, 2004 #15
    Ok ok Ok after some time I got it all pretyt much wokring ok now... I have narrow my problem down to this test.cpp i have created. Idealy what should be displayed by this function is two number between 1 and 6. If you attempt ot run this you get 0 and then some huge ass number.... and no total. Any help would be appericated.
     
  17. Nov 29, 2004 #16
    Ok ok Ok after some time I got it all pretty much have everything working ok. Now... I have narrowed my problem down to this test.cpp, that I have created. Idealy what should be displayed by this function is two numbers between 1 and 6. If you attempt to run this you get 0 and then some huge ass number.... and no total. Any help would be appericated.


    Code (Text):
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>

    #define N 6




    int main() /*
        purpose: generate a series of random numbers for the dice
        goal state: return total of number in ptotal
                    ruturn number of values entered in ptotal
    */
    { // begin toss_dice
      // variable declaration
         int i, j;    // Loop index
         double array_1,
                array_2,
                total;


         srand( (unsigned)time( NULL ) );


        // begin loop for dice 1
       
        for (i = 0; i < 1; i++)
         {
             array_1 = (int)  N * rand() / (RAND_MAX + 1.0);
             
         }
     

        // begin loop for dice 2
        for (j = 0; j < 1; j++)
        {
             array_2 = (int) N * rand() / (RAND_MAX + 1.0);
        }

        // compute total
        total = array_1 + array_2;

       

     // end toss_dice

        printf( "\nYour dice rolls are as follows: %d Dice 1 %d Dice 2.",array_1,array_2);
        printf( "\nThe total is %d",total);
      //  declare win/lose, go again

    return (0);

    }
     
    Last edited: Nov 29, 2004
  18. Nov 30, 2004 #17
    You're using %d in the printf statements, which expects an integer argument, but the values you are passing are doubles.

    You either have to change the %d to %f or cast the the doubles into ints, like this:

    printf( "\nThe total is %d", (int)total);

    By the way, your rand calculation is a little off.
     
  19. Nov 30, 2004 #18
    ahh crap i didn't even look at the format stuff.
     
  20. Nov 30, 2004 #19
    I fixed what you had suggested ceptimus, but i think i have deveopled another problem with this loop, and the way i'm going about this second part of my code:

    Code (Text):
    do
       {
           
          toss_dice(&die_1,&die_2,&total);
          point = total;
          result_one(total, &point, &game_state);
          display_toss_1(die_1, die_2, total, game_state);

          //while loop for the point comparison
          do
          {    
             toss_dice(&die_1,&die_2, &total);
             result_two(total, &point, &game_state);
             display_toss_2(die_1, die_2,total, game_state, point);
       
          } while ( point!= 0);
          // ask user to play again
          printf( "\nWould you like to play another round?  (Y or N)"  );
          scanf("%c", &run_again);
       }   while (run_again == 'y' || run_again ==  'Y');

       return 0;
    After some messing around I changed some things around in here:
    Code (Text):
    //while loop for the point comparison
          point2 = 1;
          do
          {
             toss_dice_2(&die_1,&die_2, &total);
             result_two(total, &point, &point2, &game_state);
             display_toss_2(die_1, die_2,total, point,game_state);
          }while (point2 != 0);
    The whole while point != 0 thing dosn't work. Basicly this a a craps game, and if they user rdosn't win on the first try, the program is to cycle through the code untill a decision has been reached. I comment all of that crap out invovling the second point stuff anf what not, and I got it to work OK with, with running once through. Now i just need to implelement this other stuff. Sooo I'm pretty sure the loop isn't working... but then why am I not gettting new Dice rolls?

    picture of how the program is running http://home.comcast.net/~personalcomp1/Screen.bmp

    I want to say that point2 needs to come out of that resualt_two, but i'm not really sure about how to go about that.
     
  21. Nov 30, 2004 #20
    The do-while loop is ok, it will stop when point2 is zero, so somewhere whithin function result_two() you should assign a value to point2 (like *point2 = 0;).
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: C question
  1. C++ question (Replies: 8)

  2. C question (Replies: 6)

  3. An easy c question (Replies: 7)

Loading...