C++ Variables, Functions, Conditionals, and Logic. In VSCode.

jerrymcdonald

JerryMcDonald

Posted on December 19, 2020

C++ Variables, Functions,  Conditionals, and Logic. In VSCode.

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.


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

Then create a skeleton for the program.

#include <iostream>
#include <cstdlib>

using namespace std;

void showHand(int num) {
}

int main() {
}
Enter fullscreen mode Exit fullscreen mode

#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.

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;
Enter fullscreen mode Exit fullscreen mode

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.

  srand(time(NULL));
  int computer = 1 + rand() % 5 ;
Enter fullscreen mode Exit fullscreen mode

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.

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

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

  cout << "The computer chose ";
  showHand(computer);
Enter fullscreen mode Exit fullscreen mode

Here is the logic behind Rock, Paper, Scissors, Lizard, Spock:

  rock > scissors
  scissors > paper
  paper > rock
  lizard > spock
  spock > scissors
  scissors > lizard
  lizard > paper
  paper > spock
  spock > rock
  rock > lizard
Enter fullscreen mode Exit fullscreen mode

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.

// 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";

  }
Enter fullscreen mode Exit fullscreen mode

6. Compile and play!

Here is my repo with the full code:
github.com/JerryMcDonald/spock.cpp

In your bash terminal, compile and run the program.

g++ spock.cpp -o spock
./spock
Enter fullscreen mode Exit fullscreen mode

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

Thanks for reading. If you want to connect, here is my Linked-In

Stay Focused || Love your code

Resources

  1. Learn C++ on Codecademy
  2. Mathbits rand()
  3. stackoverflow (of course)
💖 💪 🙅 🚩
jerrymcdonald
JerryMcDonald

Posted on December 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related