[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]

#include <iostream>
#include <cstdlib>
#include <time.h>
 
using namespace std;
 
 
int main(){
 
 
  //  Generate a random number
  //  Ask the user to guess the number
  //  For each guess we will tell the user if they are too high, or too low
  //  if( value == ourValue){ break; }
  //  While loops to control the flow of the game
  //  We're going to ask if they want to play again, before they exist
  srand(time(NULL));
  char quit = ' ';
  bool run = true;
 
  while (run){
    int secret = rand() % 1000 + 1;
    int guess = 0;
    while (guess != secret){
      do{
        cout << "Enter a number between 1 and 1000: ";
        cin >> guess;
      } while (guess < 1 || guess > 1000);
      if (guess < secret){
        cout << "\nYou have guessed a number that is too low.  ";
      }
      if (guess > secret){
        cout << "\nYou have guessed a number that is too high.  ";
      }
      if (guess == secret){
        cout << "\nCongratulations you guessed right  ";
      }
    }
 
    cout << "Would you like quit y/n: "; 
    cin >> quit;
    if (quit == 'y'){
      run = false;
    }
  }
 
  return 0;
}
  

[/spoiler]

Homework: http://beginnerscpp.com/forums/index.php/topic,63.0.html



Number guessing game
This number guessing game is an example of the type of program you can make with what you’ve learned up to this point with C++ using loops, and if statements. You could easily make far more complex games than this, but for a 15 minute (self-imposed) time limit, it’s not too bad. We cover a few concepts in this video that I want to put into writing.

Sentinel Loops
While we don’t directly use a sentinel loop in our program we use a bool to do roughly the same thing. A sentinel loop is a loop that is “broken” (exited) when a specific value becomes true. In this case we’re checking our variable “quit” to see if it becomes equal to y, then setting a boolean variable to false. The more ‘classic’ implementation of a sentinel loop is something like this:

...

while ( num != -999){
    cout << "Num = " << num << endl;
    cout << "Enter another value or -999 to exit";
    cin >> num; 
}

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]


#include <iostream>
#include <string>
 
using namespace std;
 
int main(){
 
  //"Hello World"
  //Get strings with spaces
  //Compare Strings
  //Show in debugger
  //"Chars" and strings
  string str = "", str2 = "";
  cout << "Enter a string: ";
  //cin >> str; //Breaks on whitespace, this is WRONG
  getline(cin, str);
 
  cout << "Enter a  Second string: ";
  //cin >> str; //Breaks on whitespace, this is WRONG
  getline(cin, str2);
 
  /*if ( str[0] == 'H' ){
    cout << "H Found" << endl;
  }*/
 
  //str = BBB
  //str2 = AAA
  // A < B
 
  if (str.compare(str2) < 0){
    cout << "str: " << str << " is before str2 in the alphabet: " << str2;
  }
  if (str.compare(str2) > 0){
    cout << "str: " << str << " is after str2 in the alphabet: " << str2;
  }
  if (str.compare(str2) == 0){
    cout << "str: " << str << " is Equal To : " << str2;
  }
 
  cout << endl;
  system("PAUSE");
  return 0;
}

[/spoiler]

Homework: None



What is a string?
A string is technically an object, but to be more straight-forward it’s a collection of single characters (for example char c = ‘A’; could be in a string) that has different functions available to act upon them. This ‘collection’ of same-type variables is known as an array, and while a string is technically an array of characters, it does have other attributes that distinguish it from a simple character array.


Functions related to string
So strings are different than normal variables, and even their counterpart char arrays (which I will not be teaching since strings are vastly superior in essentially every way). They can be loaded using cin >> stringName, but it’s not advisable. The reason why is because cin “breaks” (stops reading) on white-space. Strings are absolutely allowed to have white space in them (you can put virtually anything into a string). As a result to load a string with multiple words / numbers / symbols, we are going to use:

getline(cin,stringName); //Reads a line of user-entered input

This code will get an entire “line” (Until enter is hit) and put it into the string (stringName in the example above).

String itself has a number of handy functions in it. It allows for “random access”, which means that we can easily view a single character in a string (similarly to how we would do so with an array in a few more lessons). To view a single letter using this method you could use the following code:

//String Random Access
string hello = "Hi There";
cout << hello[0] << endl; //H
cout << hello[1] << endl; //i
cout << hello[2] << endl; //Space

Random access means that we can access any item inside of the array without having to iterate through others first. We will get more into random access when we talk about container types without random access later on.

String.compare()
Using compare in string is one of the first times that I’ve used an object function in this series, so there are subtle syntax points that I want to touch on here. First off, let’s talk about the usage of string.compare() since I did make a small error in the video.

string word  = "Apple";
string word2 = "Orange";

