C++ Recursive functions - c++

I'm learning C++ and I have trouble with getting recursion working when a function is called by itself.
#include <iostream>
using namespace std;
int countdown(int y) {
if (y==1) {
return 1 && cout << y << endl;
}
else {
return countdown(y-1);
}
}
int main () {
cout << "Countdown from ten: " << endl;
cout << countdown(10) << endl;
}
Of course there are other ways to achieve this, but really I created this example to verify my own understanding of how functions are called recursively.
In the example I added && cout << y to verify if y is being passed to the function as 1, which always appears to be the case irrespective that I call the function as countdown(10).
Could someone tell me if I'm missing something obvious here please?

Your ' cout << y ' only executes if y has been tested to be one.
This version does what I think you want:
#include <iostream>
using namespace std;
int countdown(int y)
{
cout << y << endl;
if (y==1)
{
return 1;
}
else
{
return countdown(y-1);
}
}
int main()
{
cout << "Countdown from ten: " << endl;
cout << countdown(10) << endl;
}

Your call stack looks like this:
main
countdown(10)
countdown(9)
countdown(8)
countdown(7)
countdown(6)
countdown(5)
countdown(4)
countdown(3)
countdown(2)
countdown(1)
std::cout << 1 << std::endl;
If you want to see the whole countdown, move the output command in front of the if condition.
Also, your style of writing the output is very unidiomatic. Note that it only works because 1 %&& cout converts the cout to bool and bool can be converted to int. Please don't write code like that.

Related

GCD recursion function RTE in some IDEs

