so I have made a program that works in the following way.
user decides how big the array is.
user then fills the array with x chosen integers, e.g. if they choose to make an array 5 large, they are then asked to fill the array with 5 numbers. However I'm a little stuck on how I can do this, once this bit is done everything else should work I believe as I have tested it by hard coding it with assigned values and the function dose reverse the program.
Here is my code.
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
void reverse(int [], int);
void printarray(int [], int );
void printarray(int arr[], int count)
{
for(int i = 0; i < count; ++i)
cout<<arr[i]<<' ';
cout<<'\n';
}
void reverse(int arr[], int count)
{
int temp;
for (int i = 0; i < count/2; ++i)
{
temp = arr[i];
arr[i] = arr[count-i-1];
arr[count-i-1] = temp;
}
}
int main ()
{
int x;
cout << "how big is this thing " << endl;
cin >>
const int SIZE = x;
int arr [SIZE] = {., ., ., ., ., ., ., . , ., .};
cout<<"Before reverse\n";
printarray(arr, SIZE);
reverse(arr, SIZE);
cout<<"After reverse\n";
printarray(arr, SIZE);
return 0;
}
I do believe that I have to use a for loop or something to repeat and enter the integers into each index of the array, sorry it's been so long since I have done arrays.
Any help with this issue would be greatly appreciated.
You can try the following..
#include <iostream>
#include <string>
void reverse(int arr[], int count)
{
int temp;
for (int i = 0; i < count/2; ++i)
{
temp = arr[i];
arr[i] = arr[count-i-1];
arr[count-i-1] = temp;
}
}
void print_array(int my_array[], int array_size)
{
std::cout << "Your array: ";
for (int x = 0; x <array_size; x++) {
std::cout << my_array[x] << " ";
}
std::cout << std::endl;
}
int main()
{
int array_size;
std::cout << "how big is this thing " << std::endl;
std::cin >> array_size;
int my_array[array_size];
std::cout << "Please enter the elements of the array. Press ENTER after each element." << std::endl;
for (int x = 0; x <array_size; x++) {
std::cin >> my_array[x];
}
print_array(my_array, array_size);
std::cout << "Reverse array..." << std::endl;
reverse(my_array, array_size);
print_array(my_array, array_size);
}
This sounds like a homework exercise? In most cases you would be using something like std::vector but I guess for this you will need to be sticking to native arrays.
int arr[SIZE];
This will create an array on the stack, and the size must be known at compile time. If you don't know the size until runtime you will need allocate the array on the heap using the new keyword (or via something like malloc)
int *arr = new int[x];
You'll need to free this memory yourself once you're done though
delete[] arr;
That should be enough to get you started and point you int right direction. Hope that helps
Cause the size of array is unknown at compile time you can not use int array[SIZE] construct.
You need to allocate the memory at run-time with new:
int x;
cout << "how big is this thing " << endl;
cin >> x;
int *arr = new int[x];
for(int i = 0; i < x; i++) {
cout << "enter arry[" << i << "]" << endl;
cin >> arr[i];
}
cout<<"Before reverse\n";
printarray(arr, SIZE);
reverse(arr, SIZE);
cout<<"After reverse\n";
printarray(arr, SIZE);
delete[] arr;
The delete[] arr operator frees the allocated array. You should free every allocated memory blocks to avoid memory-leaks.
As mentioned from M.M, use std::vector and insert to the beginning of the vector (you don't need you're reverse)
#include <iostream>
#include <vector>
int main(int argc, char** argv)
{
std::vector<int> values;
int n_values;
std::cout << "How mutch numbers ?";
std::cin >> n_values;
std::cout << "Now Enter " << n_values << " Values : ";
for(auto i=0; i<n_values; i++)
{
int tmp;
std::cin >> tmp;
values.insert(values.begin(), tmp);
}
for(auto elem : values)
std::cout << elem << "\n";
return 0;
}
Related
#include <iostream>
#include <array>
#include <algorithm>
void *swap(int arr[], int size);
void *swap(int arr[], int size) {
int i,j,temp;
for(int i{0}; i < size; i++) {
for(int j{i+1}; j < size; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
std::cout <<"The numbers in ascending order are: ";
for(int i{0}; i < size; i++)
std::cout << arr[i] << " ";
}
void average_score(int arr[], int size);
void average_score(int arr[], int size) {
int average {0};
for(int i{0}; i < size; i++) {
average+=arr[i];
}
std::cout << "\nThe average is: " << average / size << std::endl;
}
int main() {
int *test_scores = nullptr;
int n;
std::cout <<"Enter Size: ";
std::cin >> n;
test_scores = new int[n];
int i = 0;
int student_scores;
while(i < n) {
std::cout << "Enter Student " << i+1 << " Test Score: ";
std::cin >> student_scores;
test_scores[i] = student_scores;
i++;
}
swap(test_scores,3);
average_score(test_scores,3);
}
The assignment is also asking me to instead of stepping through the arrays, use pointers rather than array subscripts. I have already created a program where it takes in the test scores and calculates the average and sorts it into ascending order, now I just need to create a display of the student's name right next to their score. Any thoughts or helpful advice that I can use to help me build this program?
In C++ you have a data container called struct that may help you with that. (You can also use classes, but I don't think they are necessary here).
A possible struct for this problem may be declared like this:
struct student {
int grade;
string name;
};
In your main program you could change the test_scores array for a vector, which is more helpful as its size can be modified.
std::vector<student> test_scores(n);
If you want to access the attributes of your student struct you would do so by using the dot operator.
int a = test_scores[0].grade;
string s = test_scores[0].name;
You are given this error because you try to add an int into a student vector. "no matching function call" means that the compiler does not know how to transform the integer into a student. To fix it, I recommend you to ask for the name instead of only asking for the score, so you may add the following code:
student s;
for (int i = 0; i < n; ++i) {
std::cout << "Enter Student " << i+1 << " Name and Test Score: " << endl;
std::cin >> s.name >> s.grade;
test_scores[i] = s; // Don't use test_scores.push_back(s) here, if you do so,
// you would increase its size by 1 and add the element s at the end of the vector.
}
In your average_score function, you should change the int arr[] parameter for a vector <student> &arr and average += arr[i] for average += arr[i].score. The & in &arr is important because it passes the parameter as reference so that its elements are not copied into the function, which is very unnefficient.
Your swap function should be void instead of void *. Also, try using the sort function of the algorithm library. The sorting code you implemented has quadratic cost over the vector length, which is very unefficient if you have a lot of students.
I am trying to input data to an array and then print them by using a function but I am not sure how to organize the code.
#include <iostream>
using namespace std;
void showGrade(double grade[], int size);
int main()
{
double grade[];
int size;
for (int i = 0; i < size; i++)
{
cout << "Please enter the number of grade" << endl;
cin >> size;
}
showGrade(grade, size);
return 0;
}
void showGrade(double grade[], int size) //How many grade we have
{
for (int counter = 0; counter < size; counter++)
{
cout << "Please enter your grades: " << endl;
cin >> grade[counter];
cout << "Here are your grades: " << endl;
}
}
I Expect to see how many grades I input and then show them.
UPDATE 8/28/19
I figured out how to do it in main function successfully. But what I really want is to put them in a seperate function. My new codes have error at the function call which is type name is not allowed and expected a ')'. How do I make it work?
#include <iostream>
using namespace std;
void showGrades(double ar[], int size);
int main()
{
double ar[20];
int size;
showGrades(double ar[size], int size);
system("pause");
return 0;
}
void showGrades(double ar[], int size) {
cout << "Please enter the number of grade "; // array size
cin >> size;
cout << "Please enter your grades " << endl;
for (int i = 0; i < size; i++) {
cin >> ar[i];
}
cout << "The grades you entered are: " << endl;
for (int i = 0; i < size; i++) {
cout << ar[i] << endl;
}
}
First of all, you need to use the standard container
std::vector
instead of the double grade[];, since you want a variable-length
array as per user input.
Secondly, you are using un-initialized size variable in
for (int i = 0; i < size; i++)
hence it will be initialized with a garbage value. There you need no for-loop
A good starting would be:
#include <iostream>
#include <vector> // std::vector
void showGrade(std::vector<double>& grade)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -> pass the vector by ref, as the grades should be inseted to the it
{
// the logic
}
int main()
{
int size;
std::cout << "Please enter the number of grade" << endl;
std::cin >> size;
std::vector<double> grade;
grade.reserve(size); // reserve memory for unwanted re-allocations
showGrade(grade);
return 0;
}
I leave it to you to complete, after reading about the std::vector more.
Also, do not practice with using namespace std;. Read more:
Why is "using namespace std;" considered bad practice?
this is not a valid C++ code:
double grade[];
You can use std::vector:
std::vector<double> grade;
To insert a grade to the vector you can use grade.push_back(someGrade);
The strange problem appears in my program. It is working, but in debugging it shows the "Exception thrown" in random places at the outputting
cout<<"Average value:"<<u3.apr();
_getch();
Sometimes, it even throws this error after the main function (Behind the {})
It is quite annoying because the program just closes after 3 seconds because of these errors.
(Maybe that's because of class, but I'm trying to learn it ;) )
Have tried already changing lines order, rewriting class name and array name.
#include <iostream>
#include <conio.h>
using namespace std;
class vid
{
private:
int i, j;
double rez, sum=0;
public:
int size;
double *arr = new double[size];
double apr()
{
for (i = 0; i < size; i++)
{
sum += (*(arr + i));
}
return sum / size;
}
};
int main()
{
vid u3;
cout << "Enter array length:";
cin >> u3.size;
for (int i = 0; i < u3.size; i++)
{
cout << "Enter array's " << i << " element:" << endl;
cin >> *(u3.arr+i);
}
cout << "Your array:" << endl;
for (int i = 0; i < u3.size; i++)
{
cout << *(u3.arr + i) << "\t";
}
cout << endl;
cout<<"Average value:"<<u3.apr();
_getch();
}
Thanks for any help ;)
arr is initialised when u3 is constructed.
But you didn't populate u3.size until later.
So, your array has indeterminate length (which is already UB), and your accesses later may be invalid.
You're going to have to manage your class's member a bit more cleverly!
Such classes generally have a "resize" function that performs the allocation per the requested size. Don't forget to safely kill any prior allocation, transplanting data if necessary. You can find online plenty of examples of a vector implementation.
Certainly renaming classes and randomly re-ordering the lines of your program's source code is not going to solve anything.
u3.size is not set until after u3 is constructed. By setting u3.size you can avoid this compiler-time error.
It seems that as an alternative solution, you might want to consider how to get rid of the new call and the need to write a destructor that will delete arr.
By creating a constructor that takes a size parameter AND by switching arr to a std::vector, you can allow the class to hold the vector and handle memory allocation and deallocation:
#include <iostream>
#include <vector>
using namespace std;
class vid
{
private:
int i, j;
double rez, sum=0;
public:
int size;
std::vector<double> arr;
// constructor requires size to be passed in;
// constructor initializes the arr array with the passed in size to zeroes.
vid(int argSize) : size(argSize), arr(argSize, 0.0){ }
double apr()
{
for (i = 0; i < size; i++)
{
sum += arr[i];
}
return sum / size;
}
};
int main()
{
uint size;
cout << "Enter array length:";
cin >> size;
vid u3(size);
for (int i = 0; i < u3.size; i++)
{
cout << "Enter array's #" << i << " element:" << endl;
cin >> u3.arr[i];
}
cout << "Your array:" << endl;
for (int i = 0; i < u3.size; i++)
{
cout << u3.arr[i] << "\t";
}
cout << endl;
cout<<"Average value:"<<u3.apr();
char ch;
cin >> ch;
}
I am new to C++. I am trying to solve a problem in the textbook: swap the first and last element in an array. But when I run the code I wrote, nothing happened and even the sentence "Please enter the numbers in the array: " does not show up. Anyone could give some help? Thanks.
#include <iostream>
using namespace std;
int swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
cout << "Please enter the numbers in the array: " << endl;
int input;
cin >> input;
for(int i=0; i<SIZE; i++)
{
test[i] = input;
}
swap(test, SIZE);
cout << test[SIZE] << endl;
return 0;
}
There were a few mistakes:
You should get the input inside the loop and then assign it to the test array.
When printing the swapped value, access the test array with SIZE-1 instead of SIZE, because array indexes run from 0 to SIZE-1, inclusive.
You declared swap() as returning int, but provided no return statement (this suggests that you haven't enabled enough warnings from your compiler).
#include <iostream>
using namespace std;
void swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
int input;
cout << "Please enter the numbers in the array: " << endl;
for(int i=0; i<SIZE; i++)
{
cin >> input;
test[i] = input;
}
swap(test, SIZE);
cout << test[SIZE-1] << endl;
return 0;
}
#include <iostream>
using namespace std;
//Here return type should be void as you are not returning value.
void swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
cout << "Please enter the numbers in the array: " << endl;
//USE LOOP TO TAKE INPUT ONE BY ONE IN AN ARRAY
for(int i = 0; i < SIZE; i++)
cin >> test[i];
swap(test, SIZE);
//USE LOOP TO DISPLAY ELEMENT ONE BY ONE
for(int i = 0; i < SIZE; i++)
cout << test[i] << endl;
return 0;
}
I wrote a program for my assignment that involves pointers and dynamic allocation for an array, I am getting a runtime error and the program crashes, there are no compiling errors. Here is the program :
array.h :
#include <iostream>
using namespace std;
void readArray(float*, int &);
void PrintArray(float*, int);
array.cpp :
#include "array.h"
void readArray(float* array, int &size)
{
array = new float[size];
cout << endl;
cout << "Enter the array elements, use spaces: ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
cout << endl;
}
void PrintArray(float * array, int size)
{
for (int i = 0; i < size; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
main.cpp :
#include "array.h"
int main()
{
int size = 0;
cout << "How many elements would you like to enter? ";
cin >> size;
cout << endl;
float *array = NULL;
readArray(array,size);
cout << "The array size is " << size << endl;
PrintArray(array, size);
return 0;
}
Sample Output :
How many elements would you like to enter? 3
Enter the array elements, use spaces: 4.0 5.0 6.0
The array size is 3
Crashes here
Can someone let me know what the problem is with the PrintArray function?
The parameter array of readArray() is passed by value, so array in main() remains NULL even if you changed it in readArray(). To make it be passed by reference. In addition, size doesn't need be passed by reference.
change
void readArray(float* array, int &size)
to
void readArray(float*& array, int size)
Q: Can someone let me know what the problem is with the PrintArray function?
A: Your PrintArray function is fine.
The problem is that you never pass the array you've allocated outside of readArray.
BETTER:
float *
readArray(int size)
{
float* array = new float[size];
cout << endl;
cout << "Enter the array elements, use spaces: ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
cout << endl;
return array;
}
int main()
...
float *array = readArray(size);
...
NOTES:
If you declared a prototype for readArray() in array.h, you'll need to update it.
There are many ways to accomplish this, but the basic problem is you need ** (a pointer to a pointer) instead of * if you allocate your array inside the function. I believe passing the array pointer back as a function return is arguably the cleanest solution.
IMHO...