How do I return value to main function without directly calling the function - c++

I have multiple functions in my program. Each function has some conditions. If conditions are met, then it passes on the value to another function which again checks the value with some conditions, modifies it.
The first function [named 'squarefree()'] is called from main [obviously] and it further goes on to call another function which in course calls another function untill the process stops at last function named 'end()'. Like this:
#include <iostream>
using namespace std;
int squarefree(int n);
int goodnumber(int sf);
int end(int gn);
int main() {
// your code goes here
int l,r;
cin>>l;
cin>>r;
for(int p=l;p<=r;p++)
{squarefree(p);}
/*int ret=end(int gn); PROBLEM LIES HERE
cout<<ret; */
return 0;
}
int squarefree(int n){
int i;
for(int i=2;i<n;i++)
{
if((n%(i*i))==0)
{
cout<<"number not square free"<<endl;
break;
}
else{
cout<<"number square free"<<endl;
goodnumber(n);
break;
}
}
return 0;
}
int goodnumber(int sf){
cout<<"Sf is:"<<sf<<endl;
int s=0,c=0,flag=0;
for(int j=1;j<=sf;j++)
{
if(sf%j==0)
{
s+=j;
for(int k=2;k<=j/2;++k)
{
if(j%k==0)
{
c++;
}
}
}
}
cout<<"s is:"<<s<<endl;
cout<<"no.of prime numbers dividin s are:"<<c<<endl;
for(int l=2;l<=c/2;++l)
{
if(c%l==0)
{
flag=1;
break;
}
}
if (flag==0)
{cout << "C is a prime number, so this is good number and needs to be passed to next function"<<endl;
end(s);
}
else
{cout << "C is not a prime number"<<endl;
}
return 0;
}
int end(int gn)
{
int sum=0;
sum+=gn;
cout<<"SUm of factors of the good number is:"<<sum<<endl;
return sum;
}
The 'end()' function returns a value sum. Now I want this value sum to be updated everytime the for loop in main() function runs. For example: Sum in first iterations is 5, sum is 2nd iteration is 10, so total sum gets 15 and so on.
If somehow, the value returned by end function can be fetched into main function, that would be great.

Look at all those int-returning functions that are always returning 0. You might be able to take advantage of that.
A trivial example:
#include <iostream>
int step3(int val)
{
return val * val;
}
int step2(int val)
{
return step3(val + 1);
}
int step1(int val)
{
return step2(val * 2);
}
int main()
{
std::cout << step1(1);
}
But take care. You might find a case where you don't get any valid results and need to inform the caller that no result was found.

In addition to the idea of having the functions return the result of the next stage in the pipeline, which is an excellent idea, you can pass the address of the variable in which to store the result (allowing you to return more than one result, or an error code), or store the result of each stage in a temporary variable and return that (allowing you to use a result in more than one computation). I would advise against using a global variable to bypass the stack; it’s considered poor practice.
Some Examples:
// Returning the result of the next stage in the pipeline:
int g(int);
int f(int x)
{
return g(x);
}
// Passing a variable by reference:
enum errcode { success, failure };
errcode sqr( int input, int& output )
{
output = input * input; // This modifies the second variable the caller gave.
return success;
}
// Storing in a temporary variable:
int stage2(int);
int stage1(int x)
{
const int y = stage2(x); // Store the result in a temporary.
const int z = sqr(y);
return z;
}
// Passing results through a global variable is a bad idea:
int necessary_evil = 0; // Declared in global scope; should at least be
// declared static if possible to make it visible only in this source file.
// Namespaces are a fancier way to do something similar.
void kludge(int x)
{
necessary_evil = x * x; // The caller will check the global.
return;
}
There are examples of all of these in the standard library: printf() is essentially a wrapper for vfprintf(), strtol() takes a parameter by reference that the function sets to a pointer to the remainder of the string, and errno is a global variable.

Related

function parameters that are writeable only by the function itself - recursion counter

