1

This is my first post on here so please don't kill me for my noobishness.

I recently made a program for fun to put in a ton of numbers and have it put out the mean, not very useful but I thought I would see if I could. I would love it if someone could explain to me how I could improve my code using arrays instead of lots of variables, but still achieve the same thing, maybe even more efficiently.

My code looks like this:

#include "stdafx.h"
#include <iostream>

using namespace std;

int main() {

    int q1;
    int q2;
    int q3;
    int q4;
    int q5;
    int q6;
    int q7;
    int q8;
    int q9;
    int q10;
    int q11;
    int q12;

    int f;
    //Used for the total of all values

    int t;
    //Used for the total to be divided

    int a;
    //Used for dividing the numbers.
    cout << "We will be finding a mean. Enter the amount of numbers that will be        entered, the maximum is 12: ";

    cin >> a;

    cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
    cin >> q1;
    cin >> q2;
    cin >> q3;
    cin >> q4;
    cin >> q5;
    cin >> q6;
    cin >> q7;
    cin >> q8;
    cin >> q9;
    cin >> q10;
    cin >> q11;
    cin >> q12;

    f = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12;

    cout << f / a << '\n';


    system("pause");
}

Any advice is very appreciated! This was made in Visual Studio just in case you needed to know.

  • 3
    To answer the question you asked: yes, you can certainly use arrays to shorten your code. As far as some advice, I'd adise you to [not use namespace std](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice). – Sam Varshavchik Apr 30 '16 at 02:57
  • "Can I use arrays here to shorten my code?" Yes. – MikeCAT Apr 30 '16 at 02:59
  • @MikeCAT I also asked how I might go about doing that, but thanks. – PCGamingKing Apr 30 '16 at 03:03
  • @SamVarshavchik I figured I would be able to shorten the code, I was more asking for how. And since this was just a quick thing I decided to do the forbidden act of using namespace std. It was just a time saver, I'm not going to get into the habbit of doing it. – PCGamingKing Apr 30 '16 at 03:04
  • @SamVarshavchik: The `using namespace std;` is OK in this context. Our core language tools are there for us to use, they weren't willy-nilly designed by dimwits. However the silly Microsoft precompiled header `stdafx.h` serves no useful purpose in this code. It only makes it non-portable. – Cheers and hth. - Alf Apr 30 '16 at 03:07
  • Don't use using. Prefer std::vector over array. – 2785528 Apr 30 '16 at 03:09
  • @PCGamingKing What if there were 1,000 int's instead of 12? Don't tell me you would have declared 1,000 variables, and had one of the longest "+" lines in the history of programming. – PaulMcKenzie Apr 30 '16 at 03:26
  • @PaulMcKenzie Hahaha, yeah lol. That was why I asked this question, because I knew there had to be an easier way but I was having a hard time finding it. You should see some of my older programs lol. – PCGamingKing Apr 30 '16 at 03:28

4 Answers4

1

Of course arrays can make your life easier!

Here's how you could have accomplished the same task as above, with arrays:

#include "stdafx.h"
#include <iostream>

using namespace std;

int main() {

    int totalNums;
    cout << "We will be finding a mean.\n";
    cout << "You can only enter up to 12 numbers;

     // Declare an array to hold 12 int's
    int nums[12];

    // i will count how many numbers have been entered
    // sum will hold the total of all numbers
    int i, sum = 0;
    
    for(i = 0; i < 12; i++) {
        cout << "Enter the next number: ";
        cin >> nums[i];
        sum += nums[i];
    }    

    cout << "The mean is: " << (sum / totalNums) << '\n';


    //Try to avoid using system!
    system("pause");
}

But, why use an array?

There's no need to keep any of the numbers after you add them to the total, so why use an array?

You can accomplish the same task without an array and with only one variable for the numbers!

#include "stdafx.h"
#include <iostream>

using namespace std;

int main() {

    int totalNums;
    cout << "We will be finding a mean.\n";
    cout << "Enter the amount of numbers that will be entered: ";
    cin >> totalNums;

    // i will count how many numbers have been entered
    // sum will hold the total of all numbers
    // currentNum will hold the last number entered
    int i, sum = 0, currentNum = 0;
    
    for(i = 0; i < totalNums; i++) {
        cout << "Enter the next number: ";
        cin >> currentNum;
        sum += currentNum;
    }    

    cout << "The mean is: " << 1.0 * sum / totalNums << '\n';


    //Try to avoid using system!
    system("pause");
}
Community
  • 1
  • 1
