You have the following problem in your "collatzMax"-function:
long int collatzMax(long int n){
int max = 0; // max has now the value 0
if (n > max){ // Therefore we do here if (n > 0) and that is always true. N is always greater then 0
max = n; // This assignment will always been done, because the if is always true
// max is now n
}
return max; // The function will always return n
}
Your function is stateless. It does not remember the "old" max value. This will not work. It is anyway not called in your other function. And there it is needed.
If you want to have the max collatz number, then you need to calculate max-values in your main loop.
And, if you have calculated your max number in the main loop, you can return it at the end of the function.
This could then for example look like that:
#include <iostream>
long int writeCollatzSekvens(long int n) { // Changed function prototype. It will return a value now
long int maxNumber = 0;
std::cout << n << " ";
while (n != 1) {
// Continously check for a new max number
if (n > maxNumber) maxNumber = n;
if (n % 2 == 0) {
n = n / 2;
std::cout << n << " ";
}
else {
n = (n * 3) + 1;
std::cout << n << " ";
}
}
return maxNumber; // Return the calculated max collatz number
}
int main() {
long int mn = writeCollatzSekvens(7);
std::cout << "\n\nMax: " << mn << '\n';
}
Of course there are many other potential solutions
EDIT
If the function should be void, then we can add an additional output parameter maxNumber. And pass this parameter by reference or by pointer.
Please see the example below. using pointer:
#include <iostream>
void writeCollatzSekvens(long int n, long int* maxNumber) { // Changed function prototype. Use output pointer for max
*maxNumber = 0;
std::cout << n << " ";
while (n != 1) {
// Continously check for a new max number
if (n > *maxNumber) *maxNumber = n;
if (n % 2 == 0) {
n = n / 2;
std::cout << n << " ";
}
else {
n = (n * 3) + 1;
std::cout << n << " ";
}
}
}
int main() {
long int mn = 0;
writeCollatzSekvens(7, &mn);
std::cout << "\n\nMax: " << mn << '\n';
}
Using reference
#include <iostream>
void writeCollatzSekvens(long int n, long int& maxNumber) { // Changed function prototype. Use output reference for max
maxNumber = 0;
std::cout << n << " ";
while (n != 1) {
// Continously check for a new max number
if (n > maxNumber) maxNumber = n;
if (n % 2 == 0) {
n = n / 2;
std::cout << n << " ";
}
else {
n = (n * 3) + 1;
std::cout << n << " ";
}
}
}
int main() {
long int mn = 0;
writeCollatzSekvens(7, mn);
std::cout << "\n\nMax: " << mn << '\n';
}