1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - Lesson One Learning How to Compile With Visual C++ 2005

By David Bolton, About.com

7 of 8

Learn about Arithmetic Operations

Writing computer software wouldn't be much use if you couldn't do addition, subtraction etc. Here's example 2 that shows simple addition.
// exammple 2

#include "stdafx.h"
#include <iostream>

using namespace std;
int main(int argc, _TCHAR* argv[]) {
int a=7;
int b = 15;
int total = a + b;
cout << "The number is " << total <<endl;
return 0;
}
Enter it as above and Make it.

Explanation of Example 2

The function main(), like in C is the bit that windows calls.
int main(int argc, _TCHAR* argv[])
int main()
The first has calling parameters so you can read values passed in at the command line. You can omit those parameters as the second version shows. The compiler will accept either version.

Three int variables (a,b and total) are declared. A feature of C++ that C lacks is declaration of variables anywhere instead of at the start of functions. This is handy as you can leave declaring them until you need them. That cuts down on bugs.

The total variable is initialized with the result of a and b. The endl on the end of the cout is an end line. It forces output to start on a new line.

Before running this example

Here's a little tip to save time when running Command Line applications.

When you run this program from the Command Line. It should output "The number is 22".

Other Arithmetic Operations

As well as addition, you can do subtraction, multiplication and division. Just use + for addition, - for subtraction, * for multiplication and / for division.

Try changing the above program- use subtraction or multiplication. You can also change ints to floats or doubles.

On the next page : Learn about comments

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Some Arithmetic Operations

©2009 About.com, a part of The New York Times Company.

All rights reserved.