I am trying to write a program to find the sum of multiple amounts and the average of the amounts given. It doesn't seem to be working but I don't know if the issue is within my compiler of if it is my code. This is what i have so far.
#include <iostream>
using namespace std;
int main()
{
int n, i;
sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
you didn't declare "num" array anywhere, also your data declarations are missing types for sum and average. They should be floats. BTW float literals need f on the end:
float num = 0.0f; // hold the current number
float sum = 0.0f; // store the sum so far
float average = 0.0f; // store the average at the end
When reading store cin straight into num, with no [i] subscript:
cin >> num;
sum += num;
This will fix the main errors. Again, read the error messages carefully, they will always tell you the line number and a message about the type of error, you just need to learn to decipher what the messages mean.
forget about the array for now, as that would need dynamic memory allocation, since the size is inputted by the user, and you should get basic program flow and variables worked out before delving into that.
"unknown symbol" or similar means you used a name, but you never declared what type of thing that was, so you forgot to declare a variable or didn't declare a type for it (just throwing a name out doesn't tell the compiler whether it's meant to be the name of e.g. a variable, a function, a class or whatever. The compiler isn't a mind reader).
Related
I'm a freshman in IT and we're currently discussing functions in C++. I just want to ask the difference between our prof's code and the other code that I tried.
This is the sample code our prof showed us:
#include<iostream> //header file
using namespace std;
int num1, num2, sum = 0; // global variable
int addTwoNumbers(int a, int b)
{
sum = a + b;
return sum;
}
int main()
{
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
sum = addTwoNumbers(num1, num2);
cout << "\nThe sum is " << sum;
}
and as for the code I tried, I simply removed the "sum =" part. So,
addTwoNumbers (num1, num2);
cout << "\nThe sum is " << sum;
and it still did the same thing. At least, from what I saw in the output. Is there any difference between the two behind the scenes or is there really nothing?
The 1st code is ... confusing. I hope your professor didn't show this code to introduce you to functions, but to rather quiz your already knowledge of functions and global variables.
The confusing part are the global variables and how they are used inside the function. If we remove them and forget about them completely the code is better suited to teach you about functions. Let's see:
#include <iostream>
int addTwoNumbers(int a, int b)
{
int sum = a + b;
return sum;
// or simply:
// return a + b;
}
int main()
{
int num1, num2;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter second number: ";
std::cin >> num2;
int sum = addTwoNumbers(num1, num2);
std::cout << "\nThe sum is " << sum;
}
Now there are no hidden dependencies between main and addTwoNumbers (in the form of the global variables). This illustrates the procedure of passing data to function and getting data back from the function (parameters and return). Analyze this code and understand how it works. Play with it.
Now this won't work:
addTwoNumbers (num1, num2);
cout << "\nThe sum is " << sum;
Because the only way data escapes the function is via its return. Since you discard the return value (you don't assign the result of calling the function) you don't have the result of the sum.
Now you could say you could do this instead:
int sum = num1 + num2;
cout << "\nThe sum is " << sum;
and ask "what's the point of functions?"
True for this particular small function there is no practical point of having it. You'll always write the num1 + num2 instead. However its simplicity makes it perfect as a teaching tool. You will soon see functions that get more complex and you will learn (either by being told or learning yourself the hard way) that writing code in very small chinks (functions) is better for both writing (breaking down the big problem in smaller problems) as well as for reading.
First of all, the reason why the sum is returning those values is that you are assigning the sum to itself. Basically, the addTwoNumber() returns the sum, and then you are assigning that value back into the sum. Hence, you don't need to assign the sum again in other words (sum = addTwoNumbers is unnecessary).
Yes, your code is working and it is actually better than the teachers in this case. However, your teacher may want to show you that you can use global variables like this. Typically you would store that value in another variable for later use if needed.
I wanted to write a code where user will give input the element of the array and then the elements will be print as an array. Here is my code but the code do not give the array as output.
#include<iostream>
using namespace std;
int main(){
int arr[100] , size , i , num ; //Here we are defining the maximum size of array is 100. So user can choose the size of array by him/her but cannot choose more than 100
cout << "Enter the size of array (Maximum array size you can take is 100) : ";
cin >> size;
if (size > 100)
{
cout << "You cannot take the size more than 100" << endl;
}else{
cout << "Inter the elements using space : ";
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
cout << "Enter data you want to insert : ";
cin >> num;
for (int i = size - 1 ; i >= 0 ; i--)
{
arr[i+1] = arr[i];
}
arr[0] = num;
size++;
}
cout << arr[i] << endl;
return 0;
}
Your question isn't entirely clear, but I see two basic problems.
First, you define variable i at the top of your code. That's fine, although there are arguments for variable names being longer than a single character. Think about searching for uses of that variable -- you're going to get it in all sorts of places that have nothing to do with the variable. while has an i. if has an i. Be that as it may.
But here's a real problem. You have some for loops like this:
for (int i = 0; ....)
There's nothing wrong with that, not exactly. It works. HOWEVER, it's considered bad form to reuse a variable inside an inner block that matches a variable from an outer block. It's legal, but it's a common source of bugs. I recommend you don't do it.
Then, at the bottom, you do this:
cout << arr[i] << endl;
At this point, we're back to the original variable i that you declare at the top. But you never actually initialize it, so it's some random value. And you're not doing any sort of loop.
I suspect if you wrap this inside another of your for-loops, you'd get the results you want.
And get rid of declaring i at the top.
The code currently takes an input of the number of data entries and an input of number separated by a single space. My aim is to get the data entered and convert it into an array however whenever I try using the format
int array[ndata];
The build contains errors due to the variable ndata not being constant. How do I change the input for the size of the array to allow for this?
Code:
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int MAXDATA = 100;
bool ok = 1;
double sum = 0, x, data[MAXDATA];
double min = 1e32, max = -1e32;
int ndata = 0;
int count = 0;
while (ok)
{
cout << "Enter number of data to input then press <Enter>: ";
cin >> ndata;
if (ndata > 0 && ndata < MAXDATA) ok = 0;
cout << "Enter numbers separated by a single space, then press <Enter>: ";
count = 0;
while (count < ndata)
{
cin >> x;
data[count] = x;
sum = sum + x;
count++;
cout << "sum is " << sum << endl;
}
}
}
There are 2 ways you can handle this.
Declare Variables Closer To First Use
The first way is to declare your variables closer to where you intend to use them. This is a useful thing to do because it makes it easier to read the code when the declaration and use are close to each other. It would look something like this:
#include <iostream>
#include <string>
using namespace std;
int main(){
const int MAXDATA = 100;
bool ok = 1;
double sum = 0, x;
double min = 1e32, max = -1e32;
int ndata = 0;
int count = 0;
while (ok) {
cout << "Enter number of data to input then press <Enter>: ";
cin >> ndata;
if (ndata > 0 && ndata < MAXDATA) ok = 0;
cout << "Enter numbers separated by a single space, then press <Enter>: ";
count = 0;
double data[ndata];
while (count < ndata) {
cin >> x;
data[count] = x;
sum = sum + x;
count++;
cout << "sum is " << sum << endl;
}
}
}
Note that with that you'll need to add some additional checks to make sure ndata isn't greater than MAXDATA.
This works because data is declared after ndata is initialized. Note that if you don't check to ensure ndata is less than MAXDATA, you run the risk of overflowing your stack.
Dynamic Allocation
The better way to do this is to allocate the data array on the heap. This allows you to make it as large as you want (up to the limits of your OS and hardware). But it does require extra care to ensure that the data is freed after you're done with it. It would look something like this:
#include <iostream>
#include <string>
using namespace std;
int main(){
const int MAXDATA = 100;
bool ok = 1;
double sum = 0, x;//, data[MAXDATA];
double min = 1e32, max = -1e32;
int ndata = 0;
int count = 0;
while (ok) {
cout << "Enter number of data to input then press <Enter>: ";
cin >> ndata;
if (ndata > 0 && ndata < MAXDATA) ok = 0;
cout << "Enter numbers separated by a single space, then press <Enter>: ";
count = 0;
double *data = new double [ ndata ];
while (count < ndata) {
cin >> x;
data[count] = x;
sum = sum + x;
count++;
cout << "sum is " << sum << endl;
}
delete [] data;
}
}
Let's start with a reference for why your build fails: Why aren't variable-length arrays part of the c++ standard? Variable-length arrays are supported by GCC, but not by all compilers.
Vectors
As for what you could do, the safest thing to do would be to switch from arrays to vectors. A std::vector is basically a dynamically-allocated array with some convenience features that mean you don't have to worry about the dynamic allocation. A typical way to declare a vector is the following:
std::vector<double> data;
data.reserve(ndata);
The second line tells the vector to allocate enough space for your data even though the vector at this point still contains no elements. It's not required to reserve space, but it can help performance when ndata is large.
When you have something to add to (the end of) the array, you can use something like:
data.push_back(x);
Retrieving the data can be done with syntax similar to arrays: data[count].
Vectors, part 2
There is another approach you might consider when using vectors. You could declare your variable while specifying its size.
std::vector<double> data(ndata);
This is different than the first approach in that it actually (default-)constructs ndata copies of a double. The first version allocated space but kept the accessible size at zero; this version allocates the space and says that each entry is now valid to access. If you do this, you would not add to the vector, so no pushing. Instead, you could dump the x variable and read directly into the vector entry:
cin >> data[count];
You could also keep x and assign it to data[count], but at that point the push_back approach makes it clearer what is going on.
There are more things that vectors can do; hopefully this is enough to get you started.
Dynamic & Manual
If you cannot use vectors for whatever reason, you might be stuck managing the dynamic memory allocation and de-allocation yourself. The other answer covers this, so I'll just refer you to that one if this is the case.
I'm new to C++ and I have to make a program that lets the user enter a specified number of test scores and calculate the average, highest, and lowest scores. (It doesn't have to check if values are between 1 and 100.) For some reason, when it goes to print out the average score and sum of the scores, it just prints out random exponential numbers that are never the same. I haven't gotten to printing out the lowest and highest scores yet since I'm not sure if I'm even doing the average right. Again, I'm new to C++ so I'm sure I messed something up. Here's the code:
#include <iostream>
using namespace std;
int loopLimit = 0; //number of scores or how many times it will loop
double *testScores = {0}; //array scores are stored in
int main () {
cout << "How many test scores are you entering?" << endl;
cin >> loopLimit;
testScores = new double[loopLimit]; //changes array to needed size
for (int i = 0; i < loopLimit; i++) {
cout << "Enter test score #" << (i + 1) << endl;
cin >> *testScores;
}
double sum = 0.0;
double average = 0.0;
//double max = 0.0; //making these functions later
//double min = 0.0;
sum += testScores[loopLimit];
average = sum / loopLimit;
//Sum is here for testing purposes at the moment
cout << "Sum = " << sum << " Average = " << average << endl;
return 0;
}
Example output 1:
How many test scores are you entering?
3
Enter test score #1
100
Enter test score #2
100
Enter test score #3
100
Sum = 8.29874e-310 Average = 2.76625e-310
Example output 2:
How many test scores are you entering?
3
Enter test score #1
100
Enter test score #2
100
Enter test score #3
100
Sum = 8.94176e-310 Average = 2.98059e-310
Expected output:
How many test scores are you entering?
3
Enter test score #1
100
Enter test score #2
100
Enter test score #3
100
Sum = 300.0 Average = 100.0
I've been at this all week, and I honestly got nothing at this point.
OK, let's go over your code.
#include <iostream>
using namespace std;
Why are you importing all identifiers in std:: here? using namespace std; is not recommended.
int loopLimit = 0; //number of scores or how many times it will loop
double *testScores = {0}; //array scores are stored in
Bad: You should avoid global variables unless they're absolutely necessary. 99.9% of the time they're not. These could easily be local variables in main.
testScores is not an array, it's a pointer. Initializing it with {0} is just a weird way of writing testScores = nullptr;.
int main () {
cout << "How many test scores are you entering?" << endl;
cin >> loopLimit;
testScores = new double[loopLimit]; //changes array to needed size
You're using manual memory management here. Not technically wrong, but it would be much easier and less error prone to use a std::vector instead.
for (int i = 0; i < loopLimit; i++) {
cout << "Enter test score #" << (i + 1) << endl;
cin >> *testScores;
This line stores every input in *testScores, i.e. the location pointed to by testScores, which corresponds to the first index of the array allocated by new above. This means only testScores[0] is initialized (ending up containing the last number the user input), every other index is uninitialized.
You should use cin >> testScores[i] instead.
}
double sum = 0.0;
double average = 0.0;
//double max = 0.0; //making these functions later
//double min = 0.0;
sum += testScores[loopLimit];
This is an invalid memory access. As testScores points to a dynamic array of size loopLimit, the valid array indices go from 0 to loopLimit-1. Therefore testScores[loopLimit] accesses memory past the bounds of the array.
Also, it's just one element you're adding here. Even if this were a valid array index, this could would still make no sense. You should loop over all array elements here (like your for loop above), or just do this part of the calculation in your other loop. In fact, there's no need to store all numbers in memory if all you're interested in is their sum (which you can compute directly as you're reading the input).
average = sum / loopLimit;
average is computed from sum, which has a garbage value, so it's garbage too.
//Sum is here for testing purposes at the moment
cout << "Sum = " << sum << " Average = " << average << endl;
... and this is why you're getting garbage output.
return 0;
Here you're leaking the memory allocated with new. This is not really a problem in this case because your program is about to exit anyway, but in general you want delete[] testScores; here (unless you use a std::vector, which takes care of cleaning up for you).
}
A couple of things, first the line
cin >> *testScores;
is not storing the test scores in an array (I think this is what you want to do) instead at every iteration the new test score is being stored in the first element i.e testScores[0], rewriting the old value.
Next,
The line
sum += testScores[loopLimit];
looks outside the array. This means that you are looking at a random place in memory which probably has junk in it. That explains why you are seeing random numbers outputted.
Try to fix those two issues. If you don't need to save the test scores you can away keep a running sum of them, that would eliminate the need to store everything in an array.
I don't know why you want to write such a messed up code for just calculating average.But here's my approach.
Since you entered loopLimit value as 3.So according to your code,sum will contain have the value of sum[3].That is a garbage value.Since indexing starts with 0 and not 1.So your sum will have a garbage value and that is the reason why you are getting such incorrect value.I have modified your code and it works fine for me.
int loopLimit;
cout << "How many test scores are you entering?" << endl;
cin >> loopLimit;
double scores[loopLimit];
double sum=0.0;
for (int i = 0; i < loopLimit; i++)
{
cout << "Enter test score #" << (i + 1) << endl;
cin >> scores[i];
sum+=scores[i];
}
double avg=sum/loopLimit;
cout << "Sum = " << sum << " Average = " << avg << endl;
return 0;
Try avoiding using pointers during the early stage of programming as it can really mess up with your brain and can create problems.Try to go for a simple approach.
The possible issue is that you're doing this
double* testScores = {0};
which will initialize it to nullptr, potentially letting you read and write garbage data. What you should use instead is probably a dynamic resizing array such as
std::vector<double> testScores;
and to add a score to the list
double inScore = 0;
std::cin >> inScore;
testScores.push_back(inScore); // This adds to the list of scores.
#include <iostream>
using namespace std;
int loopLimit = 0; //number of scores or how many times it will loop
double *testScores = {0}; //array scores are stored in
int main () {
double sum = 0.0;
double average = 0.0;
cout << "How many test scores are you entering?" << endl;
cin >> loopLimit;
testScores = new double[loopLimit]; //changes array to needed size
for (int i = 0; i < loopLimit; i++) {
cout << "Enter test score #" << (i + 1) << endl;
cin >> testScores[i];
sum += testScores[i];
}
average = sum / loopLimit;
cout << "Sum = " << sum << " Average = " << average << endl;
delete [] testScores;
return 0;
}
*melpomene is right...that pointer "testScores" wont increment through your for loop so the array occupies garbage also put sum += testScores[i] in the loop to sum your input.
Hey guys so I just started working with arrays.
Could someone shed some light on this topic please. This was I created, I thought it made sense but I must be missing something.
I get an Debug Error Run-Time Check Failure #2 - S
Type of the Error is the following: Debug Error Run-Time Check Failure #2 - S
#include<iostream>
#include<iomanip>
#include <climits>
//Prototypes:
int lowestAmount(int[]);
int highestAmount(int[]);
using namespace std;
int main() {
const int AMOUNT = 9;
int values[AMOUNT];
int lowest, highest;
cout << "Please Insert 10 Numbers of your Choice: ";
cin >> values[0] >> values[1] >> values[2] >> values[3] >>
values[4] >> values[5] >> values[6] >> values[7] >>
values[8] >> values[9];
cout << endl;
lowest = lowestAmount(values);
highest = highestAmount(values);
cout << "/tThe Lowest out of all of them is: " << lowest <<
endl;
cout << "/tThe Highest out of all of them is: " << highest << endl ;
return 0;
}
int lowestAmount(int val[]) {
int lowest = INT_MAX;
int count = 10;
for (int i = 0; i < count; i++) {
if (val[i] < lowest)
lowest = val[i];
}
return lowest;
}
int highestAmount(int val[]) {
int highest = INT_MIN;
int count = 10;
for (int i = 0; i < count; i++) {
if (val[i] > highest)
highest = val[i];
}
return highest;
}
The code sort of works but not correctly all the time, and I can't figure out what I did wrong? I though I had the logic down??? Could someone shed some light???
Array indices start at zero, which means that the last index is the amount of elements minus one. You want the user to input 10 numbers, and you do read vales[0] up to values[9] but your array doesn't have the room for it.
const int AMOUNT = 9;
int values[AMOUNT];
That means you declare an array big enough for 9 elements, not 10. AMOUNT needs to be 10.
C++ does not automatically do bounds checking. This means that if you write outside of an array, you are going to get unpredictable behaviour, and you cannot even rely on the program always crashing.
There's also a bug in both your higher/lower functions that ignores the last element even as it stands now. Once you fix the array to be for 10 elements, you need to loop until i < 10 after that.
Also in the future, you will get better help by posting specifically what does not work, meaning you should show compiler / debugger errors, not just your code.