[go: up one dir, main page]

0% found this document useful (0 votes)
39 views56 pages

Chapter 2v2

Uploaded by

mtsm.alsmadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views56 pages

Chapter 2v2

Uploaded by

mtsm.alsmadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

The Basics of a C++ Program

• Programming language: a set of syntax rules,


semantic rules, special symbols, and reserved
words.
– Syntax rules: rules that specify which statements
(instructions) are legal or valid.
– Semantic rules: determine the meaning of the
instructions.

2
A C++ program
• A C++ program: is a collection of functions, one
of which is the function main. This is where
execution begins when you run the program.
• C++ program has two parts:
1. Preprocessor directives
2. The program
The structure of a simple C++ program
So the student should know the structure of a simple c++
program, in that, any program may be written according to
the following format
#include<iostream>
using namespace std;
int main()
{
//Program body
return 0;
}
The main Function
• A function is a named block of code that performs
some well-defined set of operations.
• Every C++ program must contain a function named
main. This is where execution begins when you run
the program.
• Complex programs contain many functions, but for
now most of your programs will only contain the
main function.
The main Function (cont’d.)
• The body of the function main has the following
form:
int main ()
{
Declare variables(Declaration statements);
Executable statements;
return 0;
}
The main Function (cont’d.)
• The first line of a
function is called
the function’s
heading:
int main()
• The statements
enclosed between
the curly braces
{ and } form the
function’s body.
Preprocessor Directives
• Your programs will often
contain preprocessor
directives. These are
commands that the
preprocessor program
executes before your
program is compiled.
• All preprocessor
directives begin with #.
• No semicolon at the end of these directives.
The #include Directive
• The most common preprocessor directive is #include,
which is how you tell the compiler that you want to use a
Standard Library file.
• Syntax to include a header file:

• For example:
#include <iostream>
– Causes the preprocessor to include the header file iostream
in the program. Without this, you could not use cout or cin
in your program.
namespace and Using cin and cout
in a Program
• cin and cout are declared in the header file
iostream, but within the std namespace.
• To use cin or cout in a program, use the following two
statements:
#include <iostream>
using namespace std;
• Without that using statement, you would need to type
std::cin instead of cin throughout your program.
The Standard Library
• The core C++ language has a relatively small number
of built-in operations.
• Many other useful operations are provided as a
collection of files called the C++ Standard Library.
• These library files make your job easier, because
they save you from having to re-invent the wheel
when you want to perform common tasks.
• A big part of becoming a C++ programmer is learning
about the many library files in the Standard Library.
The Standard Library (cont’d.)
• Each library file (or “header file”) has a name,
which is typically written inside angle brackets.
– Examples:
• <iostream>
• <string>
• <cmath>
Comments
• Comments are for the reader, not the compiler.
• Two types:
– Single line: begin with //
// This is a C++ program.
// Welcome to C++ Programming.
– Multiple line: enclosed between /* and */
/*
You can include comments that can
occupy several lines.
*/
Special Symbols
• List of special symbols in C++ :
Reserved Words (Keywords)
• Reserved words (or keywords):
– You cannot redefine these words.
– You cannot use them for anything other than their
intended use.
Examples:
– int
– using
– return
– See Appendix A (next slide) in textbook for complete list.
Tokens
• Tokens: the smallest meaningful units of a
program.
• C++ tokens include: special symbols, reserved
words, and identifiers.
Reserved words Identifier Special symbol
Identifiers
• An identifier is the name of something in a
program.
– Identifiers can contain letters, digits, and the
underscore character (_), but no other characters or
symbols.
– Identifiers must begin with a letter or underscore
(not a digit).
• C++ is case sensitive.
– For example, number, Number, and NUMBER are
three different identifiers.
Identifiers (cont’d.)
• Examples of legal identifiers in C++:
• first
• payRate2
• Employee_Salary
Data Types
• Data type: set of values together with a
set of allowed operations on those values.
• C++ data types fall into three categories:
– Simple data types
– Structured data types
– Pointers
• For the next few weeks we’ll mostly use
simple data types.
Partial Hierarchy of Data Types

Data Types

Simple Data Structured Data


Pointers
Types Types

