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

Lecture Chapter 2 IT Programming Structure Variables

This document provides an introduction to C++ programming, covering key concepts such as identifiers, variables, data types, and basic programming structure. It discusses the role of computers in information technology, the importance of programming style, and various data types including integers, floating-point numbers, and strings. Additionally, it explains the use of comments, arithmetic operators, and named constants in C++.

Uploaded by

maxmilioner8
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)
4 views56 pages

Lecture Chapter 2 IT Programming Structure Variables

This document provides an introduction to C++ programming, covering key concepts such as identifiers, variables, data types, and basic programming structure. It discusses the role of computers in information technology, the importance of programming style, and various data types including integers, floating-point numbers, and strings. Additionally, it explains the use of comments, arithmetic operators, and named constants in C++.

Uploaded by

maxmilioner8
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

Computer Programming – C++

Chapter 2
Introduction to C++

Lecturer
Dr. Majdi Owda
Outline
Parts of a C++ Program
- Identifiers
- Variables and Literals
❑ Variables
▪ Variable Name
▪ Defining a Variable
▪ Variable Assignments and Initialization
▪ Scope of a Variable
❑ Literals
- Data Types
o Integer Data Types
o Floating-Point Data Types
o The char Data Type
o The C++ string Class
o The bool Data Type
2
Outline … (cont)
- Arithmetic Operators
- Determining the Size of a Data
- Type
- Named Constants
- Comments
- The cout Object
- The endl Manipulator
- The \n Escape Sequence
- The #include Directive
- Programming Style
- Standard and Prestandard C++
- References
3
Introduction to Computers and C++

Information Technology (IT) refers to the integration between computer Technology and
Information processing.

Data: raw facts.

Information: data that have been collected and processed into a meaning form.

Computer: Is an electronic machine that can process data according to a set of


instructions.

Computer System: Is the integration of physical components called Hardware and none
physical components called Software
Introduction to Computers and C++

Hardware and Software:

A computer consists of various devices referred to as hardware


(e.g., the keyboard, screen, mouse, hard disks, memory, DVD
drives and processing units). Computing costs are dropping
dramatically, owing to rapid developments in hardware and
software technologies.

Computers process data under the control of sequences of


instructions called computer programs. These programs guide the
computer through ordered actions specified by people called
computer programmers. The programs that run on a computer are
referred
to as software.
Introduction to Computers and C++
Computing in Industry and Research:
Computers are used extensively in academic and industrial research.
Examples:

Area Description
The Internet today is accessible by billions of computers and
Internet computer-controlled devices worldwide. A lot of Academic and
Industrial research projects.
The Human Genome Project was founded to identify and analyze
the 20,000+ genes in human DNA . The project used computer
programs to analyze complex genetic data, determine the
Human
sequences of the billions of chemical base pairs that make up
Genome
human DNA and store the information in databases which have
Project
been made available to researchers in many fields. This
research has led to tremendous innovation and growth in the
biotechnology industry.
Introduction to Computers and C++
Area Description
X-ray computed tomography (CT) scans, also called CAT (computerized
axial tomography) scans, take X-rays of the body from hundreds of different
Medical
angles. Computers are used to adjust the intensity of the X-ray, optimizing
imaging
the scan for each type of tissue, then to combine all of the information to create a
3D image.
Game Kinect games include dancing, exercising, playing sports, training virtual animals and
programming more.
These might include a patient's medical history, prescriptions, immunizations, lab
Electronic health results, allergies, insurance information and more. Making this information available
records to health care providers across a secure network improves patient care, reduces the
probability of error and increases overall efficiency of the health care system.
allows you to use software, hardware and information stored in the “cloud”— i.e.,
accessed on remote computers via the Internet and available on demand—rather
than having it stored on your personal computer. These services allow you to
Cloud increase or decrease resources to meet your needs at any given time, so they can
computing be more cost effective than purchasing expensive hardware to ensure that you have
enough storage and processing power to meet your needs at their peak levels.
Using cloud computing services shifts the burden of managing these applications
from the business to the service provider, saving businesses money.
Identifiers

• An identifier is: “a programmer-defined name for some part of a program”.


❖ Examples: names of variables, functions, etc.

Note. You cannot use any of the C++ key words as an identifier. These words have
reserved meaning.

8
Identifiers …
Identifiers … (cont)

Identifier Naming Rules:


