Pass by reference

This is a discussion on Pass by reference within the C Programming forums, part of the General Programming Boards category; Hi, I'm having a problem using pass by reference to pass arrays and floats through functions. This is my assignment: ...

  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    19

    Pass by reference

    Hi, I'm having a problem using pass by reference to pass arrays and floats through functions. This is my assignment:
    http://www.comp.dit.ie/mcollins/ft22...signment2.html

    The code I've got so far (which is pass by value as its all i can do):

    Code:
    #include <stdio.h>
    #define SIZE 5
    
    main()
    {
        int i;
        float temps[SIZE];
    
        printf("\nPlease enter %d float numbers: \n\n", SIZE);
        
        read(temps);
        display(temps);
        
    }            
    
    read(float temps[])
    {
        int i;
        
        for (i = 0; i < SIZE; i++)
        {
            scanf("%f", &temps[i]);
        }
    }
    
    display(float temps[])
    {
        int i;
        
        for (i = 0; i < SIZE; i++)
        {
            printf("%f ", temps[i]);
        }
    }
    How do I change this to pass by reference?

    Many thanks in advance.

  2. #2
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    well your assignment says
    You must use pointer notation to access array elements - NOT subscripts
    here is some reading on pointersand arrays
    http://www.cprogramming.com/tutorial/lesson6.html
    http://www.cprogramming.com/tutorial/lesson8.html
    When no one helps you out. Call google();

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >How do I change this to pass by reference?
    C only supports pass-by-value. However, you can fake it with pointers:
    Code:
    #include <stdio.h>
    
    /* Pass by value */
    void f0(int x)
    {
      ++x;
    }
    
    /* Pass a pointer by value, simulate pass-by-reference */
    void f1(int *x)
    {
      ++*x;
    }
    
    int main(void)
    {
      int a = 0;
      int b = 0;
    
      f0(a);
      f1(&b);
      printf("a = %d\n", a);
      printf("b = %d\n", b);
    
      return 0;
    }
    The interesting thing is that arrays are passed as a pointer to the first element by default. These two function declarations are equivalent:
    Code:
    void f0(int array[]);
    void f1(int *array);
    So technically, you are already passing by "reference"[1].

    [1] The quotes are important.
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Nov 2004
    Posts
    19
    Thanks a lot for the replies. I've written the code but there are a couple of bits I'm finding it hard to do. Here's the code:

    Code:
    #include <stdio.h>
    #define SIZE 5
    
    void read (float *, float);
    void display (float *, float);
    void sort (float *, float);
    void conv_far (float *, float);
    void conv_cel (float *, float);
    
    main ()
    {
        float values[SIZE];    //declaring variables and initalizing them
        int i;
        int option = 0;
    
        while (option != 6) //loop
        {   //start loop
            printf("Please select an option from the list below:\n"); 
            printf("1. Enter values\n");
            printf("2. Display values\n");            //displays menu
            printf("3. Sort temperatures in increasing order\n");
            printf("4. Convert temperatures to Fahrenheit\n");
            printf("5. Convert temperatures to Celsius\n");
            printf("6. Exit Program\n");
            
            scanf("%d", &option);                    //allows user to choose option
            fflush (stdin);
            
            switch (option)                //switch statement, chooses option selected by user and performs task
            { // start switch
                    case 1:
                    {
                        read (values, SIZE);
                        fflush (stdin);
                        break;
                    }
                    
                    case 2:
                    {
                        display (values, SIZE);
                        break;
                    }    
                    
                    case 3:
                    {
                        sort (values, SIZE);
                        break;
                    }
                    
                    case 4:
                    {
                        conv_far (values, SIZE);
                        break;
                    }
                    
                    case 5:
                    {
                        conv_cel (values, SIZE);
                        break;
                    }
                    
                    case 6:
                    {
                        printf ("program ended\n");
                        break;
                    }
                    
                    default:
                    {
                        printf ("\nerror! Please enter a number between 1-6\n\n");
                    }
            } //end switch
    
        } //end loop
    
    }
    
    void read (float *array, float no_of_els) // function for case 1
    {
       int i = 0;
    
       for (i = 0; i < no_of_els; i++)
       {
           printf ("enter temperature %d: ",i+1);
           scanf  ("%f", &(*(array+i)));
       }
       printf("\n");
    
    }
    
    void display (float *array, float no_of_els)  // case 2
    {
        int i = 0;
    
         for (i = 0; i < no_of_els; i++)
         {
             printf ("temperature %d is %4.2f\n",i+1,*(array+i));
         }
         printf("\n");
    }
    
    void sort (float *array, float no_of_els) // case 3
    {
        int i, item, temp;
        
        for (item = 0; item < no_of_els - 1; item++)
        {
            for (i = item + 1; i < no_of_els; i++)
            {
                if (*(array+i) < *(array+item))
                {
                    temp              = *(array+item);
                    *(array+item) = *(array+i);
                    *(array+i)    = temp;
                }
            }
        }
       
       for (i = 0; i < SIZE; i++)
       {
           printf ("%4.2f\n", *(array+i) );
       }
       printf("\n");   
    }
    
    void conv_far (float *array, float no_of_els) // case 4
    {
        int i = 0;
        float celcius = 0;
        float fahrenheit = 0;
        
        for (i = 0; i < no_of_els; i++)
        {
            celcius = celcius + *(array+i);
            fahrenheit = fahrenheit +  (((celcius/5) * 9) + 32);
            printf ("temperature %d is %4.2f\n", i+1, fahrenheit);
            fahrenheit = 0;
            celcius = 0;
        }
        printf("\n");
    }
    
    void conv_cel (float *array, float no_of_els) // case 5
    {
        int i = 0;
        float celcius = 0;
        float fahrenheit = 0;
        
        for (i = 0; i < no_of_els; i++)
        {
            fahrenheit = fahrenheit + *(array+i);
            celcius = celcius +  (((fahrenheit-32) / 9) * 5);
            printf ("temperature %d is %4.2f\n", i+1, celcius);
            fahrenheit = 0;
            celcius = 0;
        }
        printf("\n");
    }
    The bits I'm finding it hard to do are:

    5. Provide an option to allow a user to convert the temperatures back to Celsius (only if the temperatures have already been converted to Fahrenheit). NB: You must find a way that will prevent the user selecting this option if the temperatures are already in Celsius.

    and

    The user should only be allowed to select option 4 (convert to Fahrenheit) if the contents of the 1-D array are in Celsius. Appropriate error messages should handle any potential problem. The same should happen if the user selects option 5 (convert to Celsius) i.e. this should only be allowed if the contents of the 1-D array are in Fahrenheit.

    thanks again.

  5. #5
    Registered User
    Join Date
    Nov 2004
    Posts
    19
    and just a quick question. When writing the pseudo code what should I do for the new functions?

    Cheers.

  6. #6
    Registered User
    Join Date
    Nov 2004
    Posts
    19
    Does anyone have any idea? BTW is this what the pseudo code should look like?:

    Code:
    BEGIN MAIN
       
       WHILE (option != 5) 
          DISPLAY Menu
          INPUT Option
          
          SWITCH country
            
    	CASE 1
    	  FUNCTION Read
    	BREAK
    	
    	CASE 2
    	  FUNCTION Display
    	BREAK
    	
    	CASE 3
    	  FUNCTION sort
    	BREAK
    
    	CASE 4
    	  FUNCTION Farenheit
    	BREAK
    
    	CASE 5
    	  FUNCTION Celsius
    	BREAK
    	
    	CASE 6
    	  EXIT PROGRAM
    	BREAK
       
       END WHILE
    
    END MAIN
    
    START Read
      
       FOR

  7. #7
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    You just need a flag in main() to tell you whether the temperatures are currently in Celsius or Fahrenheit.
    Code:
    int celsius_mode;
    If when you enter the temperatures, they are in Celsius, when you return from the read() function, set this to true(1):
    Code:
    celsius_mode = 1;
    Whenever you convert to Fahenheit, set this to false(0).
    Code:
    celsius_mode = 0;
    Now you know which mode you are in at any time, so if you need to check whether you're already in Celsius, you can do:
    Code:
    if (celsius_mode)
    or
    if (celsius_mode == 1)
    Or conversely, to check whether you're in Fahrenheit:
    Code:
    if (!celsius_mode)
    or
    if (celsius_mode == 0)

  8. #8
    Registered User
    Join Date
    Nov 2004
    Posts
    19
    thanks a lot, thats a great help.

  9. #9
    Registered User
    Join Date
    Nov 2004
    Posts
    19
    I've noticed that when I convert the temperatures to Fahrenheit and then try to convert back to Celsius, all its doing is using the Celsius formula ((Celsius = ( ( (Fahrenheit - 32) / 9) * 5 )) on the original Celsius values. How do I get it to convert the Farenheit values back to Celsius?

    Thanks.

  10. #10
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >How do I get it to convert the Farenheit values back to Celsius?
    Well, for example take conv_far():
    > celcius = celcius + *(array+i);
    > fahrenheit = fahrenheit + (((celcius/5) * 9) + 32);

    Here you convert to fahrenheit, but never store the value back into the array. So you would add this:
    Code:
    *(array+i) = fahrenheit;
    Or you could do the whole conversion in one statement vs three by:
    *(array+i) = *(array+i) / 5. * 9. + 32.

    Also, it makes more sense to write what you have as:
    Code:
            celcius = *(array+i);
            fahrenheit = (((celcius/5) * 9) + 32);
            *(array+i) = fahrenheit;
    As, there's no need for the addition in there, or initalizing celcius and fahrenheit to 0.

    Now you also need to do the same for your conv_cel() function.

  11. #11
    Registered User
    Join Date
    Nov 2004
    Posts
    19
    You're a star snoopy.

  12. #12
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,854
    > fflush (stdin);
    Read the FAQ
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pass by reference
    By jrice528 in forum C++ Programming
    Replies: 4
    Last Post: 10-30-2007, 02:02 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 03:39 PM
  3. C OpenGL Compiler Error?
    By Matt3000 in forum C Programming
    Replies: 12
    Last Post: 07-07-2006, 05:42 PM
  4. how can i pass by reference by "malloc 2d array"?
    By Mathsniper in forum C Programming
    Replies: 10
    Last Post: 05-22-2005, 03:23 PM
  5. Ask about function parameters and pass a reference.
    By ooosawaddee3 in forum C++ Programming
    Replies: 1
    Last Post: 11-04-2002, 12:14 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21