Member Avatar for Member #239836

Im trying to write the programme for the following question, and im really struggliing. I will be reaaly thankful if someone can give me some tips or a programme for this.

I would also like to point that im new to programming and this website so please give me some details for statements if possible.


Question-
Write a function that displays at the left margin of the screen a solid square of asterisks whose
side is specified in integer parameter side. For example, if side is 4, the function displays:
Sample Screen Display
****
****
****
****

Dani AI

Generated

For : this is exactly the sort of small task that shows how nested loops work. As pointed out, a loop inside a loop is the simplest way to print an N-by-N block of asterisks that begins at the left margin. Below are two clear C++ approaches: a direct nested-loop version (easy to follow) and a slightly more efficient one that builds a single line and prints it repeatedly.

#include <iostream>

void printSquare(int side) {
    if (side <= 0) return;   // nothing to print for non-positive values
    for (int row = 0; row < side; ++row) {
        for (int col = 0; col < side; ++col)
            std::cout << '*';
        std::cout << '\n';
    }
}
#include <iostream>
#include <string>

void printSquare(int side) {
    if (side <= 0) return;
    std::string line(static_cast<size_t>(side), '*');
    for (int i = 0; i < side; ++i)
        std::cout << line << '\n';
}

Troubleshooting tips: include <iostream> (and <string> for the second version). Use std:: (or using namespace std; if preferred). Prefer '\n' over std::endl unless an explicit flush is needed (std::endl flushes and is slower). Check for negative or huge side values—very large values will slow the terminal. To call the function, place it in main() like printSquare(4);. If a compile error appears, paste the exact error and the smallest complete code that reproduces it.

Recommended Answers

All 2 Replies

Look up the concept of nested loops in your reference material. It means a loop within a loop, and is a commonly used technique so there shouldn't be any problem finding a number of references. Then post code and specific questions about the code, error messages, etc, as necessary.

Member Avatar for Member #239836

thanks i will try that.

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.