Recursive Function Homework: Printing N Asterisks

Click For Summary

Discussion Overview

The discussion revolves around the implementation of recursive functions to print a specified number of asterisks in a triangular format, as part of a homework problem. Participants explore various approaches to achieve this without using loops, focusing on the constraints of recursion.

Discussion Character

  • Homework-related
  • Technical explanation
  • Exploratory
  • Debate/contested

Main Points Raised

  • One participant presents an initial recursive function that uses a loop to print asterisks and seeks to modify it to eliminate the loop.
  • Another participant suggests that two recursive functions could be used: one to print lines and another to print asterisks, which aligns with the homework requirements.
  • A different approach is proposed that combines the functionality into a single recursive function, although some participants express reservations about this method.
  • One participant shares their implementation in Eclipse but encounters issues with CodeLab's requirements, leading to discussions about the expected function structure and output format.
  • Clarifications are made regarding the use of return statements in void functions, with suggestions to simplify the code structure.
  • A participant seeks advice on avoiding universal constants in their recursive functions, indicating a desire to adhere to best practices in coding.

Areas of Agreement / Disagreement

Participants generally agree on the need for recursive solutions without loops, but there are multiple competing views on how best to structure the functions. The discussion remains unresolved regarding the optimal approach to implement the required functionality.

Contextual Notes

Some participants express uncertainty about the requirements of the homework problem and the constraints of the provided main function. There are also unresolved issues regarding the proper use of return statements in the context of void functions.

Who May Find This Useful

This discussion may be useful for students learning about recursion in programming, particularly in the context of homework assignments that require specific constraints, as well as for those interested in best practices for writing recursive functions without using global variables or constants.

sandy.bridge
Messages
797
Reaction score
1

Homework Statement


Hey, this isn't really homework, but my professor stated that any loop can be represented by a recursive function. Here is an example I made:

Following is a loop inside of a recursive function. I have it set up such that it takes n asterisks and prints them on a single line; prints a new line; prints n-1 asterisks; stops at n=0.

Code:
void printStars(int n)
{
	if (n > 0)
	{
		for(int i = 0; i < n; i++)
		{
			cout << '*';
		}
		cout << endl;
		return printStars(n-1);
	}
	return;
}

If printStars(5) is called, then
Output:
*****
****
***
**
*

If I get rid of the for loop and attempt the utilize a recursive function for printing that line, the issue I have is that upon printing the line, once a new line is printed, n=0 and the second line cannot be printed. For example:

Code:
void printStars(int n)
{
	
	
        if(n > 0)
	{
		cout << '*';
		return printStars(n-1);
	}
	cout << endl;
		
	
return;
}
What should I be doing such that n reverts back to what it was? Dummy variable?
 
Physics news on Phys.org
Your second version of printStars prints one line of stars and then prints a newline character. As written, this version should be called (in main, typically) once for each line.
 
Hmm, I don't have that option with the second one. The question states that only recursive functions can be used. The only code in the main function (which cannot be edited) is merely calling the function printStarts(n). Also, not supposed to use any loops in the function, only recursive calls to the function.

Edit: this is a practice problem on CodeLab. Our lectures are completed, I'm merely doing practice questions offered on the site.
 
So you need one recursive function that prints a specified number of lines, and another recursive function that prints a star or newline character (i.e., your printStars function). The first function would call printStars for each line that it prints.

Going over what you wrote, since main calls printStars, you'll need to rewrite printStars so that it calls the function that actually prints the stars for one line. I would prefer to have main call something named printLines, and printLines calls printStars, but it looks like you're stuck with what's already in main.

Say there is this line in main:
printStars(5);

Inside printStars you need to call printLine(5), which should print an *, then call itself to print an *, and so on for 5 asterisks, after which it prints a newline character.

The next recursive call to printStars will print a line of 4 asterisks, and the next will print a line of 3 of them, and so on.
 
You can make 2 functions

Code:
void printLine(int n)
{
    if (n > 0)
    {
        cout << '*';
        printLine(n-1);
    }
    else cout << endl;
}

void printStars(int n)
{
	if (n > 0)
	{
		printLine(n);
		printStars(n-1);
	}
}
 
Okay! Wanted to see if it were possible with one recursive function, rather than two. Thanks!
 
Of course it's possible with only one function but I wouldn't recommend it.

Code:
void printStars(int n, int m)
{
    if(m < n)
    {
        cout << '*';
        printStars(n, m+1);
    }
    else if (n > 0)
    {
        cout << endl;
        printStars(n-1, 0);
    }
}
And then you call the function with
printStars(5,0);
 
Alright, so I have this recursive function working properly in eclipse (to my knowledge,) however, CodeLab is telling me that my input is wrong. Perhaps one of you can see where.

Code:
#include <iostream>
using namespace std;

void printStars(int n)
{
	if(n > 0)
	{
		cout << '*';
		return printStars(n - 1);
	}
	cout << endl;
	return;
}

void printTriangle(int n)
{
	if(n > 0)
	{
		printStars(n);
		return printTriangle(n - 1);
	}
	return;
}int main() {
	printTriangle(5);
	return 0;
}

