Understanding the For Loop (examples in C)

  Рет қаралды 17,021

Jacob Sorber

Jacob Sorber

Жыл бұрын

Patreon ➤ / jacobsorber
Courses ➤ jacobsorber.thinkific.com
Website ➤ www.jacobsorber.com
---
Understanding the For Loop (examples in C) // For loops seem to give beginners more trouble than while loops. So, I thought we would break them down a bit and try to take some of the mystery out of one of the most common programming constructs out there.
***
Welcome! I post videos that help you learn to program and become a more confident software developer. I cover beginner-to-advanced systems topics ranging from network programming, threads, processes, operating systems, embedded systems and others. My goal is to help you get under-the-hood and better understand how computers work and how you can use them to become stronger students and more capable professional developers.
About me: I'm a computer scientist, electrical engineer, researcher, and teacher. I specialize in embedded systems, mobile computing, sensor networks, and the Internet of Things. I teach systems and networking courses at Clemson University, where I also lead the PERSIST research lab.
More about me and what I do:
www.jacobsorber.com
people.cs.clemson.edu/~jsorber/
persist.cs.clemson.edu/
To Support the Channel:
+ like, subscribe, spread the word
+ contribute via Patreon --- [ / jacobsorber ]
Source code is also available to Patreon supporters. --- [jsorber-youtube-source.heroku...]

