A member test using Recursion - c++

I was having trouble understanding recursion. I'm looking for some feedback here to see how this program looks.
Question :::
Write a recursive Boolean function named isMember. The function should accept three parameters: an array of integers, an integer indicating the number of elements in the array, and an integer value to be searched for. The function should return true if the value is found in the array or false if the value is not found. Demonstrate the use of the function in a program that asks the user to enter an array of numbers and a value to be searched for.
What I have::
#include <iostream>
using namespace std;
bool isMember(int[],int,int);
int main()
{
const int SIZE = 10;
int numSearch;
int elementz[SIZE];
for(int i = 0; i < SIZE; i++)
{
cout << "Element " << i + 1 << "\t";
cin >> elementz[i];
}
cout << "Enter element to search\n";
cin >> numSearch;
bool value = isMember(elementz,SIZE,numSearch);
if(value ==1)
cout << "Element is found\n";
else
cout << "Element not found\n";
return 0;
}
bool isMember(int arr[], int sizze, int num)
{
if(arr[sizze] == num)
return true;
else
isMember(arr,sizze -1, num);
}

Your function doesn't return if the if clause is false. Also, keep in mind that indexes start at 0, not 1 (and why sizze?).
I would recommend starting with an array of 3 values, rather than of 10. That way you''ll be able to manually follow and unfold the successive calls.

In order for recursions to work, you need not only a "conditional stop", but an inconditional stop too.
In your example, you only provided a conditional stop. To make it work correctly, try something like this:
bool isMember(int arr[], int sizze, int num)
{
if ( sizze < 0 ) // "inconditional stop"
return false;
if(arr[sizze] == num) // conditional stop. It could happen or not
return true;
else
isMember(arr,sizze -1, num);
}

Related

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

if, else if, else function isn't accurately displaying results

#include <iostream>
using namespace std;
// prototype functions
void DisplayResult(float MaxOrMin);
float FindMinimum(float Array[5]);
float FindMaximum(float Array[5]);
//Global Variables
float Array[5];
float MaxOrMin = 3;
float FindMin;
float FindMax;
//Main Function
int main()
{
cout << "Please enter 5 numbers: " << endl;
for (int i=0; i<5; i++)
{
cin >> Array[i]; // input for array
}
cout << "Please enter '0' for minimum or '9' for maximum:" << endl;
cin >> MaxOrMin; // input 0 or 9 for min or max
//Calling Functions
FindMinimum(Array);
FindMaximum(Array);
DisplayResult(MaxOrMin);
return 0;
}
//Function to find Minimum
float FindMinimum(float Array[5])
{
float FindMin = Array[0];
for (int y=1;y<5;y++)
{
if(Array[y] < FindMin)
FindMin = Array[y];
}
return FindMin;
}
//Function to find Maximum
float FindMaximum(float Array[5])
{
float FindMax = Array[0];
for (int x=1;x<5;x++)
{
if(Array[x] > FindMax)
FindMax = Array[x];
}
return FindMax;
}
This last part is my if, else if, else funtion:
//Function to display minimum or maximum result
void DisplayResult(float MaxOrMin)
{
if (MaxOrMin == 0)
cout << "Minimum is: " << FindMin << endl;
else if (MaxOrMin == 9)
cout << "Maximum is: " << FindMax << endl;
else
cout << "Invalid Input" << endl;
}
My project is to create a program using functions to take user input on a 5 float array. Then find the max and min and display whichever the user asks for.
Here is where my problem comes in. For both max(input 9) and min(input 0) I am getting "0". However any other input correctly returns my "Invalid Input" message.
I'm not getting any errors or warnings or errors at all on eclipse. My professor has told me that my problem was likely with my void function for displaying results. I am hoping someone could point me in the right direction here.
Apologies for my formatting and/or if this question is too basic for this site.
You misunderstand how local and global variables work. Your Find* functions shadow the globals with locals and thus they don't appear to do anything.
The problem is that your FindMinimum() (and the same with FindMaximum()) function compute the minimum (maximum) in a local variable and return it but you, in main() don't receive they in correct variables
So the computed value is lost.
I mean... instead of
FindMinimum(Array);
FindMaximum(Array);
you should write
FindMin = FindMinimum(Array);
FindMax = FindMaximum(Array);

