# Easier Ways of Writing an Average Calculation Program?

This is a discussion on Easier Ways of Writing an Average Calculation Program? within the C++ Programming forums, part of the General Programming Boards category; Hey guys, okay so i wrote a program to get the average of a maximum of 5 number using just ...

1. ## Easier Ways of Writing an Average Calculation Program?

Hey guys, okay so i wrote a program to get the average of a maximum of 5 number using just if functions and also one with just a switch function. Now i would like to know of some easier ways to write these programs, thank you.

if Average Calculator:
Code:
```#include <iostream>using namespace std;

int main()
{
int totalNumbers;

// Numbers
float a1;
float a2;
float a3;
float a4;
float a5;

// Sum
float sum;
float apa;

cout << "Amount of Numbers to Calculate: \n";
cin >> totalNumbers;

if (totalNumbers == 1)
{
cout << "Sorry, you're not able to do that!\n";
}

if (totalNumbers == 2)
{
cout << "Number 1: ";
cin >> a1;

cout << "Number 2: ";
cin >> a2;

apa = a1 + a2;
sum = apa / 2;
cout << "\nAverage = " << sum << "\n";
}

if (totalNumbers == 3)
{
cout << "Number 1: ";
cin >> a1;

cout << "Number 2: ";
cin >> a2;

cout << "Number 3: ";
cin >> a3;

apa = a1 + a2 + a3;
sum = apa / 3;
cout << "\nAverage = " << sum << "\n";
}

if (totalNumbers == 4)
{
cout << "Number 1: ";
cin >> a1;

cout << "Number 2: ";
cin >> a2;

cout << "Number 3: ";
cin >> a3;

cout << "Number 4: ";
cin >> a4;

apa = a1 + a2 + a3 + a4;
sum = apa / 4;
cout << "\nAverage = " << sum << "\n";
}

if (totalNumbers == 5)
{
cout << "Number 1: ";
cin >> a1;

cout << "Number 2: ";
cin >> a2;

cout << "Number 3: ";
cin >> a3;

cout << "Number 4: ";
cin >> a4;

cout << "Number 5: ";
cin >> a5;

apa = a1 + a2 + a3 + a4 + a5;
sum = apa / 5;
cout << "\nAverage = " << sum << "\n";
}

system("pause");
}```
switch Average Calculator:
Code:
```#include <iostream>using namespace std;

int main()
{
int totalNumbers;

// Numbers
float a1;
float a2;
float a3;
float a4;
float a5;

// Sum
float sum;
float apa;

cout << "Amount of Numbers to Calculate: \n";
cin >> totalNumbers;

switch(totalNumbers)
{
case 2:
cout << "Number 1: ";
cin >> a1;

cout << "Number 2: ";
cin >> a2;

apa = a1 + a2;
sum = apa / 2;
cout << "\nAverage = " << sum << "\n";
break;

case 3:
cout << "Number 1: ";
cin >> a1;

cout << "Number 2: ";
cin >> a2;

cout << "Number 3: ";
cin >> a3;

apa = a1 + a2 + a3;
sum = apa / 3;
cout << "\nAverage = " << sum << "\n";
break;

case 4:
cout << "Number 1: ";
cin >> a1;

cout << "Number 2: ";
cin >> a2;

cout << "Number 3: ";
cin >> a3;

cout << "Number 4: ";
cin >> a4;

apa = a1 + a2 + a3 + a4;
sum = apa / 4;
cout << "\nAverage = " << sum << "\n";
break;

case 5:
cout << "Number 1: ";
cin >> a1;

cout << "Number 2: ";
cin >> a2;

cout << "Number 3: ";
cin >> a3;

cout << "Number 4: ";
cin >> a4;

cout << "Number 5: ";
cin >> a5;

apa = a1 + a2 + a3 + a4 + a5;
sum = apa / 5;
cout << "\nAverage = " << sum << "\n";
break;

default:
cout << "Sorry, you're not able to do that!\n";
}

system("pause");
}```
Thanks for taking the time to look at this guys. First time on the forums by the way!

2. Originally Posted by Mythix
using just if functions and also one with just a switch function
Because "function" means something else in C, we would normally say "if statement" and "switch statement".

Originally Posted by Mythix
Now i would like to know of some easier ways to write these programs
Consider using an array and loops. Actually, you don't necessarily need an array since you can store a running total, but an array would be closer to what you have done.

3. Originally Posted by Mythix
Code:
```    float a1;
float a2;
float a3;
float a4;
float a5;```
Whenever you see code that has a number of variables with incrementing numbers in their name, and later lots of code tailored for each number of those variables in use, the obvious technique to simplify is to use an array.

