Is there anyway to make this code shorter, I just started learning C++

Viewed 242
#include <iostream>
using namespace std;

int main()
{
    double mark1, mark2, mark3, mark4, mark5, mark6, mark7, mark8, mark9, mark10, average;
    cout << "Input mark for learner 1";
    cin >> mark1;
    cout << "Input mark for learner 2";
    cin >> mark2;
    cout << "Input mark for learner 3";
    cin >> mark3;
    cout << "Input mark for learner 4";
    cin >> mark4;
    cout << "Input mark for learner 5";
    cin >> mark5;
    cout << "Input mark for learner 6";
    cin >> mark6;
    cout << "Input mark for learner 7";
    cin >> mark7;
    cout << "Input mark for learner 8";
    cin >> mark8;
    cout << "Input mark for learner 9";
    cin >> mark9;
    cout << "Input mark for learner 10";
    cin >> mark10;

    average = (mark1 + mark2 + mark3 + mark4 + mark5 + mark6 + mark7 + mark8 + mark9 + mark10) / 10;
    cout << "The class average mark is:" << average << endl;
    return 0;
}
5 Answers

Using an array and looping through its elements, you can use:

const int count = 10;
double mark[count];
double sum = 0;

for (int i = 0; i < count; i++)
{
    cout << "Input mark for learner " << (i+1) << ": ";
    cin >> mark[i];
    sum += mark[i];
}

double average = sum / count;


In case you don't need the separate mark's later anywhere, you could just use a local mark inside the loop

const int count = 10;
double sum = 0;

for (int i = 0; i < count; i++)
{
    double mark;
    cout << "Input mark for learner " << (i+1) << ": ";
    cin >> mark;
    sum += mark;
}

double average = sum / count;

You can use a number of standard library functions, giving you an opportunity to learn them at the same time.

#include <algorithm>
#include <array>
#include <iostream>
#include <numeric>

int main() {
  std::array<double,10> mark; // use std::vector if the number of entries is variable
  std::for_each(begin(mark), end(mark), [i = 0](auto& m) mutable {
    std::cout << "Input mark for learner " << ++i << "\n";
    std::cin >> m;
  });
  std::cout << std::reduce(begin(mark), end(mark)) << "\n";
}

Here is documentation for you to read:

Also avoid using namespace std;.

Welcome to the community! First of all, it would be a good idea to use indentation for your code, so it is readable to others as well. If you just want to calculate the average, then you can do it with the code below. I tried to keep it as simple as possible for you.

Edit: Added new functionality to get the maximum entered value.

#include <iostream>

using namespace std;

int main()
{
    int numberOfMarks = 10;
    double temp, maxValue = -1, average = 0;

    for (int i = 0; i < numberOfMarks; ++i)
    {
        cout << "Input mark for learner " << i + 1 << ": ";
        cin >> temp;
        average = average + temp; // Same as average += temp

        // Store the maximum value
        if (maxValue < temp)
        {
            maxValue = temp;
        }
    }

    average = average / numberOfMarks;
    cout << endl << "The class average mark is: " << average << endl;
    cout << "The maximum value is: " << maxValue << endl;
    return 0;
}

Welcome to the world of C++, some of the things were mentioned already in other commends but i will try to summarize and explain. well lets start that in C++ it is recommend from avoid using C Style array as C++ offer much better solution which is std::vector which is part of STL which is very central and important part of C++.

Also i would like to advice that in general when you write software it is important to try to avoid hard-coded limitation, for example you declare for every student an variable but is more generic of you can declare in run-time how many student will be. also what if you want to extend you program? suppose you also want to print all the marks that was entered? then it is very easy to traverse data in the std::vector! (which is preferable then store the sum in a variable when loop on the fly).

Another thing is try to make your program stable , for example what if user accidentally wrote 12w instead of 127, you can use exception and check you input for such cases. (used std::stod to check the input correctness)

also it is good to know that there is no need to re-invent the wheel as C++ have very large verity of algorithms that suitable for many tasks. for example std::accumulate can add all the values in the vector from begin() to end(). (which are iterators).

Now some of the things in the code most probably is unfamiliar for you but don't be "scared" as you can cover them one by one, comment\comment parts you want to enable\disable and understand how they work, as well you can try to improve the example that i gave..

and last is pay to what compiler you have, because for example std::reduce is available from C++ 17 and would not compile in older C++ version.

Below is rewrite of your program in a more stable and generic

#include <iostream>
#include <vector>
#include <numeric>

int main()
{
    size_t numberOfStudents;
    std::cout << "How many learners there is in Class : ";
    std::cin >> numberOfStudents;
    
    std::vector<double> grades;
    grades.reserve(numberOfStudents); // read about reserve when you learn how vector work.
    
    for(size_t studentIndex = 0; studentIndex < numberOfStudents; ++studentIndex)
    {
        double mark;
        std::string input;
        std::cout << "Input mark for learner [" << studentIndex << "] : ";
        std::cin >> input;
        try
        {
            mark = std::stod(input); // std::stod will throw exception if the input is wrong.
        }
        catch(const std::invalid_argument& ex)
        {
            std::cout << "Error: input is Incorrect=[" << input << "]." << std::endl;
            return -1;
        }
        grades.push_back(mark);
    }
    
    // when possible is it good practice to use const
    const double totalSum = std::accumulate(grades.begin(), grades.end(),0.0);
    std::cout << "Average: " << totalSum / numberOfStudents << std::endl;
    return 0;
}

So in summary.

  1. Avoid using std::namespace and use std:: as practice.
  2. Prefer using std::vector<> instead of C style array.
  3. Use exception and\or check you input for incorrect values, array boundary, divide by zero etc.
  4. Use STL and learn how to use STL algorithms when you feel need to write loop.( in this case instead of writing loop that will summarize doubles in a std::vector) .
  5. Think about write generic, easy to read and extensible software.

Hope this will help you! and Good Luck!

Same implementation but with dynamic arrays <:)

int main(){
    //this is our 10 mark variables
    int* arr = new int[10]
    int avr = 0;
    for (int i = 0; i < 10; ++i)
    {
        cout << "Input mark for learner " << i + 1 << ": ";
        cin >> arr[i];
        avr += arr[i];
    }
    cout << "The class average mark is:" << avr/10<< endl;
    delete[] arr;
}
Related