C++ Tutorial 3: Operators, If, While, Switch & Loops //Bonus! A small 2d game & Password Protected Program //Learn by doing

in #programming8 years ago (edited)

header
In my tutorials I always try to give you unique content while still providing you the basics.
In my second tutorial included things such as numeric limits, or string to char conversions for example.
This tutorial will show you things that will save you from a lot of hours spent googling desperately and maybe not even finding the answers. So pay attention!

Bonus!

After understanding this lesson you will be able to make a password protected executable which can contain sensitive data.

(don't use this until you learn encryption though, anyone can open the exe as a text file and find this data.)
I will also add a tutorial on how to make basic encryption later on, that is your own and you can add them to this later on!

Better yet I'm going to show you that after understanding these basic concepts you can even make a game!

Also, if you've read my tutorials so far and got to this point, congratulations!

You're well on your way to becoming a novice programmer!

Disclaimer:
I do have to warn you though, this is a lot of compressed information here and you will probably get tired after reading it!
I suggest taking a break halfway through and playing with what you learned then returning when you are rested, otherwise you risk getting bored and quitting learning altogether.
Unless you are very excited of what you're learning, in which case, please go ahead :)

READ THIS: I must add and insist, read the comments, notes or whatever I might leave in code.

They contain information which is hard to "google" because you won't even know the terms to search for!

First off let's get to the basics of how computers work.
How do you think they work?
Well they process data right?
Yes! Except how do they process this data?
Since you're going into programming you need to understand a few things
All computations are at the base very simple checks that operate through logic gates.
These are the main reason why computers are capable of doing so many things!

Here is a graphical representation of logic gates:

img
img
If the graphical representation isn't enough for you to understand it don't worry, you probably will find the next steps more self explainatory.
However take the AND for example
If electricity passes through neither A or B Output 0
If electricity passes through A but not B Output 0
If electricity passes through B but not A Output 0
If electricity passes through A and B Output 1
Don't worry to much about that, in programming we have...

Logical Operators

The logical Operators we will use are:

>== = Equal
!= = Not Equal
|| = Or
&& = And
>  = Bigger than
>= = Bigger or equal to
<  = Smaller than
<= = Smaller or equal to

The if/else if/else statements

First off let's begin with the IF statement which is the most widely used statement, also the simplest.
For a bit of added humor to show you it can always be fun to program we will be using the term "Master"
img

#include <iostream>
#include <string>
using namespace std;
int main()
{
    cout << "Only my master is allowed to see this, \nWho are you?\n";
    cout << "Enter your name: \n"; //Think of cout as console output
    string input; // Where we will store the user input
    cin >> input; //--think of it as Console-IN/Console-Input; 
                  //--It might make more sense for you
    if(input == "admin")
    {
        cout << "Yay! Master! I missed you so much, here's the data you wanted me to keep:\n";
        cout << "Data:\nMissile Launch Code: 12345\nTarget: The Moon\n";
    }
    system("pause");
}

Word of caution, this method is case sensitive so don't type with capital letters.
The output should be like this:
Program

Only my master is allowed to see this
Who are you?
Enter your name:
admin - (This is what you type and enter)
Yay! Master! I missed you so much, here's the data you wanted me to keep:
Data:
Missile launch code: 12345
Target: The Moon

And if you type anything else it should simply exit.
Now that's a bit sad isn't it?
Let's learn how to use else, which is very simple. So simple in fact we're going to add
another recognized person we will call her Amy

#include <iostream>
#include <string>
using namespace std;
int main()
{
    cout << "Only my master is allowed to see this, \nWho are you?\n";
    cout << "Enter your name: \n"; //Think of cout as console output
    string input; // Where we will store the user input
    cin >> input; //--think of it as Console-IN/Console-Input; 
                  //--It might make more sense for you
    if(input == "admin")
    {
        cout << "Yay! Master! I missed you so much, here's the data you wanted me to keep:\n";
        cout << "Data:\nMissile Launch Code: 12345\nTarget: The Moon\n";
    }
    else if(input == "Amy") // Case sensitive
    {
        cout << "Oh, secretary.. I wish it was my master.. sigh, well here you go:\n";
        cout << "Data:\nMissile Launch Code: 12345\nTarget: The Moon\n";
        cout << "Tell master I miss him!\n";
    }
    else
    {
        cout << "I do not know you, stay away!\nIf you try stealing my master's data I will personally kill you!\n";
        system("pause");
        return 0;
    }
    system("pause");
    return 0;
}
Now we have a more "interactive" version of a very emotionally attached program.

But our program is pretty dumb right? I mean, anyone can say he is Amy or admin right?
And that's why we have passwords ;)
But how do we make a check for both password and user? Adding two ifs to check if the
user is right then if the password is right? Well yeah, you can do it this way, but that's a lot of wasted effort.
Don't forget about the && (AND) operator. Let's make a simple login.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string user = "admin";
    string password = "123";
    string u, p; // Yes, it's shorter and simpler to define multiple variables like this.
                 //These will be the variables in which we will store console input
    cout << "Welcome to my program, please authenticate yourself.\nUser: ";
    cin >> u; //We input data in the u string
    cout << "Pass: "; //Notice how we don't add newlines(\n or endl), it's because when you press enter
                      //you add a newline yourself!
    cin >> p;
    if(u == user && p == password) //You don't have to store variables like this
    {                              //You could just aswell do u == "admin" like the previous example.
        cout << "You are now authenticated!\n";
    }
    else
    {
        cout << "Invalid username or password!\n";
    }
    return 0;
    system("pause");
    return 0;
}

