Learning Programming #1.3 The Basics: Conditions and Loops

In my last posts you learned what variables are and what simple operations you can do with them. In this post you will learn about the other important elements of programming which are important for any program.
Screenshot from 2019-05-02 19-03-50.png
There are 2 different structures: loops and conditions. The code inside a condition is repeated once, if the condition is true, while it is repeated until the condition is false in a loop.

Conditions

There are 3 different types of conditions: if, else if(java) or elif(python) and else.
The first two consist of a condition which is a Boolean and a body which contains code that is executed when the condition is true. else only consists of the body. else ifand else are only executed in the programm if the previous condition was false and this condition has to be directly prior to the else (if). You can see the structure of condition and body in the picture above.
You don't need to put directly a Boolean into the condition, but you can also put several Booleans combined with logical operators inside or Booleans that are result of comparing operators(see #1.2).

Task 1

Write a simple code that manipulates a number x in way that as a result you get a number, that is even and equal to the value of x or equal to the value of x+1.

Loops

There are two different kinds of loops. The for and the while loop. The while loop is similar to a condition, but the code inside the loop is repeated as long as the loop condition remains true. The for loop is a special form of the while loop, which allows to repeat the body n times easily.
The syntax of for loops is very different in java and python:
java:

for(int i = 0; i < length; i++) {
    //put your code here
}

python:

for(i inRange(length)):
    //put your code here

As you can see the python code is much simpler, but the java code allows more freedom(for example you could change i in a different stepwidth with i = i+2 you would only go through all even numbers that are smaller than length. Also you could start i at a different value other than 0).

There are also two keywords which are not necessarily needed, but that are often used(at least by me).
Those are break and continue. break instantly stops the loop and moves toward the code that is written directly after the loop. continue jumps to the start of the loop again. These keywords can be applied to both for and while loops.

Task 2

Write a simple program that calculates the sum of all integers between 0 and 1000(including 1000).

Task 3

Try to replicate the behaviour of a for loop using a while loop.

Coin Marketplace

STEEM 0.16
TRX 0.15
JST 0.028
BTC 59698.94
ETH 2303.28
USDT 1.00
SBD 2.51