Sunteți pe pagina 1din 34

Lecture Outline

• Fundamentals of C++
• Structure of C++ Program C++
• Data types
• Variables
• Escape Sequences
• I/O Statements (cin/cout)
Structure of a C++ Program

Opening brace

Closing brace

Opening brace

Closing brace
Preprocessor Directives
• A libraries that contain /* A program to print the string
functions and symbols that are Welcome to C++ to the screen
necessary to run a C++ */
program. #include <iostream>
• Every library has a name and is
int main()
referred as a header file. {
• All preprocessor commands /* print out the message */
cout<<"Welcome to C++"<<endl;
begin with #. return 0;
• In Standard C++, header files }

have the file extension .h


• There is no semicolon at the
end of these commands.
#include <headerFileName>
• The general syntax to include a
header file
#include <iostream.h>
Preprocessor Directives
• Another option to use to perform
I/O in a program: /* A program to print the string
Welcome to C++ to the screen
#include <iostream> */
equivalent
#include <iostream>
#include <iostream.h> using namespace std;

• To use the string data type in a


program, your must include the int main()
following preprocessor directive:
{
#include <string> /* print out the message */
cout<<"Welcome to C++"<<endl;
• The descriptions of some very return 0;
useful mathematics functions such }
as power, absolute, sine, etc., are
contained in the header file
cmath.
#include <cmath>
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 main equivalent It is not necessary to put word
returns a value of the type int the void in parentheses, but
and it has no arguments. the parentheses are still
needed.
The Program Part: Body of the
function
int main()
• The body of the function is enclosed
between { and } and has two types of {
statements. /* assignment statements */
• Declaration Statements int a = 10;
int b = 2;
int a, b, c;
int c;
double x, y;
int sum;
Variables (or identifies) can be
declared anywhere in the program,
/* print out the message */
but they must be declared before
they can be used. cout<<"Welcome to C++"<<endl;

// input statement
• Executable Statements
cin>>c;
a = 10; sum=a+b+c;
//assignment statement
cin>>c; /* output statement */
//input statement cout<<sum<<endl;
cout<<a+b+c<<endl;
//output statement return 0;
}
Comments
• Multiple line comments are /* A program to print the string
Welcome to C++ to the screen */
enclosed between /* and */
#include <iostream>
• Single line comments begin using namespace std;
with // int main()
• Statements that have no {
effect on the execution of // print out the message
the program cout<<"Welcome to C++"<<endl;

• The Compiler neglects these


return 0;
comments when translating
}
the program to machine
Output:
code Welcome to C++ Programming
• Comments can be place
before each of the functions
and inside the function
The Hello World Program
Indicates the beginning of the
functions body  < iostream> is included
in this program because it
#include <iostream> provides information to the
using namespace std; compiler about cout
int main (void) function
{
cout<<“hello world\n”; Block
 cout is a function from a
return 0; standard library that prints
} on the screen

End of function’s 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
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.
Token
• The smallest individual unit of a program written in any language is called a
token.

• A token is the basic vocabulary of the language.

• Tokens in C++
– keywords
– identifiers
– constants
– string constants
– operators
– punctuators

• Language syntax specifies the valid combinations of tokens in the language into
legal strings.
Token types
• Identifiers
main, payRate, score_1, conversion

• Operators
+ - * / ( )

• Keywords
int, float, double, char, void, return