As a small homework, you could add a password to the emotional program example, and make the program say:

Liar! You are not my master! in case the user inputs admin but enters the wrong password.
You would have to remove Jen though as the structure goes like IF>ELSE IF>ELSE.
From previous experiences it's better to follow that rule in any programming language.
Don't worry you will understand how to have Jen back later. (Switch Statements)

To prove you understand operators try adding an || (OR) to give admin a name so both admin and say... John
are accepted as the same user.
Syntax goes like this:
if(u == "admin" && p == "123" || u == "john" && p == "123")

Also I forgot to mention this so far, feel free to order your brackets as you wish! As they say:

img

Congratulations you can already do very simple programs! Or rather scripts.

Now that we covered the IF statement, let's move on to...

The Switch Statement

Say you need to add more switches and writing ifs over and over again would be just too much to write
and quite honestly very impractical, especially since we have the switch statement.
Say we have a list and we want a user to choose from it from about 10 options.
How do we do that?
Easy, very easy, I will demonstrate it through this List Program:

#include <iostream>
using namespace std;
int main()
{
    cout << "Welcome to the list program\n1. Contacts\n2. Passwords\n3. Notes\n";
    cout << "Choose an option from the list above (ex: 1)\nYour choice: \n";
    int option;
    cin >> option; //We need it in order to store the data the user enters;
    switch(option) //We have to pass what the user entered to the switch statement.
    {
        case 1:    //Translation: In case the user entered "1" do this:
            {      //You can also use no brackets({}) at all, I use them to organize.
                system("cls");//Let's get rid of all that text before this is executed
                cout << "~Contact List~\n"
                     << "Name    Phone\nAmy     40003231\nJoe     40003231\n"
                     << "John    40003231" << endl; //Remember this << It's useful for organizing too!
                     break; //If we don't break each case, then any case that is under it will also be
            }               //executed by the program.
        case 2:
            {
                system("cls");
                cout << "      ~My Password list~\n"
                     << "_______________________________\n"
                     << "|Website           | Password |" << endl
                     << "|==================|==========|" << endl
                     << "|www.gmail.com     | fluffy01 |\n"
                     << "|------------------|----------|\n"
                     << "|www.facebook.com  | 01234567 |\n"
                     << "|------------------|----------|\n"
                     << "|www.steemit.com   | hawh2h8a |\n"
                     << "|__________________|__________|\n";
                     break; //Remember the break, we don't want the other options below to be executed!
            }
        case 3:
            {
                cout << "~My notes - Read them~\n"
                     << "Note 1: Remember to feed your pets\n"
                     << "Note 2: Remember to add a ; to every line that finishes an instruction\n"
                     << "Note 3: Remember to follow me if you like my tutorials\n"
                     << "Note 4: Don't forget to add a break after each case in switches!\n"
                     << "Note 5: Don't forget to add a \\n after each comment so the text displays properly\n"
                     << "Note 6: Notice that one \\ in front of a newline inside a comment escapes the newline\n"
                     << "Note 7: If my tutorial is helping you please like & resteem it so you can help me aswell!\n";
                     break;
                
            }
        default:   // This is sortof the if's else statement, in case none of the above are chosen
            {      // this will be executed.
                cout << "There is no such option!\n";
                break;
            }
    }
    system("pause");
    return 0;
}

