Intro to Coding: Volume II

Intro to Coding: Volume II

By Aditya Chopra

Arrays

An array is multiple units of the same data type clubbed together for easier computing. They are declared in the following ways:
int arr[50];  //Array declaration
arr[]={25,40,30,10}; //array initialisation
or
char arr[20];
arr[]={“Hello World”};
In the shown cases, the number in the square brackets denote the array’s size and the letters proceed it denote the array’s name. Arrays can be used to input sentences, compile data and even build matrices.
A 2 dimensional array could create a 2 dimensional matrix.
int arr[4][4];  //This would create a 4×4 matrix
Loops in C++

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.

For example:

int x[10], i;

for(i=0;i<=10; i++)

{

cin>>;

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.

Thank you.