▪ The first character of an identifier must be an alphabetic character or and underscore: ( _ ), Pay,
_1pay, rate, _gross_pay, _Gross_pay, etc.

▪ After the first character you may use alphabetic characters, numbers, or underscore characters.

▪ Upper - and lowercase characters are distinct.

10
Identifiers … (cont)

Table2. Valid and Invalid Identifiers

11
Comments
- Used to document parts of the program.
- Intended for persons reading the source code of the program.
- Indicate the purpose of the program
- Describe the use of variables
- Explain complex sections of code
- Are ignored by the compiler
- Begin with // through to the end of line:
int length = 12; // length in inches
int width = 15; // width in inches
int area; // calculated area

12
Comments … (cont)

Single-Line / Multi-line Comments


- // calculate rectangle area
area = length * width;

- Multi-line Comments:
▪ Begin with /*, end with */
▪ Can span multiple lines:
/* this is a multi-line
comment

*/
▪ Can begin and end on the same line: int area; /* calculated area */

13
Single Line Comments
Multi-Line Comments
The \n Escape Sequence

- You can use the endl manipulator to start a new line of output. This will produce two lines of output:
- You can also use the \n escape sequence to start a new line of output. This will produce two lines of output:
cout << "Programming is\n";

cout << "fun!";

- cout << "Programming is\n";


cout << "fun!";

16
Programming Style

- The visual organization of the source code.


- Includes the use of spaces, tabs, & blank lines.
- Does not affect the syntax of the program.
- Affects the readability of the source code.
- Common elements to improve readability:
▪ Braces { } aligned vertically.
▪ Indentation of statements within a set of braces.
▪ Blank lines between declaration and other statements.
▪ Long statements wrapped over multiple lines with aligned operators.

17
Programming Style
// sample C++ program comment
#include <iostream> preprocessor directive
using namespace std; which namespace to use:
The std. library
int main() beginning of function named main
{ beginning of block for main
cout << "Hello, there!"; output statement
return 0; send 0 to operating system
} end of block for main

18
The #include Directive

- Older-style C++ programs:


❑ Uses .h at end of header files: #include <iostream.h>
❑ Uses #define preprocessor directive instead of const definitions.
❑ Do not use using namespace convention.
❑ May not compile with a standard C++ compiler.

19
The cout Object

- Displays output on the computer screen.


- You use the stream insertion operator << to send output to cout: cout << "Programming is fun!";
- Can be used to send more than one item to cout: cout << "Hello " << "there!";

Or: cout << "Hello ";

cout << "there!";

- This produces one line of output:


cout << "Programming is ";

cout << "fun!";

20
The endl Manipulator

- You can use the endl manipulator to start a new line of output. This will produce two lines of output:
cout << "Programming is" << endl;

cout << "fun!";


- cout << "Programming is" << endl;
cout << "fun!";
- You do NOT put quotation marks around endl
- The last character in endl is a lowercase L, not the number 1.

21
Simple Program .. Programming is great fun!
Special Characters
Simple Program .. Programming is great fun!
Simple Program .. Programming is great fun!
Simple Program .. Programming is great fun!
Simple Program .. Programming is great fun!
Common Escape Sequences
Variables and Literals
Variables
- Variable: a storage location in memory.
- Has a name and a type of data it can hold.
- Must be defined before it can be used, example: int item;

29
Variables and Literals
Variable Name
-A variable name should represent the purpose of the variable. For
example: itemsOrdered

- The purpose of this variable is to hold the number of items ordered.

30
Variables and Literals … (cont)

Defining Variables - On the same line, example:


int length, width;
Variables of the same type can be
unsigned int area;
defined
Note. Variables of different types must be in
- On separate lines, example:
different definitions.
int length;

int width;

unsigned int area;

31
Variables and Literals … (cont)

Variable Assignments and Initialization Variable Initialization


- An assignment statement uses the = operator to - Initializing a variable: Assigning it a value when
store a value in a variable: item = 12; defined: int length = 12;

- This statement assigns the value 12 to the item - Can initialize some or all variables: int length = 12,
variable. width = 5, area;

- The variable receiving the value must appear on the - Comments on the following initialization: int

left side of the = operator. This will NOT work: flightNum = 89, travelTime, departure = 10, distance;

// ERROR!
12 = item;

32
Variables and Literals … (cont)

Variable Initialization … (cont)

- Declaring Variables with the auto Key Word: Using auto instead of the data types!

auto amount = 100; // int

auto interestRate = 12.0; // a double

