You are on page 1of 51

Chapter 2

Introduction to C++

Namiq Sultan
University of Duhok
Department of Electrical and Computer Engineerin

Reference: Starting Out with C++, Tony Gaddis, 2nd Ed.

C++ Programming, Namiq Sultan 1


C++ Compiler Operation
Source Code

Preprocessor Compiler Linker

Compiler Executable
Machine Code

C++ Programming, Namiq Sultan 2


Program 2-1

//A simple C++ program


#include <iostream>
using namespace std;
int main ()
{
cout<< "Programming is great fun!";
return 0;
}

Program Output:
Programming is great fun!
C++ Programming, Namiq Sultan 3
2.1 Parts of a C++ Program
// sample C++ program comment
#include <iostream> Preprocessor directive
using namespace std; which namespace to use
int main() beginning of function named main
{ beginning of block for main
cout << "Hello, there!"; Output statement

return 0;
String constant
}
send 0 to operating system
end of block for main

Chapter 2 slide 4
Table 2-1 Special Characters
Char Name Description
// double slash Marks the beginning of a comment.
# Pound sign Marks the beginning of a preprocessor
directive
<> Opening and Encloses a filename when used with the
closing brackets #include directive
() Opening and Used in naming a function, as in
closing int main ()
parenthesis
{} Opening and Encloses a group of statements, such as
closing braces the contents of a function.
"" Opening and Encloses a string of characters, such as a
closing message that is to be printed on the
quotation marks screen
; Semicolon Marks the end of a complete
programming statement

C++ Programming, Namiq Sultan 5


2.2 The cout Object
• Use the cout object to display information on the
computer’s screen.

The cout object is referred to as the standard output
object.

Its job is to output information using the standard
output device

C++ Programming, Namiq Sultan 6


Program 2-2
// A simple C++ program
#include <iostream>
using namespace std; insertion
operator
int main ()
{
cout << "Programming is " << "great fun!";
return 0;
}

Output:
Programming is great fun!

C++ Programming, Namiq Sultan 7


Program 2-3

// A simple C++ program


#include <iostream>
using namespace std;
int main ()
{
cout << "Programming is ";
cout << " great fun!";
return 0;
}

Output:
Programming is great fun!
C++ Programming, Namiq Sultan 8
Program 2-4
// An unruly printing program
#include <iostream>
using namespace std;
int main()
{
cout << "The following items were top sellers";
cout << "during the month of June:";
cout << "Computer games";
cout << "Coffee";
cout << "Aspirin";
return 0;
}
Program Output
The following items were top sellersduring the month of June: Computer
gamesCoffeeAspirin

C++ Programming, Namiq Sultan 9


New lines
• cout does not produce a newline at the end of a statement
• To produce a newline, use either the stream manipulator endl
• or the escape sequence \n

C++ Programming, Namiq Sultan 10


Program 2-5
// A well-adjusted printing program
#include <iostream>
using namespace std;
int main()
{
cout << "The following items were top sellers" << endl;
cout << "during the month of June:" << endl;
cout << "Computer games" << endl;
cout << "Coffee" << endl;
cout << "Aspirin" << endl;
return 0;
}

C++ Programming, Namiq Sultan 11


Program Output

The following items were top sellers


during the month of June:
Computer games
Coffee
Aspirin

C++ Programming, Namiq Sultan 12


Program 2-6

// Another well-adjusted printing program


#include <iostream>
using namespace std;
int main()
{
cout << "The following items were top sellers" << endl;
cout << "during the month of June:" << endl;
cout << "Computer games" << endl << "Coffee";
cout << endl << "Aspirin" << endl;
return 0;
}

C++ Programming, Namiq Sultan 13


Program Output
The following items were top sellers
during the month of June:
Computer games
Coffee
Aspirin

C++ Programming, Namiq Sultan 14


Program 2-7

// Yet another well-adjusted printing program


#include <iostream>
using namespace std;
int main()
{
cout << "The following items were top sellers\n";
cout << "during the month of June:\n";
cout << "Computer games\nCoffee";
cout << "\nAspirin\n";
return 0;
}

C++ Programming, Namiq Sultan 15


Program Output

The following items were top sellers


during the month of June:
Computer games
Coffee
Aspirin

C++ Programming, Namiq Sultan 16


Table 2-2 Common Escape Sequences
Escape Name Description
Sequence
\n Newline Causes the cursor to go to the next line for
subsequent printing
\t Horizontal Causes the cursor to skip over to the next tab
tab stop
\a Alarm Causes the computer to beep

\b Backspace Causes the cursor to back up, or move left one


position
\r Return Causes the cursor to go to the beginning of the
current line, not the next line.
\\ Backslash Causes a backslash to be printed

\' Single quote Causes a single quotation mark to be printed

\" Double quote Causes a double quotation mark to be printed

