Function with arrays not working - c++

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;
}
}

Related

Why does my void function don't return the right value? (Newbie to c++) [duplicate]

This question already has answers here:
String 'G' is not showing
(2 answers)
Closed 2 years ago.
As you can see below, my function doesn't return the right value in int main() but it does in the function itself. I'm a newbie to c++, can anyone explain to me why or what's the problem? Thanks!
#include <iostream>
using namespace std;
int a[100],n;
void citire(int n)
{
int a[100];
for(int i = 0 ; i < n ; i ++) { // the for loop
cin >> a[i]; // entering the numbers for each
}
cout << a[5] << endl; // returns the right number
}
int main()
{
cout << "n= "; cin >> n; // how many numbers should the vector have.
citire(n); // me calling the function
cout << a[5]; // returns 0
}
Variable shadowing, where variables in different scopes have the same name. int a[100] inside the function citire is allocated on the stack will not persist when it falls out of scope at the end of the function, it's a different array to the global int a[100].
You have two different variables, a local variable and a global variable, but as you have given both of them the same name, you don't see that difference. Let me show you in a clearer way what you have programmed:
#include <iostream>
using namespace std;
int global_a[100],n;
void citire(int n)
{
int local_a[100];
for(int i = 0 ; i < n ; i ++) { // the for loop
cin >> local_a[i]; // entering the numbers for each
}
cout << local_a[5] << endl; // returns the right number
}
int main()
{
cout << "n= "; cin >> n; // how many numbers should the vector have.
citire(n); // me calling the function
cout << global_a[5]; // returns 0
}
Now, you tell me, where did you store any variable in the array global_a?
In order to avoid this, you might do the following:
#include <iostream>
using namespace std;
int global_a[100],n;
void citire(int n)
{
// int a[100]; don't declare a local variable, so while referring to "a",
// the global variable will be used:
for(int i = 0 ; i < n ; i ++) { // the for loop
cin >> global_a[i]; // entering the numbers for each
}
cout << global_a[5] << endl; // returns the right number
}
int main()
{
cout << "n= "; cin >> n; // how many numbers should the vector have.
citire(n); // me calling the function
cout << global_a[5]; // returns 0
}
For your information, the prefixes "local_" and "global_" are just there for clarification purposes. In the last example, you might just write "a" instead of "global_a", the result will be the same.

Passing value from one function to another C++

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

I'm having trouble in C++ geting input from a user in a function, adding to an array, and printing that array

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;
}
}

No suitable conversion from "vector<string>" to "vector<string>"* exists?

I am writing a program that will receive a text file, read in a list of names from that file, sort those names in alphabetical order, and then print the sorted list back out.
This originally was a project for my "Intro to Programming" class that was to use arrays, but I'm trying to retool it to work with vectors instead, allowing me to use a file of any length instead of a rigid array length.
But Intellisense is giving me an error:
No suitable conversion function from "std::vector<std::string, std::allocator<std::string>>" to "std::vector<std::string, std::allocator<std::string>>*" exists
Any time that I try to pass the filename to a function (ex at displayArray(names, nameQty), I get the error with names). I'm having a hard time googling how to pass a vector to a function, so I think that's where my problem is. The full code is pasted below:
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int readFromFile(string[], string);
void displayArray(vector<string>[], int);
void alphaSort(vector<string>[], int);
void swap(string&, string&);
int main() {
//Declare variables
string fileName;
vector<string>names(1);
int nameQty;
//Prompt for file name
cout << "Please enter the name of the file to read names from: " << endl;
cin >> fileName;
//Call function to open file and read names into a vector array. Function will return the number of names in file
nameQty = readFromFile(names, fileName);
//Display unsorted names
cout << "Unsorted names:" << endl;
displayArray(names, nameQty);
//Sort names into alphabetical order
alphaSort(names, nameQty);
//Display sorted names
cout << "Sorted names:" << endl;
displayArray(names, nameQty);
//More to come after this; program isn't done yet!
}
/*
* Function to read a list from a text file into an array.
* The array starts at size 1, then increments by 1 for each subsequent iteration
* The array then deletes the final element when there is nothing more to read
* (since the last element will be uninitialized)
*/
int readFromFile(vector<string> array, string fileName) {
ifstream inputFile;
inputFile.open(fileName);
if (!inputFile) {
cout << "Invalid file name. Please restart program and try again."
<< endl;
system("pause");
exit(EXIT_FAILURE);
}
else {
int index = 0;
while (inputFile) {
cin >> array[index];
array.push_back;
index++;
}
array.pop_back;
inputFile.close();
return (index + 1);
}
}
//Function to display list of items in array
void displayArray(vector<string> array[], int quantity) {
for (int i = 0; i < quantity; i++)
cout << array[i] << endl;
}
//Selection sort function puts array elements in alphabetical order
void alphaSort(vector<string> names[], int qty) {
for (int j = 0; j < qty - 1; j++) {
for (int i = j + 1; i < qty; i++) {
if (names[j] > names[i]) {
swap(names[j], names[i]);
}
}
}
}
//Function to swap elements a and b in array
void swap(string &a, string &b) {
string temp = a;
a = b;
b = temp;
}
Please don't worry about my using system("pause") and using namespace std. I'm aware that's poor practice, but it's what we've been asked to do in class.
You want:
void displayArray(vector<string>& array, int quantity)
or in this case even better:
void displayArray(const vector<string>& array, int quantity)
In your code it seems you are trying to pass an array of vectors (which is not that straightforward in C++ and boils down to a pointer to a vector in this case). To avoid copying you should use a reference.
You may also be interested to read about move semantics.
Also, as noted in the comments, you may also want to fix readFromFile:
int readFromFile(vector<string>& array, string fileName)
By changing it to a reference the function will modify caller's vector, instead of creating and modifying a local copy.