I trust it's very self explanatory, you should note that the switch() statement only accepts ints so don't try
using strings for a choice for example. If you really insist on this you have to use enum and nmap.
img

Now you can execute a lot of checks easily, and eficiently, totally badass!

Now that we finished with the Switch statement, it's time to move on to...

The While Statement

While... you probably can't even imagine what you can use it for except it's extremely useful and you should
definitively learn this.
It allows for more complex programs to be made.
In fact You're probably going to need to use it in almost every real program you actually make!
To demonstrate it, let's make a program that counts from 1 to 10.

#include <iostream>
using namespace std;
int main()
{
    int i = 0;
    while(i<=10)
    {
        cout << "i = " << i << endl;
        i++;// i++ is equivalent to i = i + 1;
    }       //Remember to put it under the cout as the code is executed from top to bottom(this is important)
    cout << "\nI finished counting!";
    
    system("pause");
    return 0;
}

I want to add, don't be afraid to play with code, try making it so you can specify to what number you want to count up to!

For example:

#include <iostream>
using namespace std;
int main()
{
    cout << "Enter the number you want to count up to!\n";
    int i=0, input;
    cin >> input;
    while( i<= input)
    {
        cout << "i = " << i << endl;
        i++;//Remember to put it under the cout as the code is executed from top to bottom(this is important)
    }
    cout << "BOOM TAKEOFF!\n";
    
    system("pause");
    return 0;
}

Or make it count down from the number you specify!

#include <iostream>
using namespace std;
int main()
{
    cout << "Enter the number you want to count down from!\n";
    int i;
    cin >> i;
    while(i >= 0) // if instead of >= you use != it will count down to 1 not 0! remember, Logic!
    {
        cout << "i = " << i << endl;
        i--;//Remember to put it under the cout as the code is executed from top to bottom(this is important)
    }
    cout << "BOOM TAKEOFF!\n";
    
    system("pause");
    return 0;
}

And always remember, don't be frustrated if it doesn't work, after all:
img
Alright, let's get to a more practical example now.
Remember the list program?
Well it's quite annoying to use, because after choosing an option maybe you want to choose another
and the way it was made had you exit the program after displaying each option.
Not such a good program huh?
Well now that you understand how to use while, you can add an option to exit, and you don't have to close & open the program every time you want to see another option.
Didn't already figure out how?
Think about it, it's simple if you use what you've learned.
Well, most people don't realise but you can also make...

Loops

Whether you've figured it out on your own or not don't worry here's the example:

#include <iostream>
using namespace std;
int main()
{
    int exit = 0;
    while(exit != 1)
    {
    system("cls");
    cout << "Welcome to the list program\n1. Contacts\n2. Passwords\n3. Notes\n";
    cout << "Choose an option from the list above (ex: 1)\nTo exit the program, choose 0\nEnter your choice: \n";
    int option;
    cin >> option; //We need it in order to store the data the user enters;
    switch(option) //We have to pass what the user entered to the switch statement.
    {
        case 1:    //Translation: In case the user entered "1" do this:
            {      //You can also use no brackets({}) at all, I use them to organize.
                system("cls");//Let's get rid of all that text before this is executed
                cout << "~Contact List~\n"
                     << "Name    Phone\nAmy     40003231\nJoe     40003231\n"
                     << "John    40003231" << endl; //Remember this << It's useful for organizing too!
                     break; //If we don't break each case, then any case that is under it will also be
            }               //executed by the program.
        case 2:
            {
                system("cls");
                cout << "      ~My Password list~\n"
                     << "_______________________________\n"
                     << "|Website           | Password |" << endl
                     << "|==================|==========|" << endl
                     << "|www.gmail.com     | fluffy01 |\n"
                     << "|------------------|----------|\n"
                     << "|www.facebook.com  | 01234567 |\n"
                     << "|------------------|----------|\n"
                     << "|www.steemit.com   | hawh2h8a |\n"
                     << "|__________________|__________|\n";
                     break; //Remember the break, we don't want the other options below to be executed!
            }
        case 3:
            {
                system("cls");
                cout << "~My notes - Read them~\n"
                     << "Note 1: Remember to feed your pets\n"
                     << "Note 2: Remember to add a ; to every line that finishes an instruction\n"
                     << "Note 3: Remember to follow me if you like my tutorials\n"
                     << "Note 4: Don't forget to add a break after each case in switches!\n"
                     << "Note 5: Don't forget to add a \\n after each comment so the text displays properly\n"
                     << "Note 6: Notice that one \\ in front of a newline inside a comment escapes the newline\n
                     << these are called escape characters"
                     << "Note 7: If my tutorial is helping you please resteem it so you can help me aswell!\n";
                     break;
                
            }
        case 0:
            {
                exit = 1;
                break;
            }
        default:   // This is sort of the if's else statement, in case none of the above are chosen
            {      // this will be executed.
                cout << "There is no such option!\n";//The user selected something other than the options we provide.
                break;
            }
    }
    system("pause");
    }
    return 0;
}

Still too complicated?
Alright I'll simplify:

#include <iostream>
using namespace std;
int main()
{
    bool exit = false; //Bool, it can either be true or false.
                       //0 or 1 
                       //Maybe in the new quantum mechanics we will also have "frue"?
    while(exit != true)
    {
        system("cls");//To clear text, if you like to keep it clean
        string input;
        cout << "Type something in to have it printed back to you!\n";
        cin >> input;
        if(input == "exit")
        {
            exit = true;
        }
        else
        {
        system("cls");
        cout << "You've entered: " << input << "!\nType \"exit\" when you want to exit the program!\n";
        system("pause");
        }
    }
    return 0;
}

This concludes lesson 3.

The game demonstration will be posted in the comments soon! If I haven't uploaded it on my profile already

I suggest you take a break from reading the next tutorials and play around with what you already know.

You can already do so much if you have the imagination!

I hope this tutorial helps you and please don't forget to upvote & follow if this helped!

As always, feel free to ask me anything in the comments

The header is of my own design.
Everything I've written here is my own work.
The tutorial uses Dev c++ as a compiler, don't be surprised if it may need a few changes in other compilers
List of images that are public domain:
Logic Gates
2 Types of People
Protector Meme
What does this mean

Congratulations

Sort:  

Good job there.
I hope enough people read this and learn something.

I Really hope so!
I'm so disappointed in most of today's tutorials, they never seem to also show kids and students what they can do, I really hope this will open up the minds of most young programmers who are wasted because all they see is a few mathematical examples which in the end make no sense at all.
I personally learned c++ when I was only 11 years old, and this because a friend showed me examples which almost didn't use math at all!
The problem is that when you're trying to explain anything to anyone is that you have to give them examples which are simplified.
The human brain isn't properly made for math, just as computers aren't properly made to handle human-like artificial intelligence yet, I will probably explain why in a detailed article.
I believe these examples allow a more humane approach to programming and I hope they help the future generations to create things I could never even imagine.

Coin Marketplace

STEEM 0.31
TRX 0.11
JST 0.034
BTC 66772.03
ETH 3237.54
USDT 1.00
SBD 4.25