Пікірлер: 79
@tankapdsharma8177
@tankapdsharma8177 Жыл бұрын
TNice tutorials is actually a very good and straight forward tutorial. No having ask questions or guess, no over-explaining elents, and brings
@anon_y_mousse
@anon_y_mousse Жыл бұрын
As for the value of these videos, I'd say the gain I get is tangential as the more people that learn from you the better the industry gets. On the subject of not needing for loops, C gives us many ways to do things, it is only our desires which push us in a given direction. We could after all use labels, gotos and simple ifs. That might make for a really good video to show how looping constructs break down at a low level. Maybe even demonstrate one of my favorite ways of handling cascading errors.
@ahmadhadwan
@ahmadhadwan Жыл бұрын
I would say a for loop enthusiast is one that writes infinite loops this way: for (;;) { // code }
@benhetland576
@benhetland576 Жыл бұрын
Yes, that is how you spell "forever" in C ;-)
@ahmadhadwan
@ahmadhadwan Жыл бұрын
@@benhetland576 I guess having a macro defined as #define forever for (;;) is okay, but i find while (1) clearer.
@sarimjalil6690
@sarimjalil6690 11 ай бұрын
Hi, First of all, great video great content. I have learned a lot from the video series. One thing that I want to add to the explanation is, It's perfectly right to use a while loop for everything but one difference is that my professor told me back when I was in university. If some problem requires a fixed number of iterations or you could say if you know how many times the loop is going to run then use FOR loop and if you don't know the number of iterations like you are reading from a file and the condition is read till ' ' then use While loops. I think this makes sense and it makes sometimes the implementation easy.
@_modiX
@_modiX Жыл бұрын
The lighting .... the audio .... the cringe .... the whole setup .... I'm amazed. Haha. Please keep going, I want to see how this will evolve.
@maveasna2096
@maveasna2096 Жыл бұрын
លោកគ្រូ your daughter is finally back on the video Last time I saw you all in Africa. she definitely looks after you for sure.
@sanderbos4243
@sanderbos4243 Жыл бұрын
Really fun episode!
@SimGunther
@SimGunther Жыл бұрын
15:34 What I say to myself in half of my code reviews XD
@joaomane4831
@joaomane4831 Жыл бұрын
Hi, Jacob. Could you please give your opinion on the "CuTest" unit testing framework? Should I use that one or criterion if I want to test my C applications? Thank you in advance
@kevinkkirimii
@kevinkkirimii Жыл бұрын
Hey Matthew, your videos are really dope , thank you.
@BlueSheep95
@BlueSheep95 Жыл бұрын
Who is Matthew?
@trustytrojan
@trustytrojan Жыл бұрын
This video will help coding beginners a lot!
@alexanderscheffer3882
@alexanderscheffer3882 Жыл бұрын
Thank you Jacob for this cool video 😎
@JacobSorber
@JacobSorber Жыл бұрын
You're welcome. Glad you enjoyed it.
@unperrier5998
@unperrier5998 Жыл бұрын
It's interesting to see the point of view of a beginner, especially because it's a beginner channel.
@justcurious1940
@justcurious1940 Жыл бұрын
nah i think developers from different levels can use this channel as reference
@unperrier5998
@unperrier5998 Жыл бұрын
@@justcurious1940 I've not learned much on this channel. I like to watch Jacob teaching, what's his approach, where he stops in the complexity, this sort of things.
@jimshtepa5423
@jimshtepa5423 9 ай бұрын
Jacob, what are good projects to work on to practice skills in c?
@subhajitmoyra6275
@subhajitmoyra6275 Жыл бұрын
Between Producer and Signature, wNice tutorialch SKU would you recomnd? Is Signature worth the 50% price bump? ItNice tutorialnk I want to have
@kerr1221
@kerr1221 Жыл бұрын
Your merch store is down! I'm taking a c programming for electrical engineers course and wanted that shirt to wear!
@JacobSorber
@JacobSorber Жыл бұрын
Yeah, merchonate went out of business. I'm working on an alternative. Sorry.
@cmdlp4178
@cmdlp4178 Жыл бұрын
I missed for loops iterating over lists in the video, here is the for loop I always write: NODE* head = ...; for(NODE* i = head; i != NULL; i = i->next) { ... } or simply for(NODE* i = head; i; i = i->next) { ... } or if there would have been a '->=' operator in C: for(NODE* i = head; i; i->=next) { ... }
@anon_y_mousse
@anon_y_mousse Жыл бұрын
Aha, found the for loop enthusiast. I nearly always while loop that idiom.
@AlexJacksonSmith
@AlexJacksonSmith 11 ай бұрын
You don't mention if there is a performance difference between a for and while? Is that so compiler dependent that it can't be answered generically or is there a rule of thumb? Cheers.
@skilz8098
@skilz8098 Жыл бұрын
I'm surprised you didn't get into the topic of pre and post increment within the loop counters.
@_baco
@_baco Жыл бұрын
I've tried that bit of code, but trying to compile that with GCC v13.1, I get a compilation error stating: ``` example.c: In function ‘main’: example.c:15:35: error: variable-sized object may not be initialized except with an empty initializer 15 | int myvalues[ARRAYSIZE] = {1, 2, 3, 4}; | ^ ``` What compiler are you using there?
@vaijns
@vaijns 11 ай бұрын
With clang the code compiles, just printing out a warning of "variable length array folded to constant array as an extension [-Wgnu-folding-constant]". If you'd replace the "const int ARRAYSIZE = 5;" with an macro like "#define ARRAYSIZE 5" it'd compile with both gcc and clang (and probably any other compiler). Even tho it seems he was using gcc in the video (at 4:50 you can see it after he ran the make command), not sure if anything changed in that compiler regarding this or if it is a configuration thing.
@jenselstner5527
@jenselstner5527 Жыл бұрын
Isn't the comma operator not defined in which order the statements will be executed?
@cmdlp4178
@cmdlp4178 Жыл бұрын
The comma operator is a sequence point, the order is defined from left to right. You might have confused this with the sequencing order of function parameters, which is not defined by the standard.
@AaronMatlock
@AaronMatlock Жыл бұрын
This was my question as well especially when compared to something like "x = y++ + y;" which has an undefined outcome.
@dixztube
@dixztube Жыл бұрын
Man I’ll tell ya coming from node to working on a go project it’s so cramped!!! It drives me crazy they don’t use more line breaks for convention. It’s a sin!
@belesiu
@belesiu Жыл бұрын
Does clever code compile to smaller\faster machine code?
@dmitripogosian5084
@dmitripogosian5084 Жыл бұрын
Not clever code compiles into fast machine code only if compiler developers were clever. So somebody has to be clever
@danielrhouck
@danielrhouck Жыл бұрын
I would never write this for real code for anyone but me, but a backwards iteration trick you can use as a mnemonic is the “goes to” operator -->: for (size_t i = ARRAYSIZE; i --> 0; /* no update statement */) { printf("%d", arr[i]); } (This is actually parsed as i-- > 0, but that way it’s harder to remember how to avoid off-by-one. Also note this version works with unsigned types.)
@benhetland576
@benhetland576 Жыл бұрын
I've had quite a few cases over the years needing to do this, and eventually I have come to the conclusion that this is actually the "best and safest way" to down-loop as long as we're working with indices. Just accept the pattern/idiom, even though it may look a bit weird at first.
@danielrhouck
@danielrhouck Жыл бұрын
@@benhetland576 I write it as `i-- > 0`, not `i --> 0`, when I’m not using it as a mnemonic.
@benhetland576
@benhetland576 Жыл бұрын
The idiom applies well to copying a (null-terminated) string in C as well: char to[100]; char* from = "Hello, world!"; for (char* c=from, *d=to; *c; c++, d++) *d = *c; It's becomes a one-liner, but since it's easy to forget the null-termination that way, a slightly more obfuscated way might be "better", especially if you are a for-fan: for (char*c=to,*d=from; *c++ = *d++; ); This is another example of "any non-zero value is true" being applied in C coding. (Yes, I know there is _strcpy_ too...)
@anon_y_mousse
@anon_y_mousse Жыл бұрын
Better to use an index and not do two increments per loop. If you're implementing strcpy and doing so the naive way: for ( size_t i=0; (d[i]=s[i])!=0; i++ ); is cleaner and easier to understand while being more succinct. But if you're reinventing the wheel, do so with at least 4 byte chunks if not SSE instructions and maybe 16 byte chunks.
@benhetland576
@benhetland576 Жыл бұрын
@@anon_y_mousse Why is 2 indexed lookups better than 2 increments? The indexed lookups imply 2 additions (ptr+idx) and 1 increment per loop, the latter usually being a superfast trivial operation on most CPUs; compared to only the 2 ptr increments. (Indexed lookups are also more complex and potentially a slower operation.) Reinventing the wheel is the joy of learning how the CPU works or how algorithms work, so it is, or should be, at the heart of programming knowledge IMHO. Anyway, we are probably not so concerned about how "compilers can do a much better job of optimization" in this particular context, but your suggestion to use SSE or multibyte chunks makes an excellent excersize too!
@anon_y_mousse
@anon_y_mousse Жыл бұрын
@@benhetland576 Since the processor can do an indexed reference the same as a direct reference, and you'll ideally be using registers anyway, an offset in a register can be cached better and work faster per loop because you're only incrementing once instead of twice.
@potatoYt655
@potatoYt655 Жыл бұрын
nice
@SlideRSB
@SlideRSB Жыл бұрын
If not for loops, then for what?
@ramakrishna4092
@ramakrishna4092 Жыл бұрын
hi sir . wonderful video on for loops sir can you pls explain how to return 2d array from functions statically because I faced this question in sde interview in abc company ....
@tiagomelojuca7851
@tiagomelojuca7851 Жыл бұрын
Hey, jacob. Do you have plans for KZfaq membership? Love your channel and content, and I'd like to support somehow, but I'm from a poor country and our currency is weak, a cheaper option would be great
@rhythmmandal3377
@rhythmmandal3377 Жыл бұрын
Yeah in C we don't need for loops but I like the fact that for loops in OO languages takes this mentality and applies it for iterables
@dexter117
@dexter117 Жыл бұрын
Well not in explicitely way, you're refering to for eachs loops, that in fact are just while loops that compiles in another abstraction layer of the code generation that your tecnology framework is familiarized with, so to keep it simple, for isn't a good idea in OO languages neither due the irresponsble data mutability that implies their usage
@bignaughtydog
@bignaughtydog Жыл бұрын
Will somebody please please please please please write down mathematically, in a table with columns, what is going on. When to add the increments etc. Let's say a for loop to add all odd numbers from 1 to 100. In my program I have included printf within the for loop curly braces which prints the series of numbers. I understand the for loop function, However when I put pen to paper I can't nail down what's going on. I have searched and searched for an answer but nobody is answering the question. Am I asking too much? Thanks for your content. I have subscribed etc. Steve. Bulgaria 😊
@jarvenpaajani8105
@jarvenpaajani8105 Жыл бұрын
bruh your while loop needs to be inside curly braces to be totally equivalent with the for loop. Now you can access i after while loop but not after for loop.
@justcurious1940
@justcurious1940 Жыл бұрын
wow so clever bro i have not thought about it
@metal571
@metal571 Жыл бұрын
It feels like we should be teaching preincrement rather than postincrement to exactly and directly express intent
@dixztube
@dixztube Жыл бұрын
Look at them in assembly
@oysteijo
@oysteijo Жыл бұрын
And: for( list_elem_t * iter = head; iter; iter=iter->next ) { /* Do something */ }
@edgeeffect
@edgeeffect Жыл бұрын
It's a funny thing,... as you state here, the for loop is a special case of the while loop. But the while loop came in with structured programming and Algol -> Pascal -> C ... whereas the for loop predates structured programming and can be found in the likes of Fortran IV and BASIC. No particular point to make, just an observation, just a "here's a funny thing".
@JacobSorber
@JacobSorber Жыл бұрын
Interesting. Thanks.
@tineocedric
@tineocedric 3 ай бұрын
int me = big fan of Eliza's snark and wits
@Daniel.W.R.Rehman
@Daniel.W.R.Rehman Жыл бұрын
for those who don't know the correct C idiom: for (int i = count; i--;) { // do stuff with array[i] } loops over an array backwards perfectly.
@worldshaper1723
@worldshaper1723 Жыл бұрын
Just to let you know, KZfaq has a bug that keeps unsubscribing me from your channel. This has being going on for at least a month.
@tosemusername
@tosemusername Жыл бұрын
I'm pretty sure I've seen this video way before.
@cybomer
@cybomer Жыл бұрын
I'm using VS Code with MSYS2 gcc compiler. I'm getting the following error: "Variable-sized object may not be initialized". Some sources on StackOverflow mention that this is due to initialization standardized in C99. It's interesting that memset() function isn't used here. The workaround I've found is using #define ARRAYSIZE 4 instead of const int. I'm wondering if there's something I'm missing in the JSON configurations or missing something in syntax. I'm simply wanting to print each index and value pair of the array with formatted output. Is anyone else having issues with this code from the video? Please advise and provide solution. #include #include #include const int ARRAYSIZE = 4; int main(int argc, char **argv){ int myValues[ARRAYSIZE] = {1,5,8,3}; for (int i = 0; i < ARRAYSIZE; i++) { printf("%d: %d ", i, myValues[i]); } return 0; }
@pranavnyavanandi9710
@pranavnyavanandi9710 Жыл бұрын
Who's Eliza?
@justcurious1940
@justcurious1940 Жыл бұрын
while(true) { std::cout
@jackgerberuae
@jackgerberuae Жыл бұрын
But that is C++ 🧐
@justcurious1940
@justcurious1940 Жыл бұрын
@@jackgerberuae i think loop constructs are the same
@benhetland576
@benhetland576 Жыл бұрын
@@justcurious1940 Not any more. In C++ you can now write things like _for (const auto& element: array) { /*do something*/ }_
@justcurious1940
@justcurious1940 Жыл бұрын
​@@benhetland576 yes the for range loop is the only difference but for me it can't get the size of a static 2 dimension array with 2 dimension vector works perfectly
@jackgerberuae
@jackgerberuae Жыл бұрын
I gather Eliza is your sister ?
@JacobSorber
@JacobSorber Жыл бұрын
Nope. Daughter.
@anon_y_mousse
@anon_y_mousse Жыл бұрын
@@JacobSorber Given the way she talks to you, I'm guessing teenager? I'm sorry for your loss. When they reach that age you've lost every battle and the whole war.
@JacobSorber
@JacobSorber Жыл бұрын
​@@anon_y_mousse No complaints here. She's no longer a teenager, and in most of our life battles she and I are usually on the same team. It's all good.
@anon_y_mousse
@anon_y_mousse Жыл бұрын
@@JacobSorber Glad to hear it's worked out better for you. For some, teenagers are the death knell of their relationship with their children.
@jackgerberuae
@jackgerberuae Жыл бұрын
@@JacobSorber nice to see her then. I watched your videos from Botswana’s days and your kids featured then too for a brief period of time. I am a native from neighbouring SA so was quite surprised to see you there, virtually that is. You should tell us more about your time there, as it is a mostly a lovely country.
@portblock
@portblock Жыл бұрын
Sometimes I show, just for fun for ( i=0; myProcFunc(i); i++ ); for ( init_func(); eval_func(); ); One I show new embedded programmers, I show: for ( i=0; i
@michaelkotthaus7120
@michaelkotthaus7120 Жыл бұрын
I think you missed the increment of i in the second version.
@portblock
@portblock Жыл бұрын
@@michaelkotthaus7120 if you are referring to : for ( init_func(); eval_func(); ); then nope :) But there are rare reasons to do this and it can be confusing, but it shows the understanding of for(), where the items are __RUNCODE__, __EVALCODE__, ___DOCODE__ By doing this, you can exand your eval condition example: int eval_func(int n) { int flg = 1; if (n == 5) { flg = 0; } if (SOMEVAR == SOMECOND) { flg = 0; } return flg; } for(i=0; eval_func(i); i++) { ..code.. } You can compile this src below showing no 3rd item in the for command #include int i; void init_func(void) { i = 0; } int eval_func(void) { printf("iteration: %u ", i); i++; if (i
@michaelkotthaus7120
@michaelkotthaus7120 Жыл бұрын
@@portblock No, I meant the while-loop after "translates to". I miss the increment of i. This is a reason why I also prefer for-loops: with the three common parts (initialization, condition, increment-command), it is harder to miss one.
@portblock
@portblock Жыл бұрын
@@michaelkotthaus7120 ah yes, you are correct! My apologies
@benhetland576
@benhetland576 Жыл бұрын
I observe that you are now approaching Lisp's fundamental Read-Eval-Print loop, which is perhaps claimed to be the hidden underpinnings of every other programming language at their core...
How to get better help with your programming.
4:58
Jacob Sorber
Рет қаралды 5 М.
What the FizzBuzz? (A toy problem worth caring about?)
17:16
Jacob Sorber
Рет қаралды 12 М.
Я нашел кто меня пранкует!
00:51
Аришнев
Рет қаралды 5 МЛН
Эффект Карбонаро и нестандартная коробка
01:00
История одного вокалиста
Рет қаралды 9 МЛН
Pulling Back the Curtain on the Heap
21:38
Jacob Sorber
Рет қаралды 36 М.
Loops in C++ (for loops, while loops)
12:20
The Cherno
Рет қаралды 399 М.
Master Pointers in C:  10X Your C Coding!
14:12
Dave's Garage
Рет қаралды 289 М.
Is the C programming language still worth learning?
9:27
Jacob Sorber
Рет қаралды 91 М.
The What, How, and Why of Void Pointers in C and C++?
13:12
Jacob Sorber
Рет қаралды 51 М.
Fixed and Variable Length Arrays in C and C++
20:24
Jacob Sorber
Рет қаралды 43 М.
Making variables atomic in C
11:12
Jacob Sorber
Рет қаралды 36 М.
For Loop Java Tutorial #23
7:54
Alex Lee
Рет қаралды 395 М.