0% found this document useful (0 votes)
19 views32 pages

Chap2 Basic Elements

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)
19 views32 pages

Chap2 Basic Elements

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

Introduction to Computing 1

CHAPTER 2
BASIC ELEMENTS IN C++
Introduction to Computing 2

Outline
1. Program structures
2. Data types and operators
3. Variables and declaration statements
Introduction to Computing 3

Program structures
• A C++ program is a collection of functions.
• A function is a program segment that transforms the data
it receives into a finished result.

b result
axb

Fig 1. A multiplying function


Introduction to Computing 4

Program structures
• Module: a small segment which is designed to perform a
specific task
 Modules can be functions
• Modular program: a program consisting of interrelated
segments (modules) arranged in a logical and
understandable form
 Easy to develop, correct, and modify

Fig 2. A well-designed program is built using modules


Introduction to Computing 5
Introduction to Computing 6

Function
• Each function must have a name.
• Rules for names or identifiers in C++:
 First character must be an uppercase or lowercase ASCII letter or
an underscore (_).
 Only letters, digits, or underscores may follow the initial letter (no
blanks allowed)
 Special characters, such as $, &, * or %, are not allowed
 Reserved words – keywords cannot be used for variable names.
 C++ is a case-sensitive language.
Introduction to Computing 7

Keyword

All keywords must be in lowercase


Introduction to Computing 8

Example of identifiers
• Find invalid identifiers

DegToRad E#6 FindMax1

Addnums addNums addnums

if YouAreBeautiful while

_density slope 1AB3

_ intersect hello

string-to-date dog friend

[email protected]
Introduction to Computing 9

Example of identifiers
• Find invalid identifiers

DegToRad E#6 FindMax1

Addnums addNums addnums

if YouAreBeautiful while

_density slope 1AB3

_ intersect hello

string-to-date dog friend

[email protected]
Introduction to Computing 10

The main() function


• The main() function is a
special function that runs
automatically when a
program first executes.
• All C++ programs must
include one main()
function. All other
functions in a C++
program are executed
from the main().

Fig 3. The main() function directs all other functions


Introduction to Computing 11

The main() function


• Function header line: the first line of a function, which
contains
• The type of data returned by the function (if any)
• The name of the function
• The type of data that must be passed into the function (if any)
• Arguments: the data passed into a function
• Function body: the statements inside a function (enclosed
in braces)
• Each statement inside the function must be terminated
with a semicolon “;”
• return: a keyword causing the appropriate value to be
returned from the function. It’s used to exit a function.
Introduction to Computing 12

The main() function

The line return 0; is included at the end of every main() function.


When the return statement is used at the end of main(), the value 0
indicates that the program has terminates successfully.
Introduction to Computing 13

The cout Object


• The cout object is an output object that sends data given
to it to the standard output display device.
• To send a message to the cout object, you use the
following pattern:
cout << “text”;
• The insertion operator, <<, is used for sending text to an
output device.
• The text portion of cout statement is called a text string.
Introduction to Computing 14

A simple program
#include <iostream> Header file
using namespace std; (Preprocessor directives)
int main()
{
cout << "Hello world!";
return 0;
}
• A header file is a file with an extension of .h that is
included as part of a program. It notifies the compiler that
a program uses run-time libraries.
• The iostream classes are used for giving C++ programs
input and output capabilities.
• The header file for the iostream class is iostream.h.
Introduction to Computing 15

Preprocessor directives
• Preprocessor directives: starts with a #. The preprocessor
is a program that runs before the compiler.
• #include <file name> : causes the named file to be
inserted into the source code
• C++ provides a standard library with many pre-written
classes that can be included
• Header files: files included at the head (top) of a C++
program
• Preprocessor directives and include statements allow the
current file to use any of the classes, functions, variables,
and other code contained within the included file.
Introduction to Computing 16

Preprocessor directives (cont.)


• using namespace <namespace name> : indicates
where header file is located
• A namespace is a specific named section of code within a
folder that is accessed by the compiler when it is looking
for prewritten classes or function.
• String: any combination of letters, numbers, and special
characters enclosed in double quotes (a delimiter)
• Delimiter: a symbol that marks the beginning and ending
of a string; not part of the string
Introduction to Computing 17

i/o manipulator
• An i/o manipulator is a special function that can be used
with an i/o statement.
• The endl i/o manipulator is part of iostream classes and
represents a new line character.

• Example:
cout << “Program type: console application” << endl;
cout << “Create with: Visual C++“ << endl;
cout << “Programmer: Don Gesselin” << endl;
Introduction to Computing 18

