Print a C pattern using loop in C++(any language)?

I’ve kickstarted to practice problem solving using C++ book by walter savitch and this is my first problem and in the first problem I’ve encountered difficulty.

#include <iostream>
using namespace std;
int main()
{
    int size;
    cout << "Enter the size of the pattern: ";
    cin >> size;

    for (int i = 0; i < size*2-1; i++)
    {
        for (int j = 0; j < size; j++)
        {
            if ((i==0&&j!=0||i==0&&j!=1)||(i==1&&j==1||i==1&&j==size-1)||(j==0&&i!=0||j==0&&i!=1||j==0&&i!=2*size-3||j==0&&i!=2*size-2)||(i==2*size-2&&j!=0||i==2*size-2&&j!=1)||(i==2*size-3&&j==1||i==2*size-3&&j==size-1))
                cout << "X";
            else
                cout << " ";
        }
        cout << endl;
    }

    return 0;
}

My code produces a C but not like that way although my logic is alright imo.

image

Im not going to fix your code because you failed to meet the request and I cant be bothered figuring out all your logic in the if.
Instead Ill show you how to get the correct result using JS…

let char = prompt("What character would like to make the C with?","X");
let bitmap=  [
    [0,0,1,1,1],
    [0,1,0,0,1],
    [1,0,0,0,0],
    [1,0,0,0,0],
    [1,0,0,0,0],
    [1,0,0,0,0],
    [1,0,0,0,0],
    [0,1,0,0,1],
    [0,0,1,1,1],
  ];
  let output = "";
  bitmap.forEach(line => {
    line.forEach(pixel => {
      if (pixel) output+=char
      else output+=" ";
    });
    output+="\n";
  })
  console.log(output);

It doesnt rely on some long logic, it stores the character you want to print in any array that contains lines of arrays that represent the lines and pixels of the character. This allows you to print any character that you care to make. With a bit more work we could use the canvas. Print a character on the canvas and then read the pixels to print the ascii version. Its flexible. This is the sort of thing you learn if you do graphics.
So your logic is wrong and your approach is inflexible.

EDIT: And what I meant by you didnt meet the request is that it asked you to change the character that was used to print the C, not to change the size of it.

1 Like

Ok I dont want to got through the whole flow of you code but Ill try and show you why the very first character is an X and not a space.
At the very bottom of this post is your code converted to JS (its just easier for me to follow, thanks ChatGTP), lets got through the conditions and see where it fails.
On the first iteration i==0 and j==0
(i == 0 && j != 0) False
(i == 0 && j != 1) False
(i == 1 && j == 1) False
(i == 1 && j == size - 1) False
(j == 0 && i != 0) False
(j == 0 && i != 1) True
And there you can see why the first character is an X and not a space. This is just what you have to do some times, follow the code in your head or on a piece of paper and try to see where it doesnt do what you expected.
Trying to put all conditions on one line isnt the best idea. If you really wanted to do things the logic way you would of been better doing multiple if elses because its easier to follow…

  const size = prompt("Enter the size of the pattern:");
  for (let i = 0; i < size * 2 - 1; i++) {
    let line = "";
    for (let j = 0; j < size; j++) {
      // first two lines
      if (i == 0) {
        j > 1 ? line += 'X' : line += ' ';
      } else if (i == 1) {
        (j == 1 || j == size - 1) ? line += 'X': line += ' ';
        // last two lines
      } else if (i == 2 * size - 2) {
        j > 1 ? line += 'X' : line += ' ';
      } else if (i == 2 * size - 3) {
        (j == 1 || j == size - 1) ? line += 'X': line += ' ';
        // All the other lines
      } else {
        line='X';
      };
    }
    console.log(line);
  }

This is doing it the simplest way I can think of, after this Id look at it and see that I can move two blocks together …

  const size = 7;
  for (let i = 0; i < size * 2 - 1; i++) {
    let line = "";
    for (let j = 0; j < size; j++) {
      if (i == 0 || i == 2 * size - 2) {
        j > 1 ? line += 'X' : line += ' ';
      } else if (i == 1 || i == 2 * size - 3) {
        (j == 1 || j == size - 1) ? line += 'X': line += ' ';
      } else {
        line='X';
      };
    }
    console.log(line);
  }

And then after that if I feel like torturing the next person to look at this code I could convert all those conditions to one line…

  const size = 7;
  for (let i = 0; i < size * 2 - 1; i++) {
    let line = "";
    for (let j = 0; j < size; j++) {
      if (((i == 0 || i == 2 * size - 2) && j > 1) || ((i == 1 || i == 2 * size - 3) && (j == 1 || j == size - 1)) || (j == 0 && i > 1 && i < 2 * size - 3))
        line += 'X'
      else line += ' ';
    }
    console.log(line);
  }

Because Im not the smartest chappy this is how I usually do things. Start of with the most simplest verbose way you can think of doing something so as to not confuse yourself and then got through seeing what you can make more modern, faster, shorter, woteva.

Original coverted to JS…


  const size = 7;