C++ Programming, Namiq Sultan 17


2.3 The #include Directive
• The #include directive causes the contents of another
file to be inserted into the program
• Preprocessor directives are not C++ statements and do not
require semicolons at the end

C++ Programming, Namiq Sultan 18


2.4 Variables and Constants
• Variables represent storage locations in the computer’s
memory.
• Constants are data items whose values do not change while
the program is running.
• Every variable must have a declaration.

C++ Programming, Namiq Sultan 19


Program 2-8

#include <iostream>
using namespace std;
int main()
{
int value;
value = 5;
cout << "The value is " << value << endl;
return 0;
}

Program Output:
The value is 5

C++ Programming, Namiq Sultan 20


Assignment statements:

Value = 5; //This line is an assignment statement.


• The assignment statement evaluates the expression on the right
of the equal sign then stores it into the variable named on the
left of the equal sign
• The data type of the variable was in integer, so the data type of
the expression on the right should evaluate to an integer as
well.

C++ Programming, Namiq Sultan 21


2.5 Identifiers
• Must not be a keyword
• The first character must be a letter or an underscore
• The remaining may be letters, digits, or underscores
• Upper and lower case letters are distinct

C++ Programming, Namiq Sultan 22


Table 2-3 The C++ Keywords
asm auto bool break case catch
char class const const_cast continue default
delete do double dynamic_cast else enum
explicit export extern false float for
friend goto if inline int long
mutable namespace new operator private
protected
public register reinterpret_cast return short signed
sizeof static static_cast struct switch template
this throw true try typedef typeid
typename union unsigned using virtual
void volatile wchar_t while
C++ Programming, Namiq Sultan 23
Table 2-4 Some Variable Names

Variable Name Legal or Illegal?

dayOfWeek Legal

3dGraph Illegal. Cannot begin with a digit.

_employee_num Legal

june1997 Legal

Mixture#3 Illegal. Cannot use # symbol.

C++ Programming, Namiq Sultan 24


2.6 Integer Data Types
• There are many different types of data. Variables are
classified according to their data type, which determines
the kind of information that may be stored in them.
• Integer variables only hold whole numbers.

C++ Programming, Namiq Sultan 25


Program 2-12
// This program shows three variables declared on the same line.
#include <iostream>
using namespace std;
int main()
{
int floors, rooms, suites;
  floors = 15;
rooms = 300;
suites = 30;
cout << "The Grande Hotel has " << floors << " floors\n";
cout << "with " << rooms << " rooms and " << suites;
cout << " suites.\n";
return 0;
}
C++ Programming, Namiq Sultan 26
Program Output
The Grande Hotel has 15 floors
with 300 rooms and 30 suites.

C++ Programming, Namiq Sultan 27


2.7 The char Data Type
• Usually 1 byte long
• Internally stored as an integer
• ASCII character set shows integer representation for each
character
• ‘A’ == 65, ‘B’ == 66, ‘C’ == 67, etc.
• Single quotes denote a character, double quotes denote a
string

C++ Programming, Namiq Sultan 28


Program 2-14
// This program uses character constants
#include <iostream>
using namespace std;
int main()
{
char letter;
  letter = 'A';
cout << letter << endl;
letter = 'B';
cout << letter << endl;
return 0;
}
C++ Programming, Namiq Sultan 29
Program Output
A
B

C++ Programming, Namiq Sultan 30


Strings

• Strings are consecutive sequences of characters and can


occupy several bytes of memory.
• Strings always have a null terminator at the end. This marks
the end of the string.
• Escape sequences are always stored internally as a single
character.

C++ Programming, Namiq Sultan 31


• Let’s look at an example of how a string is stored in memory.
• “Good Luck" would be stored.

G o o d L u c k \0

• ‘A’ is stored as 65

• "A" is stored as 65 0

C++ Programming, Namiq Sultan 32


Review key points regarding characters, and strings:

• Printable characters are internally represented by numeric codes.


Most computers use ASCII codes for this purpose.
• Characters occupy a single byte of memory.
• Strings are consecutive sequences of characters and can occupy
several bytes of memory.
• Strings always have a null terminator at the end. This marks the
end of the string.
• Character constants are always enclosed in single quotation
marks.
• String constants are always enclosed in double quotation marks.
• Escape sequences are always stored internally as a single
character.
C++ Programming, Namiq Sultan 33
2.8 Floating Point Data Types

• Floating point data types are used to declare variables that


can hold real numbers

C++ Programming, Namiq Sultan 34


// This program uses floating point data types
#include <iostream>
using namespace std;
int main()
{
float distance;
float mass;
distance = 1.495979;
mass = 1.989;
cout << "The Distance is " << distance << " kilometers \n";
cout << "The mass is " << mass << " kilograms.\n";
return 0;
}
C++ Programming, Namiq Sultan 35
Program Output
The Distance is 1.4959 kilometers
The mass is 1.989 kilograms.

