Sie sind auf Seite 1von 33

CHAPTER 02

AN OVERVIEW OF C++
C++

PROGRAMS
C++ programs are made of global
Preprocessor Directives

declaration section and one or more Global declarations


functions
Global declarations are placed at the int max (int a, int b)
beginning of the program outside all the {.
functions. }
Global declarations are known to all parts of
the program (all functions) char convert (char b)
A program may contain any number of {
functions. }
A program must have exactly one and only
one function named main
The main is the starting point of the
program int main ( )
Every function is divided two sections {
Local declaration: variables declared are
only known to the function and not Local declarations
known outside
Statements
Statements
}
2
PREPROCESSOR
Preprocessor Directives
DIRECTIVES
A libraries that contain /* A program to print the string
functions and symbols that Welcome to C++ to the screen
*/
are necessary to run a C++
program.
#include <iostream.h>
Every library has a name and
is referred as a header file.
int main()
All preprocessor commands
{
begin with #.
/* print out the message */
In Standard C++, header cout<<"Welcome to C++"<<endl;
files have the file extension
return 0;
.h
}
There is no semicolon at the
end of these commands.
The general syntax to include
#include <headerFileName>
a header file

#include <iostream.h>
3
THE PROGRAM PART: THE HEADING
The heading part has the following form
Every C++ program has a function
main. typeOfFunction main(argument list)
The basic parts of the function main
are:
1. The heading int main()
2. Body of the function {
/* print out the message */
cout<<"Welcome to C++"<<endl;
return 0;
}
The statement

int main(void) int main()

means that the function equivalent It is not necessary to put


main returns a value of word the void in
the type int and it has parentheses, but the
no arguments. parentheses are still
needed.
4
THE

PROGRAM PART: BODY OF THE FUNCTION


The body of the function is enclosed
between { and } and has two types of int main()
statements.
{
/* assignment statements */
Declaration Statements
int a, b, c; int a = 10;
int b = 2;
double x, y;
int c;
Variables (or identifies) can be
declared anywhere in the program,
but they must be declared before /* print out the message */
they can be used. cout<<"Welcome to C++"<<endl;

Executable Statements // input statement


a = 10; cin>>c;
//assignment statement
cin>>c; /* output statement */
//input statement cout<<a+b+c<<endl;
cout<<a+b+c<<endl;
//output statement return 0;
}
5
COMMENTS
Comments
Multiple line comments are /* A program to print the string
enclosed between /* and Welcome to C++ to the screen
*/
*/
Single line comments begin
#include <iostream>
with //
using namespace std;
Statements that have no
effect on the execution of
int main()
the program
{
The Compiler neglects these // print out the message
comments when translating
cout<<"Welcome to C++"<<endl;
the program to machine
return 0;
code
}
Comments can be place
before each of the functions
Output:
and inside the function
Welcome to C++ Programming

6
THE
IndicatesHELLO WORLD PROGRAM
the beginning of
< iostream.h > is
the functions body
included in this program
#include <iostream.h> because it provides
information to the compiler
int main (void) about cout function

{
cout<<hello world\n; Block
cout is a function from a
return 0; standard library that prints
} on the screen

End of functions body 0 is returned to the OS when


main is terminated

The string hello world\n is sent to the cout function and the
function will display the message on the screen
The \n that appears in the cout function call will cause the message
to be printed on the screen then moves the printing to the next line

7
SYNTAX
A programming language is a set of rules, symbols, and special words used
to construct a program.

There are rules for both syntax (grammar) and semantics (meaning).
Syntax: The formal rules governing how one writes valid
instructions in a language

Semantics: The set of rules that gives the meaning of


instructions written in a programming language.

The syntax rules tell us which statements (instructions) are legal, that is,
accepted by the programming language and which are not.

Metalanguage: A language used to write the syntax rules.

8
IDENTIFIERS
Identifiers allow us to name variables, constant names, functions and
objects in the program
Each piece of data in the computer is stored at a unique memory address
Identifier names allow us to symbolically deal with the memory locations so
that we dont have to deal directly with these addresses
Different programming languages use different syntactic rules to form
identifiers
A C++ identifier are formed using the following symbols
Capital letters A to Z
Small letters a to z
Digits 0 to 9
Underscore _ shift key with minus key in the keyboard

9
IDENTIFIERS
Rules to form and Identifier
First character must be an alphabet or an underscore

Can consist of alphabets, digits and underscore

C++ is case sensitive language


Some of the predefined identifiers are cout and cin.
Unlike reserved words, pre-defined identifiers may be redefined, but it
would not be wise to do so.

Valid Identifiers Invalid Identifiers