This is my code in eclipse. Console produces:
*****
****
***
**
*Here is what codelab asks of me: Assume the availability of a function named printStars that can be passed a non-negative integer n and print a line of asterisks. Write a function named printTriangle that receives a non-negative integer n and prints a triangle of asterisks as follows: first a line of n asterisks, followed by a line of n-1 asterisks, and then a line of n-2 asterisks, and so on. For example, if the function received 5 it would print:
* * * * *
* * * *
* * *
* *
* The function must not use a loop of any kind (for, while, do-while) to accomplish its job. The function should invoke printStars to accomplish the task of printing a single line. From this, I deduce printStars is already existent, and all I really need is a single recursive function to invoke printStars n times. The code I submitted is:
Code:
void printTriangle(int n)
{
	if(n > 0)
	{
		printStars(n);
		return printTriangle(n - 1);
	}
	return;
}

CodeLab is telling me that its wrong. Ideas?
 
I see two things.
1. The main function you show doesn't agree with what you said in post #3.
sandy.bridge said:
The only code in the main function (which cannot be edited) is merely calling the function printStarts(n).
I'm sure you meant printStars(n). The code in post #8 shows printTriangle in main.
2. A void function does not return a value, so it should not have startements such as "return <whatever>". You can have a bare return statement (i.e., return;). Instead of writing, say,
Code:
return printStars(n - 1);
just write
Code:
printStars(n - 1);
I'm not certain that this is your problem, but at the least, it's flaky and should be changed.
 
  • #10
The question word for word on CodeLab is:
Assume the availability of a function named printStars that can be passed a non-negative integer n and print a line of asterisks. Write a function named printTriangle that receives a non-negative integer n and prints a triangle of asterisks as follows: first a line of n asterisks, followed by a line of n-1 asterisks, and then a line of n-2 asterisks, and so on. For example, if the function received 5 it would print:
* * * * *
* * * *
* * *
* *
* The function must not use a loop of any kind (for, while, do-while) to accomplish its job. The function should invoke printStars to accomplish the task of printing a single line. From this, I deduce that printStars already exists, and all I have to input on CodeLab is the printTriangle function, which calls on printStars to print a single line of n, then n-1, etc, stars. The function that i input on codelab is
Code:
void printTriangle(int n)
{
	if(n > 0)
	{
		printStars(n);
		printTriangle(n - 1);
	}
	return;
}
EDIT: Figured it out; was missing the end line in between the function calls. ie:

Code:
void printTriangle(int n)
{
	if(n > 0)
	{
		printStars(n);
                cout << endl;
		printTriangle(n - 1);
	}
	return;
}
 
Last edited:
  • #11
Hey guys. Looking for a little bit of advice on two simple recursive functions. I have them operating properly, but I have done so utilizing universal constants, which is something I have been told we should not use. Can any of you recommend how I can avoid using them in my code? Thanks in advance!

First recursive function returns a summation of all the elements in an array. One parameter is an array, the other is the size of the array. Here is my code(which functions properly):

Code:
int total = 0;
int sum(int array[], int size)
{

	if (size > 0)
	{
		total += array[size-1];
		sum(array, size-1);
	}
	return total;
}
The next recursive function has a positive integer n as the paramter. It prints n stars, followed by n dollar signs, all on the same line. For example, printStarBucks(4) results in console displaying ****$$$$. My code works properly, but I want to avoid universal constants, which I couldn't seem to figure out. Here is my code:
Code:
int count = 0;
void printStarBucks(int N)
{
	if(N > 0)
	{
		cout << '*';
		count--;
		printStarBucks(n-1);

	}
	if (count < 0)
	{
		cout << '$';
		count++;
		printStarBucks(count);
	}	return;
 
  • #12
Sorry to bump, tomorrow is my final so if anyone can help me with my technique on those last two recursive functions I would greatly appreciate it!
 
  • #13
If by "universal constants", you mean global variables, then I agree that these can and should be avoided. What's wrong with something like this:

Code:
int sum(int* array, int size, int total)
{
    if (size > 0) {
        total += (array[size-1] + sum(array, size-1, total));
    }
    return total;
}

Here, total is a variable local to the sum function, and is passed to it as an argument.

Then in your main program, you would have something like this to call the function:

Code:
result = sum(array, size, 0);

With result, array, and size all defined appropriately, of course. Notice how 0 is passed as the initial value for total.
 
  • #14
For the printStarBucks function, you don't need a separate counter, because n is your counter. Also, you don't need two separate instances of printStarBucks(n-1) within the function. There should only be one call. Hint: when each function returns, it returns back to the function that called it, which can then do something else. :wink:
 
  • #15
Hey! Thanks for the response. The issue that I have with printStarBucks occurs when N gets to zero. I can print N stars, but once I count down N each recursive step, by the time I go to start printing the '$', N is already zero. I can't say if(N < 1) because then the function repeats infinitely.
 
  • #16
sandy.bridge said:
Hey! Thanks for the response. The issue that I have with printStarBucks occurs when N gets to zero. I can print N stars, but once I count down N each recursive step, by the time I go to start printing the '$', N is already zero. I can't say if(N < 1) because then the function repeats infinitely.

Again, as each function returns, it returns to the function that called it, so you get another n iterations for free, if you just do the prints statements in the right order.
 
  • #17
Perfect, thanks!
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 19 ·
Replies
19
Views
3K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 3 ·
Replies
3
Views
8K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
9
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K