C++ Calling - search function - c++

I was wondering how I could finish up this program. It's to perform a linear search on a list "ll" (which length is 31) for the user inputted item it, returning the user inputted numbers and their locations if they're found.
Problem: I'm not sure how to call the functions in this specific scenario, I don't really need to use pointers or pass a value, so the lack of these actually makes it more confusing for me, as those are fairly common scenarios.
#include <iostream> //enables usage of cin and cout
#include <cstring>
using namespace std;
int search (int i, int it, int ll, int z);
int printit (int i, int it, int ll, int z);
int main ()
{
int i,it,z;
int ll[] = {2,3,4,5,6,2,3,44,5,3,5,3,4,7,8,99,6,5,7,56,5,66,44,34,23,11,32,54,664,432,111}; //array hardwired with numbers
//call to search
return 0;
}
int search (int i, int it, int ll, int z)
{
cout << "Enter the item you want to find: "; //user query
cin >> it; //"scan"
for(i=0;i<31;i++) //search
{
if(it==ll[i])
{
//call to printit
}
}
return 0;
}
int printit (int i, int it, int ll, int z)
{
cout << "Item is found at location " << i+1 << endl;
return 0;
}

There is a problem with each of the parameters to search:
i's passed value gets overwritten before it gets used, and thus should be a local variable
Same thing for it
ll should be an array of ints
z isn't used at all
Things are even worse for printit: 3 of the 4 parameters are ignored.

Search and print don't need to return int, if you have already print out the results. Also some declared variables are useless. The following code would work:
#include <iostream> //enables usage of cin and cout
#include <cstring>
using namespace std;
void search (int ll[]);
void printit (int n);
int main ()
{
// int i,it,z;
int ll[] = {2,3,4,5,6,2,3,44,5,3,5,3,4,7,8,99,6,5,7,56,5,66,44,34,23,11,32,54,664,432,111}; //array hardwired with numbers
//call to search
search(ll);
return 0;
}
void search (int ll[])
{
cout << "Enter the item you want to find: "; //user query
cin >> it; //"scan"
for(i=0;i<31;i++) //search
{
if(it==ll[i])
{
//call to printit
printit(i);
}
}
// return 0;
}
void printit (int n)
{
cout << "Item is found at location " << n+1 << endl;
// return 0;
}

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

Array Issue & Returning Functions

So I'm new to C++ and am writing a program to calculate the mean, median, standard deviation, min, and max of a program. The issues I'm having are that I don't know how to correctly call functions from other files in the project, and when I try to print(c out <<) my array, it returns a weird value like 0 x 0017 c 530 (disregard the spaces). If anyone could help me correctly return these functions, and print the list correctly, I would be very grateful! Here's my code (not including the .h file):
#include <iostream>
using namespace std;
#include "stats.h"
int main()
{
double nums[10000] = {};
int n;
cout << "Enter number of values: ";
cin >> n;
for (int i = 1; i <=n; i++) {
cout << "Enter number " << i << ": ";
cin >> nums[i-1];
}
// me trying to print the nu ms list
cout << nums << endl;
// me trying to call the function
double mean(double nums[], int n);
return 0;
}
stats. cpp
#include "stats.h"
double mean(double nums[], int n)
{
double sum = 0;
double average;
for (int i = 0; i > n; i++) {
sum += nums[i];
}
average = sum / n;
return average;
}
Instead of
cout << nums << endl;
Just like you have a loop to enter one value at a time in an array, you also need a similar loop to print one value at a time from the array.
To call a function from another translation unit, you would typically declare the function in a header file, your stats.h would be an excellent candidate:
double mean(double nums[], int n);
And then just invoke it from your main:
std::cout << mean(nums, n) << std::endl;
That's it.
Also:
using namespace std;
You need to have someone help you to get an amnesia, and completely forget that C++ has anything like this. This is bad programming practice.
double mean(double nums[], int n); is declaration of function, not invoking of function. You should
double mean_value = mean(nums, n);
cout << mean_value << endl;
And cout << nums << endl; won't print out the elements of the array, just the address of the array. You need to loop the array to print out all the elements.

creating a sum function for summing only part of a vector

