# Getting Started

## Learn by Example

One of the best ways to learn how to program in a new language is by looking
at lots and lots of example programs. The best thing to do is to copy and paste
each program below into a text file and compile it. Then, try the experiments.
By extending these example programs, you will gain familiarity with different aspects
of C++, and you will feel more confident when it comes time to write programs from
scratch.


### Example 1: Get your compiler working!

If you have not already done so, copy and paste the following classic program
into a text file and compile it. Instructions on compiling are available
[here](http://arachnoid.com/cpptutor/setup_unix.html).

It's likely that you worked through the details of this program in the tutorial,
so we will not provide a line-by-line description here. There are a few things
to notice, however, regarding *readability*. This refers to comments
and formatting that help make programs easy to read, understand and maintain.

- Every program we write begins with a header comment, providing the name of the author, their contact information, a short description, and usage (if relevant). Every function begins with a comment on operation and usage.
- We add explanatory comments using full sentences, whenever the code does not document itself, for example, if the processing is tricky, non-obvious, interesting, or important.
- Always use descriptive names: variables are lower-case words separated by _, as in my_variable. Function names use upper-case letters to mark words, as in MyExcitingFunction(). Constants start with a "k" and use upper-case letters to mark words, as in kDaysInWeek.
- Indentation is in multiples of two. The first level is two spaces; if further indentation is needed, we use four spaces, six spaces, etc.

```
// hello.cpp: Maggie Johnson
// Description: a program that prints the immortal saying "hello world"

#include <iostream>
using namespace std;

int main() {
  cout << "Hello World!" << endl;
  return 0;
}
```

Some experiments to try:

- The most important thing is to make sure you can compile and run this program.
- Modify the above program to print "Hello World!" 4 times on a line for 6 lines, where each is printed in a field of 17 spaces. Use for-loops to do this. Click [here](https://cplusplus.com/reference/iostream/cout/) to learn about formatting output with cout. Click [here](https://developers.google.com/edu/c++/solutions/1-1) to see the solution.
- Using the program you just completed, figure out how to print "Hello World!" left-aligned in the fields of 17 spaces (the default is usually right-aligned). Click [here](https://developers.google.com/edu/c++/solutions/1-2) to see the solution.

<br />

### Example 2: Get some input

It's easy to get input from the keyboard in C++ using cin. Here is an example:

```
// get_input.cpp: Maggie Johnson
// Description: Illustrate the use of cin to get input.

#include <iostream>
using namespace std;

int main() {
  int input_var = 0;
  // Enter the do while loop and stay there until either
  // a non-numeric is entered, or -1 is entered. Note that
  // cin will accept any integer, 4, 40, 400, etc.
  do {
    cout << "Enter a number (-1 = quit): ";
    // The following line accepts input from the keyboard into
    // variable input_var.
    // cin returns false if an input operation fails, that is, if
    // something other than an int (the type of input_var) is entered.
    if (!(cin >> input_var)) {
      cout << "You entered a non-numeric. Exiting..." << endl;
      break;
      // exit the do while loop
    }
    if (input_var != -1) {
      cout << "You entered " << input_var << endl;
    }
  } while (input_var != -1);
  cout << "All done." << endl;
  return 0;
}
```

An experiment:

- When an input error is made, the stream "breaks," cin returns false, and the program stops. It's very important to guard against such errors as we did in the program above. But what if we want to recover from the error, rather than have the program stop? There are two steps to recovering from an error:
  1. Clear the error with cin.clear().
  2. Remove the incorrect characters from the stream. One way to do this is with cin.ignore().

Write a program that recovers from bad input using these two steps. Use
Google to search for how these methods work. Our solution is [here](https://developers.google.com/edu/c++/solutions/1-3).

<br />

### Example 3: What does this program output?

```
#include <iostream>
using namespace std;

int main() {
  cout << " 1\t2\t3\t4\t5\t6\t7\t8\t9" << endl << "" << endl;
  for (int c = 1; c < 10; c++) {
    cout << c << "| ";
    for (int i = 1; i < 10; i++) {
      cout << i * c << '\t';
    }
    cout << endl;
  }
  return 0;
} 
```

<br />

### Example 4: Decomposing makes everything easier...


Time for us to start writing computer games! This first one will be a bit simple,
but it's a start. Our task is to write a program that implements a guessing
game. Our program generates a random number between 0 and 100. The player must
guess the secret number. The program provides hints like "that's too high" or "that's
too low" until the player finally guesses the secret number.

We will work on this game in three steps.

1. Figure out how to generate a random number within a given range of values.
2. Create a main function that processes one guess from the player, and provides hints.
3. Add what we need to allow for multiple guesses until the player guesses the number.

This process of development is called decomposition, which means breaking a task
into sub-tasks, each of which is easy to do.

Starting with step 1, do a Google search to see how to generate a random number
using C++. Try searching on "rand C++". [Here](https://developers.google.com/edu/c++/solutions/1-4) is
our solution.

For step 2, we need to receive an integer input from the player (with appropriate
error-checking on cin), and check it against the secret number. Try and write
this part of the game yourself before checking [our
solution](https://developers.google.com/edu/c++/solutions/1-5).

Finally, we need to add a loop that keeps collecting guesses from the player
until they finally guess the secret number. After completing this part of the
program, you can check [our solution](https://developers.google.com/edu/c++/solutions/1-6).

Decomposition is one of the most important skills for a programmer to learn.
Being able to break a task down into manageable pieces, and then complete one
at a time is critical, no matter how big or how small the project. Here are some
other opportunities for you to practice decomposition.

- Many everyday tasks provide opportunities to build skills in decomposition. It might surprise you to discover that your mind just works this way! For example, if I have to clean up a really messy kitchen (perhaps some
  little girls just baked a cake), I break the tasks down to provide a plan,
  and to make sure I don't have to re-do work later. I don't want to wash the
  floor first if there's all kinds of stuff on the counters to clean up - I'll
  probably have to do the floor again later. So, maybe I put all the ingredients
  away first; move all the dishes into the sink; clean off the counters; wash
  the dishes; and finally, clean up the floor. There are other ways to perform
  this task, but by thinking it through first, it helps me define a plan that
  will not require re-work.

  Use everyday tasks as examples for developing your decomposition skills.
  Who knows - it might even make you more efficient around the house!
- The **greatest common divisor** of two integers is the largest number that divides them both evenly. For example, gcd(12, 18) = 6, gcd(−4, 14) = 2. The most efficient way to compute gcd is with the Euclidean algorithm. Write a program with a function to compute gcd for two integers. Try doing the function without recursion first - it will help you understand how the algorithm works.

  Explicitly define your sub-tasks, for example, find the code for the Euclidean
  algorithm; create a non-recursive function for the algorithm; etc. [Here](https://developers.google.com/edu/c++/solutions/1-7) is
  our solution.

<br />

### Example 5: Math Puzzles

One of the powers of computing is being able to do a brute-force search for
a solution to a problem. Trial and error works just fine for some problems.
In fact, computers can be especially good at such problems. Consider this:

Horses cost $10, pigs cost $3, and rabbits are only $0.50. A farmer buys 100
animals for $100, How many of each animal did he buy?

There is a remarkably simple solution to this problem. See if you can find
it before you look at [ours](https://developers.google.com/edu/c++/solutions/1-8).

Here is another one to try:  

How many ways can you arrange 6 different books, left to right, on a shelf?

This time we will just give you the solution and let you write the program:
720.

<br />

### Example 6: Strings for your consideration

What does the following program output?

```
#include <iostream>
using namespace std;

int main() {
  string str1 = "To be or not to be, that is the question";
  string str2 = "only ";
  string str3 = str1.substr(6, 12);
  str1.insert(32, str2);
  str1.replace(str1.find("to be", 0), 5, "to jump");
  str1.erase(9, 4);
  cout << str1 << endl;
  for (int i = 0; i < str3.length(); i++)
    cout << str3[i]; cout << endl;
}
```

Click
[here](http://www.yolinux.com/TUTORIALS/LinuxTutorialC++StringClass.html) for some help.

<br />

### Example 7: Next steps with decomposition - Your first day on the job

<br />

You have just gotten a position as a salesperson for the ExerShoe company, specializing
in high-end exercise shoes costing around $225 per pair. Your boss has given you
three options for compensation, which you must choose before you begin your first
day:

1. Straight salary of $600 per week;
2. A salary of $7.00 per hour plus a 10% commission on sales;
3. No salary, but 20% commissions and $20 for each pair of shoes sold

<br />

You, being an expert C++ programmer, figure you can write a program to help
decide the best choice of compensation.

A common approach in doing decomposition for a larger program is to create
a main function that reads like an outline to solving the problem. Then,
we write the functions to do each task.

Here is a first pass at the main program:

```
  GetInput(WeeklySales);
  CalcMethod1(WeeklySales);
  CalcMethod2(WeeklySales);
  CalcMethod3(WeeklySales); 
```

See if you can implement each of these functions, before you look at [our
solution](https://developers.google.com/edu/c++/solutions/1-9).

<br />

### Example 8: What is available where?

What is the output of the following program?

```
// scope.cpp, Maggie Johnson
// Description: A program to illustrate different scopes

#include <iostream>
using namespace std;

int a = 18;
int b = 6;

int function1(int a, int b) {
  return a - b;
}

int function2() {
  int c;
  c = a + b;
  return c;
}

int main() {
  int b = 12;
  int c = 0;
  a = function1(b, a);
  c = function2();
  cout << "a: " << a << " b: " << b << " c: " << c << endl;
}
```

Once you have figured out your answer, check our commented version of the code [here](https://developers.google.com/edu/c++/solutions/1-10).

<br />

### Example 9: Processing Files

File processing in C++ is performed using fstream. To save to a file, we
declare an ofstream, and open it using the "out" mode. Check this
out in the following example.

```
// file.cpp, Maggie Johnson
// Description: An illustration of file processing
#include <fstream>
#include <iostream>
using namespace std;

int main() {
  char first_name[30], last_name[30]; int age;
  char file_name[20];
  // Collect the data.
  cout << "Enter First Name: "; cin >> first_name;
  cout << "Enter Last Name: "; cin >> last_name;
  cout << "Enter Age: "; cin >> age;
  cout << endl << "Enter the name of the file: "; cin >> file_name;

  // Create an ofstream called People, open the stream for output.
  ofstream People(file_name, ios::out);
  // Write the output to the stream.
  People << first_name << endl << last_name << endl << age << endl; return 0;
} 
```

- See if you can figure out how to open the file just created, and display the data. [Here](https://developers.google.com/edu/c++/solutions/1-11) is our solution.
- Now see if you can modify this program to allow the user to enter many records of data using a loop. We also want to read back all the data, one record at a time. [Here](https://developers.google.com/edu/c++/solutions/1-12) is our solution.

Now you are ready to try some [exercises and
projects](https://developers.google.com/edu/c++/getting-started#exercises-and-projects)[](http://208.89.114.52/mod/resource/view.php?r=19 "Exercises and Projects") on your own!


## What it's like to be a software engineer at Google

Read about what it's like to work at Google on [this
website](http://www.google.com/careers/lifeatgoogle/).

## Exercises and Projects

The following exercises will
give you more practice with basic C++. We do not provide solutions to these exercises
and projects because we would like you to work with other students in this
course.

1. The common field cricket chirps in direct proportion to the current temperature. Adding 40 to the number of time a cricket chirps in a minute, then dividing that value by 4 gives us the temperature. Write a program that takes as input the number of chirps in a minute and prints the current temperature. For example,

   ```
   Number of chirps: 120
   The temperature is: 40.0 degrees. 
   ```
2. Write a program that will compute your final grade for a programming course you are taking. Here is the grading scheme:

   ```
   Final grades will be based on the following:
   40% Assignments   15% Midterm Examination
   35% Final Examination
   10% Class Participation Grade 
   ```

   Your program should ask the user for the four assignment scores, the midterm,
   final and section grades. Then, the final score is calculated and printed.
   To do the calculations, you average the four assignment scores together
   and then multiply it by 0.4 (40%). You then multiply the midterm score
   by 0.15, the final by 0.35 and the participation grade by 0.1. Then you
   add all the results of these multiplications together.

   Use functions wherever you can in this program. You can create a function
   to get the input by passing in as a parameter the string to be displayed
   in an explanatory cout. Here is an example run:

   ```
   Enter the score for the first assignment. 75
   Enter the score for the second assignment. 85
   Enter the score for the third assignment. 82
   Enter the score for the fourth assignment. 94
   Enter the score for the midterm. 81
   Enter the score for the final. 89
   Enter the score for the section grade. 100
   The final grade is: 86.9
   ```
3. As electronic stopwatches become cheaper and more accurate, we will no doubt be deluged with impossibly accurate measurements of time. Write a program that takes as input a time period given in seconds, and outputs the number of hours, minutes and seconds it represents. For example,

   ```
   Number of seconds: 3662
   Hours: 1
   Minutes: 1
   Seconds: 2     
   ```
4. **In the following, do decomposition prior to writing your program.
   Use functions wherever possible to create well-structured programs.**
5. Suppose we wanted to print a banner for the following: "FREEZY BREEZE MAKES THREE TREES FREEZE"

   We want the letters to be pretty big since this is a banner:

   ```
   FFFFF
   F
   FFF
   F
   F

   EEEEE
   E
   EEE
   E
   EEEEE
   ```
   etc.

   Being a good problem decomposer, you probably noticed that rather than
   put all the cout's in the main function, it would be far more efficient
   to put them in functions. So we could have a "printE" function
   and a "printZ" function and so on.

   Write a program with functions that creates a banner of a word or phrase
   with lots of repeated letters. Some possibilities:

   ```
   FREEZY BREEZE MAKES FLEAS
   SNEEZE TWEETLE BEETLE PADDLE BATTLE
   SIX SICK CHICKS KICK
   SUE SEWS SUE'S SOCKS
   BEN BENDS BIM'S BROOM 
   ```
6. Here is a "magic number" problem: Ask a user to enter a three-digit number whose first digit is greater than its last. Your program will reverse the number, and subtract the reversal from the original number. Finally, reverse the resulting number, and add it to its unreversed form. Output the final result. The original number that the user enters must be of integer type (not three chars). Think about how to write a function that takes an integer as input and returns the reverse of that number. Example:

   ```
   input number: 901
   reverse it: 109
   subtract: 901 - 109 = 792
   reverse it: 297
   add: 297 + 792 = 1089   
   ```
7. The law requires that food product manufacturers place expiration dates on their products, but there is a loophole in the law: it does not require the expiration date to be in any particular form. So, it can be written in Swahili and still be legal. Ralph Nader's third cousin, Nadine is a self-appointed Food Quality Spy.
   She has learned that many food product manufacturers have started encoding
   the product expiration dates to keep customers from knowing how old the
   stuff is.

   But the encoding does allow grocers to figure out the expiration dates
   if for some reason, they want to.

   One popular encoding method:
   - encode the months from Jan to Dec as 'A' through 'L'
   - encode each digit of the date as 'Q' through 'Z'
   - encode the year as 'A' through 'Z' meaning 1 through 26 which is then added to 1995.

   Nadine found a particularly questionable loaf of bread with this date: ARZM.
   Write a program to determine the date.
8. This is a number analogy to a famous card trick. Ask the user to enter a three-digit number. Think of the number as ABC (where A, B, C are the three digits of the number). Now, find the remainders of the numbers formed by ABC, BCA, and CAB when divided by 11. We will call these remainders X, Y, Z. Add them up as X+Y, Y+Z, Z+X. If any of the sums are odd, increase or decrease it by 11 (whichever operation results in a positive number less than 20; note if the sum is 9, just report this and stop the process). Finally, divide each of the sums in half. The resulting digits are A, B, C. Write a program that implements this algorithm.

## Application: Visualizing Music with Animation

Software engineers create a wide variety of often interesting and innovative applications.
In each module of this course, we present a different application that engineers
designed and implemented, to help you understand all the different areas in which
engineers work.

[Here](http://www.musanim.com/mam/overview.html) is one interesting
application that was built to visualize music.