Professional Documents
Culture Documents
Simple C++ Programs
Simple C++ Programs
2
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1(1), y1(5), x2(4), y2(7),
side1, side2, distance;
C++
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2);
// Print distance.
Program
Structure
cout << "The distance between the two points is "
<< distance << endl;
// Exit program.
return 0;
}
//--------------------------------------------------------
3
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1(1), y1(5), x2(4), y2(7),
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
Comments:
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2);
•document the
// Print distance. program’s purpose
cout << "The distance between the two points is " •Help the human
<< distance << endl; reader understand the
// Exit program.
program
return 0;
}
•Are ignored by the
//-------------------------------------------------------- compiler
•// comments to end-of
line
•/* starts a comment
block ending with */
4
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1(1), y1(5), x2(4), y2(7),
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1; Preprocessor
side2 = y2 - y1; Directives:
distance = sqrt(side1*side1 + side2*side2); •Give instructions to the
// Print distance.
cout << "The distance between the two points is "
preprocessor before
<< distance << endl; the program is
// Exit program. compiled.
return 0; •Begin with #
}
#include directives ‘add’
//--------------------------------------------------------
or ‘insert’ the named
files (and the
functionality defined in
the files)into the
program
5
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1(1), y1(5), x2(4), y2(7),
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2);
‘using’ Directives:
// Print distance.
cout << "The distance between the two points is "
•Tell the compiler to
<< distance << endl; use the library names
// Exit program. declared in the
return 0; namespace.
}
The ‘std’, or standard
//--------------------------------------------------------
namespace contains
C++ language-defined
components.
6
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1(1), y1(5), x2(4), y2(7),
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2); Main function header:
// Print distance. •Defines the starting
cout << "The distance between the two points is " point (i.e. entry point)
<< distance << endl;
for a C++ program
// Exit program.
return 0;
•The keyword ‘int’
} indicates that the
//-------------------------------------------------------- function will return an
integer value to the
system when the
function completes.
7
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1(1), y1(5), x2(4), y2(7),
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
Code blocks:
distance = sqrt(side1*side1 + side2*side2); •are zero or more C++
// Print distance. declarations or
cout << "The distance between the two points is " statements enclosed by
<< distance << endl;
curly brackets { }
// Exit program.
return 0;
The code that defines
} what a function does (in
//-------------------------------------------------------- this case, the main
function of the
program) is often
defined in a code block
following the header.
8
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1(1), y1(5), x2(4), y2(7),
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2); Declarations:
// Print distance. •Define identifiers (e.g.
cout << "The distance between the two points is " variables and objects)
<< distance << endl;
and allocate memory.
// Exit program.
return 0;
•May also provide initial
} values for variables.
//-------------------------------------------------------- •Must be made before
actions can be
performed on
variables / objects.
9
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1(1), y1(5), x2(4), y2(7),
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2);
// Print distance.
cout << "The distance between the two points is "
<< distance << endl;
// Exit program. Statements :
return 0; •specify the operations
}
to be performed.
//--------------------------------------------------------
10
General Form
11
Sample shortest code
12
Constants
and
Variables
13
Variables
• What is a variable in math?
f(x) = x2+x+4
• In C++,
– An identifier or variable name is used to
reference a memory location.
14
Constants and Variables
• Constants and variables represent memory locations
that we reference in our program solutions.
• Constants are objects that store specific data that can not
be modified.
– 10 is an integer constant
– 4.5 is a floating point constant
– "The distance between the two points is" is a string
constant
– 'a' is a character constant
• Variables are named memory locations that store values
that can be modified.
– double x1(1.0), x2(4.5), side1;
– side1 = x2 - x1;
– x1, x2 and side1 are examples of variables that can be modified.
15
Rules for selecting a valid identifier
(variable name)
1. Must begin with an alphabetic character or underscore
(e.g., abc, ABC, f3, _65gh, _Jn )
2. May contain only letters, digits and underscore (no
special characters ^%@)
3. C++ is CASE SENSITIVE, so ( ‘a’, ‘A’ are different) ,
etc…
4. Cannot use C keywords as identifiers (e.g., if, case,
while)
5. May be of any length, but the first 31 characters must
be unique.
16
C++ Keywords
17
Are the following valid identifiers?
1. distance
2. 1x
3. x_1
4. rate%
5. x_sum
6. Switch
7. initial_time
8. DisTaNce
9. X&Y
18
C++ Identifiers
• Should be carefully chosen to reflect
the contents of the object.
Variables name, file name, function name, etc. should be self
describing.
int myWeightInPounds; int timeoutInMsec;
19
Common C++ Data Types
• Keyword Example of a constant
– bool true
– char '5'
– int 25
– double 25.0
– string "hello"
//#include<string>
20
Symbolic Constants
• A symbolic constant is defined in a declaration
statement using the modifier const.
• A symbolic constant allocates memory for an
object that can not be modified during execution
of the program. Any attempt to modify a
constant will be flagged as a syntax error by
the compiler.
• A symbolic constant must be initialized in the
declaration statement.
21
• Better solution, define as a symbolic constant,
e.g.
…
area = PI * r * r;
circumference = 2 * PI * r;
22
Declarations
• A type declaration statement defines new identifiers
and allocates memory.
• An initial value may be assigned to a memory
location at the time an identifier is defined.
Syntax
[modifier] type specifier identifier [= initial value];
[modifier] type specifier identifier[(initial value)];
Examples
double x1, y1(0);
int counter=0;
const int MIN_SIZE=0;
bool error(false);
char comma(',');
23
Initial Values
• C++ does not provide initial values
for variables.
– Thus using the value of a variable before it is
initialized may result in ‘garbage’.
int x, y; //declaration
24
Memory Snapshots
• Memory ‘snapshots’ are diagrams that
show the types and contents of variables
at a particular point in time.
25
Example Data-Type Limits
27
Assignment Operator
• The assignment operator (=) is used
in C++ to assign a value to a memory
location.
• The assignment statement:
x1 = 1.0;
– assigns the value 1.0 to the variable x1.
– Thus, the value 1.0 is stored in the memory
location associated with the identifier x1.
(Note: x1 must have been previously declared.)
28
Assignment Statements
29
Assignment Statements
• Example 1
double sum = 0;
Memory snapshot:
• Example 2
int x; double sum 0
x=5; int x 5
• Example 3 char ch
char ch; ‘a’
ch = ‘a’;
• Example 4
int m , s;
m+1=s; (INVALID)
m+s=m/12; (INVALID)
30
Arithmetic Expressions
• Expressions appearing in assignment
statements for numeric variables may be:
– simple literals (e.g. x1 = 10.4;)
31
Order of Types
• Because different types are different
representations, frequently we need to
convert between types.
– Sometimes these conversions may loose
information.
– Conversion from lower types to higher
types results in no loss of information.
– Conversion from higher types to lower
types may loose information. High: long double
double
float
long integer
integer
Low: short integer
32
Assignment examples with different
types
int a, b(5); ? a
double c(2.3); 5 2 b
…
2.3 5.0 c
a=c; /* data loss */
c=b; /* no data loss */
(Long double, double, float, long integer, integer, short integer, char)
Data may be lost. Be careful!
No data loss 33
33
Arithmetic Operators
• Addition + sum = num1+num2;
• Subtraction - age = 2007-my_birth_year;
• Multiplication * area = side1*side2;
• Division / avg = total / number;
• Modulus % lastdigit = num % 10;
– Modulus returns remainder of division between two
integers
– Example
5%2 returns a value of 1
34
Operator Basics
• The five operators (* / % + -) are
binary operators - operators that require
two arguments (i.e. operands).
• C++ also include operators that require only a
single argument – unary operators.
– For example, a plus or a minus sign preceding an
expression can be unary operators: (e.g. -x2).
35
Arithmetic Operators (cont’d)
• Note that ‘id = exp‘ means assign the result of
exp to id, so
• X=X+1 means Memory snapshot:
36
Integer Division
• Division between two integers results in an integer.
• The result is truncated, not rounded
• Example 1:
int A= 5/3; A will have the value of 1
int B= 3/6; B will have the value of 0
37
Exercise
Declare a=2, b=5, c=7, d as int
Declare x=5.0, y=3.0, z=7.0, w as double
d = c%a d=?
d = c/a d=?
w = z/x w=?
d = z/x d=?
w = c/a w=?
a=a+1 a=?
… try other arithmetic operations too..
38
Mixed Operations
• Binary operations on two values of
same type yield a value of that type (e.g.
dividing two integers results in an integer).
• Binary operations between values of different
types is a mixed operation.
– Value of the lower type must be converted to the
higher type before performing operation.
– Result is of the higher type.
39
Casting
• The cast operator.
– The cast operator is a unary operator that requests that the
value of the operand be cast, or changed, to a new type for the
next computation. The type of the operand is not affected .
• Example:
int count(10), sum(55); Memory snapshot:
double average; int count 10
int sum 55
average = sum/count; (5.0)
double average 5.5
40
Mixed operations and Precedence of
Arithmetic Operators
41
Operator Precedence
Precedence Operator Associativity
1 Parenthesis: () Innermost First
2 Unary operators: Right to left
+ - ++ -- (type)
3 Binary operators: Left to right
* / %
4 Binary operators: Left to right
+ -
5 Assignment Operators Right to left
= += -= *= /= %=
42
Exercise: Arithmetic operations
int a = 6, b = -3, c = 2;
c= a - b * (a + c * 2) + a / 2 * b;
43
Step-by-step show how C++ will
perform the operations
c= a - b * (a + c * 2) + a / 2 * b;
c = 6 - -3 * (6 + 2 * 2) + 6 / 2 * -3;
c = 6 - -3 * (6 + 4) + 3 * -3
c = 6 - -3 *10 + -9
c = 6 - -30 + -9
c = 36 + -9
c = 27
• output:
Value of c = 27
44
Overflow and Underflow
• Overflow
– answer too large to store
Example: using 16 bits for short integers
result = 32000 +900;
• Exponent overflow
– answer’s exponent is too large
Example: using float, with exponent range –38 to 38
result = 3.25e28 * 1.0e15;
• Exponent underflow
– answer’s exponent too small
Example: using float, with exponent range –38 to 38
result = 3.25e-28 *1.0e-15;
45
Increment and Decrement Operators
• Increment Operator ++
• post increment x++;
• pre increment ++x;
• Decrement Operator - -
• post decrement x- -;
• pre decrement - -x;
• For examples assume k=5 prior to executing the
statement.
• m= ++k; // both m and k become 6
• n = k- -; // n becomes 5 and k becomes 4
46
Abbreviated Assignment
Operators
47
Coding Standards
Indentation
#include <iostream> // Required for cout, endl.
using namespace std;
int main() {
// Declare and initialize objects.
double x1(1), y1(5), x2(4), y2(7),
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2);
// Print distance.
cout << "The distance between the two points is "
<< distance << endl;
// Exit program.
return 0;
}
48
Standard Input / Output
49
Sample Output - cout
• cout is an ostream object, defined in the header
file iostream
• cout is defined to stream data to standard output
(the display)
• We use the output operator << with cout to
output the value of an expression.
General Form:
cout << expression << expression;
50
Simple Input - cin
• cin is an istream object defined
in the header file iostream
• cin is defined to stream data from standard input (the
keyboard)
• We use the input operator >> with cin to assign values to
variables
– General Form
cin >> identifier >> identifier;
• Note: Data entered from the keyboard must be compatible with the data type of the
variable.
51
Characters and Input
• The input operator >> skips all whitespace
characters.
• The get() method gets the next character.
• Example:
Input stream:
int x; 45 c
char ch; 39
b
cin >> x >> ch;
Memory Snapshot
cin >> x;
cin.get(ch); x 45 ch ‘c’
x 39 ch ‘\n ’
52
Manipulators and Methods
• endl – places a newline character in the output buffer
and flushes the buffer.
#include <iomanip>
Flag Meaning
showpoint display the decimal point
fixed fixed decimal notation
scientific scientific notation
setprecision(n) set the number of significant digits to be printed to
the integer value n
setw(n) set the minimum number of columns for printing the
next value to the integer value n
right right justification
left left justification
53
Good practice
54
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
const float tenth = 0.1; Example on using
const float one = 1.0;
const float big = 1234567890.0; manipulators
cout << "A. " << tenth << ", "
<< one << ", " << big << endl;
cout << "B. " << fixed << tenth << ", “
<< one << ", " << big << endl;
cout << "C. " << scientific << tenth
<< ", " << one << ", " << big << endl;
cout << "D. " << fixed << setprecision(3)
<< tenth << ", " << one << ", "
<< big << endl; output
cout << "E. " << setprecision(20)
<< tenth << endl;
cout << "F. " << setw(8)
<< 34 << 45 << endl;
cout << "G. " << setw(8) << 34
<< setw(8) << 45 << endl;
return 0;
}
55
Programming exercise
57
Basic C++ Math Functions
#include <cmath>
58
Logarithm of x
Logarithm of x to the base b can be computed using
the following relationship:
answer = log(fabs(x))/log(fabs(b));
59
Trigonometric Functions
#include <cmath>
sin(x) sine of x, where x is in radians
cos(x) cosine of x, where x is in radians
tan(x) tangent of x, where x is in radians
asin(x) This function computes the arcsine, or inverse sine, of x, where x
must be in the range [−1, 1].
The function returns an angle in radians in the range [−π/2, π/2].
acos(x) This function computes the arccosine, or inverse cosine, of x,
where x must be in the range [−1, 1].
The function returns an angle in radians in the range [0, π].
atan(x) This function computes the arctangent, or inverse tangent, of x.
The function returns an angle in radians in the range [−π/2, π/2].
atan2(y,x) This function computes the arctangent or inverse tangent of the
value y/x.
The function returns an angle in radians in the range [−π, π].
60
Parameters or Arguments of a function
• A function may contain no argument or contain one or more
arguments
• If more than one argument, list the arguments in the correct order
• Be careful about the meaning of an argument. For example, sin(x)
assumes that x is given in radians, so to compute the sin of 60
degree, you need to first conver 60 degree into radian then call
sin function:
const double PI=3.141593
theta = 60;
theta_rad = theata * PI / 180;
b = sin(theta_rad); /* is not the same as sin(theta); */
61
61
Common Functions
Defined in <cctype>
#include <cctype>
isalpha(ch) Returns true if ch is an upper or lower case letter.
isdigit(ch) Returns true if ch is a decimal digit
isspace(ch) Returns true if ch is a whitespace character.
islower(ch) Returns true if ch is an lower case letter.
isupper(ch) Returns true if ch is an upper case letter.
tolower(ch) Returns the lowercase version of ch if ch is an
uppercase character, returns ch otherwise.
toupper(ch) Returns the uppercase version of ch if ch is a
lowercase character, returns ch otherwise.
62
Exercise
What is the output of the following program
#include <iostream>
#include <cctype>
int main()
{
char ch1='a', ch2, ch3='X', ch4, ch5='8';
ch2 = toupper(ch1);
ch4 = tolower(ch3);
cout<<(isdigit(ch5));
cout<<(islower(ch1));
cout<<(isalpha(ch5));
return(0);
}
Output: 1 1 0
63
Exercise
• Write a C++ program to solve the quadratic
equation
a x2 + b x + c =0
b b 4ac
2
x
2a
64
Exercise
• Write an expression to compute velocity using the following
equation
• Assume that the variables are declared
velocity = sqrt(vo*vo+2*a*(x-xo));
velocity = sqrt(pow(vo,2)+2*a*(x-xo));
65
Exercise
• Write an expression to compute velocity using the following
equation
• Assume that the variables are declared
38.19(r s ) sin a
3 3
center
(r s )a
2 2
center = (38.19*(pow(r,3)-pow(s,3))*sin(a)) /
((pow(r,2)-pow(s,2))*a);
V r h 2
67
Solution: Compute Volume (cont’d)
• Problem Statement
– compute the volume of a cylinder of radius r and
height h
• Input Output Description
radius r
volume v
height h
68
Solution: Compute Volume (cont’d)
• Hand example
– r=2, h =3, v=3.14*2*2*3=37.68
• Algorithm Development
– Read radius
– Read height
– Compute Volume
– Print volume V r h 2
• Convert to a program ()
69