C++ Variables, Functions,  Conditionals, and Logic. In VSCode.
Tags: cpp, beginners, programming, computerscience
Published: 2020-12-19 21:23:46


In this series, I am reviewing the C++ basics, primarily for those who already understand a coding language and are curious about what makes C++ different. 

Here is part one.
[Create a C++ program. Run in Visual Studio Code.](https://dev.to/jerrymcdonald/create-a-c-program-run-in-visual-studio-code-58ea)

---


Key concepts I am going to review in this blog:
1. Structuring your .cpp file
2. `void` and `int` type functions
3. Variable type and scope
4. C++ Random number generation
5. Conditionals
6. Compile and play!

---

#Structuring your .cpp file
Open your C++ folder in Visual Studio Code and create a spock.cpp.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/57pfpghsluzoyzn7ao2t.jpg)

Then create a skeleton for the program. 
``` cpp
#include <iostream>
#include <cstdlib>

using namespace std;

void showHand(int num) {
}

int main() {
}
```

`#include <iostream>:`
`<iostream>` is our pre-processor directive providing input and output functionality, `<cstdlib>` defines several general-purpose functions, including a random number generator, which we will need. 

`using namespace std`
`std`, which is the C++ standard library, is written into the core C++ language. Declaring our namespace with `using namespace std` provides scope to our identifiers, improving organization when our code becomes more complex and reducing typing. `std::cout` becomes `cout`, and `std::rand()` becomes `rand()`.

C++, like most coding languages, works from top to bottom, so if we were to create `handThrown()` under the `main()` function, then an error would occur.  

---

# `void` and `int` type functions

When declaring functions, we also need to state what data type we expect returned. In the case of our `showHand()` function, we do not expect it to return a value; instead, we want it to perform a task, then have control return back to the caller. The `void` keyword specifies that the function does not return a value. 

The C++ standard requires `main()` to return `int`. Even if we leave the return statement out, it will return zero, indicating to the operating system that the program ran successfully. 

---

# Variable type and scope

Create a user variable and ask the user to input a number. 

```cpp
int user;
  
  cout << "=================================\n";
  cout << "rock paper scissors lizard spock!\n";
  cout << "=================================\n";

  cout << "1) ✊ rock\n";
  cout << "2) ✋ paper\n";
  cout << "3) ✌️  scissors\n";
  cout << "4) 🦎 lizard\n";
  cout << "5) 🖖 Spock\n\n";

  cout << "shoot: ";
  
  cin >> user;
```

C++ is a *strongly-typed* language. It enforces strict restrictions on intermixing values with different data types. On the other hand, Javascript (created in C++) resembles C++ closely in syntax but is a *weakly typed* language, meaning its variables still have a type but have looser type rules.

C++ basic data types include:
* `int`: integers
* `double`: floating-point numbers
* `char`: individual characters
* `string`: a sequence of characters
* `bool`: true/false

The `user` variable is considered locally scoped. It can be used only by statements inside the `main()` functions block of code. `user` is not accessible within our `showHand()` function. Global variables are declared outside of all the functions and will hold their value throughout your program's lifetime.

--- 

# C++ Random number generation

Generate a random number between 1 and 5 and assign it to the computer variable. 

```cpp
  srand(time(NULL));
  int computer = 1 + rand() % 5 ;
```

`srand(x)` is used to set the seed of the random number generator algorithm used by the function `rand()`.  In combination with `(time(NULL)`, we can use our computers 'continually changing' internal clock to set the seed to a different value on each run. 

To produce a random integer within a given range, we can use the following formula:
**int number = a + rand( ) % n;**
a = the first number in your range
n = the number of terms in your range

---

#Conditionals
C++ supports the usual logical conditions from mathematics and the `if-else` and `switch` constructs you also see in C, Java, JavaScript and Visual Basic .

Javascript was written in C++, and the similarities in syntax show in the `switch` and `if-else` statements. 

Fill your `showHand()` function with the following switch statement.

```cpp
void showHand(int num) {
  switch(num) {
    case 1:
    cout << "rock! ✊ \n";
    break;
    case 2:
    cout << "paper! ✋ \n";
    break;
    case 3:
    cout << "scissors! ✌️ \n";
    break;
    case 4:
    cout << "lizard! 🦎 \n";
    break;
    case 5:
    cout << "spock! 🖖 \n";
    break;
  }
}
```
When writing, functions are an excellent way to reduce code length if a piece of logic is required multiple times.  In our program's case, we can use `showHand()` for both the user's and computer's choice. 

```cpp
  cout << "You chose ";
  showHand(user);

  cout << "The computer chose ";
  showHand(computer);
```
---
Here is the logic behind Rock, Paper, Scissors, Lizard, Spock:
{% youtube iSHPVCBsnLw %}
```
  rock > scissors
  scissors > paper
  paper > rock
  lizard > spock
  spock > scissors
  scissors > lizard
  lizard > paper
  paper > spock
  spock > rock
  rock > lizard
```

With that logic in mind, we can write conditionals for all winning factors or a tie.  For the sake of brevity, I did not include them all here. 
```cpp
// note: more code needed; check repo
  if (user == rock && computer == scissors) {
      
    cout << " You Win!\n";
    
  } else if (user == computer) {
      
    cout << " Tie!\n";
      
  } else {
      
    cout << "You Lose!\n";
      
  }
```

---

# 6. Compile and play!
Here is my repo with the full code:
[github.com/JerryMcDonald/spock.cpp](https://github.com/JerryMcDonald/cpp-projects/blob/master/spock.cpp)

In your bash terminal, compile and run the program.

```
g++ spock.cpp -o spock
./spock
```

As Sheldon explains, "Scissors cuts paper, paper covers rock, rock crushes lizard, lizard poisons Spock, Spock smashes scissors, scissors decapitates lizard, lizard eats paper, paper disproves Spock, Spock vaporizes rock, and as it always has, rock crushes scissors."

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3xm44rgfpe7l1kmysgi7.jpg)

Thanks for reading. If you want to connect, here is my [Linked-In](https://www.linkedin.com/in/jerry-mcdonald-2089891b3/)

**Stay Focused || Love your code**

#### Resources

1. [Learn C++ on Codecademy](https://www.codecademy.com/learn/learn-c-plus-plus)
2. [Mathbits rand()](https://mathbits.com/MathBits/CompSci/LibraryFunc/rand.htm)
3. [stackoverflow (of course)](https://stackoverflow.com/questions/449851/why-do-we-need-to-use-int-main-and-not-void-main-in-c#:~:text=The%20short%20answer%2C%20is%20because,main()%20to%20return%20int%20.&text=Both%20Unix%20and%20Win32%20support,programmer%20to%20specify%20this%20value.)