[go: up one dir, main page]

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

Chap02 - Basic Elements of C++

The document discusses the basic elements of C++ programming including data types, variables, constants, and input/output statements. It covers fundamental concepts like declaring variables, assigning values, built-in data types, and using preprocessor directives and comments.

Uploaded by

chanky-wp22
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 views41 pages

Chap02 - Basic Elements of C++

The document discusses the basic elements of C++ programming including data types, variables, constants, and input/output statements. It covers fundamental concepts like declaring variables, assigning values, built-in data types, and using preprocessor directives and comments.

Uploaded by

chanky-wp22
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/ 41

C++ Programming:

Problem Solving and


Programming
Chapter 2
Basic elements of C++
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
2.1 C++ Program Structure
Basic structure:
#include <iostream>
using namespace std;
#include <iostream>
using namespace std; int main(void) **highlight word is
a must
{
int main() int x, y, total;
{ 10 assign to x
x = 10;
Declaration statements y = 20; 20 assign to y
total = x + y; x+y assign to total
Executable statements cout<<“Total:”<<total;
}
return 0;
}
2.2 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 in a Program 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;
2.3 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;
}
2.4 Identifier

• Is a programmer-defined name for program


elements such as variables, functions, etc.
• Rules for identifiers:
first write must always in the end first write

Must consist only alphabets, digits or underscores


First alphabet 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)
2.5 Data Type
• A type defines a set of values and a set of
operations that can be applied to those
values.
Data Type : Examples //niitialize empty value to any datatype

char letter= ' ';


string text=" ";
int number=0;
double decimal
Data Type Description Example
char Single character (value is ‘A’, ‘a’, ‘8’, ‘?’
//declare character and assign character 'A'
enclosed within a pair of to letter
char letter= 'A';
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. minimum 1 12.34
double Double-precision floating-point 3.14159265358
number (more accuracy). 98
2.6 Declare / Define variables
Memory:
Data Identifier /
Type variable name
gender ?

char gender;
year ?
int year;
float price;
double pi; price ?

pi ?
Assign value to variables:
Memory:
char gender;
int year; Assign (store) gender ‘F’
float price; value to
double pi; variables
year 2008
gender = 'F';
year = 2008;
price 25.99
price = 25.99;
pi = 3.1415926235898;
pi 3.1415926235898
Remark: Assign a value that is
matched with the declared data
type. Type mismatch may result
in error.
Initialization of variables:
Memory:
Initialization: assign value 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 array
o String class

• Note: String will be discussed further in


another chapter
Data Type – C-String

• Array of characters
• Example:
remaining 1 is
null value
(cannot storing

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
set size
Data Type – String Class
#include <string> Include string library

using namespace std;

string day = “Tuesday”;


string date = “1 January, 2013”;
Declare and initialize a string variable

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); if need to read multiple word

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
need to declare first

• 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
2.7 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; statement
const double PI = 3.14159;
const char HASH = ‘#’;
const char HELLO[] = “Hello World”;
2.7 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’
2.7 Declare / Define Constants
// EXAMPLE of Defined Constant
#include <iostream>
using namespace std; fixed data
#define GRAMS_PER_KG 1000
**define must be before main
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;
}
2.8 Program Statements

• A statement causes the computer to carry out


some action.
end with semi-column

• 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;
always end with semi-column
Compound statements

• Consists of several individual statements


enclosed within a pair of braces { } .
• Example: group particular statement

{
pi = 3.141593;
area = pi * radius * radius;
}
Control statements

• Used to create special program features, such as


logical tests, loops and branches. create condition
• Example:
type of loops condition
while (count <= n)
{
cout << “x = ”;
cin >> x; selection statement
if (x > 10)
controlling the sum
sum += x;
++count;
}
2.9 Mixed Type Conversion **important

• 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:
internal
1. Implicit type conversion
2. Explicit type conversion
external
Implicit Type Conversion
• C++ automatically converts one type to another,
according to the promotion order (conversion rank).
based on ranking

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 65 c = k + 1; // value of c is
‘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 double
how you want your final
Explicit Type Conversion result look like

• Cast operator is used to convert data type from one


type to another type
• Specify new type in parenthesis before the value
that need tochange
be converted from integer change to double
 (double) number;
• E.g.
int no1, no2;
double X = (double)(no1 / no2);
no 1 converted to double only divide
double X = (double)no1 / no2; by no 2
double X = static_cast<double>(no1)/no2;
no 1 converted to double only divide by
no 2
Question
• State the output of the following
int num1 = 9, num2 = 2;

1. double x = num1 / num2;

2. double y = static_cast<double>(num1/num2);

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


`x = 4.0
`y = 4.0
`z = 4

You might also like