Skip to main content

Display N characters using default arguments

Short answer

Define a function display(char ch = '*', int n = 10) that loops n times printing ch. Calls display() show 10 stars; display('#') prints 10 #; display('A',5) prints 5 A's. Arguments are matched left to right; cannot skip ch to give only n.

Write a program to display N number of characters by using default arguments for both parameters. Assume that the function takes two arguments: one character to be printed and the other number of characters to be printed.

Both parameters get default values: the character defaults to '*' and the count defaults to 10.

#include <iostream>
using namespace std;

void display(char ch = '*', int n = 10)
{
    for (int i = 0; i < n; i++)
        cout << ch;
    cout << endl;
}

int main()
{
    display();          // uses both defaults
    display('#');       // uses default count: ##########
    display('A', 5);    // no defaults used: AAAAA
    return 0;
}

Output

**********
##########
AAAAA

Explanation

  • display() : both arguments omitted, so ch = '*', n = 10.
  • display('#') : only the first is given; n takes 10.
  • display('A', 5) : both given; defaults are ignored.
  • Arguments are matched left to right, so we cannot skip ch and give only n.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 3 questions →