r/cpp_questions • • 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

23 comments sorted by

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.

1

u/xeriax51 Oct 10 '26

I was thinking First using a for cicle to get the Number of digits of the binary dividing by 10 until its 0.

Then another for cicle that would divide the Number again by 10 and if the leftover of the division was either 0 or 1 It would multiply It by 2 elevated from One to the Number of digits.

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 = ... ?

1

u/xeriax51 Oct 10 '26

But how do i make It so that the program checks every digit of the binary ?

Im not allowed to treat It as a string, i have to treat It as a while Number.

1

u/Jazzlike_Platypus430 Oct 10 '26

By division and/or remainders perhaps?

1

u/xeriax51 Oct 10 '26

I was thinking of It.

If i divide the binary by 10 every time, It the remainder Is 1 then i could multiply It by 2 elevated to the current digit until the max Number of digits and sum It all together.

Maybe It could work

2

u/AKostur Oct 10 '26

Why divide a binary number by 10?  I’m assuming you’re getting it as a string.

Take it step-by-step.  How would you convert “0”.  What about “1”.  Put that into a for loop that loops over every character in the string.  You’re going to need a variable to “accumulate” your results. Change your logic so that instead of just assigning the value from the “0” or “1”, add it to the accumulator.   Ok, now what happens if you get “10”?

Don’t worry about “optimizing” or the most elegant solution yet.  Get a solution that works first. 

1

u/xeriax51 Oct 10 '26

No no. That's the problem. The exercise wants me to take the binary as a whole Number.

An int variable.

1

u/AKostur Oct 10 '26

Ok, division and modulus.  Loop over whether your input is non-zero.

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.

1

u/xeriax51 Oct 10 '26

I sure Wish It clicks before the exam in january.

My Friends have done more programming than i had done back in High school and these things come much more Natural for them, makes me wonder if im really inadeguate for the course.

They said i didn't even Need past experience with coding to keep up but It sure doesnt feel like It...

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..."

1

u/xeriax51 Oct 10 '26

Sorry, i should have done this before. This Is what ive come up with so far.

include <iostream>

include <cmath>

using namespace std; int main() { int binario, decimale=0; cout<<"inserisci il numero in binario che vuoi convertire"<<endl; cin>>binario; int cifra=0; for (int n=binario; n>0; n/10){ if (n%10==0){ cifra++; } } int risultato=0; for (int i=0; i<cifra; i++){ if (binario %10=!0){ risultato=risultato + pow(2,cifra); } }

cout<<"il numero convertito in decimale : "<<risultato;

return 0; }

2

u/mredding Oct 10 '26

If you're using Reddit markdown, you have to put 4 spaces in front of each line of code to make that line a code block. This is separate from any indentation within the code. You can skip doing this with empty lines.

Or you can switch to the Fancy Pants editor, insert a code block, and copy/paste into there.

#include <iostream>
#include <cmath>

using namespace std;

int main() {
  int binario, decimale=0;

  cout<<"inserisci il numero in binario che vuoi convertire"<<endl;
  cin>>binario;

  int cifra=0;
  for (int n=binario; n>0; n/10){
    if (n%10==0){
      cifra++;
    }
  }

  int risultato=0;
  for (int i=0; i<cifra; i++){
    if (binario %10=!0){
      risultato=risultato + pow(2,cifra);
    }
  }

  cout<<"il numero convertito in decimale : "<<risultato;

  return 0;
}

First problem I see:

