mokkiller2 (04-16-2010)
Lesson #4 - Input and Modifying Variables
In my last tutorial you learned about variables and how to output them. But what happens if we want the user of the program to tell us what numbers or letters our variable is going to hold? This is where input comes in handy.
The format for input is very much the same as the format for output.
Instead of cout we use cin (console out console in pretty simple really)
Lets say we have the integer variable dog and we want the user to input what the value of dog is going to be. We would do that like this:
[PHP]
cin >> dog;
[/PHP]
Notice the arrows, instead of pointing left point right. If you are having trouble remembering which direction is in and which direction is out just make up something to help you. The one i used was, the right arrow points at the door which leads out of the room, the left arrow points to inside the room.
Modifying Variables
Lets say hypothetically the value of dog is 3. What happens if you want to change the value of dog to something else6, AFTER it has been declared, without having the user to input it.
All you have to do is
[PHP]
dog = 6;
[/PHP]
Now lets say you have the variables, cat, dog and mouse. You wish to make mouse equal cat plus dog. All you have to do is
[PHP]
cat + dog = mouse;
[/PHP]
This works the same when outputting. If you wish to output cat + dog then
[PHP]
cout << cat + dog;
[/PHP]
The symbols for operations are:
+ Equals Plus
- Equals Minus
* Equals Times
/ Equals Divide
Now lets use all this in a program.
Credits:Code:#include <iostream> using namespace std; int number1; int number2; int main() { cout << "please input number one" << endl; cin >> number1; cout << "please input number two" << endl; cin >> number2; cout << "number one plus number two is " << number1 + number2 << endl; cout << "number one minus number two is " << number1 - number2 << endl; cout << "number one times number two is " << number1 * number2 << endl; cout << "number one divided by number two is " << number1 / number2 << endl; return 0; }
Me :]
mokkiller2 (04-16-2010)