Integral Floating-Point
(int, bool, (float, Enumeration
char, …) double, …)
Simple Data Types
• Three categories of simple data:
– Integral: integers (numbers without a decimal).
• Can be further categorized:
– char, short, int, long, long long, bool,
unsigned char, unsigned short, unsigned
int, unsigned long
– Floating-point: decimal numbers.
• Can be further categorized:
– float, double, long double
– Enumeration type: user-defined data type.
Simple Data Types (cont’d.)

• The ranges shown above are typical. Different compilers


may allow different ranges of values.
int Data Type
• Examples of int data:
-6728
0
78
+763
• Do not use commas within numbers. Typing 1,430
instead of 1430 will usually cause an error.
bool Data Type
• The bool type has only two possible values: true
and false.
– It’s useful for keeping track of true/false (Boolean)
information, such as whether a person’s age is
greater than 21.
• This is considered an integral data type because
it’s actually implemented as a 0 for false and a
1 for true.
char Data Type
• Used for single characters: letters, digits, and
symbols.
• Each character is enclosed in single quotes:
– 'A', 'a', '0', '*', '+', '$', '&'
• A blank space is a character.
– Written ' ', with a space left between the single
quotes.
char Data Type (cont’d.)
• Different character sets exist, but we’ll use ASCII.
• ASCII: American Standard Code for Information
Interchange
– Each of 128 integer values (from 0 to 127) represents a
different character; see Appendix C in textbook (next
slide).
– Collating sequence: Characters have a predefined
ordering based on the ASCII numeric value.
For example, the ASCII code for 'A' is 65 and the ASCII
code for ‘D' is 68, so we can say that 'A' < ‘D'.
Floating-Point Data Types
• Non-integer numbers can be entered or
displayed using decimal notation or using a
modified scientific notation.
Floating-Point Data Types (cont’d.)
• float
– Typical Range: -3.4E+38 to 3.4E+38 (four bytes)
• double
– Typical Range: -1.7E+308 to 1.7E+308 (eight bytes)
• Ranges of data types are system-dependent.
• We’ll generally use double when we want a
floating-point number.
string Type
• A string is a sequence of zero or more characters enclosed
in double quotation marks.
– Contrast with char data type, which is a single character
inside single quotation marks.
• Unlike the simple data types discussed earlier, the
string data type is not built into the core C++ language.
It’s a programmer-defined type supplied in the C++
Standard Library. So a program that uses strings must have
the following line:
#include <string>
Variables
• The expressions we’ve looked at above used
constant numeric values.
– Example: 2 * 3.5
• In most programs you’ll also use variables, which
are named memory locations whose values can
change as the program runs.
– Example: 2 * payRate
• When naming your variables, be sure to follow the
rules listed earlier for identifiers.
Declaring Variables
• In C++ you must declare each variable’s data type
before you can use the variable.
• Syntax to declare one or more variables:
Putting Data into Variables
• A variable is said to be initialized the first time you place a
value into it.
• A variable that has not been initialized will hold an
unpredictable “garbage” value. Visual Studio gives an
error message if you use an uninitialized variable in an
expression.
• Ways to place data into a variable:
1. Use an assignment statement.
2. Use input (read) statements to let the user enter values
from the keyboard.
Assignment Statement
• The assignment statement takes the form:

• The expression on the right side is evaluated and its


value is assigned to the variable on the left side.
• Examples:
dailyRate = 0.0002;
annualRate = 365 * dailyRate;
• In C++, = is called the assignment operator.
Assignment Statement (cont’d.)
Declaring & Initializing Variables
• You can use the assignment operator to initialize
a variable in the same statement that declares it.
• Examples:
int first = 13, second = 10;
char ch = ' ';
double x = 12.6;
Input (Read) Statement
• cin is used with >> to let the user enter a value.

• This is called an input statement (or read statement).


• The operator >> is the stream extraction operator.
• For example, if miles is a double variable, the following statement
causes computer to get a value of type double from the keyboard and
place it in the variable miles:
cin >> miles;
Input (Read) Statement (cont’d.)
• A single input statement can assign values to
more than one variable.
• Example: if feet and inches are variables
of type int, the following statement reads
two integers from the keyboard and places
these integer values in feet and inches
respectively. :
cin >> feet >> inches;
Output Statement
• cout is used with << to display values on the
screen:

• This is called an output statement.