Consider what this does
Code:
```#include <iostream>

int main()
{
int a[5];
int i, totalNumbers;

std::cout << "Amount of Numbers to Calculate: \n";
std::cin >> totalNumbers;

if (totalNumbers >= 1 && totalNumbers <= 5)
{
for (i = 0; i < totalNumbers; ++i)
{
std::cout << "Number " << (i+1) << " : ";
std::cin >> a[i];
}
for (i = 0; i < totalNumbers; ++i)
{
std::cout << "Number " << (i+1) << " is " << a[i] << '\n';
}
}
}```
Now, okay, all the code I've given does is read in a specified number of values and then print them out again. But, notice that this code does about 90% of what your code does, but is much smaller since it doesn't have the duplication yours does. And the only explicit tests my code does (an if statement - (which is not an "if function")) is ensuring that totalNumbers is between 1 and 5 (once only) and, in the for() loop, ensuring that i does not run out of bounds.

See if you can - without duplicating code - modify what I've done to compute an average in exactly ONE place in your code. If you find yourself writing an average in five different ways (which is what your code does now) then you are making life unnecessarily difficult for yourself.

Just remember that array indices start at zero. So, an array defined as "int a[5]" has valid elements a[0], a[1], a[2], a[3], a[4]. a[-1] and a[5] are not valid values (although you need to watch that, since the compiler won't complain).

Once you've done that, think again. It is actually possible to avoid using an array in your code as well.

4. If you are using a C++11 compliant compiler, it would be better to use std::array instead of grumpy's C arrays. So:

int a[5];
you would write
std::array<int, 5> a;

Then, you could use the .at member function to index yourself in the array. If you try to access an element that doesn't exist--it will throw an exception.
Granted, relying on exceptions this to control program flow is considered bad practice. But I've seen compilers that happily accepts out-of-bounds access, while using .at will help you find and fix those errors.

However, if you want to user to be able to enter N numbers (where N is potentially unlimited), then std::vector may be a better alternative since it can grow automatically (ie, its size is not fixed).

5. However, if you want to user to be able to enter N numbers (where N is potentially unlimited) hen std::vector may be a better alternative
The max size of vector is great, but not unlimited just to be clear.

6. Originally Posted by Elysia
If you are using a C++11 compliant compiler, it would be better to use std::array instead of grumpy's C arrays.
They're not my "C arrays". They are part of the language that is easier to explain than some other features. Granted, C++11 std::array is an alternative to C arrays, and has advantages for people who understand basic concepts of containers in C++, but is harder to explain to an obvious beginner.

Originally Posted by Elysia
Then, you could use the .at member function to index yourself in the array. If you try to access an element that doesn't exist--it will throw an exception.
And, there you have made my point. Using the .at member function is something that may be obvious to you because you're familiar with it, but having to explain both the .at() member and the meaning of exceptions (which few beginners can be expected to understand) takes more effort than describing C arrays, explaining what the valid range of indices.
Originally Posted by Elysia
Granted, relying on exceptions this to control program flow is considered bad practice.
Which is another reason I would not introduce exceptions to beginners.

Originally Posted by Elysia
But I've seen compilers that happily accepts out-of-bounds access, while using .at will help you find and fix those errors.
.... that does rely on sufficient test cases to trigger the coding errors. Generally speaking, coding errors like out-of-bound access occur because the programmer overlooked the possibility of such errors. Formulating tests to trigger an exception when an out-of-bound error occurs also requires knowing the nature of coding errors that have been made. But since the programmer has made the errors by overlooking the possibility, they can't design a test suite sufficient to trigger the errors ..... Reminds me of the old ditty "There's a hole in the bucket" ....

Originally Posted by Elysia
However, if you want to user to be able to enter N numbers (where N is potentially unlimited), then std::vector may be a better alternative since it can grow automatically (ie, its size is not fixed).
As whiteflags said, the size of a std::vector is finite.

Strictly speaking, std::vector does not grow automatically either. It supports specific operations (such as resize(), push_back() and insert()) that can be explicitly used to make it grow.

Neither the operator[] (which allows accessing an element using the vec[index] syntax) nor the .at() method cause a std::vector to grow.

7. I agree it is much better that the beginner learns to use fundamentals like c-style arrays that offer learning benefits as a basic programming concept than to jump into more advanced c++ specific features, walk then run i say.

8. Originally Posted by rogster001
I agree it is much better that the beginner learns to use fundamentals like c-style arrays that offer learning benefits as a basic programming concept than to jump into more advanced c++ specific features, walk then run i say.
I think that it depends... I would teach a beginner to use std::vector before manually managed dynamic arrays.

9. dynamic arrays yes i agree, i thought the example was static though, which is failry easily learnt

10. Originally Posted by grumpy
They're not my "C arrays". They are part of the language that is easier to explain than some other features. Granted, C++11 std::array is an alternative to C arrays, and has advantages for people who understand basic concepts of containers in C++, but is harder to explain to an obvious beginner.
They may be standard, but since you prefer to mention them over C++ arrays, I think it is fair to call them "your C arrays."
This isn't about, oh it may have some advantages, but you're unlikely to see them until later. This is about teaching them to use modern constructs and omitting to teach them old constructs which are deprecated in favour of modern ones (I use deprecated, but obviously they are necessary in certain situations and projects, but that's not something a beginner necessarily needs to know).
Do you think they will ever learn about std::array unless specifically told about it here? I don't.
If you simply replace C arrays with std::array, everything will work as before, so I don't think it's necessarily "harder" to teach them to use it. Granted, using some features may require a little more explanation, but if you don't use them, then what is the harm?

And, there you have made my point. Using the .at member function is something that may be obvious to you because you're familiar with it, but having to explain both the .at() member and the meaning of exceptions (which few beginners can be expected to understand) takes more effort than describing C arrays, explaining what the valid range of indices.

Which is another reason I would not introduce exceptions to beginners.
You are by all means entitled to an opinion, but exceptions are really a core part of the language. Some/many new C++11 things tend to throw exceptions if things fail. Heck, even operator new throws an exception if it fails.
Beginners really must get familiar with exceptions and do it quickly. The future will only embrace them further.
If you don't want to explain exceptions, then that's fine. You don't have to. But you shouldn't bark at people who introduce std::array and are prepared to explain exceptions too, if newbies are unfamiliar with them. There are even tutorials on the site. What good are language features if you're going to avoid them just because it takes a little more explaining?
You don't need to make them experts. You only need to teach the basic nature of what exceptions are and possibly how to handle them when thrown from a standard library function.

We are never going to move forward is we keep looking backwards. Newbies are the fresh source of programmers who will work in the programming field of tomorrow. We must teach them the modern practices so that they don't look back and create legacy code. We do not do them a favour by omitting new and modern containers and practices.

Originally Posted by rogster001
I agree it is much better that the beginner learns to use fundamentals like c-style arrays that offer learning benefits as a basic programming concept than to jump into more advanced c++ specific features, walk then run i say.
How is C arrays more fundamental than a C++ array? Please do tell.
Perhaps you should elaobrate on your "fundamental" view, too. I think it would be fundamental for a programming language to catch my errors, such as accessing out-of-bounds elements. Clearly, C arrays cannot even offer this possibility.

11. How is C arrays more fundamental than a C++ array? Please do tell.
I mean the simple idea of an array as traditionally found in beginner teachings in programming languages, where it simply introduces the idea of being able to declare a variable that can 'contain' more than one value of the type and accessed in the basic manner with an index.

Not a templated version of that common type which has a multitude of member methods and other whistles and bells. Which is great, dont get me wrong - and all the whistles and bells can be introduced more gradually of course in learning - But then the student cannot expect to find them when creating arrays in other languages. I just think it is good to learn some things from the more nuts and bolts end, and no i dont mean to imply that means digging down to the nth lowest level method

12. Originally Posted by Elysia
They may be standard, but since you prefer to mention them over C++ arrays, I think it is fair to call them "your C arrays."
It's not fair to say that. Your is a possessive pronoun, which means that the C arrays belong to grumpy. My interpretation is you want to say he's affectionate towards them. But at face value, they aren't his or anyone else's. No one "owns" C.

This isn't about, oh it may have some advantages, but you're unlikely to see them until later. This is about teaching them to use modern constructs and omitting to teach them old constructs which are deprecated in favour of modern ones (I use deprecated, but obviously they are necessary in certain situations and projects, but that's not something a beginner necessarily needs to know).
C arrays aren't deprecated. Deprecated means that they would soon become obsolete, as in planned obsolescence. It's misinformation, even if you don't intent it to be.

Do you think they will ever learn about std::array unless specifically told about it here? I don't.

If you simply replace C arrays with std::array, everything will work as before, so I don't think it's necessarily "harder" to teach them to use it. Granted, using some features may require a little more explanation, but if you don't use them, then what is the harm?

You are by all means entitled to an opinion, but exceptions are really a core part of the language. Some/many new C++11 things tend to throw exceptions if things fail. Heck, even operator new throws an exception if it fails.
You're ignoring his actual opinion. In the preceding paragraph, you act as though he did not explain why it was harder to teach std::array than regular arrays.

Beginners really must get familiar with exceptions and do it quickly. The future will only embrace them further.

If you don't want to explain exceptions, then that's fine. You don't have to. But you shouldn't bark at people who introduce std::array and are prepared to explain exceptions too, if newbies are unfamiliar with them. There are even tutorials on the site. What good are language features if you're going to avoid them just because it takes a little more explaining?
The point is that std::array uses exceptions, therefore, to use the benefits of std::arrays, you need to know what they are, and how to program with them. By my reading, grumpy thinks this information is important and should be taught with or before std::arrays. At least, if you are going to mention, specifically, operations that can throw such as at().

You don't need to make them experts. You only need to teach the basic nature of what exceptions are and possibly how to handle them when thrown from a standard library function.
Not explaining at all just makes people who half-understand something and then have a frustrating time with it, creating errors. Plus, you did not respond to a point made: that accesses out of bounds really don't happen unless you didn't consider the possibility. If there is an out of bounds error, you have to have the knowledge of exceptions to capture the error in a unit test, find exactly where the error was and correct it. If you take exceptions away, what is the point of using std::array?

13. Originally Posted by rogster001
I mean the simple idea of an array as traditionally found in beginner teachings in programming languages, where it simply introduces the idea of being able to declare a variable that can 'contain' more than one value of the type and accessed in the basic manner with an index.

Not a templated version of that common type which has a multitude of member methods and other whistles and bells. Which is great, dont get me wrong - and all the whistles and bells can be introduced more gradually of course in learning - But then the student cannot expect to find them when creating arrays in other languages. I just think it is good to learn some things from the more nuts and bolts end, and no i dont mean to imply that means digging down to the nth lowest level method
Only C does not have all bells and whistles. All other programming languages tend to feature very rich arrays.
And simply using such a thing does not imply you have to use all the methods. That can come later.

Originally Posted by whiteflags
It's not fair to say that. Your is a possessive pronoun, which means that the C arrays belong to grumpy. My interpretation is you want to say he's affectionate towards them. But at face value, they aren't his or anyone else's. No one "owns" C.
It's a figure of speech. I'm surprised everyone is misinterpreting it. But yes, your interpretation is correct.

C arrays aren't deprecated. Deprecated means that they would soon become obsolete, as in planned obsolescence. It's misinformation, even if you don't intent it to be.
Sigh. Fine. Give me a word you would deem acceptable in this situation. Clearly, the standard committee introduced C++ arrays with the idea that they should be the default arrays in C++. Clearly, C arrays are still there for backwards compatibility. I believe C++ arrays can be exactly as efficient as C arrays, hence limiting their value if a C++ array can be used.

You're ignoring his actual opinion. In the preceding paragraph, you act as though he did not explain why it was harder to teach std::array than regular arrays.

The point is that std::array uses exceptions, therefore, to use the benefits of std::arrays, you need to know what they are, and how to program with them. By my reading, grumpy thinks this information is important and should be taught with or before std::arrays. At least, if you are going to mention, specifically, operations that can throw such as at().
Argument: To use std::array properly, one must first know exceptions.
Counter-argument: No. One can still use it as a plain C array with the added possibility for easier debug checks with compilers because it is easier to have debug checks for std::array than for C arrays.
Argument: To use at() properly, one must first know exceptions.
Counter-argument: Yes. But exceptions are a part of the core language. Therefore, it is very important that one knows it. They are ubiquitous these days, in both C++ and other languages such as C#, Java, etc. Shying away from using because of exceptions is not ideal.
Argument: When using at() without proper knowledge of exceptions, frustration will surface.
Counter-argument: You are bound to encounter them sooner or later when learning C++ anyway, and probably sooner than later. It's not worth putting off.
Argument: Exceptions can be difficult to teach properly.
Counter-argument: You don't need to teach all of it. Learning how to handle existing exceptions, or at least learning what they are, is easier than teaching everything at once. But even a little knowledge, if taught properly, is better than nothing at all.

OK, that was probably poor and lame, but I made it so it tries to show the arguments easier.

Not explaining at all just makes people who half-understand something and then have a frustrating time with it, creating errors. Plus, you did not respond to a point made: that accesses out of bounds really don't happen unless you didn't consider the possibility. If there is an out of bounds error, you have to have the knowledge of exceptions to capture the error in a unit test, find exactly where the error was and correct it. If you take exceptions away, what is the point of using std::array?
Who says it must be done in a unit test?
Just do it in your normal code and make the debugger catch it (say, no catch handler).
Out of bounds access happens even if you did consider the possibility (ie, bug). That is why it is good to catch these before they cause undefined behaviour. Then fixing the bugs.
I have seen compilers (*cough* gcc *cough*) that just silently accepts out-of-bounds access in a vector and C arrays.
And prey tell: what institutions actually teach newbies what out-of-bounds access is and its dangers?

TBH, I think it's just better to teach them to use at() all the time even if not teaching them exceptions. At least it will prevent buffer overruns even if the program will crash and burn and everything will go horribly wrong. But at least I don't have to worry about a hacker taking over the computer. Well, actually that's a slim hope, but I can dream.

14. The major problem I have with std::array it that it is much harder to write a generic function that can use a std::array of any size as a parameter.

Jim

Page 1 of 3 123 Last