A _a a123
ABcDf99_ sum average 1a_a a+2 a$1
Mark1 Mark_2 xy_1_4
Abc -abc aa.bb
Sum_of_values avg_plus_sum
A abc a9!c
these are not the same
Why they are invalid ?.
Aa aa aA AA aa
10
KEYWORDS
Keywords are words (like identifiers) that have a special meaning to
the compiler and cannot be used in your programs for other
purposes.

auto do goto signed unsigned


break double if sizeof void
case else int static volatile
char enum long struct while
continue extern register switch
default float return typedef
for short union const

11
DATA TYPE
A set of values together with a set of operations is called a data
type.

C++ data types fall into three categories


Simple Data Type.

Structured Data Type. C++s Data Types

Pointers.

Simple Structured Pointers

Integral Floating-Point Enumeration


SIMPLE DATA TYPE

C++ simple data can be classified into three categories


1. Integer, which is a data type that deals with integers, or
numbers without a decimal part.
2. Floating-point, which is a data type that deals with decimal
numbers.
3. Enumeration type, which is a user-defined data type.

Simple Data Type

Integer Floating-Point Enumeration


THE INT DATA TYPE
The type defines the size of the field in
which data can be stored
-6728, -67, 0, +78, 36782, ...

Positive integers do not have to have a +


sign in front of them.
No commas are used within an integer.
In C++ commas are reserved for
separating items in a list. So 36,782
would be interpreted as two integers 36
and 782.
C++ language supports three different
types of integer data type.

short int Int 2 long int


2 bytes or 4 bytes 4 bytes

14
INTEGERS TYPES AND RANGES
Type Sign Byte No. of Minimum value Maximum value
Size Bits
Signed -32768 32767
short int 2 16
Unsigned 0 65535
int Signed -32768 32767
2 16
16 bits Unsigned 0 65535
int Signed -2147483648 2147483647
4 32
32 bits Unsigned 0 4294967295

Signed 4 32 -2147483648 2147483647


long int 6 48
unsigned 8 64 0 4294967295
322 = 4294967296 162 = 65536
15
THE BOOL DATA TYPE
The data type bool has two values, true and false. The
central purpose of this data type is to manipulate logical
(Boolean) expressions.

We call true and false the logical (Boolean) values.

In C++, bool, true, and false are reserved words.

16
FLOATING POINT DATA TYPES
Floating point number is a number with a
Real Number C++ Floating
fraction part Point-Notation
Example for a floating point number is 75.924 7.592400E1
45.356
0.18 1.800000E-1
The C language supports three different
data types of floating point 0.0000453 4.530000E-5
-1.482 -1.482000E0
Float
7800.0 7.800000E3
Double
Long double

Type Byte No. of examples


Size bits
float 4 32 4.1f, -11.0003f, 89.00f
double 8 64 4.1, 55.78338882, 0.
Long double 10 80 3.14159626536L , 5.0L
THE CHAR DATA TYPE
To the computer, a character is any value that can be represented in the
computers alphabets
Most computers use American Standard Code for Information Interchange
(ASCII) as computer alphabets
A character requires one byte for the representations (28=256 characters,
extended ASCII table shown next slide)
Characters are stored in memory as numbers (ASCII number)

Valid character literals (ASCII values) Invalid character literals


A=65,B=66,C=67, a a
a=97,b=98,c=99, ab a11111
0=48,1=49,2=50, Why ?

18
THE CHAR DATA TYPE
Character constants are enclosed
between two single quotes 'a'
ASCII char Symbolic
Name
Some of the values belonging to Null character \0
char data type are:
Alert (bell) \a
'A', '0', '+', '$', '&'
Backspace \b
Horizontal tab \t
Blank space is a character and is
New line \n
written ' ', with a space left
between the single quotes. Vertical tab \v
Form feed \f
In addition to the character there Carriage return \r
can be a \ Single quote \
The \ is known as the escape Double quote \
character and used when the backslash \\
character cannot be printed (the
first 32 characters of the ASCII table
are not printable)
19
THE STRING TYPE
The data type string is a programmer-defined type and is not part of the C++
language. The C++ standard library supplies it.
A string is a sequence of zero or more characters.
Strings in C++ are enclosed in double quote marks.
A string with no characters is called a null or empty string.

Null or empty string

Valid string constants Invalid string constants


mary Use single quotes
mary hgshd hfd h jsdjasdhajdk for character
constants and
Hello world\n Double quotes for
How are you John? How to fix the problem? strings
I have #1 pc costs 15$
.
\n\t\r\r\r\t\thi *&^%$%$###
VARIABLES
Variables are named memory locations that have a type (int, float, double,
char, string)
Variables dont have fixed values throughout the program
In C++ language there are a set of operations to change and manipulate the
value stored in these variables
Every variable used in the program must be declared before its use
Declaration in C is used to name an object and decide a type for that object
Declaration of variable in C assigns a name and a sufficient memory is
allocated and associated with the variable based on its type
Variable names are valid identifiers and cannot be the same as any of the
reserved words (keywords)

