0% found this document useful (0 votes)
34 views

CP 2 - Part 1

The document discusses the basic elements of C++ programs, including functions, data types, variables, input/output statements, and arithmetic operators. It explains that a C++ program contains functions, with every program having a main function. It also describes the different simple data types in C++ like integers, floats, characters, and strings. The document provides examples of declaring variables, using assignment statements, reading input from the user, writing output, and performing arithmetic operations. It explains the use of escape sequences, constants, comments and other syntax elements in C++ programs.

Uploaded by

Khairul Nadzmi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

CP 2 - Part 1

The document discusses the basic elements of C++ programs, including functions, data types, variables, input/output statements, and arithmetic operators. It explains that a C++ program contains functions, with every program having a main function. It also describes the different simple data types in C++ like integers, floats, characters, and strings. The document provides examples of declaring variables, using assignment statements, reading input from the user, writing output, and performing arithmetic operations. It explains the use of escape sequences, constants, comments and other syntax elements in C++ programs.

Uploaded by

Khairul Nadzmi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

TOPIC 2 (PART 1):

BASIC ELEMENTS OF C++


OBJECTIVES

 In this chapter you will learn:


➢ 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
➢ Learn what an assignment statement is and what it does
➢ Discover how to input data into memory using input statements
➢ Examine ways to output results using output statements
➢ Discover how to use arithmetic operators
➢ Learn how to write a C++program
C++ PROGRAM

 A C++program is a collection of one or more subprograms, called functions


 A subprogram or a function is a collection of statements that, when activated
(executed), accomplishes something
 Every C++ program has a function called main

 The smallest individual unit of a program written in any language is called a token
 A token in C++ may be the following:
➢ Keyword
➢ Identifier
➢ Constant
➢ Operator
CREATING A C++ PROGRAM

 C++ program has two parts


➢ Preprocessor directive
➢ The program
 Source code must be saved in a file with the file extension .cpp

 Compiler generates the object code and saved in a file with file extension
.obj
 Executable code is produced and saved in a file with the file extension
.exe
PREPROCESSOR DIRECTIVE SYNTAX

 Tell the compiler to preprocess the source code before actual compiling
process
 All preprocessor commands begin with #
 Many functions and symbols needed to run a C++ program are provided
as collection of libraries.
 Every library has a name and is referred to by a header file

 Syntax: #include <headerfile>


 Examples of some preprocessor directives are:
➢ #include <iostream>
➢ #include <cmath>
➢ #include <cstring>
SYMBOL

 Special symbol:  Word symbols

+ ? ➢ Reserved words, or keywords

- , ➢ Include:
• int
* <=
• float
/ !=
• double
. == • char
; >= • return
SEMICOLONS, BRACKETS, COMMAS &
COMMENTS
 Commas separate items in a list
 All C++ statements end with a semicolon ( ; )

➢ Semicolon is also called a statement terminator


 { and } are not C++ statements

 Comments can be used to document code