if(word.compare(word2) < 0){
    //Word comes before word2 in the alphabet or they are equal and word is shorter in length
    cout << word << " is before " << word2 << " in the alphabet;
}
if(word.compare(word2) == 0){
    //Word and word2 are equal
    cout << word << " is equal to " << word2 << ;
}
if(word.compare(word2) > 0){
    //Word comes after word2 in the alphabet (or they are equal and word is longer)
    cout << word << " is after " << word2 << " in the alphabet";
}

...

Output: Apple is before Orange in the alphabet

A few subtle things to notice

  • There is a different bit of syntax than we’ve seen in the past. There is a . followed by a function name, then the arguments we’re passing it.
  • The .comes after what is a “normal variable”. This is because strings are actually objects
  • In the future (lesson 21 or 22) when we cover classes, this is a universal topic. Object functions will be called via dot operators.

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]

#include <iostream>
#include <string>
#include <fstream>
 
using namespace std;
 
 
int main(){
 
  // cout << "String" ;
  // cin >> variable;
  string fileName = "Text.txt";
  string fileName2 = "Text2.txt";
  string str = "";
 
  ofstream fout;
  ifstream fin;
  int wordCount = 0, lineCount=0;
 
  //getline(cin, str);
 
  fin.open(fileName);
  fout.open(fileName2);
  while (fin >> str){
    if (str != "Bird"){
      fout << str << endl;
    }
  }
  fin.close();
 
  /*while (getline(fin, str)){
    cout << str << endl;
    lineCount++;
  }*/
 
  fin.open(fileName2);
  while (fin >> str){
    cout << str << endl;
    wordCount++;
  }
 
  cout << "The number of words in this file was: " << wordCount << endl;
  //cout << "The number of lines in this file was: " << lineCount << endl;
 
  system("PAUSE");
  return 0;
}
 
/*
CONTENTS OF Text.txt
Cat Dog Bird
Cat
Dog
Bird
*/

[/spoiler]

Homework: Homework available here: http://beginnerscpp.com/forums/index.php/topic,73.0.html



File Input / Output
File input / output has been one of the most confusing topics for students. By the time they make their way to me they have tried slogging through assignments for hours. A few days ago I had a student approach me that spoke of working for 7 hours without being any closer to solving his solution. His code was a mess, and he was unable to explain how he had gotten to that point. So let me tell you before I even begin showing you code. There are differences between handling files and handling console input (via cin / cout) but for the most part, the two are VERY similar.

#include <fstream>
...
ifstream fin; //input filestream
ofstream fout; //output filestream
fin.open(fileName);
string str="";
fin >> str; //read once from the file until whitespace
getline(fin,str); //Read a line from the file until \n
fin.close(); //Close the file to free up memory
fout.open(fileName); //Open a file for output
fout << "The sum of 1+2 = " << 1+2;
fout.close();
...

As you can see in the above code, all we need to do to read a line or to read in a single word is EXTREMELY similar in syntax to the usage of cin / cout that you should be familiar with by now. To read an entire file in this manner, we just expand the single statements into a while statement:

