Count the frequency of items in an arraySearching an element in a sorted arrayCounting words, letters, average word length, and letter frequencyEncode a string using Caesar's CipherDisplaying a randomly sized array as a tableCodeAbbey #21 Array CountersFill 2D array recursivelyOptimizing a nested for loop over JS array of objectsData structure to count occurrences of wordsCount the number of ways to make a given sum using one number from each arrayMinimum Number of swaps required to group all ones together in array of 0s and 1s

How could Tony Stark wield the Infinity Nano Gauntlet - at all?

Metal that glows when near pieces of itself

"Silverware", "Tableware", and "Dishes"

Story about a demon trying to make a man insane

Gofer work in exchange for Letter of Recommendation

TechSupport Issue ID#812

Why is su world executable?

Moons that can't see each other

Earliest evidence of objects intended for future archaeologists?

How to avoid using System.String with Rfc2898DeriveBytes in C#

What can I do to keep a threaded bolt from falling out of it’s slot

90s(?) book series about two people transported to a parallel medieval world, she joins city watch, he becomes wizard

Why doesn't the Falcon-9 first stage use three legs to land?

Default camera device to show screen instead of physical camera

Is it safe to reuse the password when using AES-CTR with scrypt?

How do slats reduce stall speed?

Why should someone be willing to write a strong recommendation even if that means losing a undergraduate from their lab?

How did Apollo 15's depressurization work?

Homogeneous Equations and Linear Algebra

Can my Boyfriend, who lives in the UK and has a Polish passport, visit me in the USA?

Does git delete empty folders?

Has there ever been a truly bilingual country prior to the contemporary period?

Limits and Continuity in Multi variable calculus.

In xXx, is Xander Cage's 10th vehicle a specific reference to another franchise?



Count the frequency of items in an array


Searching an element in a sorted arrayCounting words, letters, average word length, and letter frequencyEncode a string using Caesar's CipherDisplaying a randomly sized array as a tableCodeAbbey #21 Array CountersFill 2D array recursivelyOptimizing a nested for loop over JS array of objectsData structure to count occurrences of wordsCount the number of ways to make a given sum using one number from each arrayMinimum Number of swaps required to group all ones together in array of 0s and 1s






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6












$begingroup$


The question is:




Write a program that prompts the user to input ten values between 80 and 85 and stores them in an array. Your program must be able to count the frequency of each value appears in the array.




Is there any more efficient ways to present the count for frequency number between 80 to 85? Below is the sample code which had been done in the simplest ways to count the frequency for each number.



The part which needs more efficient ways to present:



 for(int i = 0; i < inputSize; i++) 
if(inputValue[i] == 80)
tempCount80++;
else if(inputValue[i] == 81)
tempCount81++;
else if(inputValue[i] == 82)
tempCount82++;
else if(inputValue[i] == 83)
tempCount83++;
else if(inputValue[i] == 84)
tempCount84++;
else if(inputValue[i] == 85)
tempCount85++;
else
cout << "Error Accurs." << endl;



cout << 80 << " " << tempCount80 << endl;
cout << 81 << " " << tempCount81 << endl;
cout << 82 << " " << tempCount82 << endl;
cout << 83 << " " << tempCount83 << endl;
cout << 84 << " " << tempCount84 << endl;
cout << 85 << " " << tempCount85 << endl;


The original code is: -



#include <iostream>
using namespace std;

int main()
const int inputSize = 10;
int inputValue[inputSize];
int tempCount80 = 0;
int tempCount81 = 0;
int tempCount82 = 0;
int tempCount83 = 0;
int tempCount84 = 0;
int tempCount85 = 0;

for(int i = 0; i < inputSize; i++)
int tempValue = 0;
cout << "Please enter a number between 80 and 85: ";
cin >> tempValue;

if(tempValue > 79 && tempValue < 86)
inputValue[i] = tempValue;
else
cout << "The number must be between 80 and 85" << endl;
do
i--;
break;
while(i > 0);



for(int i = 0; i < inputSize; i++)
if(inputValue[i] == 80)
tempCount80++;
else if(inputValue[i] == 81)
tempCount81++;
else if(inputValue[i] == 82)
tempCount82++;
else if(inputValue[i] == 83)
tempCount83++;
else if(inputValue[i] == 84)
tempCount84++;
else if(inputValue[i] == 85)
tempCount85++;
else
cout << "Error Accurs." << endl;



cout << 80 << " " << tempCount80 << endl;
cout << 81 << " " << tempCount81 << endl;
cout << 82 << " " << tempCount82 << endl;
cout << 83 << " " << tempCount83 << endl;
cout << 84 << " " << tempCount84 << endl;
cout << 85 << " " << tempCount85 << endl;

