Function confusion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sheepman
    New Member
    • Jun 2007
    • 24

    Function confusion

    I write most of my programs using only void function. They end up long and bloated because I often write the same code over and over again in each void function. I'm even confused by void functions though. The book says void functions don't return data but I make them do it. I'm using a void function to send data to a file and the screen. I use a void function to create the random number array. Then the other void functions use the random array, like sort it low to high. So I know they return data. In this program I created a 10 x 10 display twice and wrote to sceen and file twice. If I'm doing the same thing twice I know you can send the data i.e. print to file twice ,once sorted, once unsorted. Whenever I try and do function calls I end up a huge amount of errors. Also I'm creating the 10 x 10 display twice. Can't I somehow send the unsorted and sorted data to the same fuction to be formated and that be returned for display. Below are the functions without the statements. In main I have commented on what each function call does.

    Code:
    //Function Prototypes
     
    void randNum(int[]);
    void bubbleSort(int[]);
    void show(int []);
    void tenByTen(int []);
     
    //Called Functions
     
    void randFunc(int firstArray[])
    {
    Statement
    }
    void bubbleSort(int firstArray[])
    {
    Statement
    }
    void tenByTen(int firstArray[])
    {
    Statement 
    }
     
    int main()
    {
    srand((unsigned)time(0));//Seed random number generator
    int firstArray[100];//initialize array
     
    randFunc(firstArray);//call random number genertor function, fill array, print unsorted data to screen and file in 10 x 10 format
     
     
    bubbleSort(firstArray);//Bubble sort array, lowest to highest
    tenByTen (firstArray);// Format sorted numbers in 10 x 10 display, print to screen and append to same file
    cout << endl;
    return 0;
    }
    No one in my class asks any questions, but when I ask them whats going on they say they can't explain it only do it! They just keep compiling it and correcting the errors until it works, crazy!
  • scruggsy
    New Member
    • Mar 2007
    • 147

    #2
    I'm a little confused myself, now. ;)
    Originally posted by Sheepman
    I write most of my programs using only void function. They end up long and bloated because I often write the same code over and over again in each void function.
    That's usually a hint that you should create a separate function to handle that repeated code.
    I'm even confused by void functions though. The book says void functions don't return data but I make them do it. I'm using a void function to send data to a file and the screen. I use a void function to create the random number array. Then the other void functions use the random array, like sort it low to high. So I know they return data.
    No, they don't return data. They operate on the array you sent as an argument to the function. Which is fine - judging by your code, that's exactly what you want. But they don't return anything.
    In this program I created a 10 x 10 display twice and wrote to sceen and file twice. If I'm doing the same thing twice I know you can send the data i.e. print to file twice ,once sorted, once unsorted. Whenever I try and do function calls I end up a huge amount of errors.
    Post the text of the errors.
    Below are the functions without the statements. In main I have commented on what each function call does.
    Why don't you post the full code?

    Comment

    • Sheepman
      New Member
      • Jun 2007
      • 24

      #3
      Originally posted by scruggsy
      I'm a little confused myself, now. ;)


      Why don't you post the full code?
      The forum posting rules said not to, is that incorrect? That's why I've been asking questions using only pieces of it? It would make it easier for me!

      Comment

      • scruggsy
        New Member
        • Mar 2007
        • 147

        #4
        Originally posted by Sheepman
        The forum posting rules said not to, is that incorrect? That's why I've been asking questions using only pieces of it? It would make it easier for me!
        Oh, good point. :heh:
        You can PM it to me if you'd like.

        Comment

        • phiefer3
          New Member
          • Jun 2007
          • 67

          #5
          Originally posted by Sheepman
          The forum posting rules said not to, is that incorrect? That's why I've been asking questions using only pieces of it? It would make it easier for me!
          I believe you are supposed to post your code when asking questions. But people aren't supposed to post full code answers. Meaning you can't ask how to do this and have someone give you all of the code to use. They can point out the errors in your code and and correct your code.

          How to ask a question
          Please follow these guidelines when posting questions as submitting clear and concise questions allows those reading to understand your problem and respond more easily.

          * Post your question in a relevant forum
          * Make sure you are not posting in an Articles section
          * Give the relevant Platform, OS and Version information
          o In the C/C++ forum this might be Intel/Windows/MSVC++ 6.0 or StrongArm/ThreadX/Greenhills C/C++
          o In Access it might just be the version of Access you are using 97, 2003 etc.
          * Give as much detail as possible When you post a question or problem, express the situation clearly and concisely and include all relevant information, code used, data used, result expected, result achieved and any error codes or messages that you get as a result.
          * Use Clear English to write your question in if possible, try to avoid using abbreviations
          * Do not use leet speak or text speak, they are not Clear English
          * Make use of the available formatting tags in the forum Use CODE tags around your code as appropriate:
          This will preserve white space and use a mono-spaced font making the code easier to read.
          * Do not ask people to reply by email or follow up answers with a PM
          * Please don't say that a problem is urgent if it's not. If your problem is time sensitive, please give specific time frames e.g. In 3 days, within 24 hours.
          * Please try to read your own post after you've posted it. If you can't make any sense of it, it's a fair bet that our experts will struggle and waste time just trying to understand what you're trying to say. Also, if you get bored when you're half-way through reading it because it rambles on endlessly, how will our experts fare?
          * If you wish to post a question do not post it in a discussion created by someone else unless it is about exactly the same problem. Please start a new discussion.

          Comment

          • ilikepython
            Recognized Expert Contributor
            • Feb 2007
            • 844

            #6
            Originally posted by Sheepman
            I write most of my programs using only void function. They end up long and bloated because I often write the same code over and over again in each void function. I'm even confused by void functions though. The book says void functions don't return data but I make them do it. I'm using a void function to send data to a file and the screen. I use a void function to create the random number array. Then the other void functions use the random array, like sort it low to high. So I know they return data. In this program I created a 10 x 10 display twice and wrote to sceen and file twice. If I'm doing the same thing twice I know you can send the data i.e. print to file twice ,once sorted, once unsorted. Whenever I try and do function calls I end up a huge amount of errors. Also I'm creating the 10 x 10 display twice. Can't I somehow send the unsorted and sorted data to the same fuction to be formated and that be returned for display. Below are the functions without the statements. In main I have commented on what each function call does.

            Code:
            //Function Prototypes
             
            void randNum(int[]);
            void bubbleSort(int[]);
            void show(int []);
            void tenByTen(int []);
             
            //Called Functions
             
            void randFunc(int firstArray[])
            {
            Statement
            }
            void bubbleSort(int firstArray[])
            {
            Statement
            }
            void tenByTen(int firstArray[])
            {
            Statement 
            }
             
            int main()
            {
            srand((unsigned)time(0));//Seed random number generator
            int firstArray[100];//initialize array
             
            randFunc(firstArray);//call random number genertor function, fill array, print unsorted data to screen and file in 10 x 10 format
             
             
            bubbleSort(firstArray);//Bubble sort array, lowest to highest
            tenByTen (firstArray);// Format sorted numbers in 10 x 10 display, print to screen and append to same file
            cout << endl;
            return 0;
            }
            No one in my class asks any questions, but when I ask them whats going on they say they can't explain it only do it! They just keep compiling it and correcting the errors until it works, crazy!
            A void function has no return value. Even though you are changing arrays in your function you are not returning a variable to the caller (using the return keyword). For example, if you want to create a function that doubles a certain variable, it would be simpler to return the doubled variable.:
            [code=cpp]
            int Double(int x)
            {
            return x * 2 //returns x * 2 to the caller
            }
            // ...code
            int x = 9;
            int doublex = Double(x); // return value gets stored in doublex
            [/code]
            If you use void, you would have to pass by reference which is unneccesary in this case.

            Comment

            • Sheepman
              New Member
              • Jun 2007
              • 24

              #7
              Here's the whole thing. Everything is working except the second write to file. I get the sorted data on the screen but the text file isn't appended with the sorted data. It only contains the unsorted data. The error is located in the function tenByTen just above main

              [code=cpp]
              #include <iostream>
              #include <fstream>
              #include <iomanip>
              #include <cstdlib>
              #include <ctime>
              using namespace std;
              void randNum(int[]);
              void bubbleSort(int[]);
              void show(int []);
              void tenByTen(int []);
              void randFunc(int firstArray[])
              {
              int min = -50;
              int max = 50;
              int randNum;
              for (randNum = 0; randNum < 100; randNum++)
              {
              firstArray[randNum] = rand()%(max - min + 1) + min;
              cout << setw (5) << firstArray[randNum] ;
              //cout << endl;
              }//Close for
              char yourFileName [80];
              int d1, d2;
              //Prompt user for file name to store array
              cout << "Enter name of file to store your randomly generated numbers: " << endl;
              cin >> yourFileName;
              ofstream outfile (yourFileName, ios::out);//create and open file
              if (!yourFileName)//errorcheck
              {
              cout << "Error opening your file " << endl;
              }//close error check
              //fomat array output to 10 x 10

              for (d1 = 0; d1 <= 9; d1++)
              {
              for (d2 = 0; d2 <= 9; d2++)
              {
              cout << setw(5) << firstArray[(d1 * 10) + d2];//write to screen
              outfile << setw(4) << firstArray[(d1 * 10) + d2];//write to file
              }//close nested for
              cout << endl;
              outfile << endl;
              }//close for
              cout << endl;
              cout << endl;
              outfile.close() ;
              }//close tenBy

              void bubbleSort(int firstArray[])
              {

              for (int pass = 1; pass < 100; pass++)
              {
              for (int randNum = 0; randNum < 100 - pass; randNum++)
              {
              if (firstArray[randNum] > firstArray[randNum + 1])
              {
              int swap = firstArray[randNum];
              firstArray[randNum] = firstArray[randNum + 1];
              firstArray[randNum + 1] = swap;

              }//close if
              }
              }
              }

              void tenByTen(int firstArray[])
              {
              char yourFileName [80];
              int d1, d2;
              //Prompt user for file name to store array
              //cout << "Enter name of file to store your randomly generated numbers: " << endl;
              //cin >> yourFileName;
              ofstream outfile;//create and open file
              outfile.open("y ourFileName", ios::app);
              if (!yourFileName)//errorcheck
              {
              cout << "Error opening your file " << endl;
              }//close error check
              //fomat array output to 10 x 10

              for (d1 = 0; d1 <= 9; d1++)
              {
              for (d2 = 0; d2 <= 9; d2++)
              {
              cout << setw(5) << firstArray[(d1 * 10) + d2];//write to screen
              outfile << setw(4) << firstArray[(d1 * 10) + d2];//write to file
              }//close nested for
              cout << endl;
              outfile << endl;
              }//close for
              outfile.close() ;
              }//close tenBy

              int main()
              {
              srand((unsigned )time(0));//Seed random number generator
              int firstArray[100];//initialize array

              randFunc(firstA rray);//call random number genertor function, fill array
              bubbleSort(firs tArray);//Bubble sort array, lowest to highest
              tenByTen (firstArray);// Format display in 10 x 10
              cout << endl;
              return 0;
              }
              [/code]

              My orginal idea was to create a random generating function, supply the output to a function that created a 10 x 10 output. Have that sent to a sort and print function. Then have the sorted data sent to the same print function. Couldn't even get close with that setup.

              Comment

              • phiefer3
                New Member
                • Jun 2007
                • 67

                #8
                well, for one thing in your tenByTen function you never define the yourFileName array. So it's probably writing the sorted list to a file with a name composed of the garbage data that the array contains.

                Comment

                • JosAH
                  Recognized Expert MVP
                  • Mar 2007
                  • 11453

                  #9
                  Originally posted by Sheepman
                  I write most of my programs using only void function. They end up long and bloated because I often write the same code over and over again in each void function.
                  One of my kazillion rules of thumb says this:

                  "Never write a function you can't explain in one clear sentence"

                  In other words: a function should do one single thing and it should do it well.
                  It may be necessary to return a value from a function; otherwise if you want
                  Basic, you know where to find it.

                  Repeat the rule above until you end up with a bunch of functions that do the job.

                  kind regards,

                  Jos

                  Comment

                  • Sheepman
                    New Member
                    • Jun 2007
                    • 24

                    #10
                    Originally posted by phiefer3
                    well, for one thing in your tenByTen function you never define the yourFileName array. So it's probably writing the sorted list to a file with a name composed of the garbage data that the array contains.
                    I thought that's what the
                    [code=cpp]
                    char yourFileName [80];
                    [/code]
                    was doing. The more I think I'm figuring it out...the more I'm realize how much I don't know. Isn't it also defined in main? Should I do it globally so everything sees it.? I tried changing the functions to do just specific things and send it to the other functions. Now it doesn't compile anymore, currently trying to back to the way it was. I'm just gonna figure out how to define it in tenByTen and leave it alone.

                    Does anyone know of a really good tutorial that explains how functions operate, where the data goes when called and returning data for these types types of functions
                    1. void with no parameters
                    2. void with parametes
                    3. type with no parameters
                    4. type with parameters

                    the bottom line is I have to figure this out to do the other stuff. This is currently a huge stumpling block for me!
                    Last edited by Sheepman; Jul 12 '07, 12:34 AM. Reason: typo

                    Comment

                    • phiefer3
                      New Member
                      • Jun 2007
                      • 67

                      #11
                      Originally posted by Sheepman
                      I thought that's what the
                      [code=cpp]
                      char yourFileName [80];
                      [/code]
                      was doing. The more I think I'm figuring it out...the more I'm realize how much I don't know. Isn't it also defined in main? Should I do it globally so everything sees it.? I tried changing the functions to do just specific things and send it to the other functions. Now it doesn't compile anymore, currently trying to back to the way it was. I'm just gonna figure out how to define it in tenByTen and leave it alone.

                      Does anyone know of a really good tutorial that explains how functions operate, where the data goes when called and returning data for these types types of functions
                      1. void with no parameters
                      2. void with parametes
                      3. type with no parameters
                      4. type with parameters

                      the bottom line is I have to figure this out to do the other stuff. This is currently a huge stumpling block for me!
                      That line doesn't DEFINE the array, it only DECLARES the array. In order to DEFINE it you must store a value in it, in other words you must set it equal to something.

                      It doesn't matter that you declared and defined it in main, that yourFileName array is local to main, and doesn't exist in any of the functions.

                      I would suggest making that array global, that way it can be used by all of your functions. To do that, you put its declaration (char yourFileName [80];) outside of main, up with your function prototypes. Then you do NOT declare it anywhere else.

                      Also, you didn't define it in main, you defined it in the randFunc function. simply remove the declaration line from both/all functions and put it with the prototypes (outside of all functions) and then the input statement in randFunc will store the file name in it, which will be usable in all functions.

                      Also, I noticed that in your tenByTen function, that your open file statement doesn't even use the yourFileName array, you put quotes around it, so your sorted array is probably being stored in a file named yourFileName.

                      Here I edited your code to use a global array, and I formated it a bit:

                      [CODE=cpp]#include <iostream>
                      #include <fstream>
                      #include <iomanip>
                      #include <cstdlib>
                      #include <ctime>

                      using namespace std;

                      void randNum(int[]);
                      void bubbleSort(int[]);
                      void show(int []);
                      void tenByTen(int []);

                      char yourFileName [80];//makes a global array

                      void randFunc(int firstArray[])
                      {
                      int min = -50;
                      int max = 50;
                      int randNum;

                      for (randNum = 0; randNum < 100; randNum++)
                      {
                      firstArray[randNum] = rand()%(max - min + 1) + min;
                      cout << setw (5) << firstArray[randNum] ;
                      //cout << endl;
                      }//Close for

                      int d1, d2;

                      //removed array declaration

                      //Prompt user for file name to store array
                      cout << "Enter name of file to store your randomly generated numbers: " << endl;
                      cin >> yourFileName;
                      ofstream outfile (yourFileName, ios::out);//create and open file

                      if (!yourFileName)//errorcheck
                      {
                      cout << "Error opening your file " << endl;
                      }//close error check

                      //fomat array output to 10 x 10
                      for (d1 = 0; d1 <= 9; d1++)
                      {
                      for (d2 = 0; d2 <= 9; d2++)
                      {
                      cout << setw(5) << firstArray[(d1 * 10) + d2];//write to screen
                      outfile << setw(4) << firstArray[(d1 * 10) + d2];//write to file
                      }//close nested for

                      cout << endl;
                      outfile << endl;
                      }//close for

                      cout << endl;
                      cout << endl;
                      outfile.close() ;
                      }//close randFunc

                      void bubbleSort(int firstArray[])
                      {
                      for (int pass = 1; pass < 100; pass++)
                      {
                      for (int randNum = 0; randNum < 100 - pass; randNum++)
                      {
                      if (firstArray[randNum] > firstArray[randNum + 1])
                      {
                      int swap = firstArray[randNum];
                      firstArray[randNum] = firstArray[randNum + 1];
                      firstArray[randNum + 1] = swap;
                      }//close if
                      }
                      }
                      }//close bubbleSort

                      void tenByTen(int firstArray[])
                      {
                      //removed the declaration of the array

                      int d1, d2;

                      ofstream outfile;//create and open file

                      //outfile.open("y ourFileName", ios::app);what’ s up with the quotes????
                      outfile.open(yo urFileName, ios::app);//this is what I think you meant


                      if (!yourFileName)//errorcheck
                      {
                      cout << "Error opening your file " << endl;
                      }//close error check

                      //fomat array output to 10 x 10
                      for (d1 = 0; d1 <= 9; d1++)
                      {
                      for (d2 = 0; d2 <= 9; d2++)
                      {
                      cout << setw(5) << firstArray[(d1 * 10) + d2];//write to screen
                      outfile << setw(4) << firstArray[(d1 * 10) + d2];//write to file
                      }//close nested for

                      cout << endl;
                      outfile << endl;
                      }//close for

                      outfile.close() ;
                      }//close tenByTen

                      int main()
                      {
                      srand((unsigned )time(0));//Seed random number generator
                      int firstArray[100];//initialize array

                      randFunc(firstA rray);//call random number genertor function, fill array
                      bubbleSort(firs tArray);//Bubble sort array, lowest to highest
                      tenByTen (firstArray);// Format display in 10 x 10
                      cout << endl;
                      return 0;
                      }[/CODE]

                      Comment

                      Working...