I'm writing two functions: one of them is for "filling" array with random values and int the second function I have to use the same array, choose one row and find the min element of that row.
But the problem is that I don't know how to pass values from one function to another.
Here is my code:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
void fillarray(int arr[5][5], int rows, int cols) {
cout << "Static Array elements = \n\n" << flush;
for(int i = 0; i < rows; ++i) {
cout << "Row " << i << " ";
for(int j = 0; j < cols; ++j) {
arr[i][j] = rand() % 10;
cout << arr[i][j] << " " << flush;
}
cout << endl;
}
cout << " \n\n";
}
void minarray(int a, void fillarray) { // don't know what to write here
there:
int min = INT_MAX; // Value of INT_MAX is 2147483648.
if(a > 4) {
cout << "Invalid input! " << endl;
goto there;
}
for(int counter = 0; counter < 5; ++counter) {
if(arr[a][counter] < min) min = arr[a][counter];
}
cout << "Minimum element is " << min << endl;
}
int main() {
int z;
srand(time(NULL));
const int rows = 5;
const int cols = 5;
int arr[rows][cols];
fillarray(arr, rows, cols);
cout << "Enter the number of row: ";
cin >> z;
minarray(z, fillarray)
system("PAUSE");
}
For starters the function fillarray has redundant parameter cols because this number is known from the declaration of the first parameter int arr[5][5].
Th function can be declared like
void fillarray(int arr[5][5], int rows )
You could supply the parameter cols in case when not the whole array is filled in the function.
You already filled the array by this call
fillarray ( arr, rows, cols );
The function performed its task. So there is no need to reference the function one more time as you are trying
minarray(z, fillarray)
The function minarray can be declared either like
void minarray( const int arr[], size_t n );
and called like
minarray( arr[z], cols );
with a preliminary check that z is less than 5.
Or it can be declared like
void minarray( const int arr[][5], size_t n, size_t row );
and called like
minarray( arr, rows, z );
Pay attention to that there is the standard algorithm std::min_element that allows to find minimum element in an array. And to fill an array with values you can use the standard algorithm std::generate.
And each function should do only one task. For example the function fillarray should silently fill the array with values. To output the array you could write a separate function.
I'm not sure this even compiles, but i'm guessing you want to pass int arr[x][y] from the fill Array function to the minArray function. To do that you first need to include arr as a parameter of minArray. From there you need to pass it by reference. Then, you can call minArray from fillArray.
What you need to do is call fillarray to fill your array. So it would look like
fillarray(arr, rows, cols);
Just like you have so far. Now, you have array arr all filled in. minarray doesn't care how that happened. So don't pass it your filler method. Pass it the array.
minarray(cols, arr[z]);
You don't need to pass the entire array -- just the row in question. You're also passing the width.
And change the definition of minarray:
void minarray(int length, int[] array)
Now, your minarray itself needs changes. First, get rid of the if-check. You don't need to pass a row number now, but you do need the number of columns passed as length.
Then your for loop looks like:
for (int index = 0; index < length; ++index) {
if (array[index] < min) {
min = array[index];
}
}
So, to summarize:
Main declares the data and calls your two methods.
fillarray populates the array. It is called from main the way you already have.
minarray prints the minimum on a single line. It is also called from main, passing in the array, not the method that filled it.
You have one more issue, however. fillarray hardcodes the array size as 5x5, but main uses constants defined. I'd move those contents to the top of the file and use them in both places.
Move to the top, below any #includes:
const int rows = 5;
const int cols = 5;
Define fillarray:
void fillarray(int arr[rows][cols]) {
And when you call it from main:
fillarray(arr);
I'll let the other answers answer your question and concentrate on the code around your goto that you asked about in the comments.
In main you have this:
cout << "Enter the number of row: ";
cin >> z;
minarray(z, fillarray)
In minarray you have this:
void minarray(int a, void fillarray) { // don't know what to write here
there:
int min = INT_MAX; // Value of INT_MAX is 2147483648.
if(a > 4) {
cout << "Invalid input! " << endl;
goto there;
}
First, there's absolutely no reason to use goto. You could do this:
void minarray(int a, void fillarray) { // don't know what to write here
int min = INT_MAX; // Value of INT_MAX is 2147483648.
while(a > 4) { // loop for as long as "a > 4"
cout << "Invalid input! " << endl;
}
Removing the goto made the bug rather apparent. a will never change inside the loop, so it'll just print Invalid input! forever if you give it invalid input. An alternative would be to validate the input when you actually get the input from the user (in main):
while(true) { // loop forever
cout << "Enter the number of row: ";
if(cin >> z) { // check that the user inputs an int
if(z<0 || z>4) // validate the input
cout << "Invalid input!\n";
else
break; // we got valid input, break out of the while loop
} else { // user did not input an int
std::cout << "input failed - aborting\n";
return 1; // return from main to exit the program
}
} // if the program reaches this point, it'll ask the user for input again
// and that will only happen if the user gives it an int that is <0 or >4
Related
This is my code in C++. When I am taking input {11 10 5 6 7} in the array, Every time it's giving output smallest as 0. But giving correct output to the other inputs.
#include<bits/stdc++.h>
using namespace std;
int main() {
int a[100000];
int large, small;
int n;
cin >> n;
for (int j = 0; j < n; j++) {
cin >> a[j];
}
for (int j = 0; j < n; j++) {
cout << a[j] << " ";
}
large = small = a[0];
for (int i = 1; i <= n; i++) {
if (a[i] < small) {
small = a[i];
}
if (a[i] > large) {
large = a[i];
}
}
cout << "Smallest is " << small << endl;
cout << "Largest is " << large << endl;
}
You have three loops, two of them run while i<n and the third one while i<=n. And then it uses a[n] item. How do you think what the value of a[n] is?
You were asking:
What is wrong in my code
Let me first answer this question and then we will refactor and optimize it.
So, let's list up the findings
#include<bits/stdc++.h> is non-compliant C++ code. It should never be used. It will run only on selected compilers
using namespace std; should not be used. Always use fully qualified names
C-Style arrays, like a[100000] should not be used in C++. Always use dedicated C++ containers like std::array or std::vector or others. In your case, the size of the array is determined at runtime. So, std::vector must be used
the “100000” is a magic number. Why 100000? Why not 500?. And what happens if the user enters 200000 as array size. Then the program will most likely crash
Use always meaningful variable names. Something like “n” will not be understood. The variable “arraySize” would be understood.
Variables shall always be initialized. And only defined, where they are used and not in the beginning of the program
Input should be verified (cin >> n). What will happen, if the user enters ‘x’ and not ‘5’. Remember, you do not initialize variable n.
large and small must be initialized with the smallest / largest value that the relevant data type can hold. Otherwise the result will always be wrong
array indices start with 0 and not with 1. So, your for loop will fail. The result will be wrong. And you used <=n. So, you will access an out of bounds value.
No need to use endl with cout. ‘\n’ will be sufficient
Then, from the design point of view. You do not need an array at all. You can make all checks immediately, directly after reading the next value.
Anyway, let us make the first step of refactoring. And ths adopted to your programming style. We will
still use C-Style arrays and dynamically allocate the memory
even use raw pointers for owned memory and new. Please note. This should not be done!
correct the bugs
use INT_MIN and INT_MAX
use meaningful variable names and comments
Please see the first refactoring step:
#include <iostream>
#include <climits>
int main() {
// Get the array size from the user and validate the input
unsigned int arraySize{};
if ((std::cin >> arraySize) and (arraySize > 0u)) {
// Now, allocate the memory for the array
int* const array = new int[arraySize]();
// Read all values from user into the just allocated array
for (unsigned int index = 0; index < arraySize; ++index) {
// Read value and check, if OK. If not, value will be 0
if (not (std::cin >> array[index])) std::cerr << "\nError: Wrong value\n";
}
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = INT_MIN;
int minValueInArray = INT_MAX;
// Iterate over all values and check for min and maximum
for (unsigned int index = 0; index < arraySize; ++index) {
// Compare and assign potential new values
if (array[index] < minValueInArray) minValueInArray = array[index];
if (array[index] > maxValueInArray) maxValueInArray = array[index];
}
// Free the allocated memory. We do not need it any longer
delete [] array;
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading array size\n\n";
}
So, next, let’s go a little bit more into the direction C++.
We will get rid of raw pointers, new and will use the correct limit values.
#include <iostream>
#include <limits>
#include <memory>
int main() {
// Get the array size from the user and validate the input
unsigned int arraySize{};
if ((std::cin >> arraySize) and (arraySize > 0u)) {
// Now, allocate the memory for the array
std::unique_ptr<int[]> array = std::make_unique<int[]>(arraySize);
// Read all values from user into the just allocated array
for (unsigned int index = 0; index < arraySize; ++index) {
// Read value and check, if OK. If not, value will be 0
if (not (std::cin >> array[index])) std::cerr << "\nError: Wrong value\n";
}
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = std::numeric_limits<int>::min();
int minValueInArray = std::numeric_limits<int>::max();
// Iterate over all values and check for min and maximum
for (unsigned int index = 0; index < arraySize; ++index) {
// Compare and assign potential new values
if (array[index] < minValueInArray) minValueInArray = array[index];
if (array[index] > maxValueInArray) maxValueInArray = array[index];
}
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading array size\n\n";
}
A little bit better. Now we get rid of the whole manual memory allocation and use a std::vector, which is by far better. And we will use range based for loops, which will make our life simpler:
#include <iostream>
#include <limits>
#include <vector>
int main() {
// Get the array size from the user and validate the input
unsigned int arraySize{};
if ((std::cin >> arraySize) and (arraySize > 0u)) {
// Now, allocate the memory for the array
std::vector<int> data(arraySize, 0);
// Read all values from user into the just allocated array
for (int& value : data) {
// Read value and check, if OK. If not, value will be 0
if (not (std::cin >> value)) std::cerr << "\nError: Wrong value\n";
}
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = std::numeric_limits<int>::min();
int minValueInArray = std::numeric_limits<int>::max();
// Iterate over all values and check for min and maximum
for (const int& value : data) {
// Compare and assign potential new values
if (value < minValueInArray) minValueInArray = value;
if (value > maxValueInArray) maxValueInArray = value;
}
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading array size\n\n";
}
And last but not least, we will get of the whole array/vector stuff. It is not needed.
#include <iostream>
#include <limits>
int main() {
// Get the number of values to check from the user and validate the input
unsigned int numberOfValues{};
if ((std::cin >> numberOfValues) and (numberOfValues > 0u)) {
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = std::numeric_limits<int>::min();
int minValueInArray = std::numeric_limits<int>::max();
// Read all values from user and check them immediately
for (unsigned int i{}; i<numberOfValues; ++i) {
// Read value and check, if OK. If not, value will be 0
int value{};
if (not (std::cin >> value)) std::cerr << "\nError: Wrong value\n";
// Compare and assign potential new values
if (value < minValueInArray) minValueInArray = value;
if (value > maxValueInArray) maxValueInArray = value;
}
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading number of values\n\n";
}
On the third loop it will be
for(int i=0;i<n;i++)
I started a simple coding project for myself today and I cannot figure out this error or how to combat it. The error I am getting occurs during my do loop. More specifically, it occurs with each function call that passes Nums as a parameter. The error states no suitable constructor exists to convert from to "std::vector<int, std::allocator<int>> [10]" to "std::vector<int, std::allocator<int>>"
Any help on this would be greatly appreciated! TIA!
//This program checks to see if a multiplied vector value is odd or even
//CheckOddEven.cpp
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int setSize(int size, vector <int> Nums) //Sets vector size to user defined size
{
//Prompt user to enter an integer to establish array size
cout << "How many integers would you like to multiply?: ";
//Store user input to size
cin >> size;
//Resize vector to user size
Nums.resize(size);
return size;
}
vector <int> setNum(int size, int x, vector <int> Nums) //Sets values in each index
{
//Insertion loop to Nums vector
for (int i = 0; i < size; i++)
{
cout << "Enter integer #" << i + 1 << ": ";
cin >> x;
Nums.push_back(x); //Assigns value into vector
}
return Nums;
}
int doMath(vector <int> Nums, int result)
{
//Loop through Nums vector and multiply all values
accumulate(Nums.begin(), Nums.end(), result, multiplies<int>());
return result;
}
string oddEven(int result, string msg) //Check if int is even by seeing if there is a remainder
{
//If no remainder exists then positive
if (result % 2 == 0)
{
msg += "positive.";
}
//If remainder exists then negative
else
{
msg += "negative.";
}
return msg;
}
void Display(int result, string msg)
{
cout << "The product of your integers is " << result << endl;
cout << msg;
}
char checkCont(char cont)
{
//Asks user if they want to check another integer
cout << "Would you like to check another? (y/n)" << endl;
//Assigns input as char into cont
cin >> cont;
//Displays exit message and ends do-while
if (cont == 'n' || cont == 'N')
{
cout << "Thank you for using the Odd-Even Checker!" << endl;
cout << "Have a great day!" << endl;
}
return 'z';
}
int main()
{
int size; //User defined vector size
string msg = "The number you calculated is ";
char cont = ' '; //Char value for checking another vector
vector <int> Nums[10]; //Create int vector with predetermined size..can be changed with resize
int x; //User numbers
int result;
cout << "Welcome to the Odd-Even Checker!" << endl;
cout << "This program multiplies a given amount of numbers, then checks to see if the answer is even or odd." << endl;
do //Requires to run at least once
{
setSize(size, Nums);
setNum(size, x, Nums);
doMath(Nums, result);
oddEven(result, msg);
Display(result, msg);
checkCont(cont);
} while (cont == 'y' || cont == 'Y'); //end do-while
return 0;
}
You declared an array of vectors
vector <int> Nums[10];
but passing this array to functions that expects a scalar object of the vector type
int setSize(int size, vector <int> Nums);
//...
setSize(size, Nums);
Maybe instead of the array you mean a vector with 10 elements like
vector <int> Nums(10);
or just an empty vector
vector <int> Nums;
It seems there exists one more problem that you are not passing the vector by reference. So for example the function setSize deals with a copy of the passed vector.
As a result this statement within the function
Nums.resize(size);
does not make a sense.
Change the type of the vector function parameter in functions where it is required to a referenced type like
int setSize(int size, vector <int> &Nums);
^^^^^^
Pay attention that the value of the parameter size is not used within the function, So the parameter size does not make a sense.
Also this function does not make a sense
int doMath(vector <int> Nums, int result)
{
//Loop through Nums vector and multiply all values
accumulate(Nums.begin(), Nums.end(), result, multiplies<int>());
return result;
}
the variable results is not being changed after calling the algorithm std::accumulate.
Also you are passing an uninitialized variable result
int result;
You should at least write
long long int doMath( const std::vector<int> &Nums )
{
//Loop through Nums vector and multiply all values
long long result = std::accumulate(Nums.cbegin(), Nums.cend(), 1ll, std::multiplies<long long>());
return result;
}
You should split your program into small sub-programs and test each used function separately because it seems you do not understand what you are doing. After that you can combain all sub-programs in one program.
For example to test the function setSize you could write a simple program like this
#include <iostream>
#include <vector>
std::vector<int>::size_type setSize( std::vector<int> &Nums )
{
//Prompt user to enter an integer to establish array size
std::cout << "How many integers would you like to multiply?: ";
//Store user input to size
std::vector<int>::size_type size = 0;
std::cin >> size;
//Resize vector to user size
Nums.resize( size );
return size;
}
int main()
{
std::vector<int> Nums;
auto size = setSize( Nums );
if ( size == Nums.size() )
{
std::cout << "The function works correctly.\n";
}
else
{
std::cout << "Something is wrong with the function!\n";
}
return 0;
}
After you will be sure that the function works as expected you can add it to the main program.
I'm learning c++ and I'm trying to ask the user to input 4 numbers in a function, and then simply print the array.
int getFourNums();
int main(int argc, char** argv){
int getNums;
getNums = getFourNums();
cout << "The array is: " getNums << endl;
}
int getFourNums(){
int i;
int myArray[4];
cout << "Enter 4 nums: ";
for(i = 0; i < 4; i++){
cin >> myArray[i];
}
return myArray[i];
As of now, it's letting me get the four numbers, but the result that's printing is "The array is: 0." I'm not quite sure why the array is seemingly not populating.
Your fundamental problem is that int getFourNums() can only return a single integer, not an array of them. The next problem is that functions cannot return raw arrays for historical reasons. Your choices are to return a std::array, a struct containing the array, pass the array by reference into the function, or return a std::vector. My preference for this application is a std::vector - it is flexible, and although not quite as efficient as std::array, you should probably default to std::vector unless you have a good reason otherwise. Your getNums code would then look like:
std::vector<int> getFourNums() {
std::vector<int> result;
cout << "Enter 4 nums: ";
for(int i = 0; i < 4; i++){
int v;
cin >> v;
result.push_back(v);
}
return result;
}
To print the vector, see this question. My personal preference would be a range-based for loop over the vector; your tastes may vary.
One issue in your code is that a loop like
for(i = 0; i < 4; i++){
cin >> myArray[i];
}
will end up with i==4. Hence, return myArray[i] will exceed array bounds and/or access an uninitialised value then and yield undefined behaviour.
The main issue, however, is that in C++ you'll follow a very different approach and use collection types like std::vector instead of plain arrays. See the following code illustrating this. Hope it helps.
#include <vector>
#include <iostream>
std::vector<int> getFourNums(){
int val;
std::vector<int> result;
cout << "Enter 4 nums: ";
for(int i = 0; i < 4; i++){
cin >> val;
result.push_back(val);
}
return result;
}
int main(int argc, char** argv){
std::vector<int> fourNums = getFourNums();
for (auto i : fourNums) {
cout << i << endl;
}
}
int getFourNums() will only let you return one int, not the whole array and return myArray[i]; is out of bounds since i == 4. You can only use the range [0,3] as indices for your array. Here's a reworked version with comments in the code.
#include <iostream>
#include <vector>
// don't do "using namespace std;" since it includes
// a lot of stuff you don't need.
// Here's a function that will return a vector of int's
// It'll behave much like a C style array
// but can have variable length and you can use
// a lot of standard functions on it.
std::vector<int> getNums(size_t count) {
// The "array" we'll return with "count" number of
// default constructed int:s (they will all be 0):
std::vector<int> myArray(count);
std::cout << "Enter " << count << " nums: ";
// A range based for loop that will go through
// all int:s in "myArray". "num" will be
// a reference to each int in the vector which
// means that if you change the value of "num",
// you'll actually change the value in the vector.
for(int& num : myArray) {
// read values into the int currently
// referenced by num
std::cin >> num;
}
// return the vector by value
return myArray;
}
// Put main() last so you don't have to forward declare the functions
// it uses
int main() {
// call getNums with the value 4 to read 4 int:s
std::vector<int> Nums = getNums(4);
std::cout << "The array is:";
// print each int in the vector. There's no need to use
// a reference to the int:s here since we won't be changing
// the value in the vector and copying an int is cheap.
for(int num : Nums) {
std::cout << " " << num;
}
// std::endl is rarely good when you only want to output a newline.
// It'll flush the buffer with is costly.
// Make a habit of using "\n" in most cases.
std::cout << "\n";
}
I see that you want to return entire array but just look at your return type:
int getFourNums()
You're returning an integer right? In this situation the returned integer is always myArray[4]. Be aware that it's an integer value, you're returning something that doesn't belong to you actually!
So what to do? I suggest you to pass your array to function like this:
void getFourNums(int myArray[]){
int i;
cout << "Enter 4 nums: ";
for(i = 0; i < SIZE; i++){
cin >> myArray[i];
}
}
Now you filled your array. How to print your array then? We can't simply give our array name and tell cout to print it like you did (you couldn't actually!). Nothing magical here. We're going to print your array's element one by one:
void printFourNumbers(int array[])
{
for(int i = 0 ; i < SIZE ; ++i)
{
cout << array[i] << endl;
}
}
Finally whole code looks like this:
#include <iostream>
using namespace std;
const int SIZE = 4;
void getFourNums(int myArray[]);
void printFourNumbers(int array[]);
int main(int argc, char** argv){
int myArray[SIZE];
getFourNums(myArray);
printFourNumbers(myArray);
}
void getFourNums(int myArray[]){
int i;
cout << "Enter 4 nums: ";
for(i = 0; i < SIZE; i++){
cin >> myArray[i];
}
}
void printFourNumbers(int array[])
{
for(int i = 0 ; i < SIZE ; ++i)
{
cout << array[i] << endl;
}
}
this is my first time posting on here, and I may not be doing this the right way, sorry in advance.
I am having trouble understanding how to copy two separate one dimensional arrays into one multidimensional array. It is part of my assignment, but I already turned it in and am probably going to lose points in it, but it's ok. As long as I get to understand how it's done, I'd still be happy.
The specific part I am having trouble with is section 5, I got everything else down, maybe it's because its been a long day, but I just can't seem to get it. I will post the whole assignment as well as my code. Thank you for taking the time to read all this if you did.
Write a C++ program that tests the function main and the functions discussed in parts 1 through 7. (Add additional functions, such as printing a two-dimensional array, as needed.).
Consider the following function main:
<code>int main()
{
int inStock[10][4];
int alpha[20];
int beta[20];
int gamma[4] = {11, 13, 15, 17};
int delta[10] = {3, 5, 2, 6, 10, 9, 7, 11, 1, 8};
.
.
.
}</code>
Write the definition of the function setZero that initializes any one-dimensional array of type int to 0 (alpha and beta).
Write the definition of the function inputArray that prompts the user to input 20 numbers and stores the numbers into alpha.
Write the definition of the function doubleArray that initializes the elements of beta to two times the corresponding elements in alpha. Make sure that you prevent the function from modifying the elements of alpha.
Write the definition of the function copyGamma that sets the elements of the first row of inStock from gamma and the remaining rows of inStock to three times the previous row of inStock. Make sure that
you prevent the function from modifying the elements of gamma.
5. Write the definition of the function copyAlphaBeta that stores alpha into the first five rows of inStock and beta into the last five rows of inStock. Make sure that you prevent the function from modifying the
elements of alpha and beta.
Write the definition of the function printArray that prints any one-dimensional array of type int.
Write the definition of the function setInStock that prompts the user to input the elements for the first column of inStock. The function should then set the elements in the remaining columns to two times the
corresponding element in the previous column, minus the corresponding element in delta.
Here is my code:
<code>
#include <iostream>
using namespace std;
int setZero(int alpha[], int beta[]);
int inputArray(int alpha[]);
int doubleArray(const int alpha[], int beta[]);
int copyGamma(const int gamma[], int inStock[][4]);
void copyAlphaBeta(int inStock[][4], const int numberOfRows, const int
alpha[], const int beta[], int numSize);
void printArray(int print[], int n);
int setInStock(int inStock[][4],const int delta[]);
int main()
{
int inStock[10][4];
int alpha[20];
int beta[20];
int gamma[4]={11,13,15,17};
int delta[10]={3,5,2,6,10,9,7,11,1,8};
setZero(alpha, beta);
cout << "Alpha after initialization" << endl;
printArray(alpha, 20);
inputArray(alpha);
cout << "Alpha after reading 20 numbers" << endl;
printArray(alpha, 20);
doubleArray(alpha, beta);
cout << "Beta after a call to doubleArray" << endl;
printArray(beta, 20);
copyGamma(gamma, inStock);
copyAlphaBeta(inStock, 10, alpha, beta, 20);
for (int row=0; row<10;row++)
for (int col=0; col<4; col++)
{
if (col%4==0)
cout << endl;
cout << inStock[row][col] << '\t';
}
cout << endl;
setInStock(inStock, delta);
return 0;
}
int setZero(int alpha[], int beta[])
{
for (int i=0; i<20; i++)
{
alpha[i]=0;
beta[i]=0;
}
cout << endl;
}
int inputArray(int alpha[])
{
cout << endl;
cout << "Enter 20 integers" << endl;
for (int i=0; i<20; i++)
{
cin >> alpha[i];
}
cout << endl;
return 0;
}
int doubleArray(const int alpha[], int beta[])
{
cout << endl;
for (int i=0; i<20; i++)
{
beta[i]=alpha[i]*2;
}
cout << endl;
return 0;
}
int copyGamma(const int gamma[], int inStock[][4])
{
cout << endl;
cout << "inStock after a call to copyGamma" << endl;
for (int row=0;row<10;row++)
for (int column=0;column<4;column++)
{
if (row==0)
inStock[row][column]=gamma[column];
else
inStock[row][column]=3*inStock[row-1][column];
}
cout << endl;
for (int r=0;r<10;r++)
for (int c=0; c<4;c++)
{
if (c==0)
cout << endl;
cout << inStock[r][c] << '\t';
}
cout << endl;
return 0;
}
void copyAlphaBeta(int inStock[][4], const int numberOfRows, const int
alpha[], const int beta[], int numSize)
{
cout << endl;
cout << "inStock after a call to copyAlphaBeta" << endl;
for(int r=0;r<numberOfRows;r++)
{
for(int c=0;c<4;c++)
{
for (int counter=0; counter<numSize; counter++)
{
if(r<5)
{
inStock[r][c]=alpha[counter];
}
else if (r>=5)
{
inStock[r][c]=beta[counter];
}
}
}
}
cout << endl;
}
void printArray(int print[], int n)
{
cout << endl;
for (int i=0;i<n;i++)
cout << print[i] << " ";
cout << endl;
}
int setInStock(int inStock[10][4],const int delta[])
{
int input;
cout << endl;
cout << "Enter 10 integers" << endl;
for (int r=0;r<10;r++)
for (int c=0;c<4;c++)
{
if(c==0)
{
cin >> inStock[r][c];
}
else
inStock[r][c] = 2 * inStock[r][c-1] - delta[r];
}
for (int row=0; row<10;row++)
for (int col=0; col<4; col++)
{
if (col%4==0)
cout << endl;
cout << inStock[row][col] << " ";
}
}
TL;DR - Need help understanding past homework, I just want to know the proper way to do it. Also please critique, looking for ways to improve. Thank you!
Edit:
The problem I have is with this part:
Write the definition of the function copyAlphaBeta that stores alpha into the first five rows of inStock and beta into the last five rows of inStock. Make sure that you prevent the function from modifying the
elements of alpha and beta.
and my code relating to this portion of the question is:
<code>
void copyAlphaBeta(int inStock[][4], const int numberOfRows, const int
alpha[], const int beta[], int numSize)
{
cout << endl;
cout << "inStock after a call to copyAlphaBeta" << endl;
for(int r=0;r<numberOfRows;r++)
{
for(int c=0;c<4;c++)
{
for (int counter=0; counter<numSize; counter++)
{
if(r<5)
{
inStock[r][c]=alpha[counter];
}
else if (r>=5)
{
inStock[r][c]=beta[counter];
}
}
}
}
cout << endl;
}</code>
Thank you for the links, I am not allowed to use vectors at the moment, but I am definitely going to study up on them.
First of all, if you're allowed to use std::vector you should use it. Read up on std::vector here for more details.
Vector provides a dynamically allocated (in the back) chunk of memory that can "expand" and change at runtime depending on adding/deleting elements. You might want to learn to use a vector as they are very useful.
However, you don't really need a vector to do your copying. You can use std::copy to do this for you. More info for it here: std::copy
You can use it to take 3 inputs for your case. First two are the beginning and end pointers, the last input is the starting pointer for the destination. You should be able to figure out what they are for your project.
In your nested for-loops, the last loop is wrong and it will repeatedly put different values of alpha[count] and beta[count] into a same inStock[r][c] element.
You can remove this loop and change the code like
for(int r=0;r<numberOfRows;r++)
{
for(int c=0;c<4;c++)
{
if(r<5)
{
inStock[r][c]=alpha[c]; // assuming size of alpha is 4
}
else if (r>=5)
{
inStock[r][c]=beta[c]; //assuming size of beta is 4
}
}
}
In this code, you have assumed inStock has 4 columns, these 4 columns of each row, are going to be filled with 4 elements of alpha and beta arrays.
I need to make a program with three functions.
The main function should call the second function passing it the array as the first argument and the number of elements in the array as the second argument.
The second function is passed in an array and the number of elements in the array. The function should get 8 names from the user and return the number of names read back to main. Use the return statement to do this.
After the array is filled by the second function, main should then call a third function passing it the array as the first argument and the value returned by the second function as the second argument.
The third function should display the names from the array on separate lines on the computer screen. The third function is passed in an array as the first parameter. The second parameter is the number of elements in the array to be displayed.
The main function has an array of 10 elements. The second function is passed that array of 10 elements but only reads in 8 elements. The number read in by the second function is returned back to main. Main then passes the array and the value returned back from the second function to the third function.
My code up to this point is:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// get the names and store them in the array
int const arraySize(10);
int names = 8;
string array[arraySize];
// send to second function
recievenames(array, arraySize);
// send to third function
displaynames(array, 8);
return 0;
}
int recievenames(string array[], int arraySize)
{
int names = 0;
// Get names.
for (int count = 0; count < 8; count++)
{
cout << "Enter name " << (count + 1) << " of 8: ";
cin >> array[count];
if (count < 8)
{
names++;
}
}
// Display amount of names entered.
cout << names << " received.";
}
void displaynames(string array[], int names)
{
// Display names entered in array.
for (int count = 0; count < names; count++)
{
cout << array[count] << endl;
}
}
For some reason it isn't working can someone tell me why?
you have to do a foward declartion of the function prototypes recievenames() and displaynames() and place them before main() . Then you can define and embody the functions after main.
#include <iostream>
#include <string>
using namespace std;
// declare function prototypes
int recievenames(string array[], int arraySize);
void displaynames(string array[], int names);
int main()
{
// get the names and store them in the array
int const arraySize(10);
int names = 8;
string array[arraySize];
// send to second function
recievenames(array, arraySize);
// send to third function
displaynames(array, 8);
return 0;
}
//define functions
int recievenames(string array[], int arraySize)
{
int names = 0;
// Get names.
for (int count = 0; count < 8; count++)
{
cout << "Enter name " << (count + 1) << " of 8: ";
cin >> array[count];
if (count < 8)
{
names++;
}
return 0;
}
// Display amount of names entered.
cout << names << " received.";
}
void displaynames(string array[], int names)
{
// Display names entered in array.
for (int count = 0; count < names; count++)
{
cout << array[count] << endl;
}
}