0% found this document useful (0 votes)
15 views41 pages

Chap01b - Basic Elements of C++

Uploaded by

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

Chap01b - Basic Elements of C++

Uploaded by

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

C++ Programming

Problem Solving and


Programming
Chapter 1b
Introduction To
Program Development
Objectives
In this chapter you will:
• Become familiar with the basic components of a
C++ program, including functions, special
symbols, and identifiers
• Explore simple data types and examine the string
data type
• Discover how to use arithmetic operators
Objectives
• Examine how a program evaluates arithmetic
expressions
• Learn what an assignment statement is and what
it does
• Discover how to input data into memory using
input statements
• Become familiar with the use of increment and
decrement operators
Objectives
• Examine ways to output results using output
statements
• Learn how to use preprocessor directives and
why they are necessary
• Explore how to properly structure a program,
including using comments
• Learn how to write a C++ program
C++ Program Structure
Basic structure:
#include <iostream>
#include <iostream> using namespace std;

using namespace std; int main(void)


int main() {
int x, y, total;
{
x = 10;
Declaration statements
y = 20;
Executable statements total = x + y;
cout<<“Total:”<<total;
}
return 0;
}
Preprocessor Directives
• C++ has a collection of library files
• Every library file has a name and is referred as
header file
• Syntax to include a header file in the program
#include <header file name>
Example: #include <iostream>
#include Directive
• Usually used at top of the program to insert the
contents of header file into the program
• #include <iostream>
- the codes/functions like cin and cout are found
in the iostream header file. They are made
available for use in the program
• DO NOT place a semicolon at the end of #include
line
Using cin and cout and
namespace
• cin and cout are declared in the header file
iostream, but within a namespace called std
• namespace std is a declarative region that
provides a scope for those standard functions
• To use cin and cout in a program, use the
following two statements:
#include <iostream>
using namespace std;
Comments
• It is helpful to place some comments in the code
to help the reader to understand the meaning of
the code