return 0;



The output is as expected, but need to find more efficient ways to solve the question.










share|improve this question









New contributor



Yexingys is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$




















    6












    $begingroup$


    The question is:




    Write a program that prompts the user to input ten values between 80 and 85 and stores them in an array. Your program must be able to count the frequency of each value appears in the array.




    Is there any more efficient ways to present the count for frequency number between 80 to 85? Below is the sample code which had been done in the simplest ways to count the frequency for each number.



    The part which needs more efficient ways to present:



     for(int i = 0; i < inputSize; i++) 
    if(inputValue[i] == 80)
    tempCount80++;
    else if(inputValue[i] == 81)
    tempCount81++;
    else if(inputValue[i] == 82)
    tempCount82++;
    else if(inputValue[i] == 83)
    tempCount83++;
    else if(inputValue[i] == 84)
    tempCount84++;
    else if(inputValue[i] == 85)
    tempCount85++;
    else
    cout << "Error Accurs." << endl;



    cout << 80 << " " << tempCount80 << endl;
    cout << 81 << " " << tempCount81 << endl;
    cout << 82 << " " << tempCount82 << endl;
    cout << 83 << " " << tempCount83 << endl;
    cout << 84 << " " << tempCount84 << endl;
    cout << 85 << " " << tempCount85 << endl;


    The original code is: -



    #include <iostream>
    using namespace std;

    int main()
    const int inputSize = 10;
    int inputValue[inputSize];
    int tempCount80 = 0;
    int tempCount81 = 0;
    int tempCount82 = 0;
    int tempCount83 = 0;
    int tempCount84 = 0;
    int tempCount85 = 0;

    for(int i = 0; i < inputSize; i++)
    int tempValue = 0;
    cout << "Please enter a number between 80 and 85: ";
    cin >> tempValue;

    if(tempValue > 79 && tempValue < 86)
    inputValue[i] = tempValue;
    else
    cout << "The number must be between 80 and 85" << endl;
    do
    i--;
    break;
    while(i > 0);



    for(int i = 0; i < inputSize; i++)
    if(inputValue[i] == 80)
    tempCount80++;
    else if(inputValue[i] == 81)
    tempCount81++;
    else if(inputValue[i] == 82)
    tempCount82++;
    else if(inputValue[i] == 83)
    tempCount83++;
    else if(inputValue[i] == 84)
    tempCount84++;
    else if(inputValue[i] == 85)
    tempCount85++;
    else
    cout << "Error Accurs." << endl;



    cout << 80 << " " << tempCount80 << endl;
    cout << 81 << " " << tempCount81 << endl;
    cout << 82 << " " << tempCount82 << endl;
    cout << 83 << " " << tempCount83 << endl;
    cout << 84 << " " << tempCount84 << endl;
    cout << 85 << " " << tempCount85 << endl;

    return 0;



    The output is as expected, but need to find more efficient ways to solve the question.










    share|improve this question









    New contributor



    Yexingys is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






    $endgroup$
















      6












      6








      6





      $begingroup$


      The question is:




      Write a program that prompts the user to input ten values between 80 and 85 and stores them in an array. Your program must be able to count the frequency of each value appears in the array.




      Is there any more efficient ways to present the count for frequency number between 80 to 85? Below is the sample code which had been done in the simplest ways to count the frequency for each number.



      The part which needs more efficient ways to present:



       for(int i = 0; i < inputSize; i++) 
      if(inputValue[i] == 80)
      tempCount80++;
      else if(inputValue[i] == 81)
      tempCount81++;
      else if(inputValue[i] == 82)
      tempCount82++;
      else if(inputValue[i] == 83)
      tempCount83++;
      else if(inputValue[i] == 84)
      tempCount84++;
      else if(inputValue[i] == 85)
      tempCount85++;
      else
      cout << "Error Accurs." << endl;



      cout << 80 << " " << tempCount80 << endl;
      cout << 81 << " " << tempCount81 << endl;
      cout << 82 << " " << tempCount82 << endl;
      cout << 83 << " " << tempCount83 << endl;
      cout << 84 << " " << tempCount84 << endl;
      cout << 85 << " " << tempCount85 << endl;


      The original code is: -



      #include <iostream>
      using namespace std;

      int main()
      const int inputSize = 10;
      int inputValue[inputSize];
      int tempCount80 = 0;
      int tempCount81 = 0;
      int tempCount82 = 0;
      int tempCount83 = 0;
      int tempCount84 = 0;
      int tempCount85 = 0;

      for(int i = 0; i < inputSize; i++)
      int tempValue = 0;
      cout << "Please enter a number between 80 and 85: ";
      cin >> tempValue;

      if(tempValue > 79 && tempValue < 86)
      inputValue[i] = tempValue;
      else
      cout << "The number must be between 80 and 85" << endl;
      do
      i--;
      break;
      while(i > 0);



      for(int i = 0; i < inputSize; i++)
      if(inputValue[i] == 80)
      tempCount80++;
      else if(inputValue[i] == 81)
      tempCount81++;
      else if(inputValue[i] == 82)
      tempCount82++;
      else if(inputValue[i] == 83)
      tempCount83++;
      else if(inputValue[i] == 84)
      tempCount84++;
      else if(inputValue[i] == 85)
      tempCount85++;
      else
      cout << "Error Accurs." << endl;



      cout << 80 << " " << tempCount80 << endl;
      cout << 81 << " " << tempCount81 << endl;
      cout << 82 << " " << tempCount82 << endl;
      cout << 83 << " " << tempCount83 << endl;
      cout << 84 << " " << tempCount84 << endl;
      cout << 85 << " " << tempCount85 << endl;

      return 0;



      The output is as expected, but need to find more efficient ways to solve the question.










      share|improve this question









      New contributor



      Yexingys is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      $endgroup$




      The question is:




      Write a program that prompts the user to input ten values between 80 and 85 and stores them in an array. Your program must be able to count the frequency of each value appears in the array.




      Is there any more efficient ways to present the count for frequency number between 80 to 85? Below is the sample code which had been done in the simplest ways to count the frequency for each number.



      The part which needs more efficient ways to present:



       for(int i = 0; i < inputSize; i++) 
      if(inputValue[i] == 80)
      tempCount80++;
      else if(inputValue[i] == 81)
      tempCount81++;
      else if(inputValue[i] == 82)
      tempCount82++;
      else if(inputValue[i] == 83)
      tempCount83++;
      else if(inputValue[i] == 84)
      tempCount84++;
      else if(inputValue[i] == 85)
      tempCount85++;
      else
      cout << "Error Accurs." << endl;



      cout << 80 << " " << tempCount80 << endl;
      cout << 81 << " " << tempCount81 << endl;
      cout << 82 << " " << tempCount82 << endl;
      cout << 83 << " " << tempCount83 << endl;
      cout << 84 << " " << tempCount84 << endl;
      cout << 85 << " " << tempCount85 << endl;


      The original code is: -



      #include <iostream>
      using namespace std;

      int main()
      const int inputSize = 10;
      int inputValue[inputSize];
      int tempCount80 = 0;
      int tempCount81 = 0;
      int tempCount82 = 0;
      int tempCount83 = 0;
      int tempCount84 = 0;
      int tempCount85 = 0;

      for(int i = 0; i < inputSize; i++)
      int tempValue = 0;
      cout << "Please enter a number between 80 and 85: ";
      cin >> tempValue;

      if(tempValue > 79 && tempValue < 86)
      inputValue[i] = tempValue;
      else
      cout << "The number must be between 80 and 85" << endl;
      do
      i--;
      break;
      while(i > 0);



      for(int i = 0; i < inputSize; i++)
      if(inputValue[i] == 80)
      tempCount80++;
      else if(inputValue[i] == 81)
      tempCount81++;
      else if(inputValue[i] == 82)
      tempCount82++;
      else if(inputValue[i] == 83)
      tempCount83++;
      else if(inputValue[i] == 84)
      tempCount84++;
      else if(inputValue[i] == 85)
      tempCount85++;
      else
      cout << "Error Accurs." << endl;



      cout << 80 << " " << tempCount80 << endl;
      cout << 81 << " " << tempCount81 << endl;
      cout << 82 << " " << tempCount82 << endl;
      cout << 83 << " " << tempCount83 << endl;
      cout << 84 << " " << tempCount84 << endl;
      cout << 85 << " " << tempCount85 << endl;

      return 0;



      The output is as expected, but need to find more efficient ways to solve the question.







      c++ array homework






      share|improve this question









      New contributor



      Yexingys is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share|improve this question









      New contributor



      Yexingys is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share|improve this question




      share|improve this question








      edited 4 hours ago









      1201ProgramAlarm

      4,5282 gold badges12 silver badges31 bronze badges




      4,5282 gold badges12 silver badges31 bronze badges






      New contributor



      Yexingys is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      asked 9 hours ago









      YexingysYexingys

      312 bronze badges




      312 bronze badges




      New contributor



      Yexingys is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




      New contributor




      Yexingys is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.

























          2 Answers
          2






          active

          oldest

          votes


















          7












          $begingroup$

          Answer to the Performance Issue

          Anytime there are a list of variables named NAMEi where i is an integer, there is a strong chance that a container such as std::array or std::vector should be used. Sometimes using a table rather than multiple if statements can improve performance.



          Indexing into an array will prevent the repetitive code that is currently in the solution:



          #include <array>

          int main()

          const int inputSize = 10;
          const int frequencyCount = 6;
          std::array<int, inputSize> inputValues;
          std::array<int, frequencyCount> freqs;

          ...



          The array freqs will contain the frequency of the occurrence, there are a couple of ways to index into the array freqs. One would be to subtract 80 from the input value.



          This will reduce the multiple if statements into a simple increment of an item in an array. It will also reduce the amount of code necessary to print the frequencies.



          When performance is an issue, prefer "n" over std::endl. The use of std::endl flushes the output which may mean there is a system call for each use. A system call can add a great deal of time.



          Remove the do/while loop in the error checking.



          Use the Container Classes Provided by C++

          The code currently appears to be C rather than C++. It is using the old style C arrays, C++ supplies an array container class as part of the standard library. Using the array container class would allow you to use iterators instead of indexes, at least for printing. Here is a second reference.



          Avoid Using Namespace STD

          If you are coding professionally you probably should get out of the habit of using the "using namespace std;" statement. The code will more clearly define where cout and other functions are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This stack overflow question discusses this in more detail.



          DRY Code

          There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code mutiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.



          Complexity

          The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.



          There is also a programming principle called the Single Responsibility Principe that applies here. The Single Responsibility Principle states:




          that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.




          There are at least 3 possible functions in main().

          - Get the user input

          - Get process the frequencies

          - Print the frequencies



          Magic Numbers

          There are Magic Numbers in the main() function (79 and 86), it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.



          Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.






          share|improve this answer









          $endgroup$






















            3












            $begingroup$

            using namespace std; is a bad habit you should avoid.




            Input Handling:



            for(int i = 0; i < inputSize; i++) 
            int tempValue = 0;
            cout << "Please enter a number between 80 and 85: ";
            cin >> tempValue;

            if(tempValue > 79 && tempValue < 86)
            inputValue[i] = tempValue;
            else
            cout << "The number must be between 80 and 85" << endl;
            do
            i--;
            break;
            while(i > 0);




            Although we want exactly inputSize inputs, we may have to request the input multiple times from the user. Doing this by decrementing i like that is quite inventive, but it's probably neater to use another loop to repeat the input request until we get a valid input:



            for (int i = 0; i != inputSize; ++i) 

            int number = 0;

            while (true)

            std::cout << "Please enter a number between 80 and 85: ";
            number = 0;
            std::cin >> number;

            if (number >= 80 && number <= 85)
            break;

            else
            std::cout << "The number must be between 80 and 85.n";



            inputValue[i] = number;



            The inner loop could then be moved to a separate function, so the outer loop would simply look like:



            for (int i = 0; i != inputSize; ++i) 
            inputValue[i] = getInput();



            Note that we should add error handling code to ensure that the user input is valid (e.g. what if the user enters "abc", or a number too large to fit in an int?). This is quite awkward in C++, but ends up looking something like this:



            #include <iostream>
            #include <limits>

            int getInput()

            while (true)

            // unreachable
            return 0;


            int main()

            int number = getInput();

            std::cout << number << std::endl;




            Frequency count:



            Rather than individual variables, we can use another array here. This removes a lot of the repetition. Something like:



            const int freqSize = 6;
            int frequencies[freqSize] = 0, 0, 0, 0, 0, 0 ;

            for (int i = 0; i != inputSize; ++i)
            int binIndex = inputValue[i] - 80;

            assert(binIndex >= 0 && binIndex < freqSize); // need #include <cassert>
            frequencies[binIndex] += 1;


            for (int i = 0; i != freqSize; ++i)
            std::cout << (i + 80) << " " << frequencies[i] << "n";


            We should probably define our min (80) and max (85) values as constant variables somewhere, instead of using "magic numbers".




            Note that in "real" C++ code, we would probably use a data structure such as std::map<int, int> to store the count of each input value, and avoid using C-style arrays completely.






            share|improve this answer









            $endgroup$

















              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "196"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );






              Yexingys is a new contributor. Be nice, and check out our Code of Conduct.









              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226420%2fcount-the-frequency-of-items-in-an-array%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              7












              $begingroup$

              Answer to the Performance Issue

              Anytime there are a list of variables named NAMEi where i is an integer, there is a strong chance that a container such as std::array or std::vector should be used. Sometimes using a table rather than multiple if statements can improve performance.



              Indexing into an array will prevent the repetitive code that is currently in the solution:



              #include <array>

              int main()

              const int inputSize = 10;
              const int frequencyCount = 6;
              std::array<int, inputSize> inputValues;
              std::array<int, frequencyCount> freqs;

              ...



              The array freqs will contain the frequency of the occurrence, there are a couple of ways to index into the array freqs. One would be to subtract 80 from the input value.



              This will reduce the multiple if statements into a simple increment of an item in an array. It will also reduce the amount of code necessary to print the frequencies.



              When performance is an issue, prefer "n" over std::endl. The use of std::endl flushes the output which may mean there is a system call for each use. A system call can add a great deal of time.



              Remove the do/while loop in the error checking.



              Use the Container Classes Provided by C++

              The code currently appears to be C rather than C++. It is using the old style C arrays, C++ supplies an array container class as part of the standard library. Using the array container class would allow you to use iterators instead of indexes, at least for printing. Here is a second reference.



              Avoid Using Namespace STD

              If you are coding professionally you probably should get out of the habit of using the "using namespace std;" statement. The code will more clearly define where cout and other functions are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This stack overflow question discusses this in more detail.



              DRY Code

              There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code mutiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.



              Complexity

              The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.



              There is also a programming principle called the Single Responsibility Principe that applies here. The Single Responsibility Principle states:




              that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.




              There are at least 3 possible functions in main().

              - Get the user input

              - Get process the frequencies

              - Print the frequencies



              Magic Numbers

              There are Magic Numbers in the main() function (79 and 86), it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.



              Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.






              share|improve this answer









              $endgroup$



















                7












                $begingroup$

                Answer to the Performance Issue

                Anytime there are a list of variables named NAMEi where i is an integer, there is a strong chance that a container such as std::array or std::vector should be used. Sometimes using a table rather than multiple if statements can improve performance.



                Indexing into an array will prevent the repetitive code that is currently in the solution:



                #include <array>

                int main()

                const int inputSize = 10;
                const int frequencyCount = 6;
                std::array<int, inputSize> inputValues;
                std::array<int, frequencyCount> freqs;

                ...



                The array freqs will contain the frequency of the occurrence, there are a couple of ways to index into the array freqs. One would be to subtract 80 from the input value.



                This will reduce the multiple if statements into a simple increment of an item in an array. It will also reduce the amount of code necessary to print the frequencies.



                When performance is an issue, prefer "n" over std::endl. The use of std::endl flushes the output which may mean there is a system call for each use. A system call can add a great deal of time.



                Remove the do/while loop in the error checking.



                Use the Container Classes Provided by C++

                The code currently appears to be C rather than C++. It is using the old style C arrays, C++ supplies an array container class as part of the standard library. Using the array container class would allow you to use iterators instead of indexes, at least for printing. Here is a second reference.



                Avoid Using Namespace STD

                If you are coding professionally you probably should get out of the habit of using the "using namespace std;" statement. The code will more clearly define where cout and other functions are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This stack overflow question discusses this in more detail.



                DRY Code

                There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code mutiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.



                Complexity

                The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.



                There is also a programming principle called the Single Responsibility Principe that applies here. The Single Responsibility Principle states:




                that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.




                There are at least 3 possible functions in main().

                - Get the user input

                - Get process the frequencies

                - Print the frequencies



                Magic Numbers

                There are Magic Numbers in the main() function (79 and 86), it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.



                Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.






                share|improve this answer









                $endgroup$

















                  7












                  7








                  7





                  $begingroup$

                  Answer to the Performance Issue

                  Anytime there are a list of variables named NAMEi where i is an integer, there is a strong chance that a container such as std::array or std::vector should be used. Sometimes using a table rather than multiple if statements can improve performance.



                  Indexing into an array will prevent the repetitive code that is currently in the solution:



                  #include <array>

                  int main()

                  const int inputSize = 10;
                  const int frequencyCount = 6;
                  std::array<int, inputSize> inputValues;
                  std::array<int, frequencyCount> freqs;

                  ...



                  The array freqs will contain the frequency of the occurrence, there are a couple of ways to index into the array freqs. One would be to subtract 80 from the input value.



                  This will reduce the multiple if statements into a simple increment of an item in an array. It will also reduce the amount of code necessary to print the frequencies.



                  When performance is an issue, prefer "n" over std::endl. The use of std::endl flushes the output which may mean there is a system call for each use. A system call can add a great deal of time.



                  Remove the do/while loop in the error checking.



                  Use the Container Classes Provided by C++

                  The code currently appears to be C rather than C++. It is using the old style C arrays, C++ supplies an array container class as part of the standard library. Using the array container class would allow you to use iterators instead of indexes, at least for printing. Here is a second reference.



                  Avoid Using Namespace STD

                  If you are coding professionally you probably should get out of the habit of using the "using namespace std;" statement. The code will more clearly define where cout and other functions are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This stack overflow question discusses this in more detail.



                  DRY Code

                  There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code mutiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.



                  Complexity

                  The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.



                  There is also a programming principle called the Single Responsibility Principe that applies here. The Single Responsibility Principle states:




                  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.




                  There are at least 3 possible functions in main().

                  - Get the user input

                  - Get process the frequencies

                  - Print the frequencies



                  Magic Numbers

                  There are Magic Numbers in the main() function (79 and 86), it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.



                  Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.






                  share|improve this answer









                  $endgroup$



                  Answer to the Performance Issue

                  Anytime there are a list of variables named NAMEi where i is an integer, there is a strong chance that a container such as std::array or std::vector should be used. Sometimes using a table rather than multiple if statements can improve performance.



                  Indexing into an array will prevent the repetitive code that is currently in the solution:



                  #include <array>

                  int main()

                  const int inputSize = 10;
                  const int frequencyCount = 6;
                  std::array<int, inputSize> inputValues;
                  std::array<int, frequencyCount> freqs;

                  ...



                  The array freqs will contain the frequency of the occurrence, there are a couple of ways to index into the array freqs. One would be to subtract 80 from the input value.



                  This will reduce the multiple if statements into a simple increment of an item in an array. It will also reduce the amount of code necessary to print the frequencies.



                  When performance is an issue, prefer "n" over std::endl. The use of std::endl flushes the output which may mean there is a system call for each use. A system call can add a great deal of time.



                  Remove the do/while loop in the error checking.



                  Use the Container Classes Provided by C++

                  The code currently appears to be C rather than C++. It is using the old style C arrays, C++ supplies an array container class as part of the standard library. Using the array container class would allow you to use iterators instead of indexes, at least for printing. Here is a second reference.



                  Avoid Using Namespace STD

                  If you are coding professionally you probably should get out of the habit of using the "using namespace std;" statement. The code will more clearly define where cout and other functions are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This stack overflow question discusses this in more detail.



                  DRY Code

                  There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code mutiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.



                  Complexity

                  The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.



                  There is also a programming principle called the Single Responsibility Principe that applies here. The Single Responsibility Principle states:




                  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.




                  There are at least 3 possible functions in main().

                  - Get the user input

                  - Get process the frequencies

                  - Print the frequencies



                  Magic Numbers

                  There are Magic Numbers in the main() function (79 and 86), it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.



                  Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 6 hours ago









                  pacmaninbwpacmaninbw

                  7,2722 gold badges20 silver badges44 bronze badges




                  7,2722 gold badges20 silver badges44 bronze badges


























                      3












                      $begingroup$

                      using namespace std; is a bad habit you should avoid.




                      Input Handling:



                      for(int i = 0; i < inputSize; i++) 
                      int tempValue = 0;
                      cout << "Please enter a number between 80 and 85: ";
                      cin >> tempValue;

                      if(tempValue > 79 && tempValue < 86)
                      inputValue[i] = tempValue;
                      else
                      cout << "The number must be between 80 and 85" << endl;
                      do
                      i--;
                      break;
                      while(i > 0);




                      Although we want exactly inputSize inputs, we may have to request the input multiple times from the user. Doing this by decrementing i like that is quite inventive, but it's probably neater to use another loop to repeat the input request until we get a valid input:



                      for (int i = 0; i != inputSize; ++i) 

                      int number = 0;

                      while (true)

                      std::cout << "Please enter a number between 80 and 85: ";
                      number = 0;
                      std::cin >> number;

                      if (number >= 80 && number <= 85)
                      break;

                      else
                      std::cout << "The number must be between 80 and 85.n";



                      inputValue[i] = number;



                      The inner loop could then be moved to a separate function, so the outer loop would simply look like:



                      for (int i = 0; i != inputSize; ++i) 
                      inputValue[i] = getInput();



                      Note that we should add error handling code to ensure that the user input is valid (e.g. what if the user enters "abc", or a number too large to fit in an int?). This is quite awkward in C++, but ends up looking something like this:



                      #include <iostream>
                      #include <limits>

                      int getInput()

                      while (true)

                      // unreachable
                      return 0;


                      int main()

                      int number = getInput();

                      std::cout << number << std::endl;




                      Frequency count:



                      Rather than individual variables, we can use another array here. This removes a lot of the repetition. Something like:



                      const int freqSize = 6;
                      int frequencies[freqSize] = 0, 0, 0, 0, 0, 0 ;

                      for (int i = 0; i != inputSize; ++i)
                      int binIndex = inputValue[i] - 80;

                      assert(binIndex >= 0 && binIndex < freqSize); // need #include <cassert>
                      frequencies[binIndex] += 1;


                      for (int i = 0; i != freqSize; ++i)
                      std::cout << (i + 80) << " " << frequencies[i] << "n";


                      We should probably define our min (80) and max (85) values as constant variables somewhere, instead of using "magic numbers".




                      Note that in "real" C++ code, we would probably use a data structure such as std::map<int, int> to store the count of each input value, and avoid using C-style arrays completely.






                      share|improve this answer









                      $endgroup$



















                        3












                        $begingroup$

                        using namespace std; is a bad habit you should avoid.




                        Input Handling:



                        for(int i = 0; i < inputSize; i++) 
                        int tempValue = 0;
                        cout << "Please enter a number between 80 and 85: ";
                        cin >> tempValue;

                        if(tempValue > 79 && tempValue < 86)
                        inputValue[i] = tempValue;
                        else
                        cout << "The number must be between 80 and 85" << endl;
                        do
                        i--;
                        break;
                        while(i > 0);




                        Although we want exactly inputSize inputs, we may have to request the input multiple times from the user. Doing this by decrementing i like that is quite inventive, but it's probably neater to use another loop to repeat the input request until we get a valid input:



                        for (int i = 0; i != inputSize; ++i) 

                        int number = 0;

                        while (true)

                        std::cout << "Please enter a number between 80 and 85: ";
                        number = 0;
                        std::cin >> number;

                        if (number >= 80 && number <= 85)
                        break;

                        else
                        std::cout << "The number must be between 80 and 85.n";



                        inputValue[i] = number;



                        The inner loop could then be moved to a separate function, so the outer loop would simply look like:



                        for (int i = 0; i != inputSize; ++i) 
                        inputValue[i] = getInput();



                        Note that we should add error handling code to ensure that the user input is valid (e.g. what if the user enters "abc", or a number too large to fit in an int?). This is quite awkward in C++, but ends up looking something like this:



                        #include <iostream>
                        #include <limits>

                        int getInput()

                        while (true)

                        // unreachable
                        return 0;


                        int main()

                        int number = getInput();

                        std::cout << number << std::endl;




                        Frequency count:



                        Rather than individual variables, we can use another array here. This removes a lot of the repetition. Something like:



                        const int freqSize = 6;
                        int frequencies[freqSize] = 0, 0, 0, 0, 0, 0 ;

                        for (int i = 0; i != inputSize; ++i)
                        int binIndex = inputValue[i] - 80;

                        assert(binIndex >= 0 && binIndex < freqSize); // need #include <cassert>
                        frequencies[binIndex] += 1;


                        for (int i = 0; i != freqSize; ++i)
                        std::cout << (i + 80) << " " << frequencies[i] << "n";


                        We should probably define our min (80) and max (85) values as constant variables somewhere, instead of using "magic numbers".




                        Note that in "real" C++ code, we would probably use a data structure such as std::map<int, int> to store the count of each input value, and avoid using C-style arrays completely.






                        share|improve this answer









                        $endgroup$

















                          3












                          3








                          3





                          $begingroup$

                          using namespace std; is a bad habit you should avoid.




                          Input Handling:



                          for(int i = 0; i < inputSize; i++) 
                          int tempValue = 0;
                          cout << "Please enter a number between 80 and 85: ";
                          cin >> tempValue;

                          if(tempValue > 79 && tempValue < 86)
                          inputValue[i] = tempValue;
                          else
                          cout << "The number must be between 80 and 85" << endl;
                          do
                          i--;
                          break;
                          while(i > 0);




                          Although we want exactly inputSize inputs, we may have to request the input multiple times from the user. Doing this by decrementing i like that is quite inventive, but it's probably neater to use another loop to repeat the input request until we get a valid input:



                          for (int i = 0; i != inputSize; ++i) 

                          int number = 0;

                          while (true)

                          std::cout << "Please enter a number between 80 and 85: ";
                          number = 0;
                          std::cin >> number;

                          if (number >= 80 && number <= 85)
                          break;

                          else
                          std::cout << "The number must be between 80 and 85.n";



                          inputValue[i] = number;



                          The inner loop could then be moved to a separate function, so the outer loop would simply look like:



                          for (int i = 0; i != inputSize; ++i) 
                          inputValue[i] = getInput();



                          Note that we should add error handling code to ensure that the user input is valid (e.g. what if the user enters "abc", or a number too large to fit in an int?). This is quite awkward in C++, but ends up looking something like this:



                          #include <iostream>
                          #include <limits>

                          int getInput()

                          while (true)

                          // unreachable
                          return 0;


                          int main()

                          int number = getInput();

                          std::cout << number << std::endl;




                          Frequency count:



                          Rather than individual variables, we can use another array here. This removes a lot of the repetition. Something like:



                          const int freqSize = 6;
                          int frequencies[freqSize] = 0, 0, 0, 0, 0, 0 ;

                          for (int i = 0; i != inputSize; ++i)
                          int binIndex = inputValue[i] - 80;

                          assert(binIndex >= 0 && binIndex < freqSize); // need #include <cassert>
                          frequencies[binIndex] += 1;


                          for (int i = 0; i != freqSize; ++i)
                          std::cout << (i + 80) << " " << frequencies[i] << "n";


                          We should probably define our min (80) and max (85) values as constant variables somewhere, instead of using "magic numbers".




                          Note that in "real" C++ code, we would probably use a data structure such as std::map<int, int> to store the count of each input value, and avoid using C-style arrays completely.






                          share|improve this answer









                          $endgroup$



                          using namespace std; is a bad habit you should avoid.




                          Input Handling:



                          for(int i = 0; i < inputSize; i++) 
                          int tempValue = 0;
                          cout << "Please enter a number between 80 and 85: ";
                          cin >> tempValue;

                          if(tempValue > 79 && tempValue < 86)
                          inputValue[i] = tempValue;
                          else
                          cout << "The number must be between 80 and 85" << endl;
                          do
                          i--;
                          break;
                          while(i > 0);




                          Although we want exactly inputSize inputs, we may have to request the input multiple times from the user. Doing this by decrementing i like that is quite inventive, but it's probably neater to use another loop to repeat the input request until we get a valid input:



                          for (int i = 0; i != inputSize; ++i) 

                          int number = 0;

                          while (true)

                          std::cout << "Please enter a number between 80 and 85: ";
                          number = 0;
                          std::cin >> number;

                          if (number >= 80 && number <= 85)
                          break;

                          else
                          std::cout << "The number must be between 80 and 85.n";



                          inputValue[i] = number;



                          The inner loop could then be moved to a separate function, so the outer loop would simply look like:



                          for (int i = 0; i != inputSize; ++i) 
                          inputValue[i] = getInput();



                          Note that we should add error handling code to ensure that the user input is valid (e.g. what if the user enters "abc", or a number too large to fit in an int?). This is quite awkward in C++, but ends up looking something like this:



                          #include <iostream>
                          #include <limits>

                          int getInput()

                          while (true)

                          // unreachable
                          return 0;


                          int main()

                          int number = getInput();

                          std::cout << number << std::endl;




                          Frequency count:



                          Rather than individual variables, we can use another array here. This removes a lot of the repetition. Something like:



                          const int freqSize = 6;
                          int frequencies[freqSize] = 0, 0, 0, 0, 0, 0 ;

                          for (int i = 0; i != inputSize; ++i)
                          int binIndex = inputValue[i] - 80;

                          assert(binIndex >= 0 && binIndex < freqSize); // need #include <cassert>
                          frequencies[binIndex] += 1;


                          for (int i = 0; i != freqSize; ++i)
                          std::cout << (i + 80) << " " << frequencies[i] << "n";


                          We should probably define our min (80) and max (85) values as constant variables somewhere, instead of using "magic numbers".




                          Note that in "real" C++ code, we would probably use a data structure such as std::map<int, int> to store the count of each input value, and avoid using C-style arrays completely.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 3 hours ago









                          user673679user673679

                          4,8741 gold badge14 silver badges34 bronze badges




                          4,8741 gold badge14 silver badges34 bronze badges























                              Yexingys is a new contributor. Be nice, and check out our Code of Conduct.









                              draft saved

                              draft discarded


















                              Yexingys is a new contributor. Be nice, and check out our Code of Conduct.












                              Yexingys is a new contributor. Be nice, and check out our Code of Conduct.











                              Yexingys is a new contributor. Be nice, and check out our Code of Conduct.














                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              Use MathJax to format equations. MathJax reference.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226420%2fcount-the-frequency-of-items-in-an-array%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                              Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                              François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480