➢ Single line comments begin with ( // ) anywhere in the line

➢ Multiple line comments or pair comments are enclosed between


/* and */
USE OF BLANKS

 Use of Blanks
➢ One or more blanks separate input numbers
➢ Blanks are also used to separate reserved words and identifiers from
each other and other symbols
 Blanks between identifiers in the second statement are meaningless:
➢ int a,b,c;
➢ int a , b , c;
 In the statement: inta,b,c;
➢ No blank between the t and a changes the reserved word int and the
identifier a into a new identifier, inta.
IDENTIFIER

 Identifier is the name of something that appears in a program


➢ Identifiers consist of letters, digits, and the underscore character ( _ )
➢ Must begin with a letter or underscore
➢ Name identifier with meaningful name

 C++ is case sensitive


➢ NUMBER is not the same as number

 Some predefined identifiers are cout and cin


IDENTIFIER (CONT.)
 Example of valid or legal identifier
➢ first
➢ number1
➢ averageScore
➢ latest_CGPA

 Example of invalid or illegal identifier


DATA TYPE

 Data type is a set of values together with a set of


operations
 C++ data can be classified into three categories:
➢ Simple data type (focus on this type)
➢ Structured data type
➢ Pointers
SIMPLE DATA TYPE

 Categories of simple data type:


➢ Integral: integers (numbers without a decimal)
• Can be further categorized: A Boolean type (bool), Character
type (char), Integer type (int)
➢ Floating-point: decimal numbers
SIMPLE DATA TYPE -INTEGRAL
 int Data Type
➢ Positive integers do not have to have a + sign in front of them
➢ No commas are used within an integer
➢ Commas are used for separating items in a list

Output:
SIMPLE DATA TYPE –INTEGRAL (CONT.)
 bool Data Type:
➢ Has two values, true and false
➢ Manipulate logical (Boolean) expressions
➢ true and false are called logical values
➢ bool, true, and false are reserved words

Output:
SIMPLE DATA TYPE –INTEGRAL (CONT.)
 char Data Type:
➢ The smallest integral data type
➢ The character variable can store only one character
➢ Used for characters: letters, digits, and special symbols
➢ Some of the values belonging to char data type are: 'A', 'a', '0', '*', '+', '$’, '&'
➢ A blank space is a character and is written ' ', with a space left between the single
quotes

Output:
SIMPLE DATA TYPE – INTEGRAL (CONT.)

 string Data Type:


➢ Sequence of zero or more characters
➢ Enclosed in double quotation marks
➢ Null: a string with no characters
➢ The last character in a string is the null
character (‘\0’)
➢ Length of a string: number of characters in string
• Example: length of “William Jacob” is 13 Output:
➢ Position of first character is 0, the position of the second is 1,
and so on
SIMPLE DATA TYPE – FLOATING POINT

 C++ uses scientific notation to represent real numbers (floating-point notation)


SIMPLE DATA TYPE – FLOATING POINT (CONT.)

 float Data Type:

➢ represents any real number


➢ Range: -3.4E+38 to 3.4E+38
➢ Memory allocated for the float type is 4 bytes
➢ Maximum number of significant digits (decimal places) for float values
is 6 or 7
SIMPLE DATA TYPE – FLOATING POINT (CONT.)

 double Data Type:

➢ represents any real number


➢ Range: -1.7E+308 to 1.7E+308
➢ Memory allocated for double type is 8 bytes
➢ On most newer compilers, data types double and long double are
same
➢ Maximum number of significant digits for double is 15
➢ Double values are called double precision
VARIABLE

 Variable is a program element containing a value that can be changed


 Variables declared inside a function or a block is called local variables
 Variables declared outside of all functions is called global variable
 Syntax: <data type> <identifier> <identifier> . . . ;
VARIABLE (CONT.)

Global variable

Local variables
ASSIGNMENT STATEMENT
 The assignment statement takes the form:
variable = expression;
 Expression is evaluated and its value is assigned to the variable on the
left side
 In C++, (=) is called the assignment operator
CONSTANT

 Constants refer to fixed values that the program may not alter during
execution
 Constants can be any of the basic data types
 Defining Constants:
➢ There are two simple ways in C++ to define constants:
➢ Using #define preprocessor
➢ Using const keyword
 In C++, const is a reserved word

 Constants are treated just like regular variables except that their values
cannot be modified
CONSTANT (CONT.)

 Constant Example:
INPUT AND OUTPUT

 Output Statement
➢ To display output on screen or to write output into file
➢ Using cout keyword and output stream called insertion operator (<<)

➢ Syntax :
cout << <string | constant | variable | expression > ;
➢ Expression evaluated and its value is printed at current position on the screen
➢ Manipulator: alters output
➢ endl: the simplest manipulator

• Causes cursor to move to beginning of the next line


INPUT AND OUTPUT (CONT.)

 Output example:
➢ Output of the C++ statement
cout << a;
is meaningful if a has a value
➢ For example, the sequence of C++ statements,
a = 45;
cout << a;
produces an output of 45
INPUT AND OUTPUT (CONT.)

 Input (Read) Statement


➢ To received input from keyboard or read input from a file
➢ Using cin keyword and input stream called extraction operator
(>>)
➢ Syntax: cin >> <variable> >> <variable> . . . ;
➢ For example, if miles is a double variable
cin >> miles;
• Causes computer to get a value of type double
• Places it in the memory cell miles
INPUT AND OUTPUT (CONT.)

 Example of input statement:

Prompt to the user to


cout << “Enter a score : “;
enter a value
cin >> score;
Read a value from the
user
ESCAPE SEQUENCE IN C++

 These are used to add special effects (generally for output)


 Every escape sequence begin with slash symbol (\)
ESCAPE SEQUENCE IN C++ (CONT.)

 Example:

Output:
ARITHMETIC OPERATION

 Five basic operations:

Addition (+) Sum of two numbers


Subtraction (-) Different of two numbers
Multiplication (*) Product of two numbers
Division (/) Quotient of two numbers
Modulo (%) Remainder of division operation
ARITHMETIC OPERATION (CONT.)

 Example:

Output:
SEMANTICS

 Possible to remove all syntax errors in a program and still not have it run
 Even if it runs, it may still not do what you meant it to do
 For example,
➢ 2 + 3 * 5 and (2 + 3) * 5

are both syntactically correct expressions, but have different meanings


PROGRAMMING EXAMPLE

 Write a program that takes as input given lengths expressed in


feet and inch.
 The program should then convert and display the length in
centimeters.
 Assume that the given lengths in feet and inch are integers. (One
feet is 12 inches; One inch is equal to 2.54 centimeters)
PROGRAMMING EXAMPLE (CONT.)

 Algorithm

Start
1. Read length in feet
2. Read length in inch
3. Calculate the length in centimeter using formula:
totalInches = 12 * feet + inch;
totalCentimeter = 2.54 * totalInches;
4. Display totalCentimeter
End
PROGRAMMING EXAMPLE (CONT.)

Output:
SUMMARY

 C++ program : collection of functions where each program has a function


called main
 Identifier consists of letters, digits, and underscores, and begins with letter
or underscore
 The arithmetic operators in C++ are:
➢ addition (+),
➢ subtraction (-),
➢ multiplication (*),
➢ division (/), and
➢ modulus(%)

You might also like