21
DECLARING

VARIABLES
The following Syntax diagram shows how The following are valid
to declare a variable: declaration statements

One variable Multiple


Data type Identifier ; variable
int sum; int m1,m2;
double d1; int mark,
, float average; avg;
char ch1; float a,b,c;
char c; float a,
Every declaration statement must end char _char; b,
with a semicolon char a_1; c,
d;
double d1,
The syntax for declaring one variable is d2;

dataType identifier;

The syntax for declaring multiple variables is


dataType identifier, identifier, . . .;
22
VARIABLE INITIALIZATION
When variables are created there is a need to assign them initial values
In order to do that an assignment operator is used (=)
The following syntax diagram shows the syntax of a modified declaration of
a variable including the initialization process

= Literal

type identifier ;

int sum = 0 ;
23
EXAMPLES OF VARIABLE DECLARATION AND
INITIALIZATION
int a = 10, b, c = 20; char a = a,b = 65;

a is an integer variable with a is character variable with


initial value equal to 10, b is an initial value equal to a.
integer variable, c is an integer b is a character variable
variable with initial value equal with initial value equal to
to 20. 65 or A .
ASCII code of A is equal
float f = 10.0f,
to 65
g = 9.81f ;
Variables of char data type
f is a float variable with
can be assigned and
initial value equal to 10.0
initialized to integer values
and g is a float variable
between 0 and 255 only
with initial value equal to
and any character literal
9.81.
24
INPUT AND OUTPUT FUNCTIONS IN C++
LANGUAGE
C++ uses two functions for formatted input/output
cin reads data from the keyboard and stores it to a buffer
cout prints out data to the monitor
Keyboard is known as the standard input device (stdin).
The monitor is known also as the standard output device (stdout)

cin>>

cout<<

25
INPUT (READ) STATEMENT: CIN
Syntax of cin together with >>:

cin>>variable>>variable. . .;

In C++, >> is called the extraction operator.

Suppose miles is a variable of the type double.


The statement
cin>>miles;
causes the computer to get a value of the type double and
place it in the memory cell miles.

26
INPUT (READ) STATEMENT: CIN
By using more than one variable in cin, more than one value
can be read at a time.

Suppose feet and inch are variables of the type int. A


statement like
cin>>feet>>inch;

gets two integers (entered at the keyboard) and places them in


the memory location feet and inch, respectively.

27
OUTPUT : COUT
The syntax of cout together with << is
cout<<expression or manipulator<<expression or manipulator...;

In C++, << is called the insertion operator.


expression is evaluated and its value is printed at the
current cursor position on the screen.
manipulator manipulates the output. The simplest
manipulator is endl (the last character is the letter el),
which causes the cursor to move to the beginning of the next
line.
Strings and expressions involving only one variable or a single
value are evaluated to itself.

28
OUTPUT : COUT
Statement Output
1. cout<<29/4; 7
2. cout<<"Hello there. "; Hello there.
3. cout<<12; 12
4. cout<<"4+7"; 4+7
5. cout<<4+7; 11
6. cout<<"A"; A
7. cout<<"4 + 7 = "<<4 + 7; 4 + 7 = 11
8. cout<<2+3*5; 17
9. cout<<"Hello \nthere. "; Hello
there.
\n is called new line escape sequence.
\ (back slash) is called the escape character.

29
NEW LINE CHARACTER
The new line character, '\n'.
cout<<"Hello there.";
cout<<It is sunny day.";
Output
Hello there.It is sunny day.

Now consider the following C++ statements.


cout<<"Hello there.\n";
cout<<"It is sunny day.";
Output
Hello there.
It is sunny day.

30
ESCAPE SEQUENCES
The following statement is illegal in C++.

cout<<"It is sunny, warm, and not a windy day.


Let us go golfing."<<endl;

The return (or Enter) key on your keyboard cannot be part of the string.

Commonly Used Escape Sequences


31
ESCAPE SEQUENCES

Statement 1
cout<<"The new line \\n"<<endl;
Output 1
The new line \n

Statement 2
cout<<"The tab character \'\\t\'"<<endl;
Output 2
The tab character '\t'

Statement 3
cout<<"The string \"Sunny\" contains 5 characters\n";
Output 3
The string "Sunny" contains 5 characters

32
PROMPT LINES
cout<<"Please enter a number between 1 and 10 and"
<<" press ENTER"<<endl;
cin>>num;

When these two statements execute in the order given, first the cout statement causes
the following line of text to appear on the screen:

Please enter a number between 1 and 10 and press ENTER

After seeing this line, users know that they must enter a number and press the return
key.

33

Das könnte Ihnen auch gefallen