how do i write a C++ function called RepeatingWords that displays a word (passed in through a string type parameter) N (also passed through a parameter) times. Then, write a calling statement for the function

Dani AI

Generated

: a simple, safe way to implement RepeatingWords is to accept the word as a const std::string& (to avoid unnecessary copies), validate N, then loop and print. As suggested, break the task into steps: validate input, loop N times, print each occurrence.

#include <iostream>
#include <string>

void RepeatingWords(const std::string& word, int n) {
    if (n <= 0) return;              // nothing to do for non-positive counts
    for (int i = 0; i < n; ++i) {
        std::cout << word << '\n';
    }
}

int main() {
    RepeatingWords("hello", 3);      // passing a literal (binds to const ref)
    std::string w = "bye";
    RepeatingWords(w, 2);            // passing a std::string
}

Notes and small variations: use std::size_t for n if you want only non-negative counts. If you prefer the words on one line separated by spaces, print a space instead of '\n' and handle trailing space. For modern C++ (C++17+), std::string_view works well if you want to avoid constructing std::string copies from literals. Decide whether the function should print (side effect) or return a composed std::string — returning is easier to test, printing is simpler for console tasks. Validate or document how you want negative or zero n handled.

Recommended Answers

All 3 Replies

You start by figuring out what you want the function to do. Then you work out steps for how to do it. Then you define the function (and possibly even provide a prototype). Finally, you call the function.

Read this before posting again, please.

lolz [caveman]you make funny ha ha [/caveman]

Funny or not, until you stop being such a lazy ass and actually ask a smart question, I'll refuse to help you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.