Chapter 2. C++ Program Structure C++ program is a collection of subprograms Subprograms in C++ are...

Preview:

Citation preview

Chapter 2

C++ Program Structure

• C++ program is a collection of subprograms

• Subprograms in C++ are called FUNCTIONS

• Each function performs a specific task

Main Function

• Every C++ program must have a function name main.

• Main is the master function.

• Main calls (or invokes) other functions.

• When main calls another function control is given over to that function.

• When that function executes control is returned to main.

Sample Program#include <iostream>

using namespace std;

int Square ( int);int Cube (int);

int main(){

cout<<“The square of 27 is “ << Square (27)<<endl;cout<<“The cube of 27 is “ << Cube (27) << endl;

}

int Square (int n){

return n * n;}

int Cube (int n){

return n*n*n;}

Syntax

• The formal rules governing how valid instructions are written in a programming language.

• Syntax is grammar of how we combine letter, numbers and symbols in a programming language.

• Syntax rules are the building blocks of programming.

Semantics

• The set of rules that determines the meaning of instructions written in a programming language.

Metalanguage

• A language that is used to write the syntax rules for another language.

• Oldest Metalanguage: Backus-Naur Form (BNF)

• Example: identifier in C++ must be at least one letter or underscore which may or may not be followed by additional letters,underscores, or digits.– <identifier>::= <NondigitOrDigitSequence>– <NondigitOrDigit>::= <Nondigit>|<Digit>

<Digit>::= 0|1|2|3|4|5|6|7|8|9

Syntax Templates

• Our book uses syntax templates to demonstrate syntax rules.

• Syntax Templates are generic examples of C++ constructs.– Boldface word or symbol is a literal word or

symbol– Nonboldface word can be replaced by another

template.

Template Example

• Identifier • Shading means optional• Three dots {…} means

preceding symbol or shaded block may be repeated.

• Identifier must begin with a letter or underscore and is optionally followed by one or more letters, underscores, or digits.

• Nonboldface can be replaced with another template

Letter Letter …

_