• Punctuators
. ; ? , {

• Others
<= != == >=

• Comments are not tokens (remember they are removed from the program)
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 don’t have to deal directly with these addresses
• 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”
Identifiers A Syntax diagram of the identifier
• Rules to form and Identifier
– First character must be an Letter
alphabet or an underscore
Letter digit
– Can consist of alphabets, digits and
underscore underscore 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
A”bc -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
Keywords (reserve words)
• 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
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.
C++’s Data Types
– Structured Data Type.
– Pointers.
Simple Structured Pointers

Integral Floating-Point Enumeration


Simple Data Type
• C++ simple data can be classified into three categories
1. Integral, 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

Integral 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, ...
• C++ language supports three different types
of integer data type.

short int Int 2 long int


2 bytes or 4 bytes 4 bytes

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.

 In C++, bool, true, and false are reserved


words.
Floating – Point Data Types
float: The data type float is used in C++ to represent any real number
between -3.4E+38 and 3.4E+38.The memory allocated for the float data
type is 4 bytes.
double: The data type double is used in C++ to represent any real number
between -1.7E+308 and 1.7E+308.The memory allocated for the double
data type is 8 bytes.

• On most newer compilers, the data types double and long double are
the same.
• The maximum number of significant digits—that is, the number of decimal
places—in float values is 6 or 7 and double is 15.

Floating-Point Data Type

float double long double


The char Data Type
• To the computer, a character is any value that can be represented in the
computer’s 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 ?
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 for
“mary” “ hgshd hfd h” jsdjasdhajdk” character constants
and Double quotes
“Hello world\n” for strings
“How are you John?” How to fix the problem?
“I have #1 pc costs 15$”
“……………….”
“\n\t\r\r\r\t\thi *&^%$%$###”
Constants and Variables
• Storing data in the computer’s memory is a two step process.
• Instruct the computer to allocate memory.
• Include statements in the program to put data into the
allocated memory.

• Allocating Memory with Constants and Variables


– Named Constant: A memory location whose content is not
allowed to change during program execution.
– Variable: A memory location whose content may change during
program execution.
Named Constant
• The syntax to declare a named constant is

const dataType identifier = value;

const double conversion = 2.54;


• This mean that conversion has a value of 2.54 and cannot be changed
throughout the program execution.
• In C++, const is a reserved word.

int main ()
{
const int noOfStudents = 20;
const char blank = ' ';
const double payRate = 15.75;
return 0;
}
Variables
• Variables don’t have fixed values
throughout the program dataType identifier;
• In C++ language there are a set of
operations to change and
manipulate the value stored in int conversion = 2.54;
these variables
• Every variable used in the program
must be declared before its use = Literal
• Variable names are valid identifiers
and cannot be the same as any of
the reserved words (keywords) type identifier ;

• When variables are created there is ,


a need to assign them initial values
• In order to do that an assignment
operator is used (=)
int sum =
0;
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<<…
Input (Read) Statement: cin Output : cout
• Syntax of cin together with • The syntax of cout together with <<
>>: is
cin>>variable; cout<< variable;

• In C++, << is called the insertion


• In C++, >> is called the operator.
• expression is evaluated and its
extraction operator. value is printed at the current
Suppose miles is a variable cursor position on the screen.
of the type double. • manipulator manipulates the
output. The simplest manipulator is
The statement endl (the last character is the letter
cin>>miles; el), which causes the cursor to
move to the beginning of the next
line.
causes the computer to get a
• Strings and expressions involving
value of the type double and only one variable or a single value
place it in the memory cell are evaluated to itself.
miles.
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.
Use of Blanks, Semicolons, Brackets And Commas
• In C++, one or more blanks are used to separate numbers when data is input.
• Blanks are also used to separate reserved words and identifiers from each other
and other symbols.

int a,b,c;
int a, b, c;
The blanks between the identifiers in the second statement
are meaningless.

inta,b,c;
no blank between the t and a changes the reserved word
int and the identifier a into a new identifier inta.

• Commas are used to separate items in a list.


• All C++ statements terminate with a semicolon  statement terminator
• Brackets{ and } are not C++ statements.
Naming Identifiers
const double a = 2.54; //conversion constant
double x; //variable to hold centimeters
double y; //variable to hold inches

x = y * a;
Consider the following
const double conversion = 2.54;
double centimeters;
double inches;

centimeters = inches * conversion;

• Run-together-word
inchperfoot inchPerFoot inch_per_foot.
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.
Escape Sequence
• Escape sequences are used to
represent certain special Escape
Description
sequence
characters within string
\' single quote
literals and character literals.
\" double quote
\? question mark
\\ backslash
\a audible bell
\b backspace
\n line feed - new line
\r carriage return
\t horizontal tab
More about cout
• precision (int) sets the number of significant digits of
float type numbers

float y = 23.1415;
cout.precision(1);
cout << y << '\n'; // Outputs 2e+01
cout.precision(2);
cout << y << '\n'; // Outputs 23
cout.precision(3);
cout << y << '\n'; // Outputs 23.1
Summary
• The body of the function is enclosed between { and } and has two types of
statements.
• Statements enclosed in // have no effect on the execution of the program.
• Identifiers allow us to name variables, constant names, functions and objects in the
program.
• C++ data types fall into three categories: Simple Data Type. ,Structured Data Type.,
Pointers
• Named Constant: A memory location whose content is not allowed to change
during program execution.
• Variable: A memory location whose content may change during program
execution.
• cin reads data from the keyboard and stores it to a buffer
• cout prints out data to the monitor
• In C++, >> is called the extraction operator
• In C++, << is called the insertion operator

33

S-ar putea să vă placă și