Loops 3: For
Hello everyone,
this is the third and the final part of the loops section.Yes we will be dealing with for loops. In while and do-while, you do the changes for termination criterion in the loop. In for loop, initialization of termination criterion, checking termination and changing its value are done at the top of the loop. Let's check the structure of this loop.
for(termination_variable initialize; check termination_criterion; termination_variable change)
{//do something;
}
Let's write an example code to calculate factorial of a number
#include <stdio.h>
int main()
{int number,counter,factorial;
printf("Enter the number you want to calculate its factorial: "); scanf("%d",&number);factorial = 1;
for(counter=1;counter<=number;counter++)
{factorial = factorial*counter;
}
printf("Factorial of %d is %d\n",number,factorial);return 0;
}
In this code, termination variable is counter and termination criterion is "counter is less then or equal to number". If this criterion returns false, you will be done with the loop and program will flow normally. By the way you don't have to write all the fuss about termination. You can put an if statement and a break inside that if statement. So if the termination criterion returned false you can use break and get out of loop.
To all who read these tutorialish writngs, i will put examples about the subject every time i find a small gap in my program. So don't worry about lack of examples. You can write code about things in your mind. For example I did write a database management program when i took the c programming language course, it wasn't even a project or homework. All i knew was i need to use loops to display data, scanf-printf also required and using control statements to check the situation of data,db and flags. By this way, you can easily develop your writing and reading algorithm skills.
