Here I have a program that prompts the user to enter size of array, then ask user for integers and calculate average. I'm missing something, the numbers are not being stored into the array.
int n;
int *sizeOfArr;
double total = 0;
double avg;
cout << "Please enter n, for size of array: ";
cin >> n;
sizeOfArr = new int[n]; //dynamically allocates n amount of memory
for (int i = 1; n >= i; i++){
cout << "Enter number " << i << ": ";
cin >> sizeOfArr[n];
if (sizeOfArr[n] < 0){
do{
cout << "Please enter postive number for number " << i << ": ";
cin >> sizeOfArr[n];
} while (sizeOfArr[n] <= 0);
}
total += sizeOfArr[n];
}
avg = total / n; //average formula
cout << "\nAverage of the numbers stored in dynamic array = " << avg << endl; //output
return 0;
system("pause");
Use std::vector instead of dynamic array int*. You do not need to ask the user for size(), you can just dynamically add a variable via std::vector.push_back(). The size can be obtained by calling std::vector.size().
Some mistakes in your Code: Your loop starts int i=1; That's wrong. The first index of the array is 0. Same thing when referencing the vector items: you have to set sizeOfArr[i] not sizeOfArr[n].
Now the point to calculate the mean value:
Your calculation runs with int. If you calculate that way your result will be wrong. You should use double to to so.
Actually it should be sizeOfArr[i-1] instead of sizeOfArr[n]
Your iteration index i starts from 1 but instead array index should start from 0
You're using the wrong variable to index sizeOfArr[] - you should be using the loop variable i as an index. Also, since you're iterating from 1 to n, and not the more usual 0 to n - 1, you need to adjust the index to compensate for this. So, either change all occurrences of:
sizeOfArr[n]
to:
sizeOfArr[i - 1]
or change the for loop to the more canonical form:
for (int i = 0; i < n; ++i)
and then just use:
sizeOfArr[i]
Use sizeOfArr[i] instead of sizeOfArr[n]
Related
i am confused about how does this code flows especially after inputtedin the set of integers.
for example how will the input be stored and then compared to find the largest among the set?
#include <iostream>
using namespace std;
int main()
{
int n, num, max, k=1;
cout << " Enter how many integers " << endl;
cin >> n;
cout << " enter " << n << " integers: "; // where input be stored
cin >> max; // this will input the last number right?
// if i entered 50 55 60 where they will be stored dont i need to store them in in 3 seprate places
while (k<n)
{
cin >> num; // what is the function of this line? from where the input will be
if (num > max)
max = num;
k++;
}
cout << " largest integer is :" << max << endl;
return 0;
}
Let's walk through this.
Let's consider the case the user selects n >= 1. (note also k = 1).
We first need the user to enter one number.
cin >> max;
We say that this number is the max, we don't know if it's true or not but we make this assumption.
We then read in integers while k < n is true.
while (k < n)
{
cin >> num;
if (num > max)
max = num;
k++;
}
So, we read a number into num (which we declared outside the while loop).
We then check if this number is greater than our assumption that the first number was the biggest, if it is we reassign max to be equal to num.
We then increment k.
We do this until we have read in n integers.
Resulting in max being the largest number we entered.
As for storage, we're not needing to store anything, inside the scope of the while loop we can do the check if the number is larger than max or not, if it wasn't we just discard it with the next iteration.
It doesn't store the entire set of numbers read.
It compares each new one entered to the current maximum. The initial maximum value is set to the first number read.
Problem statement of this program will be like : You are given n integers. Now you have to print the largest integer among all these integers.
cin >> max will take only one integer as input. max will hold the value.
cout << " enter " << n << " integers: "; will print this output in the console. For example, if value of n is 2, then this will print: enter 2 integers:
Look in the comment for further details:
#include <iostream>
using namespace std;
int main() {
int n, num, max, k = 1;
cout << " Enter how many integers " << endl; // print
cin >> n; // number of integer to input;
cout << " enter " << n << " integers: "; // print how many integers to enter as input
cin >> max; // input for 1st integer, assume it is the maximum integer
// this while loop will take input of the remaining n-1 intergers
// initially k=1, while loop will run until k is less than n
// while loop will run for n-1 times
while (k < n) {
cin >> num; // input for 1 integer
if (num > max) max = num; // if this input integer 'num' is greater than 'max', then update 'max'
k++; // increment 'k'
}
cout << " largest integer is :" << max << endl; // print the largest integer
return 0;
}
My professor is saying that The while loop runs provided n>=1. But I did not put any value into the variable n so depending on its “default” value, the loop may not be entered. And I'm not sure how to fix what he is talking about!?
#include <iostream>
using namespace std;
int main()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
int n, count;
double sum;
while (n >=1)
{
cout << "Enter a positive integer N (<1 to stop): ";
cin >> n;
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0/count);
cout << "Sum = " << sum << endl;
}
cout << "Bye! ";
return 0;
}
Here is the line where n is declared
int n, count;
In this case the value of n is unspecified as it is left uninitialized. You should initialize it
int n = 1;
If you always want a loop to run at least once then you want a do...while(); loop. It will always enter the loop on the first iteration and execute the loop body then it will check the while condition to determine if it loops again or exits. A do...while(); has the form of
do
{
statements
} while (condition);
In this case it would save you from having to initialize n before you get the input from the user.
In this case though that doesn't seem like exactly what you want as you want nothing to happen if the user enters a number less than 1. One way you can solve that is to put your output and input into the while loop along with the check for n. This will stop anything from happening if the user enters less than 1 but still allowing you to prompt the usr and get the input on each iteration.
while (cout << "Enter a positive integer N (<1 to stop): " && cin >> n && n >= 1)
{
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0 / count);
cout << "Sum = " << sum << endl;
}
The problem is that n has not been initialized. Unlike in other languages like Java or C#, primitive variables do not have any pre-defined "default" value. The simply occupy whatever stack space was there previously; for all intents and purposes, the default value of uninitialized variables can be considered "random".
To fix this, simply initialize the variable before entering the loop.
n = 1;
Set n to a value greater than or equal to 1 so the loop is guaranteed to enter. Since you aren't setting it yourself, the default value can be something less than 1 meaning that the look has a chance, but isn't guaranteed to fire.
int n = 1
Also, you should set count = 0 in your for loop, because if n and count is equal to each other, the for loop automatically breaks and doesn't execute at all, leaving sum at 0.
To make sure your dividing by 0, set count to count + 1.
for (count = 0; count <= n; count++)
sum = sum + (1.0 / (count + 1) );
You need simply to use another kind of loop that is the do-while loop. For example
do
{
cout << "Enter a positive integer N (<1 to stop): ";
cin >> n;
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0/count);
if ( n > 0 ) cout << "Sum = " << sum << endl;
} while ( n > 0 );
cout << "Bye! ";
And instead of the declaration
int n, count;
you should use declaration
unsigned int n, count;
You could else check whether the input is valid. For example
if ( !( cin >> n ) || n == 0 ) break;
Taking this into account you could use also the following kind of loop
while ( true )
{
cout << "Enter a positive integer N (<1 to stop): ";
unsigned int n;
cin >> n;
if ( !( cin >> n ) || n == 0 ) break;
sum = 0;
for (unsigned int count = 1; count <= n; count++)
sum = sum + (1.0/count);
if ( n > 0 ) cout << "Sum = " << sum << endl;
}
cout << "Bye! ";
I've got a small task I need to complete and I'm rather confused. This task has 3 parts to it which are:
Write a program that dynamically allocates a float array of a size specified by a user (currently working on - if anyone could check my code for this it would be appreciated.
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
Program should print what was saved into the array, the sum, and the average value in the array, and exit.
As you could tell I'm new to C++ and coding in general so please spell it out for me wherever possible. It is mandatory that I am using pointers so I'm afraid I can't change that.
#include <iostream>
using namespace std;
int main()
{
int length;
cout << “Please enter the length of the array: “;
cin >> length;
float * dArray = new float [length];
for (int i = 0; i < length; i++)
{
cin >> dArray[i] = i;
for (int i = 0; i < length; i++)
{
cout << dArray[i] << “ “;
}
cout << ‘/n’;
int sum = 0;
for (int i=0; i < length; i++)
{
sum +=dArray[i];
avg =sum/length;
cout << “Sum is “ << sum << “/nAverage is “ << average;
delete [] dArray;
}
return 0;
}
Please explain the 2nd part.
Thanks in advance.
Regarding
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
It means that you have to let the user input the values to that array. What you are doing is giving them values yourself.
What you need to do is change
for (int i = 0; i < length; i++)
{
dArray[i] = i;
}
to
for (int i = 0; i < length; i++)
{
cin>>dArray[i];
}
Also Note that length should be an int and not a float.
After completion, this would probably be the code you need ( although I would advice you to do the part of finding the sum and average by yourself and use this code I have posted as reference to check for any mistake, as finding the sum and average for this is really easy )
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
float sum = 0 , avg; // variables to store sum and average
cout << "Please enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for (int i = 0; i < length; i++)
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
delete[] dArray;
return 0;
}
EDIT
After getting your comment, I decided to post this new code. ( I am assuming what you meant is that the program should repeat as long as the user wants )
I have done it by using a do while loop.
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
char a; // a variable to store the user choice
do
{
float sum = 0 , avg; // variables to store sum and average
cout << "\nPlease enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for ( int i = 0; i < length; i++ )
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++ ) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
cout << "\n\nDo you want to try again ( y/n ) ?\n";
cin >> a;
delete[] dArray;
}while( a =='Y' || a == 'y' ); // The do while loop repeats as long as the character entered is Y or y
return 0;
}
Well, hope this is what you were looking for, if not, please do notify me with a comment... :)
Just so you know, the new code you have posted doesn't even compile. Here are some of the problems.
cin >> dArray[i] = i;
You don't need to use = i here. Just cin >> dArray[i] ; is enough.
The next problem is
cout << ‘/n’;
First of all, its \n and not /n. You also need to enclose it in double quotes and not single quotes. That is cout << "\n";
Next one, you have not defined the variable avg . Also note that you have also used an undefined variable average, which I assume you meant avg.
Now here's one of the main problems , You have not closed the curly brackets you opened. You open the brackets for for loops, but forget to close it. I'm leaving that part to you as you need to learn that part yourself by trying.
Now Here's one problem I don't understand, you have used “ “, which is somehow not the same as " ". I don't know if it's something wrong with my computer, or if it's a totally different symbol. My compiler couldn't recognize it. If its not causing any trouble on your end, then don't mind it.
Well, this sums up the problems I noticed in your code ( the problems that I noticed ).
Your issues are too simple for us to just give you the answers, but I've commented your code with suggestions on how to solve your problem:
#include <iostream>
using namespace std;
int main()
{
float length; //it doesn't make sense for something to be of a float length
//should be size_t instead
cout << "Please enter the length of the array: ";
cin >> length;
float *dArray = new float[length];
for (int i = 0; i < length; i++)
{
dArray[i] = i; //this line is incorrect
//how should we read the data into this array?
//we've used cin before
}
for (int i = 0; i < length; i++)
{
cout << dArray[i] << " ";
}
cout << '\n';
//now we've output the array, just need to output the sum and average value
int sum = 0;
for (int i=0; i < length; i++)
{
sum += //what should go here?
}
int average = //how should we calculate the average?
cout << "Sum is " << sum << "\nAverage is " << average;
delete[] dArray;
return 0;
}
Write a program that asks the user to input the
dimension (n) of the square (n x n) array, and then asks the user to input the values 1 row
at a time. For example:
“Enter the size of a 2D array: ”
“Enter the values in the array for row 1, separated by a space, and press enter: ”
- Limit the size of the array to maximum 10 x 10 and check for errors.
Once the array is initialized, check if there is any negative element in the array and display the result:
If there is no negative value: “All values are non-negative!”
If there are # negative values: “There are # negative values!” … where # is the
number of negative values found.
Example runs:
Enter the size of a 2D array: 4
Enter the values in the array for row 1, separated by a space, and press enter: 1 5 6 3
Enter the values in the array for row 2, separated by a space, and press enter: -5 6 -12 5
Enter the values in the array for row 3, separated by a space, and press enter: 9 4 -3 1
Enter the values in the array for row 4, separated by a space, and press enter: 7 5 -3 9
There are 4 negative values!
Enter the size of a 2D array: 12
ERROR: your array is too large! Enter 1 to 10
Here is what I have so far but I can't figure how to enter the info one row at a time.
Do I enter the values of into two separate arrays then try to combine them? But the values need to stay in their receptive rows.
Thanks
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
cout << "please enter the size of the 2D array" << endl;
cin >> num;
while (num < 1 || num > 10)
{
cout << "You have entered an invalid number that is less than 10"<< endl;
cout << "Enter a new # " << endl;
cin >> num;
}
cout <<"Enter a sequence of numbers separated by spaces" << endl;
int c = 0;
int arr[num][num];
for(int i = 0; i < num; i++)
{
for(int j = 0; j < num; j++)
{
cin >> arr[i][j];
if(arr[i][j] < 0 )
{
c = c+1;
}
}
}
for(int i=0; i < num; i++)
{
for(int j=0; j < num; j++)
{
cout << arr[i][j] << endl;
}
}
cout << c << endl;
return 0;
}
With your code, it is already capable of reading one row of integers each time. In fact you can type in each integer and press enter and then type in the next...and so on. You can also type in a whole row of integers, the program will accept it as long as the count is correct.
For example, if I want to type in a 2x2 array,
I can either type in:
1
2
3
4
or do:
1 2
3 4
It will both work.
A couple of things:
Since the dimension of the array is dynamic, this line isn't valid (see this link for more: http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/):
int arr[num][num];
As such, you need either an array of pointers (which point to arrays), or a vector with which to allocate and manage the memory (given that this is an assignment, you may not be able to use a vector, and will have to use a pointer instead).
Regarding your question:
Do I enter the values of into two separate arrays then try to combine
them?
You don't have to do so.
If you use a pointer (technically: an array of pointers which point to arrays) or a vector, then you should be able to directly access and modify the contents at a particular row and column index.
Example: if you're going the pointer route:
#include <iostream>
#include <cstdlib>
int main() {
std::size_t size;
std::cout << "Enter a dimension: " << std::endl;
std::cin >> size;
int **arr = new int*[size];
//allocate the memory for the columns:
for (int i = 0; i < size; ++i) {
//remember, it's an array of pointers which in turn point to arrays
//so, that's why we have to allocate the memory for each row manually
arr[i] = new int[size];
}
//now you can alter the data in the array:
for (int i = 0; i < size; ++i) {
//the following for loop is how you would prompt the user to enter the value for a specific row:
for (int j = 0; j < size; ++j) {
std::cout << "Enter a value for row " << i << " and column " << j << std::endl;
std::cin >> arr[i][j];
}
}
//now print the entire thing:
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
std::cout << arr[i][j] << " ";
}
//print a new line at the end of each row:
std::cout << std::endl;
}
//free the memory we've allocated:
for (int i = 0; i < size; ++i) {
delete [] arr[i];
}
delete [] arr;
return 0;
}
However, as you've noticed: this has a lot of boilerplate code. If the option is available to you, it's arguably a better idea to use a vector instead.
For more on that discussion, consult these:
When would you use an array rather than a vector/string?
When to use vectors and when to use arrays in C++?
int n;
int *array[8]
cout<<"Enter Number Between 0-9 Only"<<endl;
for(int i = 0; i< 9; i++){
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
array[i] = &n;
else {
cout << "Numbers from 0-9 only\n" << endl;
i--;
}
}
cout << *array[0] << endl;
}
I'm trying to store 9 entered numbers in a pointer array but its not working why?? Can you explain why to me and how to solve it or improve it. I'm just a beginner and its not homework im testing what i had read.
The line
array[i] = &n;
will store the same address in every entry in your array. This is just pointing to n so will always point to that value.
Either define the array as an array of integers
i.e. int array[9];
and then place the value into that array
i.e. array[i] = n;
OR
Allocate some memory off the heap
i.e.
int *array[9];
...
array[i] = new int;
*array[i] = n;
But you will then have to free this memory with delete to avoid a memory leak.
There are several issues here.
You have nowhere to store the values. You have an array of 8 pointers which are all set to point to the same variable n, which is on the stack and so goes out of scope.
The array has 8 elements so the loop goes one past the end
This is C++ so really best not to use C arrays unless you have a justifiable reason to.
I would have something more like *NB not compiled and run)
{
...
std::vector<int> array;
cout<<"Enter Number Between 0-9 Only"<<endl;
for(int i = 0; i< 8; i++){
int n;
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
array.push_back(n);
else {
cout << "Numbers from 0-9 only\n" << endl;
i--;
}
}
cout << array[0] << endl;
}
You are saving a pointer to n in the array, but you constantly change the value of n.
You don't really need to mess with pointers here. Change your array definition, how you populate it, and how you display and you should have better luck.
int array[9];
...
array[i] = n;
...
cout << array[0] << endl;