Logic in programming

Every code requires logic. A coder has to think about the logic behind every task needed to be performed by the computer. If you learn the approach towards the thinking of logic behind tasks and coding in some specific language like C++, it opens an endless corridor towards building your own applications through drones. By coding you can make a drone do a variety of tasks.

As we know that there are various programming languages available. Any computer program can be written by following three constructs, irrespective of the language.

Sequential statement

These are the basic simple statements in the code. These statements are used for creating a variable, calling functions, assigning values, etc.

Example: In mathematics, we assign values to variables such as let x = 10. In the same way, while coding, we sometimes require too assign values to variables. In C++, it is done in the following way:

int x = 20;
fucntion ();

Conditional statement

Sometimes, you want the computer to do a specific task by making a decision on its own, depending on the situation or condition.

For example, you could write a program where in the computer asks the user to type a number and then the computer displays whether the number is positive or negative. In such a program, you could use a conditional statement, if else. The logic would be:

If (y < 0)
cout << “the number is negativen”;
else if (y == 0)
cout << ”the number is neither positive nor negativen”;
cout << “the number is positiven”;

Here, the program will  check the first condition, it will display the concerned message. The interesting part is that you do not need to specify the last condition that the number should be greater than zero, because if the first two conditions are not satisfied, then the only remaining possibility is the third one. This is a very simple example of how you can instruct the computer to do tasks using simple logic.

Repetitive statement

The third important part of coding is repetitive or iterating statements. These statements are used where you want the computer to repeat the same set of codes again and again for a certain number of times or while a condition lasts. They are also called as loop statements. Let us take an example of a code where you want to print numbers from 1 to 10. In this case, the task for the computer remains the same, i.e. to print a specific number. Hence, the statement is going to be repeated. Here we can use a loop statement, while.

int x = 1;
while (x < 11)
cout << “x, “;
The above code will print: “1, 2, 3, 4, 5, 6, 7, 8, 9, 10, “

All the problems, 0 simple or complex can be solved by these three parts as a solution. The number of times each of these parts is used in a code can vary, depending on the logic and the level of simplicity in the code.