In the previous chapter, we learned about algorithms.
An algorithm is simply a sequence of steps that describes how to solve a problem. For example:
- Ask the user for their age.
- Check whether the age is 18 or older.
- If it is, display "Access granted."
- Otherwise, display "Access denied."
Once you have that sequence figured out, a question naturally arises: how do we hand this recipe over to a computer?
When newcomers first look at computer programs, they often see a bewildering landscape: C, Java, Python, JavaScript, Rust, Go, C#… each filled with strange punctuation, semicolons, brackets, and keywords. It looks like a tower of Babel.
Here is the industry's best kept secret: they are all saying the exact same things.
The rules for writing a programming language are called its syntax. Every programming language is merely an agreed-upon vocabulary (syntax).
Human languages have grammar. For example, English has rules about where words belong in a sentence. Programming languages also have rules.
The purpose of a programming language's syntax is to translate four fundamental algorithmic actions into machine instructions:
- Input & Output (communicating with the world)
- Process & Storage (remembering and calculating)
- Decisions / Conditionals (branching paths)
- Loops / Repetition (doing things until finished)
In this chapter I will explain these actions; in the next chapter I will dive deeper into more language syntax and structures like functions, object-oriented programming, and more.
I will demo each of the above actions in 4 languages, and I will also explain that some of the syntax differences are driven by each language's original purpose.
Meet the four languages
- C: the old, respected grandfather (1972), still running inside operating systems and devices. It gives the developer more power to control the system, like managing memory.
- Java: the serious enterprise worker, found in banks, insurance companies, and Android phones. It was the first popular language that let you write code once and run it on any operating system, like Windows, Linux, or Mac. With other languages, you had to compile the code separately for every target operating system (we explained compiling in earlier tutorials).
- Python: the friendly one, famous for code that reads almost like English, and the favorite of AI and data science. It became popular because it's easy, and because people who are not necessarily programmers (like data scientists) could use it easily.
- JavaScript: the language of the web, running inside every browser in the world.
You will notice in the following examples that C, Java, and JavaScript have a very similar syntax, while Python is a little bit different.
Variables
Before we jump into the examples, there is one important concept you must learn: variables. All languages have them, with some differences.
A computer program constantly works with data, as I explained in my first tutorial, "all is data." For example:
- a person's age
- a customer's name
- the price of a product
- the current temperature
- the number of items in a shopping cart
Programs need somewhere to keep these values. Why? Because when you write code, you don't know what data the user will input, so you need a named place to use in your code, and when the user enters values, you store them in the variables so you can use them later.
A variable is simply a named place where the program keeps a value.
Imagine a labeled box. The label might say:
age
Inside the box we place:
25
Later, when the program uses the word "age," it can retrieve the value 25.
A simple example: when you follow a recipe, you put the flour in one bowl and the eggs in another.
Different languages express the assignment of a value to a variable slightly differently.
Python
age = 25
JavaScript
let age = 25;
Java
int age = 25;
C
int age = 25;
They look different, but all four statements mean essentially: create something called "age" and store the number 25 in it.
Notice the int prefix in C and Java. C and Java are the strict librarians: every box must have its type written on it (int for whole numbers, double for decimals, String for text, boolean for true/false). If you try to put text into a number box, they refuse before the program even runs. Programmers call these statically typed languages.
Python and JavaScript are more relaxed. You just put something in the box and they look inside to see what it is. This is called dynamic typing. It is faster to write, but mistakes may only show up later, while the program is running.
Different words. Same thought.
Input and output: the program's ears and mouth
In our algorithm, the first step was often "get the input" and the last was "show the result." A program without input is deaf, and a program without output is mute: it may think, but nobody will ever know what it thought.
Input
Most useful programs need information from somewhere.
- A banking application receives account information.
- A weather application receives weather data.
- A search engine receives your search query.
- A game receives input from the keyboard or controller.
In an algorithm, we might simply write:
INPUT: Ask the user for their name.
Programming languages provide commands or functions that allow programs to receive information. In the following examples, the program reads the user input into a variable called "name."
Python
name = input("What is your name? ")
JavaScript — in a web browser, we could write:
let name = prompt("What is your name?");
Java — requires a little more preparation
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
C
char name[50];
scanf("%s", name);
These examples look very different. But from the algorithm's point of view, they represent exactly the same step: get information from the user and store it. This is our input step.
We can see 2 main differences:
Python and JavaScript combine the output command (asking the user "What is your name?") and reading the result into a variable in one command. For Java and C, you will need to add a line of output before the code above, asking for the name, as we will see later on.
The second difference is in the C programming language. As I mentioned, C gives you more control over the computer memory, but at a cost: you need to define the exact size of the variable, char name[50], meaning a variable that can hold up to 50 characters. This makes C much harder to code and more prone to mistakes, for example, if you define a variable that is too small for the value you store in it, the program may crash.
Output - showing the result
Programs also need to communicate information back to us.
- A calculator displays an answer.
- A banking application displays your balance.
- A website displays a page.
- A game displays your score.
In an algorithm, we might say:
OUTPUT: Display "Hello".
Programming languages provide their own syntax.
Python
print("Hello")
JavaScript
console.log("Hello");
Java
System.out.println("Hello");
C
printf("Hello");
We can see again different syntax that is driven by the language's purpose.
For example, JavaScript runs inside a browser, so it can show answers to the end user in many ways: show the result inside the web page, pop up a window, or write to the console. End users usually don't see the console, but developers can, and they can use it, for example, to debug a program for errors. So the JavaScript command console.log("Hello") just says: print the result to the console.
Another example is that Java uses the command System.out.println. Remember that I mentioned that a Java program can run on any operating system. Input and output are actually handled by the operating system; it knows which screen, speakers, or keyboard are connected. Java hides the need to know the operating system and lets the programmer simply write: use the System's out device and print (println means print and move to a new line).
Process - doing something with the data
A process is an action the computer performs. For example: add two numbers. Our algorithm could say:
- Receive the first number.
- Receive the second number.
- Add them together.
- Store the result.
Or it can calculate a more complex task: calculate a total, add tax, convert dollars to euros.
Here the languages are almost identical, because they all borrowed their math from the same place: school.
Let's calculate the price of 3 items at 19.90 each, plus 17% VAT.
C
double price = 19.90;
int quantity = 3;
double total = price * quantity * 1.17;
printf("Total: %.2f\n", total);
Java
double price = 19.90;
int quantity = 3;
double total = price * quantity * 1.17;
System.out.printf("Total: %.2f%n", total);
Python
price = 19.90
quantity = 3
total = price * quantity * 1.17
print(f"Total: {total:.2f}")
JavaScript
let price = 19.90;
let quantity = 3;
let total = price * quantity * 1.17;
console.log("Total: " + total.toFixed(2));
As you can see, the main differences between the languages are, as shown earlier, the need to define variable types in C and Java, and how we write the output command.
Decisions - if something is true
Computers become much more useful when they can make decisions. In the algorithm we drew it as a diamond: a question with a "yes" path and a "no" path.
In real life we make these decisions all day: if it is raining, take an umbrella; otherwise, take sunglasses.
Every programming language on earth has this command, and almost all of them call it by the same English word: if.
Let's see an if example. If the algorithm says:
If the temperature is above 30 degrees, display "It is hot."
The code will be:
Python
if temperature > 30:
print("It is hot")
JavaScript
if (temperature > 30) {
console.log("It is hot");
}
Java
if (temperature > 30) {
System.out.println("It is hot");
}
C
if (temperature > 30) {
printf("It is hot");
}
As you can see, in C, Java, and JavaScript the code looks almost the same, except for the output command.
C, Java, and JavaScript also use braces, { and }, as boundaries of the action, grouping all the lines of code between them as belonging to the same condition. I will explain it later on in more detail. Python uses a colon (:) and indentation instead.
Often, an algorithm contains two possible paths. For example:
If the user is 18 or older, allow access. Otherwise, deny access.
Here we will see another piece of syntax that is common to almost all languages: the word else. Let's code our example:
Python
if age >= 18:
print("Access granted")
else:
print("Access denied")
JavaScript
if (age >= 18) {
console.log("Access granted");
} else {
console.log("Access denied");
}
Java
if (age >= 18) {
System.out.println("Access granted");
} else {
System.out.println("Access denied");
}
C
if (age >= 18) {
printf("Access granted");
} else {
printf("Access denied");
}
An IF statement needs a question that can be answered with True or False. Programming languages provide comparison operators for this. For example:
age > 18
means: is age greater than 18?
A decision is only as good as its question. These comparison and logic symbols are shared by all four languages, with only small differences:
| Question | C / Java / JavaScript | Python |
|---|---|---|
| Equal to? | == | == |
| Not equal? | != | != |
| Greater / smaller? | > < >= <= | > < >= <= |
| Both conditions true? | && | and |
| At least one true? | || | or |
| Opposite? | ! | not |
Notice how Python again chooses plain English words (and, or, not) where the others use symbols. This is exactly why many people find Python friendly for beginners.
Some signs you know from your math lessons, but some are new:
if (a==b)
== means equals. It is important not to use = here, since a=b means put the value of b into a.
if (a!=b)
! means not, != means not equals.
if (a==b && b==c)
&& means AND: if A equals B AND B equals C.
if (a==b || a==c)
|| means OR: if A equals B OR A equals C.
More than two paths
Sometimes a decision has more than two answers. Think of exam grades: 90 and above is excellent, 70 and above is good, anything else needs improvement.
Languages handle this by chaining decisions; they use else if to chain:
C, Java, and JavaScript
if (grade >= 90) {
result = "Excellent";
} else if (grade >= 70) {
result = "Good";
} else {
result = "Needs improvement";
}
Python shortens "else if" to "elif":
Python
if grade >= 90:
result = "Excellent"
elif grade >= 70:
result = "Good"
else:
result = "Needs improvement"
Loops: doing repetitive work without getting tired
Computers excel at doing repetitive chores millions of times without fatigue or errors. In algorithms, repetition is handled by loops. There are two classic kinds of repetition, and every language has both.
For loops
The first type is called a for loop; it is used when you know exactly how many times you need to loop.
Let's give an example. Imagine having to display the numbers from 1 to 1,000. You could write: Display 1, Display 2, Display 3, Display 4… but that would be ridiculous.
Instead, algorithms use repetition. We could say:
Start with number 1. Display the number. Increase the number by one. Display the new value. Repeat until we reach 1,000.
Let's code it. To keep it short, the example prints the numbers 1 to 5.
Python
for number in range(1, 6):
print(number)
JavaScript
for (let number = 1; number <= 5; number++) {
console.log(number);
}
Java
for (int number = 1; number <= 5; number++) {
System.out.println(number);
}
C
for (int number = 1; number <= 5; number++) {
printf("%d\n", number);
}
All four examples display:
Output
1
2
3
4
5
Python expresses the idea differently, but every version describes a repetition. Let's explain how Java, C, and JavaScript express it:
for (int number = 1; number <= 5; number++)
for means it's a for loop.
int number = 1 means: we create a variable named "number" of type int (whole number) with an initial value of 1.
number <= 5 means: it's the loop exit condition, in this case, if the value of the variable "number" is smaller than or equal to 5, continue to the next round, and when the value will be 6 the loop will stop.
And the last part is by how much to increase the value of "number" every loop: number++ increases it by 1 every loop. You can also decrease it by writing number--.
While loops
But what about cases where you don't know how many times you need to loop, you just know the exit condition, meaning you want to code: loop until some condition is true. Like "keep stirring until the sauce thickens." You do not know how many times, only when to stop.
This is a while loop. Let's code an example: imagine a login system. The algorithm might say:
While the password is incorrect, ask the user to enter the password again.
This is commonly represented by a while loop.
Python
while password != correct_password:
password = input("Enter password: ")
JavaScript
while (password !== correctPassword) {
password = prompt("Enter password:");
}
Java
while (!password.equals(correctPassword)) {
password = scanner.nextLine();
}
C
while (strcmp(password, correctPassword) != 0) {
scanf("%s", password);
}
The syntax varies more here because languages also handle text differently. I will explain text handling differences in the next chapter about object-oriented languages like Java.
But the algorithm is still identical:
WHILE the condition is true, repeat the action.
I know it looks complicated right now, but in the next tutorials I will give more and more examples that will help you understand better.
Organizing code: braces and blocks
Before I summarize this tutorial: in the next tutorial we will see that programming languages also strive to help programmers write code faster and with higher quality, and to help organize the code in a way that is easy to read and maintain. We will learn about functions, libraries, and object-oriented programming.
But you already saw in this tutorial some examples of syntax whose purpose is to organize the code.
For C, Java, and JavaScript it's the use of braces, { and }. Braces help organize lines of code with the same logic into one block. For example:
if (A>10){
B=A;
C=B+A;
D=B*A;
}
We can see that in the condition above (A>10), we need to take 3 actions, but all these 3 actions will be done only if A>10.
We can also see the sign ; at the end of the line. In these languages, ; means end of command. You can go down one line in the middle of a command and it will still be the same command until you add the ; sign.
Python has the same concept, but instead of using { it uses :, and all lines of code indented beneath it belong to this command:
if age >= 18:
print("Access granted")
else:
print("Access denied")
Putting it all together: our triangle, in four languages
In the previous chapter we built an algorithm that receives three side lengths and decides what kind of triangle they make.
In the example below I give a preview of functions, which I will explain in the next tutorials.
As a reminder, here is the thought, in plain words:
- Get three sides: a, b, c.
- If any two sides together are not longer than the third, it is not a triangle.
- Otherwise, if all three sides are equal, it is equilateral.
- Otherwise, if two sides are equal, it is isosceles.
- Otherwise, it is scalene.
Now watch the same thought written in four different sets of words.
C
const char* triangleType(double a, double b, double c) {
if (a + b <= c || a + c <= b || b + c <= a) {
return "Not a triangle";
} else if (a == b && b == c) {
return "Equilateral";
} else if (a == b || b == c || a == c) {
return "Isosceles";
} else {
return "Scalene";
}
}
Java
static String triangleType(double a, double b, double c) {
if (a + b <= c || a + c <= b || b + c <= a) {
return "Not a triangle";
} else if (a == b && b == c) {
return "Equilateral";
} else if (a == b || b == c || a == c) {
return "Isosceles";
} else {
return "Scalene";
}
}
Python
def triangle_type(a, b, c):
if a + b <= c or a + c <= b or b + c <= a:
return "Not a triangle"
elif a == b and b == c:
return "Equilateral"
elif a == b or b == c or a == c:
return "Isosceles"
else:
return "Scalene"
JavaScript
function triangleType(a, b, c) {
if (a + b <= c || a + c <= b || b + c <= a) {
return "Not a triangle";
} else if (a === b && b === c) {
return "Equilateral";
} else if (a === b || b === c || a === c) {
return "Isosceles";
} else {
return "Scalene";
}
}
Same thought, different words
There are hundreds of programming languages in the world, and new ones appear every year. That sounds frightening, until you realize that almost all of them are built from the same handful of ideas: store, listen, calculate, decide, repeat, reuse, speak.
This is why an experienced programmer can pick up a new language in a few weeks. They are not learning to think again. They are only learning a new vocabulary and a few local accents, like a traveler who already knows how to order coffee and just needs the local word for it.