Intro to Coding: Volume II
By Aditya Chopra
Till now you learnt the very basics of coding. You can display a few statements, run a few mathematical operations etc.
But there is more to coding than menial tasks which can be carried out by humans.
The first in the list of a million things coding enables you to do is repeat a similar task n number of times in just a few seconds. For this we use loops- namely if loop, for loop and while loop- which run until a condition is satisfied or dissatisfied. A few important loops are shown below.
Loops are closely linked to arrays as to insert values into an array, loops can be a useful tool.
int x, i;
This is an example of the for loop. The for loop uses a variable (in this case i) which is initialised to a value. This value is the first statement denoted in the bracket succeeding for. The second statement gives a condition as to till what value of i will the loop continue running till. The last statement shows what will happen to the value of i after every run of the loop.
Thus in the loop above, i starts from 0, is allowed to exceed to a value which is less than or equal to 10 and every time the loop runs, i is incremented to a value greater by 1.
Thus we first use cin>>x[i]; to input the zeroth element. Then i moves to 1 and we input the 1st element and so on till the condition i<=10 is no longer satisfied.
We could also use this to input a matrix. For this we would use a nested for loop and two different variables, i and j, to run two different loops. Why don’t you try yourself and you can check if you were right in next edition’s article.
Continue coding at cpp.sh
P.S to code on cpp.sh please use the statement
using namespace std;
which has no significance in coding but is just unique to the compiler.