C++ - Variables

Nov. 22, 2020 pexels-pixabay-35888.jpg Vuong Huynh

Introduction to Variables

A variable is simply a name that represents a particular piece of your computer’s memory that has been set aside for you to store, retrieve, and use data.

The basic data types:

  • int: integer numbers - 0, -10 , 255
  • double: floating-point numbers - 3.14, -50.0
  • char: individual characters - 'a', '$' - inside single quote
  • string: a sequence of characters - "Hello", "$%#^&" - inside double quote
  • bool: true/false values - true, false (or 1, 0 )

Every variable has a type, it tells the compiler how much memory to set aside for the variable. Each data type has different size.

Datatype Modifiers:

  • signed
  • unsigned
  • short
  • long

Const:

const (constant) variables cannot be changed by your program during execution.


Type Conversion:

A typecast is basically a conversion from one type to another. The notation (type) value means “convert value to type“. So for example:

double weight1;
int weight2;

weight1 = 154.49;
weight2 = (int) weight1;

Note: Going from a double to an int simply removes the decimal. There’s no rounding involved.


Declare a Variable

"Every variable in C++ must be declared before it can be used!"

We need two things to declare a variable:

  • A type for the variable.
  • A name for the variable.
int score;
  • The int is the type of the variable.
  • The score is the name of the variable.
  • The ; is how we end a statement.

Note: C++ is known as a strongly typed language. (Or static type)


Initialize a Variable

Set a value to a variable.

score = 0;
  • The score is the name of the variable.
  • The = indicates assignment.
  • The 0 is the value you want to store inside the variable.

Note: In C++, a single equal sign = does not really mean “equal”. It means “assign”.

We can combine declaring and initializing in a single line of code:
int score = 0;


Arithmetic Operators

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • % modulo (divides and gives the remainder)


Chaining

We can chain literal strings with variables

int age = 28;
 
std::cout << "Hello, I am " << age << " years old\n";

Notice how we use quotes around the characters in "Hello, I am " but not in age.

  • We use quotes when we want a literal string.
  • We don’t use quotes when we refer to the value of something with a name (like a variable).


User Input

We have cout for output, and there is something called cin that’s used for the input!

std::cout << "Enter your password: ";
std::cin >> password;

The name cin refers to the standard input stream (pronounced “see-in”, for character input). The second operand of the >> operator (“get from”) specifies where that input goes.


Challenge: Temperature

The mad scientist Kelvin has mastered predicting the weather in his mountain-side meteorology lab.

Recently, Kelvin began publishing his weather forecasts on his website, however, there’s a problem: All of his forecasts describe the temperature in Fahrenheit degrees.

Let’s convert a temperature from Fahrenheit (F) to Celsius (C).

The formula is the following:

C = (F - 32) / 1.8C=(F−32)/1.8

  1. Declare a double variable named tempf and initialize it with the temperature. Declare another double variable named tempc.
  2. Let’s ask the user what the temperature is using cin!
  3. Tell the user “Enter the temperature in Fahrenheit: “ using std::cout. And get their input using std::cin and store it in tempf.
  4. Calculate the temperature to Celsius and store it in tempc.
  5. Compile and execute the program using the terminal.
#include <iostream>

int main() {
  
  double tempf;
  double tempc;
  
  // Ask the user
  std::cout << "Enter the temperature in Fahrenheit:";
  std::cin >> tempf;
    
  tempc = (tempf - 32) / 1.8;
  
  std::cout << "The temp is " << tempc << " degrees Celsius.\n";
}
$ g++ temperature.cpp -o temp
$ ./temp
Enter the temperature in Fahrenheit:50
The temp is 10 degrees Celsius.


Challenge: BMI

The body mass index (BMI) is commonly used by health and nutrition professionals to estimate human body fat in populations.

It is computed by taking the individual’s weight in kilograms (kg) and dividing it by the square of their height in meters (m²):

bmi = weight / height2

Complete the bmi.cpp program.

#include <iostream>

int main() {
  
  double height, weight, bmi;
  
  // Ask user for their height
  std::cout << "Type in your height (m):\n";
  std::cin >> height;
  
  // Now ask the user for their weight and calculate BMI
  std::cout << "Type in your weight (kg):\n";
  std::cin >> weight;

  bmi = (weight)/(height*height);

  std::cout << "Your BMI is: " << bmi;
  
  return 0;
}
$ g++ bmi.cpp -o bmi
$ ./bmi
Type in your height (m):
172
Type in your weight (kg):
70
Your BMI is: 0.00236614


