Sie sind auf Seite 1von 51

Introduction to

The ++
language
The C++ language

General purpose programming language


Modern control flow and data structure
Uses economy of expression
Convenient and effective
Useful for writing compilers and operating systems
History of C language

Designed by Dennis Ritchie


Evolved from a language called B in the seventies at
AT&T Bell labs
First implemented on the UNIX operating system
Written to help non-scientists develop computer
programs
Characteristic of C language

Features structured programming


Top-down
Steps in C programming

Write the program


Debug and Edit
Compile
Link
Execute
Your first C program
/* This program is to introduce
students to C++ for the first
time */

#include <iostream>
int main (void)
{
cout <<Hello World!! \n;
return 0;
} /* main */
Structure of a program in C
/* This program is to
introduce students to C++
Pre-processor directives for the first time */

Global declarations
#include <iostream>
The main( ) function int main (void)
Local declarations {
Statements cout <<Hello World!! \n;
Other functions return 0;
} /* main */
Structure of a program in C+
+ Preprocessor Directives

Global Declarations
int main ( void)
{
Local declarations

Statements
}
int main ( void)
Function header
{{
Local definitions
Local declarations

Statements
}}
Preprocessor Directives
Starts with a pound sign (#)
Commands to prepare for translation into machine
language, to look for special code libraries
Examples of directives:
#include - To access or link to functions from selected
libraries through header files
E.g. #include <stdio.h>
Attach header file called stdio.h
To allow use of standard I/O functions
#define to define data constants

Global Declarations

Visible to all parts of the program


May contain data or function declarations
The main function

The executable part of a program begins with


this function definition
int main (void)
int returns integer value
main name of function
void has no parameter
Programming Codes

Declarations Statements Comments


Program codes
consists of
Lexical Units

Identifiers Keywords Symbols

e.g. e.g.
names of e.g. ;
variables: int, return &&
sum, i
Identifiers in C++
Names used to represent data memory
areas

variables

constants
Identifiers are
names of
functions

data definition
Rules on Identifiers in C++

Starts with a letter, followed by letters, digits


or underscore
Not more than 31 characters
Must not use C reserved words or keywords
Case sensitive
Index is NOT equal to INDEX
Should be meaningful and readable
Declaration of Identifiers

All identifiers must be declared before it is


used
To define or variables, constants, function
prototypes
Reserves memory location for the declared
identifier
Size of memory allocation depends on its type
Keywords in C++

32 keywords, all in lowercase


As reserved words used for C++ compiler
Cannot be used as identifier
Keywords:
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
Variables

a way the computer stores value in memory

Variable Name: name to which variable is


referred to within the program
Scalar Data

Variables Constants

Data that can Data that cannot


change change
Variable Declaration
To declare variables and the data type
Syntax:
datatype Variablename;
Examples:
int Age;
char Grade;
Variable definition
Can be declared and initialized at the
same time
Syntax:
datatype Variablename = value;

Examples:
int Counter = 0;
Constants
Values that do not/cannot change during
execution of a program
Types of constants:
Named Constant
Defined constant
Memory constant
Literal constant
Defined Constants
Uses preprocessor directive #define:
Syntax:
#define ConstantName Value
Example
#define PI 3.14159256
Convention: use uppercase for constant
names
Notice: No semicolon
Memory Constants
Declared together with other variables
Syntax:
const datatype CONSTANTNAME = Value;
Example
const double PI = 3.14159256;

Note: Must use semicolon


Literal Constants
Constants typed and used directly within
programming codes
Example:
A a character literal
4 a numeric literal
3.14159 a float numeric literal
Hello world! a string literal
Advantages of Using Named
Constants
Named constants:
Memory constants
Defined constant
Make program more readable than using
directly-typed literal constants
Value defined in a single place, easier to
change a constant value
Data Types

Classification of data (both variables /


constants)
Tells how much space to allocate and how it
operates
Two levels of data types:
Standard data types
Derived data types
Standard (atomic)
data types

Void Character Integer Floating point

void char int float


short int double
long int long double
unsigned int
Integer data types

For numbers without decimal places


unsigned short/long int stores positive
integers only
Other symbols not allowed: $, comma (,),
percent (%)
Integer data types
Type Bytes used from to
int 2 bytes -32768 32767
short int 1 byte -128 127
long int 4 bytes -2147483648 2147483647
unsigned int 2 bytes 0 216-1
unsigned 1 byte 0 28-1
short int
unsigned 4 byte 0 232-1
long int
Floating point data types

For numbers with decimal accuracy


float: with 6 digits of accuracy
double: uses twice amount of storage than
float (with 14 digits of accuracy)
long double
sizeof( ) operator

Returns the number of bytes reserved by


the compiler for the variable
Example:
sizeof (num1) //returns 2 if num1 is an integer
Derived data types
Built using standard data types

Array

Enumerated types
Derived Data Types
Pointer

Structure

Union
Statements in C
Causes an action to be performed by the
program
Terminated by semicolon ( ; )
Assignment statements

Function statements
Types of
Statements
Control statements

Null statements
Assignment statements
Syntax:
variable = operand;
(operand can be constant, a variable or a valid C expression)
Syntax:
VariableName = Value / literal;

VariableName = Variable;

VariableName = Expression;

VariableName = Value returned by function;

Example:
year = 1988;
sum = sales;
sum = sales + tax;
Use of Assignment
statements
Uses assignment operator ( = ) to assign /
store a value or evaluated expression on the
right to the identifier on the left
Assignment is used for the following
operations:
Initializing
Accumulating
Counting: Incrementing/decrementing
Accumulating and counting
Assignment statements widely used in accumulating
and counting
Accumulating:
variable = variable + value;
sum = sum + 25;

Counting/incrementing
variable = variable + fixedvalue;
i = i + 1;

Can also be expressed as using increment operator


(++) :
++i
Function statements
Call to functions
Types of functions
User defined
Library (built-in)
Control statements

Control flow of program and branches to


the next statement to be executed

Two types of branching


Selection
Repetition
Null Statements

Terminated by semicolon
Does nothing
Used where a statement is syntactically
required, but no action is called for
Expressions
Made of combination of :
operators
operands
Operators: Symbols used to represent a
certain operation
Operands: variable or constant name, value /
literal, value returned by function
Type of operands must match
Mathematical Expressions
Types of mathematical expression
Integer Expression
Floating-Point Expression
Mixed Mode Expression
Integer Expression
E.g. num = num + 10;
Floating-Point Expression
E.g. price = price * (1 0.2);
Mixed Mode Expression
E.g. num = num * 2.5;
Types of Expressions

Logical/Boolean Mathematical
Expressions Expressions

evaluated to evaluated to a
True or False numerical value
Operators
Symbols used to represent a certain
mathematical or logical operation
Operator symbols:
Mathematical: ( ), *, /, %, +,
Logical: >, <, >=, <=, ==, !=
Binary operators versus Unary operators
Binary: 2 + 5
Unary: -7
Precedence and
Associativity:
The priority by which expressions are

evaluated in a compounded expression


Operators Precedence
*/%
+-
Brackets are used to override precedence
Expression of same precedence are
evaluated according to associativity
Left to right
Right to left
Exercises on
Precedence
If x = 10, and y = 20, what are the values for
expressions below:

x + 5 * y 12 = ?
(x + 5) * y 12 = ?
x + 5 * (y 12) = ?
(x + 5) * (y 12) = ?
Exercises on
Precedence
If c = A, and d = 10, what are the values for
expressions below:

c+5*d2=?
(c + 5) * d 2 = ?
Use of Escape Sequence
Tells the compiler to escape from the
character normal interpretation
\n new line
\b backspace
\t tab
\f form feed
***To display Backslash(\) itself: use \\
Example:

printf (Number is %f \n, average);


Documentation in C
programs
Two ways to add lines of comment for
documentation purposes

Use of /* */ pairs to enclose comments

Using // to disregard the remaining of line as


comments
Adding Documentation

Example:
/* This is a comment
for my first program */

Example:
int firstnum; // declare first number
End of Slides