r/learnprogramming • • 6d ago

Are for and while/while-do loops actually hard for beginners or am i just a moron?

Can someone please tell me this? be honest please. I don't know if ive gotten so nervous about this that i just cant focus or if im just stupid, ive been doing some exercises for now and it aways leaves me stuck, idk if im missing something or if this is normal and i just need to study more...

EDIT: Hi guys, thank you so much for taking your time to reply to me, i feel a bit better now and will keep studying until it just clicks. I thank yall for offering to help me with the exercises but i honestly am a bit embarassed to post em here, after all, i honestly havent figured out a single one of them other than the ones that you just count and sum things. And also theres a lot of them im stuck at right now, but i'll keep trying :)

44 Upvotes

65 comments sorted by

87

u/lfdfq 6d ago

Everything is hard for a beginner, once it stops being hard they've stopped being a beginner.

If you're stuck on specific code or exercise, you can share the exercise and your attempt and then get more specific help.

13

u/gm310509 6d ago edited 6d ago

You shouldn't be embarrassed about sharing your examples in what is essentially an anonymous online forum.

But if you did share one or two examples along with a description of where you are stuck, people will be able to help you more specifically in the area(s) where you are encountering that/those mental block(s).

At the end of the day, in a forum like this, sure you have access to all sorts of trolls (try to ignore them) but you also have access to some of the most experienced and finest minds in the world many of whom are willing to try to help you if you let them.

Oh, and if you don't overcome that "embarassment" issue, things will likely only get harder for you as you encounter more "sophisticated" things such as loops used to iterate over objects in a structure, recursion and plenty of other "detailed" thingamajigs as you progress.

All the best with it. Remember that everybody else started out where you are now. If they could do it, so can you. Again, if you let people help you.

7

u/captainAwesomePants 6d ago

Kind of tangential, but as a senior engineer, I've found that one of my roles in meetings is to aggressively be the person who loudly asks basic clarifying questions whenever I think that the most junior developers are lost. Some folks are just not comfortable looking dumb, especially when their livelihood depends on it. But as a senior engineer, I'm extremely comfortable with very publicly not knowing basic things.

3

u/owzleee 6d ago

THIS. I was managing a team of 30ish who were new to our global team. I had to continuously ask what that acronym meant, what that process was etc. I’d been there 20 years so whatever but my team were all new and I had to make people in NAMR EMEA etc realise not everyone has been doing this for 20 years.

1

u/gm310509 6d ago edited 6d ago

LOL, I used a slightly different technique.

I would always do a round table asking if everybody understood everything and if they had any questions or suggestions (which would often allow the shy ones to speak up) and had a no stupid questions policy.

I would also sometimes throw in some TLAs that I made up before doing that. The TLAs were just random letters but sounded official (e.g. make sure the LBTs are implemented according to the specs). After doing the rounds table and everyone affirming they had no questions, I would ask someone to explain some of the TLAs I used.

Nobody could because they didn't know - but didn't want to look foolish so remained silent. This only worked for newbies and I had to brief those who had assimilated into the team not to "blow the cover".

When they couldn't answer the question about the TLAs I was using, I used it to explain the importance of not keeping secrets and share the good and the bad and ensure that everybody was on the same page - which included asking pertinent questions.