Trying to implement gcd int function using Euclidean Algorithm with recursion. Results from CodeBlocks differ from IDEone (which I use to test my code before submitting to a CP website, TLX: https://tlx.toki.id, which I assume has similar compilers etc. because a lot of times IDEone and TLX got RTE while in CodeBlocks it ran without any problem). First Question: 1. Do they actually have something different that affects the output?
My first attempt was as follows:
#include <iostream>
#include <cmath>
using namespace std;
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#define pass (void)0
#include <cstdio>
#include <cstring>
#define ll long long
int gcd(int x, int y){
if(y!=0){
gcd(y, x%y);
//return x%y;
} else {
return x;
}
}
int main() {
cout << "test" << endl;
int z = gcd(100, 10);
cout << z << " bruh" << endl;
cout << "hello" << endl;
}
which IDEone spits out
Runtime error #stdin #stdout 0.01s 5380KB
test
while it ran as expected (z = 1 and prints out the correct stuff) in CodeBlocks
I tried to pinpoint where the error exactly occurs by 1. printing out at what part of the code my computer went error by the following way
void gcd(int x, int y){
if(y!=0){
cout << "if " << x << ", " << y << endl;
gcd(y, x%y);
} else {
cout << "else " << x << ", " << y << endl;
//return x;
}
}
int main() {
cout << "test" << endl;
//int z = gcd(100, 10);
gcd(100, 10);
//cout << z << " bruh" << endl;
cout << "hello" << endl;
}
which in both IDE, it outputted:
test
if 100, 10
else 10, 0
hello
then I also tried:
int gcd(int x, int y){
if(y!=0){
gcd(y, x%y);
//return x%y;
} else {
return x;
}
}
int main() {
cout << "test" << endl;
int z = gcd(100, 10);
cout << z << " bruh" << endl;
cout << "hello" << endl;
}
CodeBlocks outputted the first, while IDEone had an error as in the second
test
10 bruh
hello
Runtime error #stdin #stdout 0.01s 5380KB
test
from what I've tried and understand so far, it seems there's an error when the function gcd() calls the gcd() function. 2. Is my assumption correct? 3. and how am I supposed to solve this problem?
Thanks in advance
The problem is that the recursive case of the gcd() function does not run a return statement. Thus, it should be modified like this:
int gcd(int x, int y){
if(y!=0){
return gcd(y, x%y);
} else {
return x;
}
}
This could easily have been caught by enabling and reading compiler warnings.

Difference in the usage of function prototype with / without pointers

I'm following simple C++ tutorial.
#include <iostream>
using namespace std;
int main()
{
int a = 1, b = 2;
cout << "Before swapping " << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(a,b);
cout << endl;
cout << "After swapping " << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
void swap(int &n1, int &n2)
{
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
The above code works fine (both g++ and icc), but if I were to use pointers in the functions the code fails if I do not include the prototype at the head of the program.
#include <iostream>
using namespace std;
void swap(int*, int*); // The code fails if I comment this line.
int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(&a, &b);
cout << endl;
cout << "After swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
As far as I know, C++ compiling process is top-bottom, so the 2nd code seems more reasonable in which the information of the function is provided before int main() is encountered. My question is, why the 1st code works fine even without the knowledge of function before int main()?
The issue with the first program is you're not actually calling your own swap function. At the top of the file, you have:
using namespace std;
which brings std::swap into scope and that's the function that you're actually calling. If you put a cout statement in your own swap you'll see that it's never actually called. Alternatively, if you declare your swap before main, you'll get an ambiguous call.
Note that this code is not required to behave like this, since iostream doesn't necessarily bring std::swap into scope, in which case you'll get the error that there is no swap to call.
In the second program, the call to swap(&a, &b) fails because there is no overload of std::swap that accepts 2 temporary pointers. If you declare your swap function before the call in main, then it calls your own function.
The real bug in your code is the using namespace std;. Never do that and you'll avoid issues of this nature.
The reason why the first version works is because it doesn't call your swap(...) function at all. The namespace std provides - Edit: depending on the headers you (and the standard headers themselves) include - swap(...) functions for various types and integers are one of them. If you would remove using namespace std you would have to type std::swap(...) to achieve the same effect (same goes for std::cout, std::endl).
That's one reason why using namespace is a double-edged sword for beginners in my opinion but that's another topic.
Your code is fine; but you're right, it fails if you comment on the line you point to.
But actually, as the others tell you, there is a Swap function in c ++, so it doesn't matter if you create a prototype of the function and do it later because the compiler calls its own swap function.
But since swap works for any data type, except for pointers, then you will understand the reason for your problem, since in this case you do have to create your own swap function that accepts pointers as parameters.
Just move your function above main to make it work correctly, nothing more:
#include <iostream>
using namespace std;
//void swap(int*, int*); // The code fails if I comment this line.
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(&a, &b);
cout << endl;
cout << "After swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

Statement cannot resolve address of overloaded function C++ indicators

Statement cannot resolve address of overloaded function.
I try to learn indicators in C++, how to make it work?
#include <iostream>
using namespace std;
int XD = 330;
int *iks;
int main()
{
iks = &XD;
cout << "Hello" << endl;
cout << iks; << endl;
cout << *iks; << endl;
return 0;
}
You have unnecessary semicolon in lines 13 & 14, should be:
cout << iks << endl;
cout << *iks << endl;
And, by the way, the thing you call indicators are really called pointers in English.

int function parameter not working properly

I'm trying to make something in C++ and I have a problem. I have this code:
#include <iostream>
#include <string>
//---MAIN---
using namespace std;
int af1 = 1;
int af2 = 1;
void lettersort(int cnt1) {
cout << "RESULT:" << cnt1 << endl;
cnt1++;
cout << "RESULT WHEN+:" << cnt1 << endl;
cout << "RESULT IN GLOBAL INT:" << af2 << endl;
}
int main()
{
lettersort(af2);
return 0;
}
So is there any way so that cnt1++ affects af2 too, to make it bigger ? I don't want to use af2++ directly because I want to sometimes use af1.
At the moment you are just passing af2 to cnt1 by value, so any changes to cnt1 are strictly local to the function lettersort. In order to get the behaviour you want you need to pass your cnt1 parameter by reference. Change:
void lettersort(int cnt1)
to:
void lettersort(int &cnt1)
You are passing the argument by value. I.e., you are copying the value of af1 to a local variable in lettersort. This integer is then incremented, and disposed of when the function ends, without affecting the original af1. If you want the function to be able to affect af1, you should pass the argument by reference:
void lettersort(int& cnt1) { // Note the "&"
if i understood your question:
there are 2 ways you can do that.
make lettersort function return the new value, and put it in af2
int lettersort(int cnt1) {
cout << "RESULT:" << cnt1 << endl;
cnt1++;
cout << "RESULT WHEN+:" << cnt1 << endl;
cout << "RESULT IN GLOBAL INT:" << af2 << endl;
return cnt1;
}
int main()
{
af2 = lettersort(af2);
return 0;
}
pass the value by reference. you can read about it here, but generally its about passing a pointer to that value. meaning whatever you do on the argument you are passing, will happen on the original var.
example:
void foo(int &y) // y is now a reference
{
using namespace std;
cout << "y = " << y << endl;
y = 6;
cout << "y = " << y << endl;
} // y is destroyed here
int main()
{
int x = 5;
cout << "x = " << x << endl;
foo(x);
cout << "x = " << x << endl;
return 0;
}
here you have to just modified the argument pass to lettersort
function as passed by reference.
for example if you declare and initialize any variable like:
int a=10; int &b = a;
now a and b refer to the same value.if you change a then the changes
also reflect in b also.
so,
cout << a; cout << b;
both statement produce the same result across the program. so using
this concept i modified the function argument and made it as by
reference.
your correct code is :
#include <iostream>
#include <string>
using namespace std;
int af1 = 1;
int af2 = 1;
void lettersort(int &cnt1) {
cout << "RESULT:" << cnt1 << endl;
cnt1++;
cout << "RESULT WHEN+:" << cnt1 << endl;
cout << "RESULT IN GLOBAL INT:" << af2 << endl;
}
int main()
{
lettersort(af2);
return 0;
}

Is assigning a value while using it valid c++?

I had a boolean that needs to be flipped each time its used, since the code was rather simple every other line was me flipping the boolean. I fiddled around a little and came up with this (even more simplified example)
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
bool flippy = 0;
cout << (flippy = !flippy) << "\n";
cout << (flippy = !flippy) << "\n";
cout << (flippy = !flippy) << "\n";
cout << (flippy = !flippy) << "\n";
system("PAUSE");
return 0;
}
It produces 1 0 1 0 as expected but looks a bit odd, is this valid use of the language?
Yes it is valid.
It is not exactlly something I would call good style.
Your code is of course valid. You can also use a bitset as the following example.
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
bitset<1> myBit;
cout << myBit << endl;
cout << myBit.flip() << endl;
cout << myBit.flip() << endl;
cout << myBit.flip() << endl;
}