(Because I felt like helping someone out, and avoiding doing work)
For loops are used when a particular action needs to be carried out a set number of times - ie; printing an int to the screen 10 times (a boring example, but a simple one).
The basic statement in C is as follows:
for (initialization_expression; loop_condition; increment_expression)
// code goes here…
Basically, for EACH for loop, you need a counter value. For nested loops, these counter values must be declared before any loop begins, or the value will be initialised each loop, and you may end up in an infinite loop.
//An example of properly set out nested for loops:
for(i=0; i<=10; i++)
//code can go here
for(j=0; j<=5; j++)
//code goes here
This code demonstrates the first loop running 10 times, with the second loop running 5 times per each first loop. At the end of all execution, the first for loop would have run 10 times, but the second would have run 50 times all up.
- “i++” is the same as “i = i + 1”
- The 10 in “i<=10” and the 5 in “j<=5” were picked at random. These values will change depending on how many loops are needed.
- If the program had “int k = 5”, then “j<=k” would also work.
- variable names such as “i”, “j” and “k” aren’t very good - it’s always best to use descriptive terms. I used these for the sake of simplicity though.
Also, notice that the second loop is indented (or should be at least, unless tumblr ruined my formatting >.>). This indenting is great programming practise, making it easier for others to read and also makes it easier for you to visualise what code is in which loop.
That’s enough attempted explaining for now - it’s 1am and I’m off to get back to my assignment work. Questions welcome though :)
- girlboss likes this
- laboulette likes this
- rapplatt reblogged this from doodlesalot and added:
- unrealisananagramfor likes this
- strychinine likes this
- nitrovert-red47 reblogged this from doodlesalot
- xplusplus likes this
- justinherrick likes this
- anarchyagogo likes this
- doodlesalot reblogged this from lifeandcode and added:
- pocketforstupidcomments likes this
- lifeandcode reblogged this from rapplatt and added:
- pterabites likes this
- omiwankenomi likes this
- distractiblescholar reblogged this from rapplatt
- placeblogger likes this
- rapplatt posted this