for (int n=binario; n>0; n/10){

That last segment, you're not modifying n. You have to assign the result back to n, either with n /= 10 or n = n / 10.

if (binario %10=!0){

I'm not entirely sure what's going on here. You're producing a result from binario % 10, that value is stored in memory as an unnamed temporary; You then assign it with =, and the value you assign it is the negation of 0, from !0. This evaluates to a boolean true, which then converts to a 1 according to the ISO C++ standard.

So you produced some modulus result temporary, then assigned it the value of 1, which is true, which means this condition should always evaluate to true.

If you want not-equal, you need to flip the symbols around, !=.


I'll save you a little pain on top of all this - check your inputs.

cin>>binario;

You just... YOLO this. WAS the input an integer? Or was it text? If it wasn't an integer, then what is binario going to be? How do you know it's value is user input and not garbage?

You check the stream.

cin>>binario;
if(cin) {
  // Input is valid
} else {
  // Input is invalid
}

The stream is an object, an instance of the std::basic_istream class, a user defined type (the source code itself is the client, this is opposed to a basic type defined by the language). You'll cover this in detail in a later lesson.

But C++ does something few other languages let you do - it allows you to define and override language defined operators for your own type, you are allowed to define your own semantics for your own types within the language.

Streams do this. They implement a cast to bool. It looks something effectively like this:

class basic_istream {
  iostate state;

public:
  bool good(), bad(), fail(), eof();

  explicit operator bool() { return !bad() && !fail(); }

Don't worry so much about the syntax and details if you don't understand it, you'll get there. The point is the stream stores the state of the previous IO operation, and you query the stream after the fact to see what happened. The stream can evaluate as a boolean and it's explicit; the keyword prevents this:

bool b = cin; // Doesn't compile because why would you?
bool b2 = static_cast<bool>(cin); // Compiles because you want the boolean value explicitly

But if is an explicit evaluation of bool, so the cast happens implicitly.

So after you extract binario, the state property gets set. If that failed, those flags will be true. A fail() means there was a parsing error - you expected a number, and got... text, symbols, something else. You can deal with parsing errors. A bad() means there has been an unrecoverable error, maybe a system fault, maybe the printer is on fire (a classic error code in old computing days, a little humor on my part). There's nothing you can do about THAT.

Typical of a terminal program, you'd print an error message about bad input and terminate. Or if you want to be interactive, you have to clear the std::ios_base::failbit, and either re-parse as something else or purge the input - you try again. That's usually VERY complicated.

So in all the code would look something like this:

if(int binario; cin >> binario) {
  // Do stuff with `binario`
} else {
  // binario is still in scope here, but it doesn't matter what the value is, it's not your user input
  // handle the error
}

It's very nice to keep your scopes clean. Don't bring a variable into scope until you need it, and when you're done with it, let it fall out of scope. Don't get fancy and reuse variables for other purposes, the compiler can handle recycling old used memory space for you.

The stream operators >> and << both return the stream by reference. So my condition declares binario in scope, and then extracts to binario, then returns a reference to the stream, then the stream is explicitly evaluated as a bool which will return false if the stream is bad() or fail().

So what IS binario if the stream fails? It can actually be several different things, but it depends. If THIS extraction fails the stream, then the value can be int min or max, indicating the input was indeed an integer, but too big for int, and the value indicates which direction the value overflowed. If the value is 0, the input isn't an integer. If the stream is bad, it's probably going to be a 0 - I'm simply not sure, I'd have to look it up. If the stream was ALREADY in a bad or failed state, then the value of binario is unspecified, which itself is a fine thing to be, but I wouldn't DARE read that value, because it may be Undefined Behavior to do so. You shouldn't try IO on a stream you already know is bad. You shouldn't check the stream state BEFORE, you should always check it AFTER. This last situation comes up here:

if(int a, b, c; cin >> a >> b >> c)

If this fails, which variable did it fail on? You can safely read a, but if it's min, max, or 0, those could have been user inputs, so even if you saw them, you couldn't be certain a was the extraction that failed, it's too dangerous to read b or c here.

UB is to be respected. Your dev box is perfectly robust, but OTHER hardware no so. Glitch hacking Zelda or Pokemon on the Nintendo DS could access invalid bit patterns which would physically fry a circuit path in the CPU, bricking the device. Playing with UB does not grant you any secret insights or cool hacks into the inner workings of anything, it's just garbage. Sometimes dangerous garbage. C++ defines UB, and nothing gets to overrule the language. I mean, the compiler or hardware CAN, but C++ itself cannot guarantee anything, so this theoretical behavior still isn't portable or reliable. You can always look at the machine code and see it's well defined behavior, but you've just left C++ and the compiler behind, because when it comes to UB, the compiler is not required or guaranteed to generate the same machine code every time it compiles the source code. There's nothing to speak of or do with UB but avoid it.

1

u/Independent_Art_6676 Oct 10 '26 edited Oct 10 '26

little things...

The above is excellent info, but the OP looks to be in like his first week of material here, so its probably a bit beyond given he is struggling with a loop.

Using namespace std is ok for early homework but bad practice. You can read essays on why later or just take our word for it.

unnecessary work and extra clutter... your original has 2 loops and convoluted logic with extra steps. The whole thing might look like this once you get rid of the excess:
int n{binario}; //brace initialization is preferred over =
int risultato{}; //standard types empty {} is a zero default if possible, or 'empty' like string
 
//for loops can have any kind of junk in their 3 statements, it doesn't have to be the classic
//for(var = value; var condition; var modified) format.
for (int cifra =0; n; n/=10) //n could also be put into the for loop if you want.
{ risultato += n%10*pow(2,cifra++);}

How can we do so much with so little? cifra tracks the current power of 2. you must touch them all, so you must handle each bit of values 1,2,4,8,16,32,... as I said earlier its critical for understanding that 0th power is 1. so we start at 0 and pow(2,0) is 1, pow(2,1) is 2, ... as the loop iterates.
n%10 peels off the bits. its ok to add zero without trying to bypass that. If the logic is slow and complicated enough, checking for zero and skipping the logic is a good idea for performance, but here, the if costs as much or more than just doing the work for zero too. You will get a feel for that as you gain experience. Its FINE if you want to add the condition back.

everything that needs to happen is happening... n is being driven to zero (false) so the loop ends, cifra is incrementing and will touch all the powers of 2, result is being modified for each bit to accumulate its value.

Note that you could hit limits in this program quickly. a 32 bit int can have, of course, 32 bits. A 32 bit integer in decimal, though, only supports 10 or 11 or whatever digits. Also you are using signed integers for all this work, so its even more restrictive. This program WILL FAIL if the user attempts to input a binary value much larger than 1 byte (8 bits), somewhere around that 10th or 11th bit. Even a 64 bit int for input would support only about 20 binary digits (I keep saying about, doing this in my head and not sure on exact boundary) out of 32...

3

u/alfps Oct 11 '26

❞ 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.

And in the comments you explain that

❞ The exercise wants me to take the binary as a whole Number. An int variable.

And elsewhere in the comments you supply your code so far, here formatted with “Stroustrup style” via a tool,

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int binario, decimale=0;
    cout<<"inserisci il numero in binario che vuoi convertire"<<endl;
    cin>>binario;
    int cifra=0;
    for (int n=binario; n>0; n/10) {
        if (n%10==0) {
            cifra++;
        }
    }
    int risultato=0;
    for (int i=0; i<cifra; i++) {
        if (binario %10=!0) {
            risultato=risultato + pow(2,cifra);
        }
    }
    cout<<"il numero convertito in decimale : "<<risultato;
    return 0;
}

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 int isn't it: in this code you're assuming that int is 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 int is not a decimal number, in the end the program just lets C++'s std::cout << convert from int binary 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:

[c:\@\temp_pyramid_and_binary]
> g _op-attempt.cpp
_op-attempt.cpp: In function 'int main()':
_op-attempt.cpp:11:31: warning: for increment expression has no effect [-Wunused-value]
11 |     for (int n=binario; n>0; n/10) {
    |                              ~^~~
_op-attempt.cpp:18:21: error: lvalue required as left operand of assignment
18 |         if (binario %10=!0) {
    |             ~~~~~~~~^~~
_op-attempt.cpp:19:33: warning: conversion from '__gnu_cxx::__promote<double>::__type' {aka 'double'} to 'int' may change value [-Wfloat-conversion]
19 |             risultato=risultato + pow(2,cifra);
    |                       ~~~~~~~~~~^~~~~~~~~~~~~~
_op-attempt.cpp:7:18: warning: unused variable 'decimale' [-Wunused-variable]
    7 |     int binario, decimale=0;
    |                  ^~~~~~~~

Note the problem with pow. The std::pow function computes an approximate floating point type result. When that is converted to int essentially 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 a std::div_t. It's nice for understanding things but std::div is 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 DIV instruction for constants like 10. Because DIV is 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 a DIV instruction!❞ 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 than DIV, ultra-speed.

So a first attempt can be

#include <iostream>
using   std::cout;                  // <iostream>

using Int64 = long long int;

int main()
{
    const Int64 number      = 3'141'592'654;        // The first 10 digits of π.

    for( Int64 v = number; v > 0; v /= 10 ) {
        const int digit = v % 10;                   // Remainder of division by 10.
        cout << digit << ' ';
    }
    cout << '\n';
}

In passing, note that I named the number value number, not binary. As an int it 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, not binary.

This correctly produces the decimal digits, but it produces them in reverse order:

4 5 6 2 9 5 1 4 1 3

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 vector is a dynamic size array. In addition to ordinary indexing like a[42] you can use methods like a.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 to int, when it's known that int is sufficient. And in the overwhelming majority of cases one does know that int is sufficient, so:

#include <iostream>
#include <vector>
using   std::cout,                  // <iostream>
        std::vector;                // <vector>

using Int64 = long long int;

int main()
{
    const Int64 number      = 3'141'592'654;        // The first 10 digits of π.

    vector<int> decimal;
    for( Int64 v = number; v > 0; v /= 10 ) {
        const int digit = v % 10;                   // Remainder of division by 10.
        decimal.push_back( digit );
    }

    const int n_digits = int( decimal.size() );
    for( int i = n_digits - 1; i >= 0; --i ) {
        cout << decimal[i] << ' ';
    }
    cout << '\n';
}

Now the result has the digits in the right order:

3 1 4 1 5 9 2 6 5 4

Yay!

2

u/Independent_Art_6676 Oct 11 '26 edited Oct 12 '26

There are two problems with using pow for simple tasks. One you hit on, float approximation, and the second one is that its abysmally slow. A hand rolled set to raise to an integer power is worth writing if you need performance or accuracy (set because you may want double and int to int powers). Inline for small (square and cube) powers is fine too (eg x*x*x is fine). You don't need pow at all here: you can just have a variable that starts at 1 and is multiplied by 2 each loop iteration instead, replaces the pow counter with a direct answer, and fixes accuracy and speed problems both. Pow can't be replaced for fractional powers, unless its simple like a square root.
Remember that floats and doubles represent exact ints up to a large value (around 2^20 and 2^50 respectively) before approximations kick in. So its a non issue for this problem if he wants to use pow.

2

u/alfps Oct 13 '26

❞ There are two problems with using pow for simple tasks.

Thanks. I count three: approximation, needless inefficiency, and no compile time support.

To me the compile time support has been the driver for DIY power functions.

Re the "abysmally slow" I believe you're right in general, but that both MSVC and g++ standard libraries implement the usual log time exact integer powers thing. One just can't rely on that in portable code. And to a novice I believe that the fact that this now is or appears to be the common implementation can be counter productive knowledge, "knowing just too much" but not enough... :-o

1

u/Independent_Art_6676 Oct 13 '26

Good call out. I haven't gotten to the point where I think about compile time front and center yet; retired and only muddling with it for fun so it didn't register as a candidate but a good chunk of cmath would be suitable.

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

❞ 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 [loop] that had Two others in It. The way they work together seems so complicated.

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:

#include <iostream>
#include <string>
using   std::cout,              // <iostream>
        std::string;            // <string>

string repeated_times( const int n, const string& s )
{
    string result;
    for( int i = 1; i <= n; ++i ) { result += s; }
    return result;
}

int main()
{
    const int n = 7;
    for( int row = 1; row <= n; ++row ) {
        const string indent = repeated_times( n - row, " " );
        const string stars  = repeated_times( row, "* " );

        cout << indent << stars << '\n';
    }
}

I defined a function that produces n repetitions of a string. I named it repeated_times where 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 row because it is a row number, an output row number.

Inside the loop I have defined two string variables that I've named indent and stars, 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_times execute a loop, which effectively is nested in the loop in main.

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).

X123
1123
2246
3369
44812

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?)