So I'm trying to write a recursive function that keeps track of how often it got called. Because of its recursive nature I won't be able to define an iterator inside of it (or maybe it's possible via a pointer?), since it would be redefined whenever the function gets called. So i figured I could use a param of the function itself:
int countRecursive(int cancelCondition, int counter = 0)
{
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
Now the problem I'm facing is, that the counter would be writeable by the caller of the function, and I want to avoid that.
Then again, it wouldn't help to declare the counter as a const, right?
Is there a way to restrict the variable's manipulation to the function itself?
Or maybe my approach is deeply flawed in the first place?
The only way I can think of solving this, is to use a kind of "wrapper-function" that keeps track of how often the recursive function got called.
An example of what I want to avoid:
//inside main()
int foo {5};
int countToZero = countRecursive(foo, 10);
//countToZero would be 15 instead of 5
The user using my function should not be able to initially set the counter (in this case to 10).
You can take you function as is, and wrap it. One way I have in mind, which completely encapsulates the wrapping is by making your function a static member of a local class. To demonstrate:
int countRecursive(int cancelCondition)
{
struct hidden {
static int countRecursive(int cancelCondition, int counter = 0) {
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
};
return hidden::countRecursive(cancelCondition);
}
Local classes are a nifty but rarely seen feature of C++. They possess some limitations, but fortunately can have static member functions. No code from outside can ever pass hidden::countRecursive an invalid counter. It's entirely under the control of the countRecursive.
If you can use something else than a free function, I would suggest to use some kind of functor to hold the count, but in case you cant, you may try to use something like this using friendship to do the trick:
#include <memory>
class Counter;
int countRecursive(int cancelCondition, std::unique_ptr<Counter> counter = nullptr);
class Counter {
int count = 0;
private:
friend int countRecursive(int, std::unique_ptr<Counter>);
Counter() = default; // the constructor can only be call within the function
// thus nobody can provide one
};
int countRecursive(int cancelCondition, std::unique_ptr<Counter> c)
{
if (c == nullptr)
c = std::unique_ptr<Counter>(new Counter());
if(cancelCondition > 0)
{
c->count++;
return countRecursive(--cancelCondition, std::move(c));
}
else
{
return c->count;
}
}
int main() {
return countRecursive(12);
}
You can encapsulate the counter:
struct counterRecParam {
counterRecParam(int c) : cancelCondition(c),counter(0) {}
private:
int cancelCondition;
int counter;
friend int countRecursive(counterRecParam);
};
Now the caller cannot modify the counter, and you only need to modify the function slightly:
int countRecursive(counterRecParam crp)
{
if(crp.cancelCondition > 0)
{
--crp.cancelCondition;
++crp.counter;
return countRecursive(crp);
}
else
{
return crp.counter;
}
}
And the implicit conversion lets you call it with an int
counterRecursive(5);
One way to do this is to use a functor. Here's a simple example:
#include <iostream>
class counter
{
public:
unsigned operator()(unsigned m, unsigned n)
{
// increment the count on every iteration
++count;
// rest of the function
if (m == 0)
{
return n + 1;
}
if (n == 0)
{
return operator()(m - 1, 1);
}
return operator()(m - 1, operator()(m, n - 1));
}
std::size_t get_count() const
{
return count;
}
private:
// call count
std::size_t count = 0;
};
int main()
{
auto f = counter();
auto res = f(4, 0);
std::cout << "Result: " << res << "\nNumber of calls: " << f.get_count() << std::endl;
return 0;
}
Output:
Result: 13
Number of calls: 107
Since the count is stored in the object itself, the user cannot overwrite it.
Have you tried using "static" counter variable. Static variables gets initialized just once, and are best candidates to be used as counter variables.

C++ Boolean statement errors (I think)

This program is supposed to ask for an integer, if you want to add or subtract, then another integer, then do the math, but it declares both subtraction and addition as false inputs and i think there are errors in my boolean. Any help is appreciated.
/***********************************************************
Program Name: Simple Math Calculator
Program Author: Kyle NoCompile
Date Created: 9/12/16
Program Description:
This program performs simple arithmetic calculations.
The user enters numbers and the math operation to
perform on those numbers. The program will then display
the result of the operation.
Modified Date:
Modified Description:
***********************************************************/
#include <iostream>
using namespace std;
// Function prototypes:
void showWelcome();
int getUserIntegerInput();
char getMathChoice();
int getInteger(bool);
bool validateMathChoice(char choice);
int doAddition(int int1, int int2);
int doSubtraction(int int1, int int2);
int doMath(int firstInt, int secondInt, char mathFunc);
int showResult();
// This is the main function (where the program begins)
int main()
{
// Variables to hold local data
int firstNum;
int secondNum;
int mathChoice;
int result;
// Call the showWelcome() function
void showWelcome();
// Call the getInteger() function (for the first integer)
// and store the result in the "firstNum" variable
firstNum = getInteger(true);
// Call the getMathChoice() function and store result in "mathChoice" variable
mathChoice = getMathChoice();
// Call validateMathChoice() function, passing it the user's math choice
// and using the return value to decide what to do next
if (validateMathChoice() = true)
{
// Call the getInteger() function (for the second and subsequent integers)
// and store the result in the "secondNum" variable
secondNum = getInteger(false);
// Call the doMath() function and pass it all of the user input
// and store the return value in the "result" variable.
int result = doMath(firstNum,secondNum,mathChoice);
// Call the showResult() function to show the result
int showResult(int result);
}
else
{
// If the user chose an invalid math function...
cout<<"Not a valid math choice"<<endl;
}
return 0;
}
// This function shows a nice welcome message
void showWelcome()
{
cout<<"******************************************"<<endl;
cout<<"Welcome to the simple calculator program!"<<endl;
cout<<"This program will do simple addition and"<<endl;
cout<<"subtraction. Math is fun, so enjoy!"<<endl;
cout<<"******************************************"<<endl;
}
// This function gets integer input from the user
int getUserIntegerInput()
{
int input;
cin>>input;
return input;
}
// This function asks the user for a math function
// and returns the user's input
char getMathChoice()
{
char choice;
cout<<endl<<"Please select a math function to perform (\"+\" = Addition, \"-\" = Subtraction): ";
cin>>choice;
return choice;
}
// this function asks the user for either the first integer
// or the second and returns the user's input
int getInteger(bool firstNum)
{
cout<<endl<<"Please enter the ";
// if the "firstNumber" variable is true, then this
// is the first number being collected
if (firstNum)
{
cout<<"first ";
}
// Otherwise, it's the second number being collected
else
{
cout<<"second ";
}
cout<<"integer: ";
// Call the getUserIntegerInput() function and return the return value from it
return getUserIntegerInput();
}
// This function validates the user's match function choice
// by returning a true for valid, and a false for invalid
bool validateMathChoice(char choice)
{
if (choice == '+' || choice == '-')
{
return true;
}
else
{
return false;
}
}
// This function adds two integers
int doAddition(int firstInt,int secondInt)
{
return firstInt + secondInt;
};
// This function subtracts the second integer
// parameter from the first integer parameter
int doSubtraction(int firstInt, int secondInt)
{
return firstInt - secondInt;
};
// This function determines the result of the math
// operation requested by the user
int doMath(int firstInt, int secondInt, char mathFunc)
{
// Initialize result to zero (0)
int result = 0;
// If the math function is a "+", then call the
// doAddition() function and store the return
// value in the "result" variable
if (mathFunc = '+')
{
result = doAddition(firstInt, secondInt);
return result;
}
// If the math function is a "-", then call the
// doSubtraction() function and store the return
// value in the "result" variable
else (mathFunc = '-');
{
result = doSubtraction(firstInt, secondInt);
return result;
}
return result;
}
// This function displays the result of a math operation
int showResult(int result)
{
cout<<endl<<"The result is "<<result<<endl;
}

replace all negative value from array using recursion C

I want replace all negative value by zero(recursively). And I have use C and recursion. It's was my homework.
Desired output:
0 4 0 3
What I get:
0 4 -9 3
My code:
#include <stdio.h>
int zeros_value(int n, int tab[])
{
if (n==0) return 0;
if(tab[n-1] < 0){
tab[n-1]=0;
}
else{
return zero_value(n-1,tab);
}
}
int main(void)
{
int tab[4] = {0,4,-9,3};
int number = 0;
int i;
zero_value(4, tab);
for(i=0;i<4;i++)
printf("%d ", tab[i]);
return 0;
}
When you hit the first negative, the recursion doesn't continue anymore and the function returns. You don't really need to return any value from the function. You can rewrite it to make a void function.
#include <stdio.h>
void zero_value(int n, int tab[])
{
if (n==0) return;
if(tab[n-1] < 0) tab[n-1]=0;
zero_value(n-1,tab);
}
int main(void)
{
int tab[4] = {0,4,-9,3};
int number = 0;
int i;
zero_value(4, tab);
for(i=0;i<4;i++)
printf("%d ", tab[i]);
return 0;
}
I see the following problems with your code.
The function zero_values does not have a valid return statement when tab[n-1] is negative. You can see it more clearly if you change the function to:
int zeros_value(int n, int tab[])
{
if (n==0)
{
return 0;
}
if(tab[n-1] < 0)
{
tab[n-1]=0;
// No return here.
}
else
{
return zero_value(n-1,tab);
}
// No return here either.
}
Calling such functions leads undefined behavior.
The printf line in main is not right.
printf("%d%d%d%d", zeros_value(4,tab));
That line needs four arguments of type int after the format string to work correctly. Not providing enough arguments to printf is also cause for undefined behavior.
You can use solution provided in the answer by #usr to solve both problems.
If you have any valid reasons to return an int from zero_value, you need to change the implementation appropriately. It's not clear from your post what that return value is supposed to be.

Run time error for dynamic memory allocation in C++

I am a newbie for OOP concepts and while trying to solve Project Euler Problem 7, to find 10001th prime number, I tried to do it using a class but encountered 2 major errors.
instantiating the class prime_n
initializing its argument
I have posted the code here for reference:
#include<iostream>
#include<cstdio>
using namespace std;
class prime_n
{
int j,k;
int n;
int *store;
public:
prime_n(int num)
{
n=num;
store[n];
}
static int isPrime(int j)
{
for(int i=2;i*i<=j;i++)
{
if(j%i==0) return 0;
}
return 1;
}
void find_n()
{
for(int i=0;i<n;i++)
{
store[i]=0;
}
store[0]=2;
j=3;
k=1;
while(store[n-1]==0)
{
if(isPrime(j)) store[k++]=j;
j+=2;
}
}
int get_num()
{
int value=store[n-1];
return value;
}
};
int main()
{
int num, req_num;
printf("Enter the position at which prime number is to be found ");
scanf("%d",&num);
printf("\nnumber = %d",num);
prime_n p = new prime_n(num);
req_num = p.get_num();
printf("The required prime number is %d\n",req_num);
return 0;
}
It would be a great help if someone could help me figure out where I am actually going wrong. Thanks a lot in advance!
Use
prime_n p(num);
or (not recommended in this particular case)
prime_n * p = new prime_n(num);
// some other code
req_num = p->get_num(); // note the -> operator replacing . in case of pointers
delete p;
The first case declares p on stack and it is automatically deallocated when the program leaves the scope (main function in this case)
The second one allocates space on heap and p is the pointer to it. You have to deallocate the memory manually.
As for your second question, the C++ way would be
#include <iostream>
...
int num;
std::cout << "Enter the position at which prime number is to be found "
std::cin >> num;
std::cout << std::endl << "Number = " << num << std::endl;
You provide a constructor:
prime_n(int num)
{
n=num;
store[n];
}
I think you are under the impression that store[n] creates an array with n elements, but that is not so; it attempts to access the (n+1)th element of an an array. Since store does not point anywhere (we are in the constructor, after all), the program crashes.
You probably want to write store = new int[num] instead.
And then I cannot see any call to find_n() originating from get_num() which is called in main(), so that your program would for now just return a random value.

maintaining a recursion count

I'm trying to count the number of calls within a recursive permutation function.
I've written a function that fills a queue with all the permutations but I can't seem to figure out how to maintain an accurate count.
Ultimately i'd like the function to return a subset of the permuatations specified by lbound and ubound arguments, and to do so I think i need someway to keep an internal count.
Using the size of the returned queue will not work since i'd like the function to be able to handle permutations too big to hold in memory.
For this code i'd like the count to be returned as 100.
#include <vector>
#include <iostream>;
using namespace std;
int& Permutations(vector<vector<int>> param, vector<vector<int>> &perm, int index=0)
{
static vector<int> iter;
static int count = 0;
if (index == param.size())
{
perm.push_back(iter); // add permutation to queue
count++;
return count;
}
for (int i=param[index][0]; i<=param[index][1]; i+=param[index][2])
{
if (iter.size() > index) iter[index] = i;
else iter.push_back(i);
Permutations(param, perm, index+1); // recursive function
}
}
void main()
{
vector<vector<int>> params; // vector of parameter vectors
vector<int> param1, param2;
int arr1[3] = {0,9,1}; // range for each parameter vector
int arr2[3] = {0,9,1}; // specified as lbound, ubound, step
param1.insert(param1.end(),arr1,arr1+3);
param2.insert(param2.end(),arr2,arr2+3);
params.push_back(param1);
params.push_back(param2);
vector<vector<int>> queue; // queue of generated permutations
int permcount = Permutations(params,queue);
cout << "the permutation count is " << permcount << endl;
cin.get();
}
Using a static count will not work, because it's not going to ever be reset (and will cause problems if you ever go multi-threaded).
Instead, how about this:
int Permutation(/* params */)
{
int count = 1; // Count ourself
for (whatever)
{
count += Permutation(whatever); // Count cumulative sum from recursion
}
return count;
}
Each call to Permutation() returns the total number of calls that were made below it in the call tree. As we unwind, all the counts from the sub-trees get summed together, to eventually produce the final return value.
int foo(int count,/*Other Params*/) {
/*Calucation*/
if (!terminatingCondition) {
foo(count++,/*Other Params*/);
}
logger.log("foo was called " + count + "times");
return /*calcualtion*/;
}
I'm just trying to answer the question by ignoring your actual algorithm purpose. The two statics should be moved to argument references, or you don't have a good way to reset their values.
void Permutations(vector<vector<int>> param, vector<vector<int>> &perm, vector<int> &iter, int &count, int index=0)
{
++count;
// ...
}