auto stockCode = ‘D’; // a character

auto customerNum = 459L; // a long int

33
Variables and Literals … (cont)

Scope of a Variable

- The scope of a variable: the part of the program in which the variable can be accessed.

- A variable cannot be used before it is defined.

34
Variables and Literals … (cont)

Literals

- Literal: a value that is written into a program’s code.

- Examples: "hello, there" (string literal)

12 (integer literal)

Note. More on Literals later in this chapter.

35
Data Types

Integral Data Types

- Integer variables can hold whole numbers such as 12, 7, and -99.

Table 3. Integral Data Types, Sizes and Ranges

36
Data Types
Data Types … (cont)

38
Data Types … (cont)

Character Strings

- A series of characters in consecutive memory locations: "Hello"

- Stored with the null terminator, \0, at the end:

- Comprised of the characters between the " ".

39
Data Types … (cont)

Character Strings

40
Data Types … (cont)

The C++ string Class

- Special data type supports working with strings: #include <string>

- Can define string variables in programs: string firstName, lastName;

- Can receive values with assignment operator:


firstName = "George";

lastName = "Washington";

- Can be displayed via cout: cout << firstName << " " << lastName;

41
Data Types … (cont)

The C++ string Class … (cont)

42
Data Types … (cont)

Floating-Point Data Types

- The floating-point data types are: float, double, long double

- They can hold real numbers such as: 12.45, -3.8

- Stored in a form similar to scientific notation

- All floating-point numbers are signed

Table 4. Floating-Point Data

43
Data Types … (cont)

Floating-Point Data Types … (cont)

- Can be represented in Fixed point (decimal) notation: 31.4159, 0.0000625

- E notation: 3.14159E1, 6.25e-5

- Are double by default.

- Can be forced to be float (3.14159f) or long double (0.0000625L).

- All the following floating-point literals are equivalent:

1 . 4959E11 1 .4959e11

1. 4959E+11 1 .4959e+11

149590000000.00

44
Data Types … (cont)

Assigning Floating-Point Values to Integer - Assigning a floating-point variable to an integer


Variables variable has the same effect. For example, look at the
- When a floating-point value is assigned to an integer following code:
variable, the fractional part of the value is discarded.
int i ;
For example, look at:
float f;
int number;
f = 7. 5;
number = 7.5 ; // Assigns 7 to number
i = f ; // Assigns 7 to i.
- This code attempts to assign the floating-point value
- When the float variable f is assigned to the int variable
7.5 to the integer variable number. As a result, the
i , the value being assigned (7.5) is truncated. After
value 7 will be assigned to number, with the fractional
part discarded (truncated). this code executes, i will hold the value 7 and f will
hold the value 7.5.

45
Data Types … (cont)

The bool Data Type


- Represents values that are true or false
- bool variables are stored as small integers
- false is represented by 0, true by 1:
bool allDone = true;
bool finished = false;

1 0

46
Determining the Size of a Data Type

- The sizeof operator gives the size of any data type or variable:

47
Ways of Declaring A Variable
Arithmetic Operators

- Used for performing numeric calculations.


- C++ has unary, binary, and ternary operators:
➢ unary (1 operand): -5
➢ binary (2 operands): 13 - 7
➢ ternary (3 operands) exp1 ? exp2 : exp3

Table 5. Mathematical Operators


49
Arithmetic Operators … (cont)

50
Arithmetic Operators … (cont)

A Closer Look at the / Operator


➢ / (division) operator: performs integer division if both operands are integers
cout << 13 / 5; // displays 2
cout << 91 / 7; // displays 13
➢ If either operand is floating point, the result is floating point
cout << 13 / 5.0; // displays 2.6
cout << 91.0 / 7; // displays 13.0
➢ % (modulus): operator computes the remainder resulting from integer division
cout << 13 % 5; // displays 3
➢ % requires integers for both operands
cout << 13 % 5.0; // error

51
Arithmetic Operators … (cont)

A Closer Look at the / Operators … (cont)

52
Named Constants

- Named constant (constant variable): A variable whose content cannot be changed during the program
execution.

- Used for representing constant values with descriptive names:


const double TAX_RATE = 0.0675;
const int NUM_STATES = 50;
- Often (style) named in uppercase letters.

53
Using the Modulus
Using the Modulus
References

Gaddis, T. (2018). Starting Out with C++ from Control Structures to Objects-Pearson. London: Pearson.

56

You might also like