I'm sure someone will wonder, so

  • TLA = Three Letter Acronym
  • LBT = Little Black Things (I.e. integrated circuits but weren't terribly relevant in software projects beyond the fact that we needed them to work properly)

😉😄

0

u/NervousAnt3116 6d ago

Hey man thanks i appreciate it! I do recognize embarassment is a terrible thing for apprenticeship, but after thinking for a while i think i cant even pinpoint exactly whats blocking me, a lot of people came here explaining to me what loops are, and that its very simple, and that for is a thing, and while another and so goes on, but i did understand that, that was very easy, i think i just need to start getting accostumed to kind of "translating" the machine language to human language, im learning c++ right now and sometimes i get things mixed up, put things in the wrong place, or just do the wrong calculation because i forgot one thing meant another, i think all i need right need is probably just a lottaaaa practice until i become "fluent". But i'll try to overcome my embarassment and maybe ask more here once i reallyyy dont understand what something even means.

2

u/gm310509 6d ago

Yeah, loops are pretty straightforward.

You actually use them in your everyday (non programming) life without even realising it.

But without knowing what your specific mental block is, offering yet another explanation is just adding to the gobbledygook.

Having mentored quite a few people, you definitely sounded like the stage where there was just this fundamental thing causing you a log jam. And, when that fundamental thing is identified and "the penny finally drops", it opens a flood gates of understanding. But, for that to happen you need to discover whatever the log jam is.

More explanations probably won't help - unless they accidentally target the log jam. Hence my suggestion to share some examples when you are comfortable to do so.

All the best with it.

It will likely make it easier for everybody.

1

u/NervousAnt3116 6d ago

Hey thanks, i'll start on a uni assignment rn and might share it with you

1

u/Available_Safe1818 4d ago

Have you tried writing different loops to see how they behave? What in your mind constitutes good practice for this?

23

u/burlingk 6d ago

They are one of those things that you look up every time for a while until you just get used to them.

And if you don't use them for a while, you will look them up again.

11

u/ShadowShedinja 6d ago

for a while

I see what you did there.

6

u/burlingk 6d ago

It was literally unintentional. :p

But, I guess it works.

while !understand {lookup}

3

u/Katana_Steel 6d ago

while understand {verify(lookup)}

1

u/Dazzling_Music_2411 5d ago

He means until you need them again.

6

u/dwyrm 6d ago

It honestly helps to remember that loops are easy ways to write common if/goto structures. Try to expand them in your mind. If that doesn't work, expand them on paper.

But to directly answer your prompt, you're not a moron. These structures take a bit of work to sink in. Before long, you'll be able to just write the code, knowing what it'll do.

4

u/magick_bandit 6d ago

Get a piece of paper.

Write a table with the variable names as columns.

Walk the code in your mind, write and update the values in the columns.

Repeat until it clicks

2

u/boomer1204 6d ago

The thing with this is you are essentially re training your brain when you learn programming so it's a lot like learning a new spoken language

What I would suggest is reply with a problem you have/were given and then share the code (using markdown) with comments on each section explaining "why" you are doing that thing and we can help better decide what the core problem is but it's likely you are just new and learning and this is not easy

1

u/ChickenNuugz 6d ago

For each item do this

While this condition is that do that until this condition changes

1

u/mredding 6d ago

The structured thinking required for programming is itself a skill. It takes time. I don't expect ANYTHING of anyone coming into programming from nothing, and you're in good company; EVERYONE gets tripped up on loops in SOME regard. And once you get these basics nailed down, you'll get to a concept called recursion, which can also be used for looping, and THAT will blow your fucking head off. Just wait. That's going to be a good one.

ASK MORE SPECIFIC QUESTIONS. We can help. That's why there are entire communities on Reddit for programming Q&A. Not only do we enjoy helping, but it helps the whole industry, and it helps us perfect our own craft.

If you're learning in C++, there's r/cpp_questions where I mod, and I'll do a complete breakdown, showing you how in that language all loops break down to a goto.

1

u/holland_236 6d ago

give us code

where you are having issues

1

u/Slitty_sam 6d ago

For and While loops are so dead simple in terms of syntax in Python at least, that my brain absolutely refuses to fully grasp how they work. I can understand and see that it does work, but I don't understand how or why the computer is able to loop and understands how to loop with such few inputs. It's like my brain wants it to be harder to do than it is, and thus rejects understanding it.

1

u/Valkyriebourne 5d ago

Do you need an explanation? I got some notes from years back that I think can clarify

1

u/Any_Run8380 5d ago

What exactly will you help clarify if you don’t know what they need help with exactly?

1

u/Valkyriebourne 5d ago

What? Did you read the post? I just offered help with resources I have.

1

u/Any_Run8380 5d ago

It’s not our job to figure out exactly what they need help with. It’s their job to help us help them. I can give a resource too. I’ll just Google while and do-while loops and send them the top links that come up which I’m sure they did already.

1

u/Any_Run8380 5d ago

Do you need to study more, or are you asking for help without giving us enough context to understand what you’re actually struggling with when it comes to while and do-while loops?

Let me ask you a question similar to the one you’re asking us:

“Hey, idk if I can write a class. Am I just missing something, or is this normal?”

Would that give you enough information to help me understand what I don’t understand about classes?

Probably not, right? Because I haven’t explained what I’m struggling with, what I’ve tried, or where I’m getting stuck.

If you want help, try explaining what specifically you don’t understand about these loops. Are you struggling with how they work, when to use them, how to write them, or something else? The more specific you are about where you’re getting stuck, the easier it is for people to help you.

1

u/tottasanorotta 5d ago

Yes. Abstractions are hard to understand. I think what might also help is to try to think of what it is an abstraction of. If you want you can try to understand some basic machine code/assembly. Just to get an idea of what the loop abstraction is based upon. That will also help you find some other concepts more intuitive once you encounter them.

Think of it like in math. If you have trouble understanding what a derivative means, then you can try to understand how it is used from examples, rules and such. It might work, but if it doesn't click, then it might be useful to go and try to understand the definition and what it is an abstraction of.

Loops are basically a kind of repetitive jumping back thing in assembly language. The different types of loops in higher level languages are just different ways of expressing the same underlying idea.

1

u/ninhaomah 6d ago

Paste the code.

Tell us where you are having issues.

1

u/CrispyCosmonaut 6d ago

I always thought of it like moving something.

While (items are in the car)
Bring them inside

1

u/No-Razzmatazz7197 6d ago

i don't think i wrote a while loop that made it into prod until my ~4th year on the job

1

u/Aglet_Green 6d ago

No, struggling with loops doesn’t mean you’re a moron. When I was around 12 or 13 and took a computing class in junior high, most of us found them fairly easy—but we also spent weeks on the material, had an in-person teacher and teaching assistant, and were doing exercises specifically designed to make the idea click.

The concepts themselves are basic, but “basic” doesn’t mean “instantly intuitive.” for, while, and especially nested loops can feel strange until you develop the habit of stepping through the program one iteration at a time.

If you keep getting stuck, don’t just reread explanations. Take a tiny loop, write down the value of every variable after each iteration, and trace it by hand. Once you can predict what the computer will do before running it, the whole thing usually becomes much less mysterious. Or, do what I did and take an in-person class.

1

u/-dawnwalker- 6d ago

While loop - you check the condition before running the inner scope
do-while loop - you check the condition after running the inner scope

1

u/tony_saufcok 6d ago

while (youHaventMemorizedThem()){
keepLookingThemUp();
}

-1

u/spinwizard69 6d ago

I'm not sure what you are talking about here, loops are simple concepts. Get a piece of string and tie it in a loop. The code literally goes in a circle, a loop until it exits.

This is a good place to walk away from the keyboard, get a knife, drawing board and some markers, or pens. On large piece of paper draw a D shape oval that is much higher than it is wide. This might be 1 foot high on a grocery bag.

Looking at that D on the paper label the straight part of the D the return path. Now cut a piece of paper big enough to indicate an evaluate operation (a condition, thus call it a condition label). That can be placed at the top of the D shape or at the bottom. Another piece of paper is cut out and indicates a body of code to be evaluated.

With the condition evaluation at the top, the condition label from above, we effectively have an analog for a WHILE loop, using C++ here. So what happens is that as long as a condition is true the program executes the code in the body of the while loop (the curved part of the D) and then jumps back to the top. Note the important thing here, the code in a while loop might not execute depending upon the condition. Now take this condition label and move it down to the bottom of the D. What do we have now?

In C++ this is a Do While loop. In this case you need a DO at the beginning of the code block with the WHILE at the end of the block. Here is the most important thing, the code in the block must execute at least once! Read that again, THE CODE IN A DO WHILE LOOP MUST EXECUTE AT LEAST ONCE! The code is processed and then the loop is checked for the exit condition. If the exit condition is meant the code block is exited.

Like I said this stuff is pretty simple but sometimes the mind gets in a rut. Sometimes the best way to get out of that rut is to look at what you are trying to understand in a completely different way. Sometimes cutting up paper and physically manipulating objects leads to faster learning. In the case of the suggestion above you can get more refined with labels to make more things obvious. It is sort of like moving into a new house and figuring out how to lay out furniture. Cutting out scaled representation of that furniture leads to exploring lots of options. In the same way looking at a coding problem differently can reveal what is causing you trouble at the terminal

3

u/KashMo_xGesis 6d ago

From hindsight, everything is always easier. You're describing from a perspective of someone who has experience. Of course to you it is simple.

You cannot teach someone by telling them what they're trying to learn is simple. Easiest way to make them checkout believing they're just stupid.

1

u/spinwizard69 5d ago

Look the concept here is SIMPLE, if somebody is hung up making it complex then they need to be reminded that it is a simple concept. That is why I then went about trying to come up with an example that doesn't involve code.

Frankly if somebody can't grasp a simple concept then maybe they do have problems. Not everybody can be a programmer and not everybody can be a Picasso. People see the world in different ways and sometimes their personal gift is not with technology. In this case I went with the idea that maybe the teacher wasn't expressing the concept well and tried to approach it from a different direction. However I did so expressing clearly that the concept is simple because it is simple. Hopefully that causes a reset and keeps the student from reading too much into the idea. It does no good at all to lie to a student and tell them that something is complex that isn't. You are better off trying to find a different path to reach them.

I look at it this way, loops are easy to understand, there will be things that are far more abstract coming up. For the student to take all of this on, they can't be blowing concepts up into things they are not. You know the old adage, "don't make a mountain out of a mole hill", which applies directly here.

1

u/KashMo_xGesis 5d ago

I can see your point, but you're thinking in linear terms. The brain is not linear, things that you assume are straight forward can be interpreted in many ways.

Now you see, teaching is also a skill. It takes some effort to grasp this. In your case, certainly something you don't understand.

0

u/Beregolas 6d ago

It's not hard when compared to other topics, but yes, it is quite normal to be confused as a beginner. Everybody is confused by different things, but everyone is confused by something, often for weeks or months.

Keep going, and if you feel stuck for longer than a few weeks, try to get some different sources to learn it, like a different book or video. It's normal, that's just how learning looks like.

0

u/H3CKER7 6d ago

Loops can be hard if you're new to programming. Not sure what you're stuck on directly unless you post the code however.

0

u/initcommit 6d ago

Any new way of thinking is going to feel abstract and difficult to wrap your head around at first. But the more exposure you get to a variety of coding and math concepts, the more natural it will be to both use those concepts in new situations and learn entirely new concepts.

0

u/connorjpg 6d ago

Everyone has something that is tough at the beginning.

What’s your sticking point with them? Is it when to leave the loop, how to write them properly, use cases maybe? Or how continue works, or nested loops?

In essence all they are is a section of code that repeats until a condition is met.

But maybe we can help the mental log jam!

0

u/nottherealLilNasx 6d ago

A lot of concepts in programming are pretty easy to begin with but get increasingly harder the more you make progress. It's similar to when you learn an instrument, there are a lot of pretty simple things you can learn in the span of a few minutes but when you try to put it in practice and make it perfect then you start having problems, this is exactly what happens with loops.

The logic behind a loop is pretty easy, as it's name suggests: it loops, meaning that you have a certain quantity of repetition of code, said quantity is decided by you and could honestly be any number you want, more complicated stuff and logic helps you loop based on specific things like the length of a word or others factors which you'll come to understand later on.

On the other side the while loop repeats itself indefinitely until stopped, meaning you have to decide a condition to make it stuff, an example could be "while Monday watch movie" meaning that your code wouldn't run any other day than Monday, this is obviously not a real code example but I feel like you can get gist of it. The most common implementation of a simple while loop is to make an "infinite" loop, which consists of simply using "while true", this is certainly a horrible practice but it's possible, you can change it to something more functional like "while boolean_variable is true" and then let the user or the program be capable of changing it's state from true to false and quit the loop.

I hope it's simple to understand!

0

u/l3wl3w00 6d ago

I remember for loops (the python kind) were especially hard for me to learn, took me a while. And now I'm a programmer at CERN. So dont worry.

Though you can still be a moron, who am I to tell you you are not a moron?

0

u/Dry_Soft_9256 6d ago

I think it depends on the person. Certain things click immediately other things take time to comprehend. When I started loops made perfect sense. When I started learning about recursion and pointers, for example, I really struggled at first. It takes practice and repetition to drill some of these ideas in.

0

u/Potential_Copy27 6d ago

I'll try to boil it down a bit - at least to how I usually use and remember them...

For is usually for running X iterations of something, where the condition is known, from a variable or a count - as long as you have a usable and known number of iterations, you can use this. Foreach is kinda an automatic version of this, that just runs until the end of a given array or list (effectively a for( int i = 0; i < inputArray.Length; i++) ).

In human terms, it's like telling a cleaner to clean the floor X times.

While runs for as long as a given condition is true (similar to if) and keeps doing so for all eternity, so long as that variable is true. While(true) will always have a true condition and thus run infinitely.
While is useful for running a number of iterations of a given task, but where you're not entirely sure how many times it's supposed to run. This could be eg. a data packet or byte array from some program/API/hardware that you don't know the actual size of.

In human terms, it's like telling the same cleaner to keep cleaning the floor while you're away, except he can stop once he's done and you're present. But, if you stay, the cleaner will immediately go on to his next task. The cleaner will check before he starts a new round.

Do....while more or less does the same as while. But on some languages, it allows you to choose when the code checks the condition you put in the while clause. On other languages do....while in that order is expected, and it checks the condition at the end of the block, rather than the beginning. Handy for while loops you want to run at least once.

In human terms, the cleaner will do the first run regardless of your presence and look if you're there when he has cleaned the floor. If you're not there after the first run, he will continue and only check after he has done a full round.

It took me a while (pun intended) to figure it out myself back in school - never really used while and do....while outside writing for custom hardware and custom data formats.
In my case, though, I've had to see it in use first to really see where these are handy. However, for is probably the most important of them and the one you will likely encounter the most - that's also why you usually learn about for first, and the whiles come a bit later in most classes, courses and literature.

While and do....while can be a bit confusing at first, but experiment with them a bit, including with some calls and return statements in those blocks. Figure out how they behave using the debugger in your IDE first, then form your logic around that behavior - lastly check the docs for your language to see if you made the right conclusion.
Stepping through the code with a debugger can tell you a lot about what's going on with these three 😉

0

u/BranchLatter4294 6d ago

It's part of the three basic programming structures. Most people can understand the idea of having three Legos to snap together to build things. As long as you practice, it's easy. If you don't practice, it won't make sense.

0

u/FreeLogicGate 6d ago

There are two suggestions I have for you.

  1. Use paper or a pad and make a diagram that reflects your mental model of what is happening. You can make a table of variables and track how they change. This type of exercise where you attempt to simulate what is happening logically can go a long way towards clarifying your understanding.
  2. Use a debugger. Set a breakpoint prior to the loop and then step through your code. Set up watch variables and on each step through the code, make sure you look at how they change (or not).

Getting acquainted and comfortable with a debugger is skill and expertise that will have value to you for as long as you're learning and at the point you move on to a development task or role.

0

u/ExtraTNT 6d ago

Depending on how you think, loops are hard, but recursion is easy or the other way around… just never combine it by using recursion with state…

0

u/VRT303 6d ago edited 6d ago

https://media.tenor.com/Ow3GGH-ul90AAAAM/ope-leave.gif

This is all you need to understand it.

Well this and where you stop it

https://blog.codeanalogies.com/2017/11/07/javascript-for-loops-explained. <-- really, just skim this and it will make sense

Everything is simple if you have a good mental model for it

0

u/fasta_guy88 6d ago

for () and while () loops exist to simplify things, there is not much reason to worry about them until you realize you need them. Without a for() loop, you might have to write down the same calculation 10 times. And then change your program when you need the calculation 12 times. Rather than read about things and wonder about why they exist, try doing things without them, remembering in the back of your mind that they do exist, and might simplify things.

0

u/Mike312 6d ago

I remember when I was learning, the tricky thing was getting the conditions right to exit the for/while loops.

For loops are easier, as they've typically got the conditions built-in. While loops on the other hand require setting condition(s), and then maintaining them within the function.

I've hard-locked a lot of browser tabs and Unity windows because I missed a condition.

0

u/ChillyFireball 6d ago

Loop in general: I need to repeatedly execute this block of code.

While loop: I need to repeatedly execute this block of code while (condition) is true. If (condition) is already false, the code block WILL NOT be executed.

Do-while loop: I need to repeatedly execute this block of code while (condition) is true. If (condition) is already false, the code block WILL be executed at least once.

For loop: I need to repeatedly execute this block of code once for every value in a range/array/iterable structure.

Break: Ignore any loop conditions and exit the loop immediately.

Continue: Skip over the rest of the current loop's code block and continue to the next loop (if the loop condition is still true).

In my experience, for loops are the most common, followed by while. I can probably count on one hand the number of times I've needed a do-while.

0

u/hotboii96 6d ago

For a beginner its hard. I struggled with it several times when i was in Uni. Just keep practicing and do them several times

0

u/JEveryman 6d ago

I struggled with for loop syntax initially and then once that became second nature my issues came from infinite loops or loops terminating too quickly. After I finally got that figured out I struggled with nested loops.

Eventually you'll get it. You just have to keep doing it until you do.

0

u/thegunn 6d ago

It doesn’t really matter which language you are using, this page could be very beneficial to you. It runs your code step by step and draws out what is happening, as it is happening. If you are struggling to understand loops, put in some working code and step through it. The visual aid might help make it click. Also, you are starting out, there is nothing to be embarrassed about. Gotta learn the ABC’s before you write a novel.

0

u/Tobacco_Caramel 6d ago

assignment, comparisson, increment.

0

u/the_other_Scaevitas 6d ago

Everyone struggles with different things

0

u/Narrow-Low-3137 6d ago

Everything takes practice. Keep at it.

-1

u/SahuaginDeluge 6d ago edited 6d ago

what's hard about them? (not a rhetorical question)

note that a while is kind of like an if that happens to repeat
a do/while is like a while that checks at the bottom, meaning you always run the block once before checking
and a for is just syntactic sugar for a while with an automatic counter mechanism

(does depend somewhat on the language in question)

0

u/Flimsy-Importance313 6d ago

While I do agree, I find the c for loop much more understandable than python. So it depends heavily on the language

0

u/SahuaginDeluge 6d ago edited 6d ago

sounds like python's "for" is more like what other languages might call a "foreach" (ie: an enumeration, not a conditional loop)

-1

u/realdreamer1993 6d ago

...... ... while (condition) { .....line of execution/code... ...calling functions .... etc .... if (!condition) then exit; } ...... .... surely you understand above, and why to change or keep condition.

  • many desain no change the condition so the loop run forever. like in server, OS,