The Basics of Coding in C++ - Part 1
in Cpp-tutorial on C++
Now that you’ve set the compiler up, we can start coding!
if
Conditions
Syntax:
if(variable)
{
//some code
}
Here, the if
command checks if some variable is true. What do I mean by true? Let me show you.
if
Example
#include <iostream>
using namespace std;
int main()
{
bool a;
a = true;
if(a)
{
cout<<"Hey, it works!!";
}
if(!a)
{
cout<<"Hey, it doesn't work! Fix it!";
}
return 0;
}
Lemme explain every part of this program. But before that, can you try and tell me what this program will give as an output? Keep thinking. I’ll reveal it at the end of this.
Dissecting a simple program
Right now, we have a very simple program in our hands. Here’s how it works:
#include <iostream>
using namespace std;
This part of the program just includes some headers. You could also switch it with #include <iostream.h>
if you were using Borland C++.
We’ll get to the usefulness of this later.
bool a;
a = true;
A Boolean, which is exactly what a
in this program is, is a data type. A data type is how C++ distinguishes between, say, 2 (an integer, called int
), a decimal number like 3.2 (called float
), a long decimal number like 3.1415925 (called double
) and a character, called char
. We will go through examples of this in a while.
If one has some basic knowledge about Electronics, he/she would say that this data type can hold either one or zero.
Not exactly.
The boolean data type is designed in this way:
When bool becomes 0:
\displaystyle bool \rightarrow false
In any other case:
\displaystyle bool \rightarrow true
if(a)
{
cout<<"Hey, it works!";
}
This part of the program is how every boolean in the world is used, more or less.
What it does is that, it asks, if a
is true, do the thing inside the brackets. Therefore, it is the same as a == true
.
Why the ==
, you ask?
Why, that’s the next part of this tutorial.