Arithmetic Operators and Basic I/O: You Can Add Two Numbers With A Plus Sign
Arithmetic Operators and Basic I/O: You Can Add Two Numbers With A Plus Sign
Arithmetic Operators and Basic I/O: You Can Add Two Numbers With A Plus Sign
int num = 3 + 4;
Now the variable num has the value 7. As always, command lines end with a semi-colon. You can
also add variables and carry out multiple sums at once:
int n1 = 3, n2 = 4, n3 = 8;
int sub = n1 - n2;
// subtraction
// multiplication
// remainder (modulo)
Sometimes you might want to change a variable by adding to (or subtracting from, multiplying by,
etc.) its current value. Suppose integer n has some value and you want to increment its value by 3.
The following is a valid statement:
n = n + 3;
However, the designers of C++ added a more concise way of doing this:
n += 3; // also adds 3 to n
n++;
You can even use this shortcut in the middle of another expression:
In this case, c will take on the value 6 (= 2*3) and b will subsequently be incremented to 4. If you
want b incremented before the rest of the evaluation takes place, you could write:
c = a * (++b);
Notice the placement of the ++ operator. This example increments b first, and then carries out the
rest of the evaluation. Thus c will be equal to 8 since 8 = 2*(3 + 1) . The -- operator works in the
same fashion, except that it decrements the variable's value by 1.
Each of the outputs can be a string, character, number, variable, an expression,endl (which inserts
a new line and flushes the output stream), or a function whose return value is any of these.
Similarly, the cin ("see in") stream asks for user input. Both cin and cout are defined in
the iostream.h header file, as described in section #1 of "Getting Started". Here is a simple
example that demonstrates the usage of cout and cin:
#include <iostream.h>
main()
{
// variable declarations
char initial;
int age;
double dog_years;
// ...and output it
cout << "Your age in dog years is: " << dog_years << endl;
}
Because the first cout statement does not print out a newline character \n orendl, there is no new
line, and the next input or output will take place after the end of the sentence. In this case, the user
will be asked to type his or her input after the colon. Notice that cin can also take several
arguments; that is, you can ask for more than one input value with a single line of code.
Operator - An operator is a special symbol that performs an action with one or more variables.
Examples are the addition operator +, the extraction operator >>, and the not-equals logic
operator !=.
Cin - The basic C++ input command, defined in the iostream.h header file. cinasks the user of the
program to enter a value for some specified variable.
If-Statement - If-statements, or if/else statements, are lines of code that decide whether or not a
piece of code should be executed, based on a test condition.
Test Condition - A test condition is a boolean expression that is usually used to branch the
execution of the program.
Switch-Statement - A switch-statement is a statement that performs different actions based on the
value of a variable.
Break - The break keyword is used to immediately exit from a loop or a switch statement.
Loop - A loop is a fragment of code that is repeated until a specified condition does not hold.
Default - The default keyword is used to provide code to a switch statement that is executed if
none of the other cases are matched.
Problem : Can you use more than one arithmetic operator in a line of code?
Yes! Be sure to keep order of evaluation in mind (ie. multiplication will be evaluated before
subtraction), and in general try to use parentheses to make your expressions clear.
Problem : What are three ways of incrementing a variable?
The first is to use a statement like x = x + 5;. C++ makes this easier with a second method, which
looks like x += 5;. The third method increments by 1: x++.
Problem : What is the difference between using the ++ operator before a variable name and using it
after the variable name?
If it is used before the variable name, the variable will be incremented before any other calculation is
done with your expression. When the operator is used after the variable name, the incrementing
takes place after the rest of the expression is evaluated.
Problem : What is endl?
It is a stream manipulator. cout << endl; tells the computer to print out a new line on the screen,
and tells it to flush the output stream meaning that it tells the computer to print out anything it was
waiting to print out in a buffer.
Problem : How many input variables can the cin command take?
The command can take as many variables as you want to supply it with. However, you should strive
to use only one at a time to make it less confusing for your program's users.
=
=
=
=
myInt
myInt
myInt
myInt
/
*
+
-
10;
10;
50;
50;
//myInt
//myInt
//myInt
//myInt
is
is
is
is
now 10
back to 100
up to 150
back to where it started
Math functions[edit]
Now that we have the C math library let's use some neat functions.
Square Root[edit]
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float myFloat = 0.0f; //the f (requires decimal) tells the compiler to
treat this real number as a 32 bit float
//and not as a 64 bit double. this is more of a
force of habit than a requirement
cout << "Enter a number. ENTER: ";
cin >> myFloat;
cout << "The square root of " << myFloat << " is " << sqrt(myFloat) <<
endl;
cin.clear();
cin.sync();
cin.get();
return 0;
}
Powers[edit]
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float myFloat = 0.0f;
";
= " << sin(myFloat) << endl;
= " << cos(myFloat) << endl;
= " << tan(myFloat) << endl;
return 0;
}
case the address of the object itself is passed to the function. However, let's first look at what
passing arguments by value means:
Consider the following program that accepts a number and prints its cube:
#include <iostream>
using namespace std;
float cube(float a)
{
return a*a*a;
}
int main()
{
float num;
cout << "Enter a number : ";
cin >> num;
cout << "The cube of " << num << " is " << cube(num)<< endl;
return 0;
}
If you want the cube of 19, the output should look like this:
Enter a number : 19
The cube of 19 is 6859
That was quite a basic example. I think you got an idea of what a function can do anyways. Let us
go a little more complex.
void interchange(int arg1, int arg2)
{
int temp = arg2;
arg2 = arg1;
arg1 = temp;
}
int main()
{
int num1 = 4;
int num2 = 5;
What? Doesn't that look like the complete opposite to the rules of the language? Seems to be, but
isn't. Let us discuss what actually took place. We will need to go into the works of the compiler. A
little knowledge is essential to properly understand the functions of the pass by reference and
pointers.
Pass By Reference[edit]
Now, let's redefine the interchange function from the above example. The change will be
explained in more detail in a later lesson, but let's look briefly at what passing data by
reference means.
void interchange(int& arg1, int& arg2)
{
int temp = arg2;
arg2 = arg1;
arg1 = temp;
}
First the change in the type of the data passed into interchange . Previously the arguments were
of type int but they are now of type int& . The additional & is very important: it tells the compiler
that the data is a reference to an int value rather than simply an int value.
The default C++ behavior is to copy the function arguments. The use of a reference type changes
this behavior and a copy is no longer made. As an analogy, think of asking someone to proof-read
and markup a printed document. You can either give them a photocopy (pass by value) or hand
them the original document (pass by reference). In the same way, you can tell the compiler whether
to pass a copy of the arguments or the original variables themselves depending on whether you
want the originals to be changed or not.
This time the result of the program using pass by reference semantics will be:
Number 1 : 5
Number 2 : 4
#include <iostream>
using namespace std;
int main()
{
char myChar;
cout << "Enter a characer. ENTER: ";
cin >> myChar;
cout << "You entered: " << myChar << endl;
cin.clear();
cin.sync();
cin.get();
return 0;