• 2 types of comments:
- Block comment ( /* and */ )
- Line comment ( // )
Block Comment
/* This is a block comment that
covers two lines. */

/*
This is a very common style to put the opening token
on a line by itself, followed by the documentation and
then the closing token on a separate line. Some
programmers also like to put asterisks at the
beginning of each line to clearly mark the comment.
*/
Line Comment

// This is a whole line comment.

a = 5; // This is a partial line comment.


Example
Add block comment and line comment into the
following program:
/* Author: Michael Tan
Date written: 20 Oct 2019
Purpose: Program is written to find total of 2 numbers */
#include <iostream>
using namespace std;
int main ( )
{ // Declare variables
int num1= 5, num2 = 10, total;
total = num1 + num2; // find total of 2 numbers
cout << “Total = “ << total; // output result
return 0;
}
Identifier
• Is a programmer-defined name for program
elements such as variables, functions, etc.
• Rules for identifiers:
✔Must consist only alphabets, digits or underscores
✔First character must be alphabet or underscore
✔Cannot be same with keywords / reserved words
C++ Key Words
You cannot use any of the C++ key words as an identifier.
These words have reserved / pre-defined meaning. They
are in lower case.
Valid and Invalid Identifiers

IDENTIFIER VALID? REASON IF INVALID

totalSales Yes

total_Sales Yes

total.Sales No Cannot contain ‘.’

4thQtrSales No Cannot begin with digit

totalSale$ No Illegal symbol $


Remember!!
• Use meaningful / descriptive names for
identifiers.

• E.g. to store the future value of an investment:


− f (too short)
− fv (too short)
− future_value_of_an_investment (too long)
− future_value (OK)
Data Type

• A type defines a set of values and a set of


operations that can be applied to those
values.
Data Type : Examples
Data Type Description Example
char Single character (value is ‘A’, ‘a’, ‘8’, ‘?’
enclosed within a pair of
single-quote).
int Integer number. 0, 123, -456
bool Contain true or false value true, false
(In memory, 1 represents true,
0 represents false)
float Floating-point number. 12.34
double Double-precision floating-point 3.14159265358
number (more accuracy). 98
Declare / Define variables
Memory:
Data Identifier /
Type variable name
gender ?

char gender; year ?


int year;
float price;
double pi; price ?

pi ?
Assign values to variables
Memory:
char gender;
int year;
float price; Assign (store) gender ‘F’
double pi; values to
variables
gender = 'F'; year 2008
year = 2008;
price = 25.99;
price 25.99
pi = 3.1415926235898;

Remark: Assign a value that pi 3.1415926235898


is matched with the declared
data type. Type mismatch
may result in error.
Initialization of variables
Memory:
Initialization: assign values to
variables while creating them. gender ‘F’

char gender = 'F';


int year = 2008; year 2008
float price = 25.99;
double pi = 3.1415926235898;
price 25.99
Remark: Uninitialized variable
invites “garbage value” (not pi 3.1415926235898
meaningful) . Thus it is good to
always initialize the variable
before you use it later.
Data Type - String

• String is a sequence of characters


• Can be declared as
o C-string
o String class

• Note: String will be discussed further in


another chapter
Data Type – C-String

• Array of characters
• Example:
o char name[21];
o Indicates the string contains 20 characters in
length plus one terminating null character (\0)

• Note: To read string


o cin >> name; // read a single word string
o cin.getline(name, 21); // read multiple words string
Data Type – String Class
#include <string> Include string
library
using namespace std;
Declare and initialize a string
variable
string day = “Tuesday”;
string date = “1 January, 2013”;

char space = ‘ ’;
You may replace this with string space = “
”;
cout << day << space << date;
Data Type – String Class

string name=“”, mood=“”;


cout << “Enter your name:”;
cin >> name; Can only read ONE
word
cout << “How is your mood?”;
getline(cin, mood);
Will read the entire line of input
into mood variable
Scope
• The part of the program in which the variable
can be accessed
• A variable cannot be used before it is declared
• Example:
Allocating Memory

• Variable: memory location whose content can


be changed during program execution
• Named Constant: memory location whose
content can’t be changed during program
execution
Declare / Define Constants
Named Constant
•Syntax: const <data type> <identifier> = value;
•const is a reserved word
•Data value MUST be initialized during declaration
and can’t be changed (read-only) during program
execution.
•Examples:
const int THIS_YEAR = 2019;
const double PI = 3.14159;
const char HASH = ‘#’;
const char HELLO[] = “Hello World”;
Declare / Define Constants

Defined Constant
•A defined constant is a name that replaces the
constant name in the program body with the
expression associated with that constant name.
•The preprocessor command #define is used.
•Examples:
#define PI 3.14159
#define YEAR 2019
#define PET_NAME “Doggy”
#define GOOD_GRADE ‘A’
Declare / Define Constants
// EXAMPLE of Defined Constant
#include <iostream>
using namespace std;
#define GRAMS_PER_KG 1000

int main() {
double grams, kgs;

cout << “Enter weight in KG : ”;


cin >> kgs;

grams = kgs * GRAMS_PER_KG;

cout << kgs << “KG is equal to ” << grams << “grams” << endl;
return 0;
}
Program Statements

• A statement causes the computer to


carry out some action.

• Statements consists of:


− Expression statements
− Compound statements
− Control statements
Expression statements

• Consists of an expression followed by a


semicolon.
• Examples:
a = b + c;
cout << “a = ” << a;
Compound statements
• Consists of several individual statements
enclosed within a pair of braces { } .
• Example:
{
pi = 3.141593;
area = pi * radius * radius;
}
Control statements
• Used to create special program features,
such as logical tests, loops and branches.
• Example:
while (count <= n)
{
cout << “x = ”;
cin >> x;
if (x > 10)
sum += x;
++count;
}
Mixed Type Conversion
• To evaluate the expressions involve data of
different type, one of the type must be converted
− E.g. integer * float
• In an assignment expression, the final expression
value must have the same data type as the left
operand, which receives the value.
• There are 2 types of conversion:
1. Implicit type conversion
2. Explicit type conversion
Implicit Type Conversion
• C++ automatically converts one type to another,
according to the promotion order (conversion rank).

E.g., int a;
double x, b;
x = a + b;

• The conversion is only temporary; the converted


value is back in its original data type as soon as the
expression is finished.
Implicit Type Conversion

High

Low

FIGURE 4-11 Conversion Rank


Implicit Type Conversion
Example:
Expression Intermediate Type

char + float float

int - long long

int * double double

float / long double long double

(short + long) / float long then float


Implicit Type Conversion

• Example 1: • Example 2:
char c = ‘A’; char c = ‘A’;
int i = 1234; int k = 65;
i = c; // value of i is c = k + 1; // value of c is
65 ‘B’
• Example 3:
char c = ‘A’;
int i = 3650;
short s = 78;
long double d = 3458.0004;
cout << i * s; // result is in int
cout << d * c; // result is in long
Explicit Type Conversion
• Cast operator is used to convert data type from
one type to another type
• Specify new type in parenthesis before the value
that need to be converted
✔ (double) number;
• E.g.
int no1, no2;
double X = (double)(no1 / no2);
double X = (double)no1 / no2;
double X = static_cast<double>(no1)/no2;
Question
• State the output of the following
int num1 = 9, num2 = 2;

1. double x = num1 / num2;

2. double y = (double)(num1/num2);

3. int z = num1 / (double)num2;

You might also like