_ Digit{ {

Main Template

• MainFunction • First line is the function header

• Left { indicates the beginning of the function

• Right } indicates the end of the function

• Shading and … means the body of the function may contain zero to many statements

int main (){

Statements . . .}

Main Function

• When the function header contains int it must return an integer value.

int main(){

return 0;}

Identifiers

• A name associated with a function or data object and used to refer to that function or data object.

• Made up of letters, digits and the underscore• RULE1: Identifiers must begin with a letter or

underscore.• RULE2: Identifiers may not contain spaces or

special characters• RULE3: Identifiers may not use reserved words• RULE4: C++ is case sensitive so be consistent.

Data and Data Types

• Data is the symbols that represent people, places, ideals, etc. that is stored in memory and used to produce output.

• In C++ all data must be data typed

Data Type

• A specific set of data values along with a set of operations on those values.

• Determines:– how the data is represented in the computer.– what processes can be performed on the data.

• Some data types are defined by C++ while others are user-defined.– C++ defined

• int• float• char

Memory

• Memory is divided into separate cells• Each Cell holds a piece of data.• Each cell has a unique address• C++ uses identifiers to name cells to hold data• The compiler translates the name into binary addresses.

100 101 102 103 104

105 106 107 108 109

110 111 112 113 114

115 116 117 118 120

Data Types and Memory Cells

• Data typing restricts what data can be put inside a memory cell and what processes can be done on it.

Data Types

• int – only allows integer values

• float – only allows decimal or floating point values

• char – only allows character values

• string – only allows string values

char

• C++ built in data type

• One alphanumeric character – a letter, a digit or a special symbol

• ‘A’, ‘a’, ‘2’, ‘+’,’$’

• characters are enclosed in single quotes

• ‘8’ is not 8

• Characters are represented in machine language differently than integer values.

string

• User defined data type.• Stored in the C++ standard library.• A sequence of characters i.e. word, name or

sentence• “C++”, “Problem Solving”, “My Name is”• Enclosed in double quotes• Do not split across lines.

– “my name is cynthia Jensen”

• “” is the null string but will not give you a string of blank characters.

int

• Integral or integer type

• Whole numbers no fractions

• 1 25 14 6 9 41 100

• -25 -78

float

• Floating-point data type

• Represents real numbers

• 18.0, 4., 1.8798,

DECLARATIONS

• Declaration: A statement that associates an identifier with a data object, a function, or a data type so that the programmer can refer to that item by name.

• Tells the computer to set aside a memory cell

• Names the memory cell

• Data types the memory cell

Variable

• A memory cell that has been:

• Named (identifier)

• Data typed (int, float, char, string)

• Data it hold can be changed

Declaring a Variable

int main(){

int num;string FirstName;char MiddleInitial;float PayRate;string First, Last, City;...

}

Constants

• Two types of constants in C++:– Literal value: any constant value written in a

program– Named Constant: A memory cell that has

been named and data typed but whose contents may NOT change

Literal Constant

• Any things enclosed in single quotes ‘a’ or double quotes “Hello”.

• cout<<“My name is”;

Named Constant

• Memory cell that has been named and data typed but whose contents cannot be changed.

• Declaring a constant:

#include <iostream>#include <stringusing namespace std;

const string FIRSTNAME = “Donald”

int main(){

Assignment Statement

• Assignment statements assign an initial value to a variable or constant.

• Assignment statements assign a new value to a variable.

• The assignment operator is the =– int num = 0; – num = 8;– num = num1;

Variable Assignment Statement

Variables may be assigned an initial value at declaration– int num1 = 8;– float payrate = 7.50;– string name = “Duncan”;– char middleinitial = ‘A’;

• Variables may have their contents changed with an assignment statement inside the body of the program.– payrate = 7.75;– name = “Joe”;– middleinitial = ‘B’;– Name = name;

Constant Assignment

• Constants must be assigned a value and it may NOT be changed after the initial assignment.– const string FIRSTNAME = “Mary”;

Expressions

• An arrangement of identifiers, literals and operators that can be evaluated to compute a value of a given type.

– Num = num1 + num2;– Fullname = firstname + lastname;– Fullname = firstname + ‘ ‘+ last name;

Mathematical Expression

• Math Expression is not the same as a math equation.

• Right hand of assignment operator (=) is evaluated.

• Result is stored in the variable to left of the =– Num = num1 + num2;– Sum = num1 + num2;– Product = num1 * num2;– Diff = num1-num2;

String Expressions

• Concatenation – uses the + to join to strings into 1 (NOT MATH)

• Can be used with string constants, literals, variables and character data.– string firstname = “Charles”;– string lastname = “Smith”;– char middleinitial = “G” – string Fullname;– Fullname = firstname + lastname;

• Fullname now contains CharlesSmith

– Fullname = firstname + ‘ ‘ + middleinitial +‘. ‘+’ ‘ + lastname;• Fullname now contains Charles G. Smith

COUT

• Used in an output statement.• Special variable declared in the iostream library

file.• Used along with an insertion operator.<<• cout<<variableidentifier<<constantidentifier<<“lit

eral”;– cout<<“hi there”;– cout<<‘c’;– cout<<FIRSTNAME;– cout<<num;– cout<<FIRSTNAME<<LASTNAME<<endl;

Program Construction

• Comments• Preprocessor Directives• Using Directive• Global declaration area• Main function header• Local declaration area• Body of function• Return statement

Comments

• Every Program begins with a comment block:

//Your Name

//Due Date

//Problem Description

Preprocessor Directives

• #include is a preprocessor directive• Preprocessor is a filter• <iostream> is a header file• Header files contain constants, variables, data

types and functions needed by the program.• Preprocessor physically inserts the contents of

the header file into your program. These can be very large– #include <iostream>– #include <string>

Using Directive

• Allows us to use cout, endl and other variables without fully qualifying them.

• Without the using directive:– std::cout<<“HI”; :: called a scope resolution

operator

• With using directive:– cout<<“Hi”;

Global Declaration Area

• Global Variables and Constants are available to any function in your program.

• Declaration: identifying and data typing a memory cell.– int num;

• Assignment: variables may be assigned an initial value; constants must be assigned an initial value;– int num = 0;– const string FIRSTNAME = “Sue”;

Main Function Header

• C++ may contain many functions but it must contain a main function

int main ()

{

Local Declaration Area

• Just after the opening { of any function is the local declaration area.

• Declarations made in the local area are available to only the local function.– int main ()

{

int num = 0;

Body of Function

• The body of the function is where statements and expressions are handled.int main(){

string name;cout<<“Please enter your name”;cin>>name;return 0;

}

Return Statement

• Return statement returns a value to the calling function.

• int main returns an integer value to the operating system indicating a successful execution.– 0 successful execution– 1 stops execution

• Called an exit status

//Your Name

//Due Date

//Problem Description

#include <iostream>

#include <string>

using namespace std;

const string FIRSTNAME = “sue”;

int main ()

{

string lastname;

cout<<“Please enter your lastname:”<<endl;

cin>>lastname;

cout<<FIRSTNAME<<lastname<<endl;

return 0;

}

OUTPUT FORMATTING

• Use endl to create vertical spacing.– cout<<“Hi there”<<endl;– cout<<endl<<endl;

• Use \n inside literals to create vertical spacing.– cout<<“Hi there \n”;

• Use spaces to create horizontal spacing.– cout << “Hi “;

• Use \t inside literals to tab across line– Cout<<“\t \t \t Hi”;

Recommended