for (let i = 0; i < size * 2 - 1; i++) {
  let line = "";
  for (let j = 0; j < size; j++) {
    if (
      (i == 0 && j != 0) ||
      (i == 0 && j != 1) ||
      (i == 1 && j == 1) ||
      (i == 1 && j == size - 1) ||
      (j == 0 && i != 0) ||
      (j == 0 && i != 1) ||
      (j == 0 && i != 2 * size - 3) ||
      (j == 0 && i != 2 * size - 2) ||
      (i == 2 * size - 2 && j != 0) ||
      (i == 2 * size - 2 && j != 1) ||
      (i == 2 * size - 3 && j == 1) ||
      (i == 2 * size - 3 && j == size - 1)
    ) {
      line += "X";
    } else {
      line += " ";
    }
  }
  console.log(line);
}

thanks man, I find what you said complex, easy to write. I can understand it can be tough to read though.

Easy?..You got it wrong :stuck_out_tongue_winking_eye:
And how easy something is to read is important, not just for others but for you in 6 months after you write it and if you need to adjust it later.

That’s why I’m going to add thought process in my notes from now on.Like this. Otherwise the code alone is useless I agree.

honestly javascript should rename itself as hardscript. What in earth does forEach means? And what in earth do we need arrow functions to overcomplicate things. I feel I am feeling programming imposter mainly because of wrong choice of language. I think I should switch to other language. Any recommendations? C#.Net, flutter, java, kotlin?

forEach is um…(bad at terminology, bad memory)…a way of iterating over an array. Here is what ChatGTP converted the main bit of the first post when I asked “can you please rewrite the following javascript so that it doesnt use forEach…” and then underneath pasted the whole code from the first post…

for (let i = 0; i < bitmap.length; i++) {
  for (let j = 0; j < bitmap[i].length; j++) {
    const pixel = bitmap[i][j];
    if (pixel) {
      output += char;
    } else {
      output += " ";
    }
  }
  output += "\n";
}

Can you see the relation? The first forEach iterates over bitmap, passing each element to the function as line which is also an array and then the next one iterates over that array and passes each element to the function as pixel.

arrow functions: I hated the inclusion of these at first as I just saw them as a time saver and pointless until I realized that this is different in them. You should look up on MDN what that is. You should be looking up EVERY function/statement you dont understand there.

I really feel your pain. I have memory problems amongst other things and found all modern languages hard until I fell in absolute love with JS. It had bugger all instructions and had arrays and objects with dot syntax…what else do you need!!! It took me two years to memorize how to do a for loop, my memory is that bad. It stayed stagnant for years until now they add stuff all the time making it much harder for new comers that dont have those true nerd brains or prior knowledge like I had gained. But even so I still consider it one of the easier languages by FAR. So much less boiler plate and stuff and systems that they FORCE you to do. On a side note the one language that TRULY is misnamed is BASIC!!! I HATE IT!!! :stuck_out_tongue_winking_eye:

As to what language to pick, what Steve told you in another post is absolute gold, agree with ever word of it. But at the end of the day, what YOU click with is very important.

Doing stuff on paper is an AWESOME idea!!! You made me think, I had forgotten just how much I use to do on paper to SEE it until I could do it in my brain. How to see and organize data (Im awfully data centric) was a big point of my original teacher and paper use to help me a lot.

I wish I could tell you what to do and help you more, you putting in the effort and your moving forward, you just seem to be in a rush. It takes time. Theres HEAPS to learn, but you at least seem to be getting the logic down. And its harder now because soooooo much info on the web seems to act like you have prior knowledge.

In the future if you ask anything JS Ill try to not use modern stuff, which is actually easy for me because thats still how my brain thinks, I usually convert it later. Other wise try putting stuff in Chat and get it to remove/change the stuff you dont get.

FML…
I been asked to “help out” with an excel wannabee database that just keeps getting more and more “features” (forms, pivot tables, cross workbook mods, saving, password protection).

They wont allow the JS excel add in (some firewall BS) and they wont do a DB or server.

Everything about it stinks… its so hard to build something maintainable in basic.

If I could just chuck it into a DB and serve it as even just a HTML table with JS forms and maybe svg graphs, this would be done by now… :unamused:

Who thought it was a good idea to call variables “Dim” sim??

I still haven’t figured out variable scoping… sometimes it works sometimes it doesn’t :unamused:

for loops and arrays are in basic are just stupid…

TBH IDK how much basic I will have to learn to get it done… Maybe I should tell them to shelve it…

I was lucky, I learnt HTML1 (before CSS) for school projects/ essays in primary school in 1995 (I was 7).

There was no JS, everything was just an academic article on some university server and our librarian taught us how to use the AlstaVista search engine to “query” the World Wide Web…

I was talking to a member of my daughters school board about how lucky I was and he asked if “building websites” could be taught in primary school and what that would look like.

I’ve been working on a side project “teach your 7 year old” web dev course and when It’s done, I’ll be running weekly meetups at the local library.

When I’m finished the course I might open source it… It will be very basic BUT complete (think Vanilla JS pocket guides but more basic)

You can program in JS like you can in C++ for the most part (imperative, OO, functional ect)

1 Like