Obviously I need a sum function for this and accumulate will not cut it
I need to create program - a vector - with n number of elements the user can prescribe - and the sum function can only sum POSITIVE elements even though the user can enter negative elements as well...
In the computeSum function I also need to add a "success" to the whole group
computeSum (dataVec, howMany, total, sucess);
and create a parameter for people who enter - all negative numbers but want to sum them but are unable to because there are no positive numbers
if (success) {
cout << "The sum is " << total << endl;
}
else {
cerr << "Oops, you cannot add these elements.";
}
So here is what I got
#include <iostream>
#include <vector> // need this in order to use vectors in the program
using namespace std;
int main()
{
vector<double> dataVec;
double i, n, howMany, total;
cout << "How many numbers would you like to put into the vector?";
cin >> n;
dataVec.resize(n);
for(vector<double>::size_type i=0;i < n;i++)
{
cout << "Enter the numbers: \n";
cin >> dataVec[i];
}
cout << "How many POSITIVE numbers would you like to sum?";
cin >> howMany;
cout << computeSum (dataVec, howMany, total);
}
double computeSum (vector<double> &Vec, howMany, total)
{
double total =0;
for(int i=0;i < howMany;i++)
total+=Vec[i];
return total;
}
I also seem to having trouble compiling just this - computeSum() is not being understood in int main(); howMany is not being understood in computerSum(); and on a gloabl scope total() and howMany() are undeclared (I guess that would mean i would need to decalre globally???)
In fact, accumulate will “cut it”, with an appropriate functor that only regards positive values:
int sum_positive(int first, int second) {
return first + (second > 0 ? second : 0);
}
…
std::accumulate(data.begin(), data.begin() + how_many, 0, sum_positive);
Getting on my hobby horse: Boost Range Adaptors. Hits the sweet point with me
#include <boost/range/adaptors.hpp>
#include <boost/range/numeric.hpp>
bool isnatural(int i) { return i>=0; }
using namespace boost::adaptors;
int main(int argc, char** args)
{
static const int data[] = { -130, -1543, 4018, 5542, -4389, 15266, };
std::cout << "sum: " << boost::accumulate(data | filtered(isnatural), 0) << std::endl;
return 0;
}
Output:
sum: 24826
With C++11 awesomeness1 spice:
std::cout << "sum: " << boost::accumulate(data
| filtered([] (int i) { return i>=0; }), 0) << std::endl;
1: to be honest, I really hate the clumsyness of lambda syntax:
having to specify the parameter type always
having to spell out the return statement to
For this scenario, it seems to that filtered([] (i) { i>=0 })
could be figured out by the compiler. Well, perhaps in c++22 :)
Your computeSum() function must appear above your main() function in the source file for it to be in scope. Also in your computeSum() function signature you haven't given types to the howMany and total variables. I'm guessing they should be double howMany and double total?

How can I get rid of fixed sentinel value (-32767)?

Below is the program I wrote to find sum of a subarray from given array, however somehow I am not getting how can I get rid of the sentinel value (-32767 in this case)? and how can I optimise it?
and how can I keep track of range of max subarray?
#define EVALUE -32767
using namespace std;
int findMaxSubArray(vector<int>,int low,int high);
int findMaxSubArray_Mid(vector<int>,int low,int high);
int main()
{
vector<int> v;
int j=0;
cout << "Enter array values(-32767 to end): ";
while(1)
{
cin >> j;
if (EVALUE==j)
break;
v.push_back(j);
}
if(v.size()!=0)
cout << "Max sum is: " << findMaxSubArray(v,0,v.size()-1) << "\n";
else
cout << "No array elements entered, exiting...\n";
system("pause");
return 0;
}
int findMaxSubArray(vector<int> v, int low, int high)
{
if(low==high) return v[low];
int max_mid_sum=findMaxSubArray_Mid(v,low,high);
int max_left_sum=findMaxSubArray(v,low,(low+high)/2);
int max_right_sum=findMaxSubArray(v,(low+high)/2+1,high);
if (max_mid_sum>max_left_sum) return (max_mid_sum>max_right_sum?max_mid_sum:max_right_sum);
else return(max_left_sum>max_right_sum?max_left_sum:max_right_sum);
}
int findMaxSubArray_Mid(vector<int> v,int low,int high)
{
int mid=high/2;
int max_left_sum=0;
int max_right_sum=0;
int sum=0;
for(int i=mid;i>=low;--i)
{
sum+=v[i];
if(sum>max_left_sum)
{
max_left_sum=sum;
}
}
sum=0;
for(int i=mid+1;i<=high;++i)
{
sum+=v[i];
if(sum>max_right_sum)
{
max_right_sum=sum;
}
}
return (max_right_sum+max_left_sum);
}
When reading from a textfile, the last character that cin will get is the "EOF" character, or end of file character. You can send this character to your program in the command line with control+d. You're going to want to check for this rather than -32767.
This is a basic program that should identify a simple fix for your problem:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> v;
int j;
cout << "Enter array values (Control+D (EOF) to end): ";
cin >> j;
while(cin.good())
{
v.push_back(j);
cin >> j;
}
return 0;
}
If you want to get really smart you can use the below and it will directly insert the contents of the memory at cin (from the beginning until EOF) into your vector. As far as running time goes, this will probably be faster than your solution and the above solution.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<int> v;
cout << "Enter array values (Control+D (EOF) to end): ";
istream_iterator<int> in(cin);
istream_iterator<int> eof;
copy(in, eof, back_inserter(v));
ostream_iterator<int> out(cout, "\n");
copy(v.begin(), v.end(), out);
return 0;
}
About the sentinel, IIRC with Control+D you close standard input(may depend of OS). That will cause the << to fail (I am not sure how, probably you'll have to catch an exception).
Anyway, the rest of the code is just a recursive (binomial) adding of the vector. You can sustitute all of it with a simple for
for(int i = 0; i < v.size(); i++) {
total += v[i]
}
The question about range of max subarray is already managed by the class Vector