Vous êtes sur la page 1sur 11

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:

double a = 4.10009, b = 9.02, c = 15.0;


double d = a + b + c;

The other basic arithmetic operators are used similarly:

int n1 = 3, n2 = 4, n3 = 8;
int sub = n1 - n2;

// subtraction

int mul = n4 * n1;

// multiplication

int div = n3 / n2;

// make sure the denominator is not 0

int rem = n3 % n1;

// remainder (modulo)

Parentheses can be used to clarify order of calculations:

int parens = ((n1 + n2) * (n3 / n2)) % n1;

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;

// adds 3 to the value of n

However, the designers of C++ added a more concise way of doing this:

n += 3; // also adds 3 to n

And this will work similarly with other arithmetic operators:

n *= 2; // doubles the value of n

Furthermore, there is a special way to increment a value by 1:

n++;

You can even use this shortcut in the middle of another expression:

int a=2, b=3;


int c = a * (b++);

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.

Basic Input and Output


The standard method to output something to the screen in C++ is to use the output operator (<<) to
send values to the cout (pronounced "see-out") stream:

cout << output1 << output2 <<...<< outputN;

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;

// get the user's initial and age


cout << Enter your first initial, and then your age: ";
cin >> initial >> age; // sets the variables
// initial and age to
//
dog_years = age / 7;

whatever the user inputs.

// calculate user's dog age...

// ...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.

Simple C++ Math[edit]


Math in C++ is very simple. Keep in mind that C++ mathematical operations follow a particular order
much the same as high school math. For example, multiplication and division take precedence over
addition and subtraction. The order in which these operations are evaluated can be changed using
parentheses.

Adding, Subtracting, Multiplying and Dividing[edit]


#include <iostream>
using namespace std;
int main()
{
int myInt = 100;
myInt
myInt
myInt
myInt

=
=
=
=

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

myInt = myInt + 100 * 2; // myInt is now 300 because multiplication


takes precedence over addition
myInt = (myInt + 100) * 2; // myInt is now 800 because we have changed
the precedence using parentheses
cout << myInt << endl;
cin.get();//Taking one character or waiting after displaying output
}

//C++ arithmetic operators


// + (add)
// - (subtract)
// / (divide)
// * (multiply)
// % (modulus division) 4 % 5 = 4 the remainder is returned 6 % 5 = 1
// += (add and assign)
// -= (subtract and assign)
// /= (divide and assign)

// *= (multiply and assign)


// %= (mod and assign)

C++ math library[edit]


The C++ math library is actually C's math library. It is easy to use and is accessed by including
cmath.
#include <cmath>

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;

cout << "Enter a number. ENTER: ";


cin >> myFloat;
cout << myFloat << " in the power of 2
is " << pow(myFloat, 2 ) <<
endl;
cout << myFloat << " in the power of 3
is " << pow(myFloat, 3 ) <<
endl;
cout << myFloat << " in the power of 0.5 is " << pow(myFloat, 0.5) <<
endl;
cin.clear();
cin.sync();
cin.get();
return 0;
}
Trigonometry[edit]
Note: Trigonometric functions in cmath use RADIANS.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float myFloat = 0.0f;
cout << "enter a number. ENTER:
cin >> myFloat;
cout << "sin(" << myFloat << ")
cout << "cos(" << myFloat << ")
cout << "tan(" << myFloat << ")
cin.clear();
cin.sync();
cin.get();

";
= " << sin(myFloat) << endl;
= " << cos(myFloat) << endl;
= " << tan(myFloat) << endl;

return 0;
}

Function Arguments Passed By Value[edit]


In C++, by default variables are passed by value to functions. This means that a copy of the data is
made and passed to the function. This is in contrast to passingby reference or by pointer, in which

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;

// Have a careful look at this function call


interchange(num1, num2);
cout << "Number 1 : " << num1 << endl;
cout << "Number 2 : " << num2;
return 0;
}
Before looking below, think what the output should be. Probably as the function should work, num1
should be 5 and num2 should be 4. Let's see what the compiler has to say.
Number 1 : 4
Number 2 : 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

Getting User Input[edit]


Let's start simple. We'll read in a char and put it back out.
#include <iostream>
int main()
{
char myChar;
std::cout << "Enter a character. ENTER: ";
std::cin >> myChar;
std::cout << "You entered: " << myChar << std::endl;
std::cin.clear(); //ignore any superfluous input
std::cin.sync(); //synchronize with the console
std::cin.get();
//wait for the user to exit the program
return 0;
}

you could also go with a namespace, as shown here:

#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;

Vous aimerez peut-être aussi