Hi folks! Was wondering if you could help with a problem. I'm supposed to write a function that writes n, n-1, n-2, …, 3, 2, 1. I'm pretty sure I've got it but for some reason I keep getting 0 whenever I run it. It doesn't have to be a recursive function but I've been writing it that way. Any help would be awesome. Thanks!

#include <iostream>
using namespace std;

int backwards (int);

void main ()
{
	int key;

	cout << "Enter a positive integer : ";
	cin >> key;

	cout << backwards(key) << endl;
}

int backwards (int n)
{
	if (n==0)
		return 0;
	else
		for (n=1; n>0; n++)
		return (n-1);


}
#include <iostream>
using namespace std;

void backwards(int);

int main() {
	int key;

	cout << "Enter a positive integer : ";
	cin >> key;

	backwards(key);
}

void backwards(int n) {
	if (n<=0)
		return;
	cout << n << ' ';
	backwards(n-1);
}

or

#include <iostream>
using namespace std;

void backwards(int);

int main() {
	int key;

	cout << "Enter a positive integer : ";
	cin >> key;

	backwards(key);
}

void backwards(int n) {
	if (n<=0)
		return;
	for(int i = n; i > 0; --i )
	cout << n-- << ' ';
}
#include <iostream>
using namespace std;

void backwards(int);

int main() {
	int key;

	cout << "Enter a positive integer : ";
	cin >> key;

	backwards(key);
}

void backwards(int n) {
	if (n<=0)
		return;
	cout << n << ' ';
	backwards(n-1);
}

or

#include <iostream>
using namespace std;

void backwards(int);

int main() {
	int key;

	cout << "Enter a positive integer : ";
	cin >> key;

	backwards(key);
}

void backwards(int n) {
	if (n<=0)
		return;
	for(int i = n; i > 0; --i )
	cout << n-- << ' ';
}

Awesome! Thank you so much! :)

awesome is fine .. but i hope you understood your mistake... just taking his code blindly and using it will not help...

FYI you were not using recursion at all !!!

This article has been dead for over six months. Start a new discussion instead.