Sum of positive integers, using functions.

I'm trying to break this problem into function, but my problem is that I always get different sum, positive and negative count when I print out the result.
Can someone give me a hint?
Write a program that reads ten integer numbers and outputs the sum of all the positive numbers among them. The program should ignore all numbers which are less than or equal to 0. The program should also display count of positive numbers and count of negative numbers or zero.
#include <iostream>
using namespace std;
void input(int number, int positiveCount, int negativeCount, int sum);
void output(int positiveCount, int negativeCount, int sum);
int main()
{
int number, positiveCount, negativeCount, sum;
input(number, positiveCount, negativeCount, sum);
output(positiveCount, negativeCount, sum);
return 0;
}
void input(int number, int positiveCount, int negativeCount, int sum)
{
cout << "Enter 10 integers: " << endl;
for (int i = 0; i < 10; i++)
{
cin >> number;
if (number > 0)
{
positiveCount++;
sum = sum + number;
}
else
{
negativeCount++;
}
}
}
void output(int positiveCount, int negativeCount, int sum)
{
cout << sum << endl;
cout << positiveCount << endl;
cout << negativeCount << endl;
}
Your input() function needs to take its arguments by reference so it can modify them. And you need to initialize all those ints to 0 at the start or they contain garbage.
The operations you have done inside input() function is lost because the scope of the variables are only inside the function.
You need to use either pointers or reference while passing the parameters into the input() function so as not to use a local copy.
While using pointers you need to do dereferencing also.
And initialize the variable to 0 before passing to the function.
Because there is serious mistake in your program. You define four local variables in function main() and send them by value when invoking function input(). This function DO NOT modify variables defined in the function main(). It simply modify their copies. These copies is deleted when you're out of function input().
In order to modify them you should use reference:
void input(int &number, int &positiveCount, int &negativeCount, int &sum);
But it has no meaning to create four integers in function main() and to send them in the functions input() and output(). You can create four local variables in input() and then print them in this function. Then you shouldn't define function output() and you can delete it in your code. I.e. you should modify your program.
In your assignment there is written:
Write a program that reads ten integer numbers and outputs the sum of
all the positive numbers among them
So there is no need to write separate functions for this simple program. It can look like
#include <iostream>
int main()
{
const size_t N = 10;
std::cout << "Enter " << N << " integers: ";
size_t i = 0, count = 0;
long long sum = 0;
int num;
for ( ; i < N && std::cin >> num; i++ )
{
if ( num > 0 )
{
sum += num;
++count;
}
}
std::cout << "You have entered " << count << " positive numbers\n"
<< "and " << i - count << " negative numbers or seroes\n"
<< "Sum of positive numbers is " << sum << std::endl;
return 0;
}
If you want to write separate functions then for example function input could be declared as
long long input( size_t &positive_count, size_t &negative_count );
or
long long input( size_t &total_count, size_t &positive_count );
or
long long input( size_t *positive_count, size_t *negative_count );
or
long long input( size_t *total_count, size_t *positive_count );