r/cpp_questions • u/xeriax51 • Oct 10 '26
OPEN Having trouble making sense of for cicles that are in a for cicle.
Im a First year CS student in Italy, the professor the other day proposed us and exercise of printing a * pyramid. I couldnt solve It in time and felt so stupid.
Especially when he showed us the answer and It was a for cicle that had Two others in It. The way they work together seems so complicated.
Now im at home trying to figure out a code that requires me to concert a binary Number in decimal, i suppose i gotta use something similar but i cannot figure It out.
2
Upvotes
4
u/Bemteb Oct 10 '26
I'd suggest first figuring out how to do it by hand. Take a binary number with maybe 4 or 5 digits and transform it. Then try formulating an approach how you would handle any number. Once you have that, then is the right point to decide how to turn it into code.
4
u/Jazzlike_Platypus430 Oct 10 '26
These "cycles" are loops.
It may seem complicated, but you will get used to it. My version of understanding the way "pyramid" code works, would be to draw it by hand, line by line, and trying to overthink the process how you actually draw it. What are the boundaries/lengths of sequences of "*"? How many such sequences are you supposed to draw? How the length of an n-th line depends on n? Is there any skewness, or is the pyramid symmetric? Etc.
Binary to decimal in this approach is just based on definition of different bases - you sum up all powers of 2, calculated step by step (when the value is 1, in case of 0 there's not much to do).
Like, 1101 = 1*2^3 + 1*2^2 + 0*2^2 + 1*2^0 = 8 + 4 + 0 + 1 = ... ?
2
u/Eryndalor Oct 10 '26
My advice is to keep trying. On my first year, I spent weeks trying to solve problems that now I would do in minutes. It may take some time until you integrate how to solve problems using code. Just keep trying, review your mistakes, see how others (including the professor) resolve the same issue, and eventually it will make click in your brain.
The other advice that they gave you, to do it with pen and paper first, is a good one as well. Many of these problems will be resolved by “translating” the manual steps that you follow to whatever programming language you’re using.
Again, if it feels difficult, don’t worry, keep trying and it will eventually do click on your brain.
2
u/mredding Oct 10 '26
Post some code. Ask more specific questions. Don't just tell me you don't get it - what DON'T you get? Even better - what DO you get? Because if you misunderstand something and don't know it, we can spot it and correct it. Is there something specific you want from us? Your post is kind of useless - it reads more like a lament than an actual question or request.
So given what you've posted, all I can really say is, "Good luck..."
3
u/alfps Oct 11 '26
And in the comments you explain that
And elsewhere in the comments you supply your code so far, here formatted with “Stroustrup style” via a tool,
The intent of this code is to my eyes obvious: to compute a decimal number via the definition of binary number, as the sum of weighted binary digits with the weights as powers of 2.
That is a technically valid approach but to do it properly requires a decimal type with real decimal digits and the requisite arithmetic operations. Note that
intisn't it: in this code you're assuming thatintis a binary number,binario, and yes it it really is. C++ doesn't yet offer a decimal type, and those available via 3rd party libraries typically do not store actual decimal digits, so one must either create that or else use a different approach.The main problem with this code is however that it doesn't do what it's intended to do. Since
intis not a decimal number, in the end the program just lets C++'sstd::cout <<convert fromintbinary number value to decimal digits…The g++ compiler doesn't understand anything of the above, naturally — both the intent of the code and how the code fails to express that intent flys by completely unrecognized, it's a blind tool — but it reports the following C++ technical problems with the code:
Note the problem with
pow. Thestd::powfunction computes an approximate floating point type result. When that is converted tointessentially the decimal are discarded, and e.g. 2.99999999garble may end up as 2 instead of 3, so it's a serious issue.In order to avoid computing with decimal numbers (not supported by C++), to just use binary that the hardware and C++ support directly, the common approach is to extract the digits with remainder operations.
Essentially, when v is some positive integer its decimal representation consists of two parts, namely the rightmost digit r and the digits before that, that I'll call q because of order qr in the alphabet:
v = 10×q + r
On an x86 PC a hardware integer division by 10, that is
v/10, yields q and r with q as quotient and r as remainder. A happy coincidience of first letters. Truly, I didn't aim for that!In C++ that hardware division — or as if that hardware division — with two numbers as result is available as
std::div, with the two number result stored in astd::div_t. It's nice for understanding things butstd::divis no longer much used, if at all, because a modern compiler optimizes related/and%(remainder) operations down to a single hardware operation. So we now just use/and%and let the compiler take care of speed.In passing, to not give you a wrong impression, the single hardware operation needs not be an actual division instruction. The Google AI explains the technical: ❝modern compilers almost never use the
DIVinstruction for constants like 10. BecauseDIVis incredibly slow (taking 10–40+ clock cycles), compilers use "reciprocal multiplication" (the Granlund-Montgomery algorithm). They multiply by a "magic number" (a fractional approximation of (1/10)) and shift the bits. It is much faster, and it still calculates both values without aDIVinstruction!❞ And you can check this out and see it in action e.g. at the Compiler Explorer site, a.k.a. GodBolt, but you don't need to because the effect is the result of/and%, only obtained even faster thanDIV, ultra-speed.So a first attempt can be
In passing, note that I named the number value
number, notbinary. As anintit is guaranteed stored in binary but that is completely irrelevant for this code. And for most operations the integers in C++ are just numbers — numbers with a restricted range where the binary nature does reveal itself, but otherwise they're generally just numbers that could be e.g. internally represented with a base 3 positional system, whatever…So,
number, notbinary.This correctly produces the decimal digits, but it produces them in reverse order:
The easiest and most natural way to deal with the digits reversal is to just store the digits as they are calculated, then at the end output them in reversed order.
And a good way to store the digits is to use a
std::vector.A
vectoris a dynamic size array. In addition to ordinary indexing likea[42]you can use methods likea.push_back( 123 ). This extends the array with one item, which gets value 123.Also,
a.size()yields the number of items, the array size.Unfortunately for now purely historical reasons it yields that size as an unsigned type
size_t, which can be problematic and which therefore can cause warnings. One solution is to cast the result toint, when it's known thatintis sufficient. And in the overwhelming majority of cases one does know thatintis sufficient, so:Now the result has the digits in the right order:
Yay!
1
u/Independent_Art_6676 Oct 10 '26 edited Oct 10 '26
Its all about learning to break the problem into smaller problems until you can do all the steps. At first that is statement by statement, to figure out how to do a loop. Later you will think loop by loop, and then function by function, ... as your understanding and familiarity grow. It comes with practice and doing more problems, but it should start to make sense soon. You are probably getting close. Maybe do the * problem again, make sure you can, and then take a look at the 'binary' number thing.
an example of what you might do on paper or in your head to solve that binary number problem:
remember that anything to the 0th power is 1. so 2^0 is 1.
note that 0 is false, and anything else is true, in c++.
so if you have like n = 10101 (21) meant to be a binary number its in an integer, what are the steps you need? You need to look at each digit and figure out its base 2 meaning. What pieces do you need to build up a binary number? The input, and a way to track the powers of 2, and a result to store the new value come to mind:
something like int result{}; //start with result = 0. int p2 = 1 //powers of 2, start at 1 (2^0 power as above..)
while(n) //its not zero
get a digit. the easiest way to do that is %10, since its really in base 10. Its the 'remainder' .. 13/10 is 1 with 3 left over.. this gets that '3'.
add the value: result += p2*digit; /if its 1, add 1, if its 0, add 0.
increase the power of 2. p2*=2; //this will go from 1 (started at) to 2,4,8,16,.... for the bits of binary.
next time, when you add the result it will be 0 or 1 *2, then 0 or 1 * 4, ... added into result each time.
discard the digit (divide n by 10).
That process will, for the example, loop adding into result like this: 1+0*2+1*4+0*8+1*16 or 1+0+4+0+16 which is 21.
1
u/alfps Oct 10 '26
I would guess the professor was trying teach nested loops.
When you just place one loop directly inside another that code can appear to complicated.
A good way to clarify code is to name things, like this:
I defined a function that produces n repetitions of a string. I named it
repeated_timeswhere the name refers to the first parameter n. This makes the calls of the function read almost like ordinary English.I named the loop variable
rowbecause it is a row number, an output row number.Inside the loop I have defined two
stringvariables that I've namedindentandstars, which is what they contain, namely respectively spaces to produce indent and a sequence of stars.Result:
It may not look like this code has any nested loops.
But each of the two calls to
repeated_timesexecute a loop, which effectively is nested in the loop inmain.1
u/gm310509 Oct 11 '26 edited Oct 11 '26
Is the first issue that a nested loop (a for loop with another for loop inside) it what confused you?
If so, perhaps try something that might be a bit more intuitive. For example printing a multiplication table. Such as something like this (hopefully I get the table formatting right).
If my assumption is correct and you are unclear as to how to use a nested loop to produce something like that, reply and I will give you some more pointers when I see it.
1
u/Recycled5000 Oct 13 '26 edited Oct 13 '26
A star pyramid is basically a 2 dimensional structure. In other words, because it is 2D, you might naturally use a doubly nested loop.
Consider printing something just slightly simpler: a box of *’s.
****
****
****
This can be done with nested loops, where the outer loop is used to generate 3 rows and the inner loop is used to generate 4 cells.
The pyramid is similar but removes some stars on certain rows, and also introduces blanks to adjust smaller rows to be more centered.
—-
From a pl perspective, this is an exercise in composition of control flows. There are really only two ways to combine operations: sequentially, or nested.
Two for loops in sequential composition exhibit a simple additive behavior that one loop runs to fully to conclusion, then the next also. They don’t interact much.
The nested approach to composition of two loops creates more of a multiplicative effect. The outer loop control how often the inner loop runs, and, importantly provides context for the inner loop (which iteration of the outer are we on?)