Click here to Skip to main content
15,443,549 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good afternoon, I want to know how can I print an square where the numbers grow an unity, as the following (depending of the number of square lines, in this case, 5 lines):


How can I do that by C++/C?

Best regards.
Ángel Manuel.

[NOTE: I've tried to found that by Google but I can't found any answer]
Updated 18-Sep-11 0:30am

Here is another solution, this time non-recursive (i.e dynamic):
#include <stdio.h>

#define MAX (5-1)
int gSquare [MAX+1][MAX+1];

/* copy a source row to destination row */
void cpRow (int dstRow,int srcRow){
    for (int col=0; col<= MAX; col++)
        gSquare[dstRow][col]= gSquare[srcRow][col];

/* fill all the cells of a given row with zeros */
void ZerFil (int row){
    for (int col=0; col<= MAX; col++)
/* Print out a given row on screen */
void PrnRow (int row){
    for (int col=0;col<=MAX;col++)
        printf ("%d\t",gSquare [row][col]);
    printf ("\n");

/* Dynamically define each rows values based on previous rows */
void CalcRow (int row){
    if (2 * row > MAX+1) {/* we are on lower half */
        /* copy symmetrically ~ mirror flip */
        cpRow(row, MAX-row);

    cpRow (row, row-1); /* Initiate me as previous row */
    /* increase required cells */
    for (int i=row; i<= MAX-row; i++) 

int main() {
    /* Zero the initial row as zero for base of calculation */
    PrnRow (0);

    for (int row=1; row<=MAX;row++){
        CalcRow (row);
        PrnRow (row);
    return 0;
Share this answer
void printSquare(int sideLength)
    int curCol, curRow;
    int val;
    for (curRow=0; curRow<sideLength; curRow++)
        for (curCol=0; curCol<sideLength; curCol++)
            /* CALCULATE val HERE

Share this answer
Ali Fakoor 19-Sep-11 7:22am     CRLF
There is no more information available in this solution than saying: void main(void){ //perform the job here!!! } It is like saying a rectangle is a 2-dimensional object. or a N x N matrix has N rows and N columns!!!, isn't it? The reason for posting the solution below was that it appeared to have no relevant information even regarding the first solution by the same author ("how far ... from ...").
enhzflep 19-Sep-11 9:23am     CRLF
Perhaps I would agree with you here, had I not already posted Solution2. Solution3 is a clear and logical continuation of the advice and discussion contained within. In your solution, each cell requires an awful lot of calculation. Just for a laugh, I ran them both with some precision timing code to gauge their performance for myself. Here are the results: ----------Enhzflep's code---------- 100000000 iterations took 0.696718s Million Iterations/Second: 144 ----------Ali Fakoor's code---------- 1000 iterations took 9.973154s Iterations/Second: 100.269 Million Iterations/Second: 0.000100 Furthermore, if you study your code it immediately becomes apparent that as the size of the square increases, the time needed to calculate each cell increases. So not only do you have more cells to calculate, but they also take longer to solve. This task is very easy. Your recursion simply serves to demonstrate how easy it is to over-complicate a task. I'd also be a little curious as to the motivation for making the function modular, yet leaving half of it in main. Are you likely to do other things with the helper-functions? Are you likely to do nothing else with the main? In any case, full source code demonstrating the above figures is available on request. Cheers :wink: EDIT: All timings done on a 2.13Ghz I3 running Windows7, with 12 programs and 21 browser tabs open.
This can be done recursively as follows:
#include <stdio.h>

int padOffset (int row, int n){
    int off1 = row - n;
    if (off1 < 0)
        off1 = off1 * (-1);
    return(row<off1)? row:off1;
int diffCount (int row, int col, int n){
    int loc1 =  padOffset(row, n);
    int loc2 = n - loc1;
    int dif = (loc1 ==row)?1:-1; //determine sign
    if (dif<0) {loc1++; loc2--;} //strechen halfway down
    if (loc1> col || col > loc2)
    return dif;
int getCell (int row, int col, int n){
    if (row <= 0)
        return row;
    int inc = diffCount(row,col,n);
    return getCell(row-1,col,n)+ inc;
int main() {
    int n;
    printf ("Enter n:");scanf ("%d",&n);
    n--; // indexing at zero!
    for (int row=0; row<=n;row++){
        for (int col=0;col<=n;col++)
            printf ("%d\t",
        printf ("\n");
    return 0;
Share this answer
enhzflep 19-Sep-11 3:15am     CRLF
My vote of 1. You've explained nothing, made the (in my opinion) foolish assumption that the OP's head will not xplode at the thought of recursion. The code is longer and more complex than necessary. If there was a zero-vote button, I'd press it! Never mind the fact that you've just handed out the functioning answer to a homework question!!
Ali Fakoor 19-Sep-11 7:23am    
On the other hand I think its length is reasonable and the concepts are modularized in different functions. well everyone has his own idea let others decide.
Ángel Manuel García Carmona 25-Sep-11 8:03am     CRLF
Hello, thanks for your answers being this answer (code) which has been useful but can you write anything more easier and not too complex. Best regards. (Thanks :))
Ali Fakoor 27-Sep-11 4:43am     CRLF
Well, recursive is always more fun to write but as you already mentioned a little more complex for reading. Well here you are presented with solution #5 below. See the CalcRow function.
As you can see from your picture above it's just a question of counting the number of digits of each type and printing them in order. Try working it out in logical terms and then converting it to code.
Share this answer
Isn't each digit that makes up the square the minimum number of steps that would have to be taken to reach the edge?

Would you not want to keep track of:
(a) how far from the left edge
(b) how far from the right edge
(c) how far from the top edge
(d) how far from the bottom edge

Simply printing which ever was the smallest value for each of the cells that make up the square..
Share this answer
Ángel Manuel García Carmona 18-Sep-11 13:07pm    
Hello, I know how can I do anything similar if I print a pyramid but I don't know how can do the same for an square. Can you give me an explanation by code?
enhzflep 18-Sep-11 13:52pm     CRLF
I could, but I wont. - it only took me 18 lines for the printSquare function. I've already given you the algorithm (which may well be frowned upon by your teacher) It's up to you to convert it to code. Here's another hint: loop for each y .loop for each x ..find minimum distance to an edge and print that number
Ángel Manuel García Carmona 18-Sep-11 16:15pm    
Sorry but I can't understand that (about loops for each 'y' (what??) and 'x' (what??)). Can you write any code lines??
enhzflep 18-Sep-11 16:51pm     CRLF
Yes, I can write code lines. As I mentioned earlier, I wrote 18 that satisfied your question. I will not be posting them. Imagine that your square in 2 dimensions - X = width, Y = height. Simply loop through each of the horizontal lines (loop for each y) Then inside that loop, loop through each 'pixel' on that horizontal line (loop for each x)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900