while(getline(fin,str)) { //do line-by-line stuff here }
while(fin >> str ){ //do word-by-word logic here }

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]

#include <iostream>
#include <string>
 
using namespace std;
int main(){
  //What is an array?
  //An array is a container of like-type variables
  //An array groups variables together
 
  //type name[size];
 
  //Values     | 1 | 2 | 3 | 4 | 5 |
  //Positions  | 0 | 1 | 2 | 3 | 4 |
  //myArray of number -- Aka myArray of 1 == myArray[1]
  // {1,2,3,4,5}  initialization
  // square brackets with a number inside  -- Array subscript [1] -- [varName]
  // When we access using a subscript it's called "Random Access"
 
 
  int myArray[5] = {0};
 
 
 
  for (int i = 0; i < 5; i++){
    cout << "myArray[" << i << "] = " << myArray[i] <<endl;
  }
  cout << endl;
  system("PAUSE");
  return 0;
}

[/spoiler]

Homework: None



Arrays
Back in the lesson about strings, I eluded a lot to how strings were an object(lesson 21) that contains same-type variables (in the case of strings, chars). A collection of same-type variables in a single container is known as an array. In ++ you can make an array of any type of variable, even user-made types. The typical way to make an array is as follows:

type arrayName[arraySize];
Examples:
string names[10]; //Creates an array of 10 strings
int prices[10]; //Creates an array of 10 ints
double sales[5]; //Creates an array of 5 doubles

Array Indexing
One of the most common error among beginner programmers is that they don’t realize that arrays are 0-indexed. This means that the first item you add in an array goes into the position array[0], rather than array[1]. This means that if you make an array with the values 1,2,3,4,5 the values would be in array[0] – array[4] respectively.

Iterating through an array with a loop
Using a for loop to output the contents of an array is fairly simple when you use the following structure: for (int counter = 0; counter < arraySize; conuter++){ cout << array[counter] << endl; Below is an example of how this might look in real-code

int myArray[5] = { 10,20,30,40,50}; 
for (int i = 0; i< 5; i++){
    cout << myArray[i] << endl;
}

Output:
10
20
30
40
50

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]

#include <iostream>
#include <string>
 
using namespace std;
int main(){
  //1. Showing how to iterate through a loop again
  //2. Show how to determine the size of an array
  //3. Pointer -- "Is the same as an array" when used with arrays
  //4. How to reverse an array.
 
  //Homework -- Make a second array, equal to the reverse of the first array
  //Bonus Create an array of 5 strings, allow the user to enter values for the strings, then output them in random order.
 
  const int size = 7;
  int myArray[size] = { 1,2,3,4,5,6,7 };
  // | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 
  // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 
 
 
 
  for (int i = size-1; i >= 0; i--){
    cout << myArray[i] << endl;
  }
 
 
  cout << endl;
  system("PAUSE");
  return 0;
}

[/spoiler]

Homework: Using an array allow a user to enter 5 numbers, then using a loop find the total and average of the numbers and output them.



Arrays
Before I want to talk about arrays, I want to first talk a bit more about variables. One of the things that we’ve all wanted a user to be able to do at some point is: “Enter x variables, enter y number to stop” and then you do something with them. And the way to do this was probably with some crazy structure of a while loop, multiple ifs, tons of variables, tons of tests to make sure that stuff was used / input correctly. Arrays are the start of a solution to the issue. Arrays are a container that allow us to hold “like-type” variables (all the same type). So for instance, an array of ints can only hold ints. If we try to put in a double, it will actually work (in some IDE, others will trigger an error), but it will trim everything after your decimal place. With any of the types we’ve used thus far, we can make an array. This includes string, but that’s a little bit special since each individual string is a little bit like an array itself.


Declaring an Array
In C++ there are a few different ways to declare an array, in this lesson we looked at 2 of them. Size-known and initialized arrays. A size-known array is one where we use either a plain number (int) or a const int that is declared at compile-time to make the size of the array known. It bears mentioning that the following is INVALID

int size =0;
cin >> size; //user inputs 10
int myArray[size]; //Error, since size is not known at compile time

We have to be very careful that we adhere to using arrays in a way that doesn’t confuse this. There are ways to create array-like structures of unknown size that we’ll get into later, but these are not as simple or straight forward.

Some good examples of array declaration are:

int myArray[7];
int anotherArray[15] = { 0 }; // sets all 15 items (anotherArray[0] - anotherArray[14] equal to 0<br /><hr />


What is an Array
All this talk of how to set them up, and how to make them, and so little talk of what they do. As I said earlier, an array is a sort of storage container that holds like type variables. But rather than just saying that, let me show you a case of when an array might be good (remember this example for later, we’ll touch it again in classes).

//THIS IS BAD CODE
double price1 = 2.09;
double price2 = 3.19;
double price3 = 5.99;
double price4 = 1.05;

int itemNum1 = 1;
int itemNum2 = 2;
int itemNum3 = 3;
int itemNum4 = 4;

string itemName1 = "Item 1";
string itemName2 = "Item 2";
string itemName3 = "Item 3";
string itemName4 = "Item 4";

The smarter way to do this (until we get to objects) is to use arrays to contain the similar data. The above example become very complex if we ever need to edit item numbers, change prices for a sale, or output them in some way that makes sense. A better example looks like this:

double prices[4]    = {2.09, 3.19, 5.99, 1.05}; //Prices
int itemNumbers[4]  = {1,2,3,4}; //Item Numbers
string itemNames[4] = {"Item 1", "Item 2", "Item 3", "Item 4"}; //Item Names

for (int i=0; i<4; i++){ 
    cout << "ItemNumber: " << itemNumbers[i] << "-"  << itemNames[i] << " :" << prices[i] << endl;
 }

output:

ItemNumber: 1 - Item 1 : 2.09
ItemNumber: 2 - Item 2 : 3.19
ItemNumber: 3 - Item 3 : 5.99
ItemNumber: 4 - Item 4 : 1.05


Off-By-One error
The off by 1 error is going to be your all-time worst enemy. These are common with loops and have been discussed there, but they are equally common for arrays. Arrays are 0-indexed. Meaning the FIRST location in an array is array[0] rather than array[1] like a lot of people seem to try. This is going to be the primary error you run into and it will present as an Array Bounds Error (or something along those lines)