Project: Dog Years

"How old is your fuzzy friend in human years?"

Here’s how we can convert your dog’s age into human years:

  • The first two years of a dog’s life count as 21 human years.
  • Each following year counts as 4 human years.

Write a C++ program called dog_years.cpp to calculate the age, in human years, of any dog older than 2.

#include <iostream>
//#include <string>

int main() {
  std::string dog_name;
  int dog_age;
  int early_years;
  int later_years;
  int human_years;

  // Ask for dog name:
  std::cout << "Please enter your dog name ";
  getline(std::cin,dog_name);
  // Ask for dog age is older than 2 years
  std::cout << "Enter your dog age if it is older than 2 year-old: ";
  std::cin >> dog_age;

  // “The first two years of a dog’s life count as 21 human years.”
  early_years = 21;

  // “Each following year counts as 4 human years.”
  later_years = (dog_age - 2) * 4;

  // Turn out to human age:
  human_years = early_years + later_years;

  std::cout << "My name is " << dog_name << "! Ruff ruff, I am " << human_years << " years old in human years.";
  }
$ g++ dog_years.cpp -o dog_years
$ ./dog_years
Please enter your dog name Kathy
Enter your dog age if it is older than 2 year-old: 6
My name is Kathy! Ruff ruff, I am 37 years old in human years.


Project: Quadratic Formula

In algebra, a quadratic equation is an equation having the form:

ax2 + bx + c = 0

The corresponding x values are the x-intercepts of the graph, while a, b, and c are constants.

Write a C++ program called quadratic.cpp that solves the quadratic equation for the x‘s:

x = (−b ± sqrt(b2 - 4ac)​) / 2a​

#include <iostream>
#include <cmath>

int main() {
  double a, b, c;
  
  std::cout << "Enter value of a: ";
  std::cin >> a;
  std::cout << "Enter value of b: ";
  std::cin >> b;
  std::cout << "Enter value of c: ";
  std::cin >> c;
  
  double root1, root2;
  root1 = (-b + std::sqrt((b*b) - (4*a*c)))/(2*a);
  root2 = (-b - std::sqrt((b*b) - (4*a*c)))/(2*a);

  std::cout << "root1 = " << root1 << "\n";
  std::cout << "root2 = " << root2 << "\n";
}
$ g++ quadratic.cpp -o quad
$ ./quad
Enter value of a: 6 
Enter value of b: -7
Enter value of c: -3
root1 = 1.5
root2 = -0.333333

The code above has a bug with NaN result - square root of negative numbers or the result of 0/0.

For example, when we run the ./quad file again will result in NaN.

$ ./quad
Enter value of a: 2
Enter value of b: 3
Enter value of c: 4
root1 = -nan
root2 = -nan


Project: Piggy Bank

You just returned from a trip to South America. The countries you visited were Colombia, Brazil, and Peru. You arrived back in your country with some foreign currencies from these three countries.

Write a C++ program called currency.cpp that prompts the user for the amount of each foreign currency. Your prompts should look like:

Enter the number of Colombian Pesos:
Enter the number of Brazilian Reais:
Enter the number of Peruvian Soles:

Your program should then convert the amount entered by the user and display the total amount of USD. Your final output should look like:

US Dollars = $______

#include <iostream>

int main() {
  double pesos, reais, soles;
  double dollars;

  std::cout << "Enter of Colombian Pesos: ";
  std::cin >> pesos;
  std::cout << "Enter of Brazilian Reais: ";
  std::cin >> reais;
  std::cout << "Enter of Peruvian Soles: ";
  std::cin >> soles;
  
  double pesos_dollars = 0.00032;
  double reais_dollars = 0.27;
  double soles_dollars = 0.3;

  dollars = (pesos_dollars * pesos) + (reais_dollars * reais) + (soles_dollars * soles);

  std::cout << "US Dollars: " << dollars;
}
$ g++ currency.cpp -o curr
$ ./curr
Enter of Colombian Pesos: 50
Enter of Brazilian Reais: 35
Enter of Peruvian Soles: 42
US Dollars: 22.066$