• The operator << is the stream insertion operator.
• The expression is evaluated and its value is printed
at the current cursor position on the screen.
Manipulators in Output Statements
• You can use manipulators to format the output.
– Example: the manipulator endl causes the cursor to
move to beginning of the next line.
Escape Sequences in Output Statements
• Escape sequences are another way to
format output. Example: The new line
character is '\n'
cout << "Hello there.";
cout << "My name is James.";
Output:
Hello there.My name is James.
cout << "Hello there.\n";
cout << "My name is James.";
Output :
Hello there.
My name is James.
Escape Sequences in Output Statements
(cont’d.)
Arithmetic Operators
• Some C++ arithmetic operators:
• + addition
• - subtraction
• * multiplication
• / division
• % modulus (or remainder)
• You can use +, -, *, and / with integral and floating-
point data types.
• You can use % only with integral data types.
Arithmetic Expressions
• Arithmetic expressions combine values (operands) and
arithmetic operators to yield a result.
• Example: 12.8 * 17.5 - 34.50

• Arithmetic expressions can be:


– Integral expressions: all operands are integers. 2 + 3 * 5
– Floating-point expressions: all operands are floating-point.
12.8/17.5 - 34.50
– Mixed expressions: some operands are integer, some are
floating-point. 6 / 4 + 3.9
Type Conversion and Casting
• Implicit type conversion (also called coercion)
occurs when C++ automatically changes a value
of one type to another type. We’ve seen an
example of this with mixed expressions.
• C++ also lets you perform explicit type
conversion using the cast operator:
static_cast<dataTypeName>(expression)
Type Conversion (Casting) (cont’d.)
Increment and Decrement Operators
• The increment operator ++ increases a variable by 1.
– Example: The statement
++x;
does the same thing as the statement
x = x + 1;
• Similarly, the decrement operator -- decreases a
variable’s value by 1.
– Example: The statement
--x;
does the same thing as the statement
x = x - 1;
Pre- and Post-Increment/Decrement
Operator Sample Expression Explanation
increment ++A (Pre-increment) Increment A by 1 then use new
operator++ value of A in the expression in
which A resides.
A++ ( Post-increment) Use the current value of A in the
expression in which A resides then
increment A by 1.
decrement --A (pre-decrement) Decrement A by 1 then use new
operator-- value of A in the expression in
which A resides.
A-- ( post-decrement) Use the current value of A in the
expression in which A resides then
decrement A by 1.
Named Constants
• Named constant: memory location whose
content cannot change during execution.
• Syntax to declare a named constant:

• By convention, constant identifiers are all


upper-case.
Preprocessor definitions (#define)
Another mechanism to name constant values is the use of preprocessor definitions.
They have the following form:
#define identifier replacement
1. #include <iostream>
2. using namespace std;
3. #define PI 3.14159
4. #define NEWLINE '\n'
5. void main ()
6. {
31.4159
7. double r=5.0; // radius
8. double circle;
9. circle = 2 * PI * r;
10. cout << circle;
11. cout << NEWLINE;
12. }
Cont.’
After this directive, any occurrence of identifier in the code is interpreted
as replacement , where replacement is any sequence of characters (until the
end of the line).
This replacement is performed by the preprocessor, and happens before
the program is compiled, thus causing a sort of blind replacement: the
validity of the types or syntax involved is not checked in any way.
Note that the #define lines are preprocessor directives, and as such are
single-line instructions that -unlike C++ statements- do not require
semicolons (;) at the end; the directive extends automatically until the end
of the line. If a semicolon is included in the line, it is part of the
replacement sequence and is also included in all replaced occurrences.
Compound Assignment Statements
• In addition to the simple assignment operator =, C++
provides several compound assignment operators,
including:
+= -= *= /= %=
• Simple assignment statement:
x = x * y;
• Equivalent compound assignment statement:
x *= y;
• Their sole purpose is to provide more concise notation. But you
don’t need to use them.
Cont.’
Compound assignment operators modify the current value of a variable by performing
an operation on it.
They are equivalent to assigning the result of an operation to the first operand:

Compound Sample Explanation


Assignment operator Expression

+= c+=y c=c+y
-= c-=3 c=c-3
*= c*=y+2 c=c*(y+2)
/= c/=4 c=c/4
%= c%=4 c=c%4
Prompt Lines
• Prompt lines are statements that tell the user what
to do.
cout << "Please enter a number between 1 and 10 and "
<< "press the return key." << endl;
cin >> num;

• Always include a correctly spelled, properly


punctuated prompt line when you want the user to
enter some input.

You might also like