In this lesson we’ll review arrays. Also you’ll learn if, if-else, while, do-while, for, foreach loops.
An array is a special variable, which can hold more than one value at a time.
In other words, array it’s a group of elements of the same type located in RAM one by one.
Following code demonstrates how to create an array according to the picture above:
Please pay your attention that first element of array has index zero - 0.
Any array element can be accessed by its index:
Use if to specify a block of code to be executed, if a specified condition is true:
Use else to specify a block of code to be executed, if the same condition is false:
switch statement is a good alternative to if-else operator if many cases has to be verified. switch can be used instead of a long if-else chain.
switch operator diagram:
In the source code it’ll look like:
With a long if-else chain it’ll look as:
The while statement continually executes a block of statements while a particular condition is true.
It can be expressed with the following source code:
do-while loop is a bit different than just while. while loop checks condition first before to execute its body code. do-while performs it vise versa. It executes body code first and then verifies condition whether to execute body code again or not. Please find do-while diagram below:
Following source demonstrates it in action:
Loop ‘for’ has more functionality than any other loop statement. ‘for’ loops can execute a block of code a predefined or calculated number of times.
This diagram demonstrates how it works:
An example below just simply iterates 9 times:
Try to build and run all examples from this lesson.
Implement a Calculator console application.
- It should ask you to enter two numbers.
- When numbers are entered, then it should as operation that has to be performed (/, *, + or -).
- Show calculation result.
- Start process from scratch. It should ask user to enter two numbers and so on…