Introduction to C++ Programming
We’ll start by examining the following simple program:
#include
<iostream>
using
namespace std;
int main()
{
cout << "Hello world!\n";
return 0;
}
Notes on program:
· Anything that starts with # is a preprocessor command.
· #include causes the contents of a file to be inserted.
· iostream is a header file that contains the definition of cout and <<.
· the line "using namespace std" allows us to use the terms defined in the iostream library.
· cout represents the standard output. << is an operator that means send what’s on the right to the location on the left. In other words, send “Hello world” to the standard output.
· All programs must have a main function - it indicates where the program starts. The word int means that the main function returns an int value.
· Curly brackets indicate the beginning and end of a function. Good style has us indent all lines between the parentheses.
· Statements always end with a semi-colon.
· Strings are surrounded by double quotes.
· \n means the newline character, which can appear anywhere in a string.
· The return 0 means that the function main ends with a value of 0.
We’ll use Visual C++ to run our program. Start by selecting Microsoft Visual Studio .NET. From the File menu, choose the New command and then the Project command. You’ll see the following dialog box:
To run a C++ project, you’ll need to enter a Project name, enter a Location, click the Win32 Project application icon, and finally click OK.
You'll then see the Win32 Application wizard.
Click Application Settings, choose Console Application and Empty Project, and then click Finish.
Your new project has now been created. Your project contains several windows. The window in the upper right corner lets you decide whether look at your project in Solution Explorer or ClassView. We’ll always use Solution Explorer in this class.
When you click the + next to “project1” files, you’ll then see three folders – Source Files, Header Files, and Resource files. We’ll only use Source Files for at least half the semester.
From the Project menu, choose Add New Item. From the dialog box, click the C++ File icon, enter the filename and click the Open button.
You now have a window to enter your program, and there is an entry in the Source Files folder in the upper-right window.
After you type your program, click the Save All icon (the disks).
To run your program, you can either build your program without running it (choose Build Solution from the Build menu). This causes the Visual C++ compiler to compile your program and create an executable file, as long as there were no errors. You can find errors in the Output window at the bottom of the screen.
After correcting the errors, you would try to Build Solution again.
To run your program, you can choose Start without Debugging from the Debug menu. This causes a DOS window to appear on the screen. This window serves as the console where you can see output and enter input.
Let’s see what files were created as you did your first C++ project.
The file ex1.cpp stores your source code in C++. When you hand in your homework assignments later in the semester, this is the only file you'll need to turn in.
The other files are necessary for the project to load successfully.
If you need to delete files for storage reason, the .cpp file is the only one you really need to save
There is also a Debug folder.
The file ex1.obj is your machine language program (object code) that was created from your ex1.cpp file (the source code). ex1.exe is your executable file. Double-clicking this will cause your program to run. The executable file is fairly large. The other files are not needed at all, and can be deleted.
After you exit from Visual Studio .NET, you can re-open your project by double-clicking the .vcproj file. If you don't immediately see your program, you can use your Solution Explorer window.
To delete a .cpp file from your project, just highlight in the Solution Explorer and press the Delete key. This won't erase the file – it'll just remove it from the project.
To load an existing .cpp file into your project, you can choose Add Existing Item from your Project menu. Your .cpp file need not be in the project folder.
Now that we’ve seen how to run our programs, let’s come back to looking at C++.
What do the following programs do?
#include
<iostream>
using
namespace std;
int main()
{
cout << "Hello\n CIS202\nGood Luck";
return 0;
}
#include
<iostream>
using
namespace std;
int main()
{
cout << "Hello";
cout << "\nCIS202";
cout << "\nGood
Luck";
return 0;
}
The program below is OK since C ignores white space in a
program. You can have spaces of carriage returns anywhere (except inside
strings and inside keywords) without it effecting the
program. But is it easy to read?
#include
<iostream>
using
namespace std;
int
main(
)
{
cout
<<
"Hello world!\n"
; return 0;
}
But C is case sensitive. The following won't work!
#include
<iostream>
using
namespace std;
int main()
{
Cout << "Hello world!\n";
return 0;
}
Comments are anything (including white space) between /* and */
/* Legal comment */
using namespace std;
int main() /*Legal comment*/
{
/* Legal
Comment */
/* /* Illegal comment */ */
return 0;
}
Use comments to explain in English who wrote a program, and what it does:
/*
Written by John Avitabile */
/*
This program prints a simple message */
#include
<iostream>
using
namespace std;
int main()
{
cout << "Hello world!\n";
return 0;
}
Comments are not printed as the program executes. They are just there for programmers to read to help explain what the program does.
If you put a // on a line, everything after the // is treated as a comment.
//
Written by John Avitabile
//
This program prints a simple message
#include
<iostream>
using
namespace std;
int main()
{
cout << "Hello world!\n";
// a simple message
return 0;
}
A variable is a named memory cell that can store a value. The rules for variable names are:
Begins with letter or underscore.
May contain only letters, underscores, and digits.
Can't be a keyword (see page 52 of text)
31 or less characters.
Finally, the name you give to a variable should be meaningful.
Each variable can store information of a certain type. Some types in C are int, float, double, and char.
int - positive or negative numbers without decimal points. The range of values depends upon the number of bytes used to store an integer (usually the range is –32768 through 32767). There is also another type called long, but this is the same thing as int so we'll ignore it.
float, double, and long double - signed or unsigned numbers having a decimal point.
The difference between float and double is that since more bytes are used to store a double than float, a double will be a closer approximation to the number. How would the number 1/3 be represented as a decimal?
You can write floats or doubles using exponential notation, for example 4.3212e3 instead of 4321.2. The "e" means "times 10 to the power of".
char - any alphanumeric character. Actually chars are really stored as ASCII numbers:
32 ' '
33 !
34 "
35 #
36 $
37 %
38 &
39 '
40 (
41 )
42 *
43 +
44 ,
45 -
46 .
47 /
48 0
49 1
50 2
51 3
52 4
53 5
54 6
55 7
56 8
57 9
58 :
59 ;
60 <
61 =
62 >
63 ?
64 @
65 A
66 B
67 C
68 D
69 E
70 F
71 G
72 H
73 I
74 J
75 K
76 L
77 M
78 N
79 O
80 P
81 Q
82 R
83 S
84 T
85 U
86 V
87 W
88 X
89 Y
90 Z
91 [
92 \
93 ]
94 ^
95 _
96 `
97 a
98 b
99 c
100 d
101 e
102 f
103 g
104 h
105 i
106 j
107 k
108 l
109 m
110 n
111 o
112 p
113 q
114 r
115 s
116 t
117 u
118 v
119 w
120 x
121 y
122 z
123 {
124 |
125 return 0;
}
126 ~
If a character is preceded by a backslash, it's called an escape sequence. Here are some examples.
\n new line
\t tab
\\ backslash character
\' single quote
\" double quote
Declaration statements
Declaration statements indicate that a certain variable can be used in a program, and what the type of that variable will be. Here are some examples of declaration statements:
int
num;
int
sum;
double
average;
float
score;
char
ch1, ch2;
Note that you can have more than one variable in a single declaration statement.
Variables must be declared before they can be used. It’s often a good idea to put declaration statements at the very beginning of the main function, right after the {.
You can also assign an initial value to a variable in a declaration statement:
int
num = 10;
int
sum = 0;
double
average = 10.0;
float
score = 0;
char ch1, ch2 = 'A';
/* put character constants in single quotes */
If a variable has not yet been given a value explicitly, its actual value is unknown and could be anything!
Printing the values of
variables
To print the value of a variable, you put the variable to the right of the << operator. Notice that you can have more than one << operator in a single statement. Also, endl is a manipulator that forces the output of a new-line and a flushing of the output stream.
What does the following program print?
#include
<iostream>
using
namespace std;
int main()
{
int num = 10;
int sum = 0;
double avg = 10.0;
float score
= 0;
char ch1 =
'a', ch2 = 'A';
cout << "num is ";
cout << num;
cout << "\n";
cout << "sum is "
<< sum << "\n";
cout << "Two more are "
<< avg << " and " <<
score << endl;
cout << "Characters are "
<< ch1 << " and " << ch2 << endl;
return 0;
}
Besides being able to assign a value when the variable is declared, we can also assign a value using the assignment operator, =.
#include
<iostream>
using
namespace std;
int main()
{
int num;
char ch;
num = 23;
ch = 'A';
cout <<
"Two variables got assigned\n";
cout <<
"num ch\n";
cout <<
num << " " << ch << endl;
return 0;
}
The & operator is used to get the address of a variable. The following program prints the addresses of two variables, and then their values.
#include
<iostream>
using
namespace std;
int main()
{
int num;
char ch;
cout <<
"Two variables\n";
cout <<
"num ch\n";
cout <<
num << " " << ch << endl;
cout <<
"Their addresses\n";
cout <<
"num ch\n";
cout <<
&num << " " <<
&ch << endl;
return 0;
}
Arithmetic Operators
The usual arithmetic operators (+ - * /) can be applied to ints, floats, doubles and even chars (use the ASCII value of the character.)
In integer division, the result is truncated to 0. In real or float division, the remainder is included. In other words, 5 / 2 is 2 and 5.0 / 2.0 is 2.5.
What does the following program print?
#include
<iostream>
using
namespace std;
int main()
{
int num = 10;
int sum = 5;
double
average = 10.0;
float score
= 5.0;
char ch1 =
'a', ch2 = 'A', ch3 = 'C';
cout << num * 10 << endl;
cout << sum + 1 << endl;
cout << sum – 1 << endl;
cout << num / sum << endl;
cout << sum / num << endl;
cout << average / score << endl;
cout << score / average << endl;
cout << ch1 + 4 << endl;
cout << ch3 - ch2 << endl;
cout << ch3 - ch2 + ch1 << endl;
return 0;
}
The % operator is the mod (or remainder) operator. It can be used only with integers.
The - operator can also be a unary operator meaning negation.
What does the following program print?
#include
<iostream>
using
namespace std;
int main()
{
int num = 10;
int sum = 6;
int num1 = 3;
cout << num % sum << endl;
cout << sum % num1 << endl;
cout << - sum << endl;
cout << - - sum << endl;
return 0;
}
In a mixed-type expression with a double (or float) operand and an int (or char) operand, the result is always a double.
What's wrong with the following program?
#include
<iostream>
using
namespace std;
int main()
{
int int1 = 10,
int2;
double d1 = 4.5, d2;
d2 = d1 + int1;
int2 = d1 + int1;
cout << d2
<< endl;
cout <<
int2 << endl;
return 0;
}
Order of Operations
If there is more than one operator in an expression, operator precedence dictates which operation will be done first. The operator precedence in C is:
unary - right to left associativity
* / % left to right associativity
+ - left to right associativity
This means that all *s will be performed before all +s, and that if there are two /s, they will be executed in left to right order.
Parentheses can be used to change the order of operations, since all operations inside parentheses are executed before operations outside of parentheses.
What will the following program print?
#include
<iostream>
using
namespace std;
int main()
{
int num1 = 10, num2 = 5, num3 = 2;
cout << num1 + num2 * num3 << endl;
cout << (num1 + num2) * num3 << endl;
cout << num1 + 4 / 2 + num2 << endl;
cout << num1 / num2 / num3 << endl;
cout << num1 / (num2 / num3) << endl;
return 0;
}
Assignment Statements
Assignment statements are used to assign values to variables. The format of an assignment statement is:
variable = value
For example:
age = 37;
next_age = age + 1;
As you can see, the value assigned to age will be 37, and the value assigned to next_age will be 38.
What will the following programs print?
#include <iostream>
using namespace std;
int main()
{
double
miles = 420, gallons = 10.5, mpg;
mpg = miles
/ gallons;
cout << "Miles per gallons is
" << mpg << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
double num1
= 4.0, num2 = 5.0, num3 = 9.0, avg;
avg = num1 + num2 + num3 / 3;
cout << "The average is not " << avg
<< endl;
avg = (num1 + num2 + num3) / 3;
cout << "The average is "
<< avg << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
char ch = 'B';
int x = 2;
ch = ch + x;
x = x + 2;
cout << "New values are "
<< ch << " and " << x
<< endl;
return 0;
}
Other assignment operators
Besides =, there are 5 other assignment operators. They are:
+= -= *= /= %=
Only the first two are used very much.
The += operator means add the value to the variable. Therefore,
a = a + 1;
a += 1; /* does same thing */
The -= operator means subtract the value from the variable. Therefore,
a = a - 1;
a -= 1; /* does same thing */
What does the following program print?
#include <iostream>
using namespace std;
int main()
{
char ch1 =
'B', ch2 = 'G';
int x = 2, y = 0;
ch1 += x;
ch2 -= x +
2;
x += 3;
y -= x;
cout << "New values are "
<< ch1 << " and " << ch2 << endl;
cout << "New values are "
<< x << " and " << y << endl;
return 0;
}
Incrementing and Decrementing
The increment operator is
++. It means add one to the variable. The ++ can be put either before or
after the variable.
a = a + 1;
++a; /* same thing */
a++; /* same thing */
The decrement operator is
--. It means subtract one from the variable. The -- can be put either
before or after the variable.
a = a + 1;
--a; /* same thing */
a--; /* same thing */
What does the following program print?
#include <iostream>
using namespace std;
int main()
{
char ch1 =
'B', ch2 = 'G';
int x = 2, y = 0;
ch1++;
++x;
ch2--;
y--;
cout << "New values are "
<< ch1 << " and " << ch2 << endl;
cout << "New values are "
<< x << " and " << y << endl;
return 0;
}
If the ++ or -- is put before the variable, it is called the prefix version. If the ++ or -- is put after the variable, it is called the postfix version.
++a is prefix
a++ is postfix
There is a difference between the prefix and postfix increments and decrements that you see only if the operation is inside of a larger expression.
The prefix operation does increment first, then uses the variable in any expression it happens to be in.
The postfix operation uses the variable in any expression it happens to be in first, then increments the variable.
a = 3;
b = ++a;
/* a becomes 4, then b is assigned 4 */
c = a++;
/* c is assigned 4, then a becomes 5 */
What does the following program print?
#include <iostream>
using namespace std;
int main()
{
char ch1 =
'B', ch2 = 'G';
int x = 2, y = 0;
cout << "New values: " << ++ch1
<< " and " << ch2++ << endl;
cout << "New values: " << ++x
<< " and " << y++ << endl;
cout << "New values: " << ch1
<< " and " << ch2 << endl;
cout << "New values: " << x << " and " << y << endl;
return 0;
}
Formatting Numbers
So far, our programs to print numbers just printed them as is. You can use manipulators to format your output. If you want to use these manipulators, you must include the header file <iomanip >.
The setw manipulator sets the field width. Consider the following program:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int x = 2, y = 23, z = 203, w = 3095;
cout << setw(3) << x << endl;
cout << setw(3) << y << endl;
cout << setw(3) << z << endl;
cout << setw(3) << w << endl;
return 0;
}
Its output is:
2
23
203
3095
Each number is printed in a field of three characters, right-aligned. If the field width is too small, it's ignored.
For floats and doubles, you must specify both the field width and the number of decimal places. The setprecision manipulator sets the number of places in the floating point precision.
Both the setw and the setprecision manipulators apply only to the next number output.
For the setprecision manipulator to work, you must send cout the ios:fixed format flag. You need only do this once.
Consider the following program:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double x= 21.23,
y = 23.3445, z = 203.8456, w = 3095.0934;
cout << setiosflags(ios::fixed);
cout << setw(7) << setprecision(3) <<
x << endl;
cout << setw(7) << setprecision(3)
<< y << endl;
cout << setw(7) << setprecision(3)
<< z << endl;
cout << setw(7) << setprecision(3)
<< w << endl;
return 0;
}
The output will be:
21.230
23.345
203.846
3095.093
You can also use setw to set the field width for a string. The setiosflags manipulator can set the flags ios::right and ios::left for right and left alignment within a field. Consider the following program:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setiosflags(ios::right);
cout << setw(7) << "This" << endl;
cout << setw(7) << "is" << endl;
cout << setw(7) << "here" << endl;
cout << setw(7) << "right now." << endl;
return
0;
}
The output will be:
This
is
here
right
now.
Inputting values
Just as cout represents the standard output stream, cin represents the standard input stream.
The operator << is used to send a value to the output stream.
The operator >> is used to get a value from the input
stream.
Consider the following program:
#include <iostream>
using namespace std;
int main()
{
int num1, num2, num3;
cout << "Enter a number:";
cin >> num1;
cout << "Enter a second number:";
cin >> num2;
num3 = num1 +
num2;
cout << "The sum is "
<< num3 << endl;
return 0;
}
It's always a good idea to prompt the user to tell them what to type in.
You can have more than one variable extracting values from cin.
#include <iostream>
using namespace std;
int main()
{
int num1, num2, num3;
cout << "Enter two numbers:";
cin >> num1 >> num2;
num3 = num1 +
num2;
cout << "The sum is "
<< num3 << endl;
return 0;
}
If you ask for two ints from cin, your program will halt until you enter two ints. You can press the Enter key as much as you like, but you'll still be waiting! Extra spaces on a single line also doesn't matter.
It's the same when you input values into a char variable. Then each character you input gets stored in the variables – but not if the character input was a space or an Enter.
If you enter too many numbers on an input line, the numbers are held in a buffer until the next extraction from cin. Then the numbers will be assigned to variables without pausing.
If you run the following program:
#include <iostream>
using namespace std;
int main()
{
int num1, num2, num3, avg;
cout << "Enter first number\n";
cin >> num1;
cout << "Enter second number\n";
cin >> num2;
cout << "Enter third number\n";
cin >> num3;
avg = (num1 + num2 + num3) / 3;
cout << "Answer is: " << avg << endl;
return 0;
}
The following might happen (user input is boldfaced).
Enter
first number
1 2 4
Enter
second number
Enter
third number
Answer
is: 2
The program will not pause for the user to enter a second or third number since these numbers are already in the buffer.
Of course you can input both a number and a char. Look at the following program:
#include <iostream>
using namespace std;
int main()
{
int grade;
char
letter;
cout << "Enter your test grade:\n";
cin >> grade;
cout << "Enter your letter grade:\n";
cin >> letter;
cout << "You got a " << grade
<< " and a " << letter << endl;
return 0;
}
Constants
If you have a number that is used throughout your program, it's a good idea to have that number assigned to a constant. Constants are defined with the keyword const. The constant declaration is usually placed before main and after the preprocessor commands.
#include
<iostream>
const
double PI = 3.1416;
using
namespace std;
int main()
{
int radii;
double perimeter, area;
cout <<
"Enter the radii of a circle:\n";
cin >> radii;
area = PI * radii * radii;
perimeter = 2 * radii * PI;
cout <<
"The area of the circle is: " << area << endl;
cout <<
"The perimeter of the circle is: " << perimeter << endl;
return 0;
}
To use mathematical functions, you must include the header file <cmath>. This file includes definitions for (among others) abs, fabs, pow, sin, cosin, tan, ceil, floor and sqrt. To use these functions, put #include <cmath> at top of file.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int i;
double s;
cout << "Enter a number: ";
cin >> i;
s = sqrt(i);
cout << "The square root of
" << i << " is "
<< s << endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int i;
double s,
c;
cout << "Enter a number: ";
cin >> i;
s = pow(i,2);
c = pow(i,3);
cout << "The square of "
<< i << " is " << s
<< endl;
cout << "The cube of "
<< i << " is " << c
<< endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double
side1, side2, hypotenuse;
cout << "Enter two sides of a right triangle: ";
cin >> side1 >> side2;
hypotenuse
= sqrt(pow(side1,2) + pow(side2,2));
cout << "Hypotenuse is: " <<
hypotenuse << endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a =
100.4, b = -20.3;
cout << abs(b) << endl;
cout << fabs(b) << endl;
cout << floor(a) << endl;
cout << ceil(a) << endl;
return 0;
}