For Loops In C
Let us first understand what are loop. Let us take a example. Suppose I ask you to do push ups 15 times. Then you will repeat the same process of going down and coming up by increasing your count every time till you reach 15. This is the most basic idea of a loop.
Every loop has an starting condition, called as initialisation.
Then is has has to check for a paricular condition to fulfil. That is the condition where it has to stop. It may also be the condition that drive the loop.
The third id the update. It is very important condition in a loop.
Think about the situation where i say do push ups 15 time, but do not increase your count and start from one. Then you will never stop (Well actually you will.) and so will the computer. So an invalid update or no update may lead us into an infinite loop and cause the program to crash.
So let us first write a code to print numbers from 1 to 10 and then understand what it means.
The code is -
The output is -
The syntax of for loop is of form
for (initialise; check; update) { }
Initialise
This part of for loop creates an initial state.
Check
Before each iteration this check condition is checked. If this eveluates to false, the loop breaks.
Update
this updates a counter that we set.
The next exapmle will make it more clear. Let us print table of 3
The output is
We will look back to loops again when we will study array.
Here are some links to practice question.
Theses questions only require knowledge of for loop, nothing else. Don't get confused by the title of the questions. These can be done without using array. Just use commonsense
Simple Array Sum (Hackerrank)
Life Universe and Everything (Hackerearth)
Factorial (Hackerearth)
Find Product