C++ Programming, Namiq Sultan 36


2.9 The bool Data Type
• Boolean variables are set to either true or false

C++ Programming, Namiq Sultan 37


Program 2-17
#include <iostream>
using namespace std;
int main ()
{
bool boolValue;
boolValue = true;
cout << boolValue << endl;
boolValue = false;
cout << boolValue << endl;
return 0;
}
C++ Programming, Namiq Sultan 38
Program Output
1
0

Internally, true is represented as the number 1 and false is


represented by the number 0.

C++ Programming, Namiq Sultan 39


2.11 Variable Assignment and Initialization

• An assignment operation assigns, or copies, a value into a


variable. When a value is assigned to a variable as part of
the variable’s declaration, it is called an initialization.

C++ Programming, Namiq Sultan 40


Program 2-19
#include <iostream>
using namespace std;
int main ()
{
int month = 2, days = 28;
cout << "Month " << month << " has " << days << " days.\n";
return 0;
}

Program output:
Month 2 has 28 days.

C++ Programming, Namiq Sultan 41


2.13 Arithmetic Operators

• There are many operators for manipulating numeric values


and performing arithmetic operations.
• Generally, there are 3 types of operators: unary, binary,
and ternary.

Unary operators operate on one operand

Binary operators require two operands

Ternary operators need three operands ( ?: in ch 4)

C++ Programming, Namiq Sultan 42


Table 2-8 Fundamental Arithmetic Operaotrs
Operator Meaning Type Example
+ Addition Binary Total = Cost + Tax;
- Subtraction Binary Cost = Total - Tax;
* Multiplication Binary Tax = Cost * Rate;
/ Division Binary SalePrice = Original/2;
% Modulus Binary Remainder = Value%3;

C++ Programming, Namiq Sultan 43


Program 2-21
// This program calculates hourly wages. The variables are:
// regWages: holds the calculated regular wages.
// basePay: holds the base pay rate.
// regHours: holds the number of hours worked less overtime.
// otWages: holds the calculated overtime wages.
// otPay: holds the payrate for overtime hours.
// otHours: holds the number of overtime hours worked.
// totalWages: holds the total wages.
#include <iostream>
using namespace std;
int main()
{
float regWages, basePay = 18.25, regHours = 40.0;
float otWages, otPay = 27.78, otHours = 10;
float totalWages;
  C++ Programming, Namiq Sultan 44
Program 2-21

  regWages = basePay * regHours;


otWages = otPay * otHours;
totalWages = regWages + otWages;
cout << "Wages for this week are $" << totalWages << endl;
return 0;
}

C++ Programming, Namiq Sultan 45


2.14 Comments
• Comments are notes of explanation that document lines or
sections of a program.
• Comments are part of a program, but the compiler ignores
them. They are intended for people who may be reading the
source code.
• Commenting the C++ Way
//
• Commenting the C Way
/* */

C++ Programming, Namiq Sultan 46


Program 2-22
// PROGRAM: PAYROLL.CPP
// Written by Herbert Dorfmann
// This program calculates company payroll
 
#include <iostream>
using namespace std;
int main( )
{
float payRate; // holds the hourly pay rate
float hours;// holds the hours worked
int empNum; // holds the employee number
 
(The remainder of this program is left out.)
C++ Programming, Namiq Sultan 47
Program 2-24
/* PROGRAM: PAYROLL.CPP
Written by Herbert Dorfmann
This program calculates company payroll */
#include <iostream>
using namespace std;
int main( )
{
float payRate; /* payRate holds hourly pay rate */
float hours;/* hours holds hours worked */
int empNum; /* empNum holds employee number */
 
(The remainder of this program is left out.)

C++ Programming, Namiq Sultan 48


2.15 Programming Style

• Program style refers to the way a programmer uses identifiers,


spaces, tabs, blank lines, and punctuation characters to
visually arrange a program’s source code.

Generally, C++ ignores white space.

Indent inside a set of braces.

Include a blank line after variable declarations.

C++ Programming, Namiq Sultan 49


Program 2-26

#include <iostream>
using namespace std;
int main( ){float shares=220.0; float avgPrice=14.67; cout
<<"There were "<<shares<<" shares sold at $"<<avgPrice<<"
per share.\n"; return 0;}

Program Output
There were 220 shares sold at $14.67 per share.

C++ Programming, Namiq Sultan 50


Program 2-27
// This example is much more readable than Program 2-26.
 #include <iostream>
using namespace std;
int main( )
{
float shares = 220.0;
float avgPrice = 14.67;

  cout << "There were " << shares << " shares sold at $";
cout << avgPrice << " per share.\n";
return 0;
}
Program Output
There were 220.0 shares sold at $14.67 per share.
C++ Programming, Namiq Sultan 51

You might also like