Comments
• Comments: explanatory remarks in the source code added
by the programmer
• Line comments: begin with two slashes (//) before the
comment text
 Line comment can be on a line by itself, or at the end of a line of code
 Line comment cannot be longer than one line
Introduction to Computing 19

Comments
• Block comments span multiple lines.
• Block comments begin with /* and end with */.
Ex:

/* This program solves a quadratic equation:


ax2 + bx +c = 0
This comment spans across 3 lines. */
Introduction to Computing 20

Data Types
• A data type is the specific category of information that a
variable contains.
• There are three basic data types used in C++: integers,
floating point numbers and characters.
Introduction to Computing 21

Integer Data Type


• An integer is a positive or negative number with no
decimal places.
• Examples:
- 259 -13 0 200
Introduction to Computing 22

Floating point number


• A floating point number contains decimal places or is
written using exponential notations.
• Examples
-6.16 -4.4 2.7541 10.5
90.1e3 0.89E8 -1.01e-1

• Note: 90.1e3 means 90.1×103
Introduction to Computing 23

Character data type


• Character data type store text.
• To store one character in a variable, you use the char
keyword and place the character in single quotation
marks.
• Example:
char cLetter = ‘A’;

• Escape sequence: the combination of a backlash (\) and a


special character
• Example:
\n move to the next line
\t move to the next tab
Introduction to Computing 24

Arithmetic Operators
• Arithmetic operators: perform mathematical calculations, such
as addition, subtraction, multiplication, and division.

Operator Description
+ Add two operands
- Subtracts one operand from another operand
* Multiplies one operand by another operand
/ Divides one operand by another operand
% Divides two operands and returns the remainder

• A simple arithmetic expression consists of an arithmetic


operator connecting two operands in the form:
operand1 operator operand2
Introduction to Computing 25

Example The output of the program:


• Examples: 3+7 15.0 plus 2.0 equals 17
18 – 3 15.0 minus 2.0 equals 13
12.62 + 9.8 15.0 times 2.0 equals 30
12.6/2.0 15.0 divided by 2.0 equals 7.5

#include <iostream>
using namespace std;
int main()
{
cout << "15.0 plus 2.0 equals" << (15.0 + 2.0) << '\n'
<< "15.0 minus 2.0 equals" << (15.0 - 2.0) << '\n'
<< "15.0 times 2.0 equals" << (15.0 * 2.0) << '\n'
<< "15.0 divided by 2.0 equals" << (15.0 / 2.0) << '\n';
return 0;
}
Introduction to Computing 26

Integer Division and % operator


• The division of two integers yields integer result.
• Example:
20/3 is 6
15/2 is 7
• Modulus % operator produces the remainder of an integer
division.
• Example:
9%4 is 1
17%3 is 2
14%2 is 0
Introduction to Computing 27

Operator Precedence and Associativity


• Expressions containing multiple operators are evaluated by the
priority, or precedence, of the operators.

Operator Associativity
unary - Right to left precedence
*/% Left to right
+- Left to right
• Example:
8+5*7%2*4
↓ ↓ ↓ ↓
4 1 2 3
Introduction to Computing 28

Variables
• One of the most important aspects of programming is storing
and manipulating the values stored in variables.
• Variable names are also selected according to the rules of
identifiers
• Example: Some valid identifiers
my_variable (python style)
MyVariable (pascal style)
myVariable (camel style , suggested style for C++)
Temperature
x1 x2
_my_variable
• Some invalid identifiers are as follows:
%x1 %my_var @x2
Introduction to Computing 29

Declaration Statements
• Declaration statement: specifies the data type and
identifier of a variable; sets up the memory location
• Syntax: <dataType> <variableName>;
• Data type is any valid C++ data type
• Example:
int count;
float sum;
• Declarations may be used anywhere in a function; usually
grouped at the opening brace
Introduction to Computing 30

Rules of variable declaration


• A variable must be declared before it can be used.
• Declaration statements can also be used to store an initial
value into declared variables.
• Multiple variables of the same data type can be declared
in a single declaration statement
• Example:
int num = 15;
float grade1 = 87.0;
double grade1, grade2, total, average;
• Note: Declaration statement gives information to the
compiler
• rather than a step in the algorithm.
Introduction to Computing 31

Assignment statements
• Assignment statement: used to store a value into a
variable
• Value of the expression on the right side of the = is
assigned to the memory location of the variable on the left
side of the =
• Examples:
num1 = 45;
num2 = 12;
total = num1 + num2;
Introduction to Computing 32

Example
#include <iostream> The output of the program:
The average grade is 91.25
using namespace std;
int main()
{
float grade1 = 85.5;
float grade2 = 97.0;
float total, average;
total = grade1 + grade2;
average = total/2.0; // divide the total by 2.0
cout << "The average grade is " << average << endl;
return 0;
}

You might also like