SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Recursion
Exercise:
Self-test Exercises
Question:2 | ISBN:9780321531346 | Edition: 7

Question

Write a recursive void function that has one parameter which is a positive

integer and that writes out that number of asterisks '*' to the screen all

on one line.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Recursive function definition:

//Recursive function of printAsterisks:
//It takes  one parameter which is a positive integer and
//that writes out that number  of asterisks '*'. 
//This astrisks display to the screen all
//on one line.
void  printAsterisks(int numOfAsterisks)
{
    cout << '*';
    if (numOfAsterisks > 1)
     printAsterisks(numOfAsterisks-1);
}

Complete program by using above given recursive function:

//Header section
#include <iostream>
using namespace std;
//Function prototype
void printAsterisks(int n);

//main program
int main( )

{
    //Call the method
    printAsterisks(10);
    return 0;
}


//Recursive function of printAsterisks:
//It takes  one parameter which is a positive integer and
//that writes out that number  of asterisks '*'. 
//This astrisks display to the screen all
//on one line.
void  printAsterisks(int numOfAsterisks)
{
    cout << '*';
    if (numOfAsterisks > 1)
     printAsterisks(numOfAsterisks-1);
}

Output of program:

0 0

Discussions

Post the discussion to improve the above solution.