1. What would you do if you wrote a big program that relied on a "magic number". So you wrote this huge program and assumed that the magic number was 2, Then somebody tells you that the number is 3. So you have to go back through your whole program and change it??? There must be a better way?
  2. There is! And they are called variables, So replace the code inside your main function with this:
     string name = "Bob";
     cout << "Hello " << name << endl;
  3. So if you run your program now, It will print out "Hello Bob", Yey! Except... Your name probably isn't bob. So why dont we make the program ask your name?

  4. Now we are going to use cin, While cout prints stuff, cin reads stuff! Try this (In your main function):

     string name;
     cout << "Whats your name?" << endl;
     cin >> name;
     cout << "Hello " << name << endl;
  5. So what exactly did we do there? Well, First of all we printed a question asking their name, Then we used cin to make the name variable be whatever the user types in. And finally, we print it out!

  6. But why did we write string before the variable name? Because in C++ we need to tell the computer what kind of information we want to store. A few common types are string, int, and bool. A string is a piece of writing, An int ( Integer ) is a whole number and a bool is a true or false!

  7. Why do we even have to care what kind of variable it is? Well, Think about it, If you define two variables a and b. And then type a+b, You could be trying to add two numbers together or you could be trying to join two sentences together. So it is important to know which!

  8. Lets make a adding calculator!
     int a = 0;
     int b = 0;
     cout << "Type two numbers: " << endl;
     cin >> a >> b;
     cout << a+b << endl;
  9. Add this into your main function and run it, After you type in two numbers( Separated either by typing one pressing enter and typing another or typing them both on one line with a space in between them. ), It should print out the answer!
  10. Say you typed in 3 5, It would output 8! But how did it know 3 and 5 were different numbers? One very important thing to remember is that cin separates input by newlines or spaces.

results matching ""

    No results matching ""