Matt C
  • 4,470
  • 5
  • 26
  • 44
  • 1
    Standard C++ won't allow using vairable-length arrays. – MikeCAT Apr 30 '16 at 03:12
  • Thanks Mike, I guess it's been a few years since I've used C++. I've edited my answer for accuracy. – Matt C Apr 30 '16 at 03:14
  • This was a really good explanation! Thank you, and what would be better than system for pausing? – PCGamingKing Apr 30 '16 at 03:17
  • Here's a good [post](https://stackoverflow.com/questions/2529617) on what to do for preventing your c++ program from closing the console. I recommend running it from the console though. You can use `std::cin::get()` or `std::getchar()` for a nice "hit any key to continue" effect. – Matt C Apr 30 '16 at 03:20
  • I also recommend reading a little on a [style guide](https://google.github.io/styleguide/cppguide.html). Using a consistent style means using the same indentation spacing, and following a certain way of naming your variables. It will keep your code readable, maintainable, and easier to debug. – Matt C Apr 30 '16 at 03:22
  • Please (1) remove `stdafx.h` (it's non-standard and has negative utility in this context), (2) remove `system( "pause" )` (ditto), (3) make the output correct when the average is not an integer. – Cheers and hth. - Alf Apr 30 '16 at 03:31
  • @Cheersandhth.-Alf I fully understand and support your argument that correct programming practices should be taught and enforced, but I'm a firm believer that if we tried to fix every possible bug and turn every question into a lecture, then beginning programmers would be discouraged to the point that they won't come back. – Matt C Apr 30 '16 at 03:35
  • @Cheersandhth.-Alf I'm sure if the author notices the bug (non integer input breaking the program), they will try to fix it and possibly come back here if they have another issue. I don't want them to not even get to that point because I've bored them with reasons why each and every part of their program could be improved. – Matt C Apr 30 '16 at 03:37
  • Point (3) is not about bad input. It's about bad output. FTFY. – Cheers and hth. - Alf Apr 30 '16 at 03:38
  • @Cheersandhth.-Alf Note that I did take the time to slip in a few suggestions. I suggested they read a style guide (which will fix most of the problem), and I've suggested they avoid using `system`. I think any more might be a little overkill. – Matt C Apr 30 '16 at 03:39
  • Ehh, I'm not sure that's a great point. Bad input, bad output.. the chicken, the egg. If you say it's only bad output, then what do you do if the user enters "lolol" instead of a number or floating point number? Then it's an input problem. There are too many ways to handle the situation and the author should at least think through the problem first. – Matt C Apr 30 '16 at 03:43
  • @Cheersandhth.-Alf Ohh, I see what you were talking about. I thought you meant when the *input* is not an integer. My mistake. – Matt C Apr 30 '16 at 03:44
0

Arrays can be considered as series of variables each of which has ids. integers between 0 and (number of elements) - 1 (both inclusive) are available ids.

Using that with loop, your code can be like this (sorry, I hate stdafx.h):

#include <cstdlib>
#include <iostream>

using namespace std;

int main() {
    int q[12];

    int f;
    //Used for the total of all values

    int t;
    //Used for the total to be divided

    int a;
    //Used for dividing the numbers.
    cout << "We will be finding a mean. Enter the amount of numbers that will be        entered, the maximum is 12: ";

    cin >> a;

    cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
    for (int i = 0; i < 12; i++) {
        cin >> q[i];
    }

    f = 0;
    for (int i = 0; i < 12; i++) {
        f += q[i];
    }

    cout << f / a << '\n';

    system("pause");
}

You may use the numbers read in the future, but currently the numbers aren't used except for calculating the sum, so you can omit the array and do addition while reading. Also I deleted the variable t, which is unused and stopped using using namespace std;, which is not considered as good.

#include <cstdlib>
#include <iostream>

using std::cin;
using std::cout;

int main() {
    int q;

    int f;
    //Used for the total of all values

    int a;
    //Used for dividing the numbers.
    cout << "We will be finding a mean. Enter the amount of numbers that will be        entered, the maximum is 12: ";

    cin >> a;

    cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
    f = 0;
    for (int i = 0; i < 12; i++) {
        cin >> q;
        f += q;
    }

    cout << f / a << '\n';

    system("pause");
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Thank you! This really helps with understanding arrays. I was having a little trouble understanding how to actually use them in practice, so I will try it like this. – PCGamingKing Apr 30 '16 at 03:08
0

You marked this question as C++.

I recommend you do not use "using", and you should prefer vector over array.

Consider the following approach:

#include <iostream>
#include <vector>

int main(int argc, char* argv[]) 
{
   std::cout << "We will be finding a mean." << std::endl
             << "Enter numbers, and press ^d when complete.\n" 
             << std::endl;

   // Declare a vector to hold user entered int's
   std::vector<int> intVec;

   // the vector automatically keeps track of element count

   do {
      std::cout << "number: ";   // prompt
      int t = 0;
      std::cin >> t;             // use std::cin, 
      if(std::cin.eof()) break;  // ^d generates eof()
      intVec.push_back(t);
   }while(1);

   // there are several way to sum a vec, 
   // this works fine:
   int sum = 0;
   for (auto i : intVec)  sum += i;

   std::cout << "\n  sum : " << sum
             << "\ncount : " << intVec.size()
             << "\n mean : " << (sum / intVec.size()) << std::endl;

   return(0);

}    

You can enter single item per line (neatness counts).

You can enter multiple integers separated by white space, but the above will give back a prompt for the integers already entered.

^d - generates an end of file input.
... press and hold 'Control' key and letter 'd' at same time

Note - does not handle error input - try entering a 'number' as 'num' string.

2785528
  • 5,438
  • 2
  • 18
  • 20
0

The accepted answer is definitely the most efficient way to transform your code using arrays, but one thing I would add is that in C++ dividing an integer by another integer can only ever result in an integer, and because you're trying to get the mean, it seems like you'd want to have the result in decimals, so you need to do one of two things:

  1. Declare sum as a float for the purposes of diving it by totalNums to get the mean.
  2. Cast one of the integers to either a float or a double so that the decimals won't get truncated, so the last cout statement would look like this:

cout << "The mean is: " << (double)sum/totalNums << endl;

In C++ the default for precision is 6, but you can change the number of decimal points that are displayed by adding #include <iomanip> and using the setprecision( ) function in the iomanip, which you can just add in the same output line:

cout << setprecision(x) << "The mean is: " << (double)sum/totalNums << endl;

where x is whatever precision you want.


If you want to try using dynamic memory

This is definitely not necessary for what you're doing, but it's interesting stuff and good practice!

One more thing is that if you want to be able to have the user enter integers indefinitely, you can dymanically allocate memory during runtime by declaring a array of pointers to integers (so it's an array of address locations instead of an array of integers) and some sentinal value so they can decide when to stop. That code would look like:

#include <iostream>
#include <iomanip>

using namespace std;

main( ) {
    const int ARRAY_SIZE = 200;
    const int SENTINAL = -999;
    int totalNums = 0;
    int sum = 0;

    //declare an array of pointers to integers so
    //the user can enter a large number of integers
    //without using as much memory, because the memory
    //allocated is an array of pointers, and the int
    //aren't allocated until they are needed

    int *arr[ARRAY_SIZE];

    cout << "We will be finding a mean." << endl;
    cout << "Enter integers (up to 200) or enter -999 to stop" << endl;

    //add a conditional into the for loop so that if the
    //user enters the sentinal value they will break out
    //of the loop
    for (int c = 0; c < ARRAY_SIZE; c++) {

        //every time you iterate through the loop, create a new
        //integer by using the new keyword using totalNums as
        //the index
        arr[totalNums] = new int;
        cout << "Enter integer: ";

        //input into the array of pointers by dereferencing it
        //(so it refers to what the pointer is pointer to instead
        //of the pointer)
        cin >> *arr[totalNums];
        if (*arr[totalNums] == SENTINAL)
            break;
        else {
            sum += *arr[totalNums];
            totalNums++;
        }
    }

    cout << setprecision(3) << "The mean is: " << (float)sum / totalNums << endl;
}