Testing if a number is a Palindrome using different functions (C++)

The code I am using is:
#include <iostream>
using namespace std;
int reverse (int number){
int t = number, m = 0;
do
{
m = m*10 + t%10;
} while(t /= 10);
return m == number;
}
bool isPalindrom(int number){
bool Palindrom = reverse(number);
if(Palindrom == true){
return true;
} else {
return false;
}
return 0;
}
int main()
{
int number;
cout << "Please input a number " << endl;
cin >> number;
if(isPalindrom){
cout << "This is a Palindrom" << endl;
} else {
cout << "This is not a Palindrom" << endl;
}
}
The issue I am having is that isPalindrom is always evaluating to true. I believe it is because I am trying to set this up incorrectly. The program asks us to use the two functions bool isPalindrom(int number) and int reverse(int number). I'm just learning to use functions in C++ so i'm not to sure what I should do. Should I have reverse return the numbers flipped self (m) then in palindrom compare number to m and if it evaluates to true, it will return true. Then in the main check with an if statement to see if isPalindrom is true/false.
You are not calling the function correctly.
if(isPalindrom){
cout << "This is a Palindrom" << endl;
} else {
cout << "This is not a Palindrom" << endl;
}
To call it you have to supply a parameter like this
if (isPalindrom(number)) {
....
In your code isPlanindrom is (I believe, but actually it does not matter if I am right on this point) a function pointer and because it is in the condition of if it gets converted to a bool, which is true always.
PS: I just noticed that I was too fast in writing the answer. I just saw this one problem and didnt look at the rest of the code. It seems like you need to learn about very basics which would be too much to cover here in an answer. My suggestion: Get a book and rtfm :P
In main, you are evaluating the existence of a function called isPalindrom; you aren't actually calling the function. if(isPalindrom){ should become if(isPalindrom(number)){.
You forget to call isPalindrom with an argument. Here's the fix:
#include <iostream>
using namespace std;
bool reverse (int number){
int t = number, m = 0;
do
{
m = m*10 + t%10;
} while(t /= 10);
return m == number;
}
bool isPalindrom(int number){
return reverse(number);
}
int main()
{
int number;
cout << "Please input a number " << endl;
cin >> number;
if(isPalindrom(number)){
cout << "This is a Palindrom" << endl;
} else {
cout << "This is not a Palindrom" << endl;
}
}
I've also:
simplified your isPalindrom() function to a simple return statement;
set the return of reverse from int to bool.
You can try a LiveDemo
Short answer: you forgot to call isPalindrom.
Long answer: isPalindom decays to a nonnull function pointer, and nonnull pointers test true, this you always see the the if branch taken.
Also:
Yes, judging both by the name and the return type, reverse is intended to return the reverse of a number.
And correspondingly, it is the job of isPalindom to do the actual comparisons.
Furthermore, in most cases,
if (boolean) { return true; }
else { return false; }
should be replaced with
return boolean;
Finally, you really ought to be testing whether or not cin succeeded and your input is valid. (e.g. is the user allowed to enter 0? -73? Zero?)

Why do I get the error "Floating point exception"?

I am trying to write a code that finds perfect numbers lower than the user's input.
Sample of correct output:
Enter a positive integer: 100
6 is a perfect number
28 is a perfect number
There are no more perfect numbers less than or equal to 100
But when I run my code, I get the error Floating point exception
and can not figure out why. What am I doing wrong?
Here is my code:
#include <iostream>
using namespace std;
bool isAFactor(int, int);
int main(){
int x, y;
int countOut, countIn;
int userIn;
int perfect = 0;
cout << "Enter a positive integer: ";
cin >> userIn;
for(countOut = 0; countOut < userIn; countOut++){
for(countIn = 1; countIn <= countOut; countIn++){
if(isAFactor(countOut, countIn) == true){
countOut = countOut + perfect;
}
}
if(perfect == countOut){
cout << perfect << " is a perfect number" << endl;
}
perfect++;
}
cout << "There are no more perfect numbers less than or equal to " << userIn << endl;
return 0;
}
bool isAFactor(int inner, int outer){
if(outer % inner == 0){
return true;
}
else{
return false;
}
}
The arguments are just swapped. You are calling the function as isAFactor(countOut, countIn) when you should be calling with isAFactor(countIn, countOut)
To clarify #Aki Suihkonen's comment, when performing:
outer % inner
If inner is zero, you will get a divide by zero error.
This can be traced backward by calling isAFactor(0, 1).
It is in your for loop in main.
The first parameter to isAFactor(countOut, countIn) is assigned in the outermost for loop:
for (countOut = 0; ...
Notice the value you are initializing countOut with.
Edit 1:
Change your `isAFactor` function to:
if (inner == 0)
{
cerr << "Divide by zero.\n";
cerr.flush();
return 0;
}
if (outer % inner ...
Place a breakpoint at either cerr line above.
When the execution stops there, look at the Stack Trace. A good debugger will also allow you to examine the parameter / values at each point in the trace.

C++ Perfect Number With Nested Loops Issue

What I am trying to do is search for a perfect number.
A perfect number is a number that is the sum of all its divisors, such as 6 = 1+2+3.
Basically what I do here is ask for 2 numbers and find a perfect number between those two numbers. I have a function that tests for divisibility and 2 nested loops.
My issue is that I don't get any result. I've revised it & can't seem to find anything wrong. The compiler doesn't shoot out any errors.
What can be wrong?
#include <iostream>
using namespace std;
bool isAFactor(int, int);
int main()
{
int startval;
int endval;
int outer_loop;
int inner_loop;
int perfect_number = 0;
cout << "Enter Starting Number: ";
cin >> startval;
cout << "Enter Ending Number: ";
cin >> endval;
for(outer_loop = startval; outer_loop <= endval; outer_loop++)
{
for(inner_loop = 1; inner_loop <= outer_loop; inner_loop++)
{
if (isAFactor(outer_loop, inner_loop) == true)
{
inner_loop += perfect_number;
}
}
if (perfect_number == outer_loop)
{
cout << perfect_number << " is a perfect number." << endl;
}
else
{
cout << "There is no perfect number." << endl;
}
}
system("PAUSE");
return 0;
}
bool isAFactor(int outer, int inner)
{
if (outer % inner == 0)
{
return true;
}
else
{
return false;
}
inner_loop += perfect_number; should be perfect_number += inner_loop;.
There are other issues -- you need to reset perfect_number to zero in each outer loop, and you should presumably print the message "There is no perfect number." if none of the numbers in range is perfect, rather than printing it once for every number in range that is not perfect.
I'd advise that you rename perfect_number to sum_of_factors, outer_loop to candidate_perfect_number and inner_loop to candidate_factor, or similar.
after the if statement:
cout << perfect_number;
cout << outer_loop;
if (perfect_number == outer_loop)
{
cout << perfect_number << " is a perfect number." << endl;
}
and see what values they have
Updated:
What is the value of your endval? is 0?, and thats why the loop ends so early
Oh, so many issues.
The variable perfect_number never changes. Did your compiler flag
this?
The outer loop will be one more than the ending value when it exits;
did you know this?
You don't need to compare bool values to true or false.
You could simplify the isAFactor function to return (outer %
inner) == 0;.
You could replace the call to isAFactor with the expression
((outer % inner) == 0).