540 likes | 607 Views
C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 2: Basic Elements of C++. Objectives. In this chapter, you will: Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers Explore simple data types
E N D
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++ Slides borrowed from Instructor: Wajih Alouini
Objectives In this chapter, you will: • Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers • Explore simple data types • Discover how to use arithmetic operators • Examine how a program evaluates arithmetic expressions
Objectives (continued) • Learn what an assignment statement is and what it does • Become familiar with the string data type • Become familiar with the use of increment and decrement operators
What Is a Program Made Of? • Common elements in programming languages: • Keywords • Programmer-Defined Identifiers • Operators • Punctuation • Syntax Slide 1- 4
The Basics of a C++ Program • Function: collection of statements; when executed, accomplishes something • May be predefined or standard • Syntax: The rules of grammar that must be followed when writing a program (keywords, operators, symbols, and punctuation) • Programming language: a set of rules, symbols, and special words • Semantic rule: meaning of the instruction
Structure of a C program Statement = Command or instruction
preprocessor directive which namespace to use beginning of function named main beginning of block for main output statement string literal end of block for main send 0 to operating system Parts of a C++ Program comment // sample C++ program #include <iostream> using namespace std; int main() { cout << "Hello, there!"; return 0; }
Comments • Comment is a statement that is not executed. • This helps reader and also yourself to understand your codes and document parts of the program. • Two types: • Single line // This is a C++ program. It prints the sentence: // Welcome to C++ Programming. • Multiple line /* You can include comments that can occupy several lines. */
Special Symbols • Special symbols + - * / . ; • ? • , • <= • != • == • >=
Punctuation • Characters that mark the end of a statement, or that separate items in a list • Example: , and ;
Reserved Words (Keywords) • Have a special meaning in C++ • Can not be used for any other purpose • Include: int, float, double, char, const, void, return, main, etc.
Identifiers • Names made up by the programmer • Not part of the C++ language • Used to represent various things: variables (memory locations), functions, etc.
Naming Identifiers • Identifiers can be self-documenting: • CENTIMETERS_PER_INCH • Avoid run-together words : • annualsale • Solution: • Capitalize the beginning of each new word • annualSale • Inserting an underscore just before a new word • annual_sale
Identifiers (cont) • Cannot duplicate a reserved word • Consist only of letters, digits, or the underscore character (_) • First character must be alphabetic character or underscore • C++ is case sensitive • NUMBER is not the same as number • Two predefined identifiers are cout and cin
Identifiers (cont) • The following are legal identifiers in C++: • first • conversion • payRate
Identifiers (cont) • Valid OR Invalid ? • A • $a • Student8 • 3name • student_name • person name • _person_name • int • TRUE • what? • FALSE
Whitespaces • Every C++ program contains whitespaces • Include blanks, tabs, and newline characters • Used to separate special symbols, reserved words, and identifiers • Proper utilization of whitespaces is important • Can be used to make the program readable
Arithmetic Operators and Operator Precedence • C++ arithmetic operators used for performing numeric calculations : • + addition • - subtraction • * multiplication • / division • % modulus operator • +, -, *, and / can be used with integral and floating-point data types
Binary Arithmetic Operators • C++ has unary, binary, and ternary operators: • unary (1 operand) -5 • binary (2 operands) 13 - 7 • ternary (3 operands) exp1 ? exp2 : exp3 1-19
Scope • The scope of a variable: the part of the program in which the variable can be accessed • A variable cannot be used before it is defined
A Closer Look at the / Operator • / (division) operator performs integer division if both operands are integers cout << 13 / 5; // displays 2 cout << 91 / 7; // displays 13 • If either operand is floating point, the result is floating point cout << 13 / 5.0; // displays 2.6 cout << 91.0 / 7; // displays 13.0
A Closer Look at the % Operator • % (modulus) operator computes the remainder resulting from integer division cout << 13 % 5; // displays 3 • % requires integers for both operands cout << 13 % 5.0; // error
Order of Precedence • All operations inside of () are evaluated first • *, /, and % are at the same level of precedence and are evaluated next • + and – have the same level of precedence and are evaluated last • When operators are on the same level • Performed from left to right (associativity) • 3 * 7 - 6 + 2 * 5 / 4 + 6 means (((3 * 7) – 6) + ((2 * 5) / 4 )) + 6
Expressions • If all operands are integers • Expression is called an integral expression • Yields an integral result • Example: 2 + 3 * 5 • If all operands are floating-point • Expression is called a floating-point expression • Yields a floating-point result • Example: 12.8 * 17.5 - 34.50
Mixed Expressions • Mixed expression: • Has operands of different data types • Contains integers and floating-point • Examples of mixed expressions: 2 + 3.5 6 / 4 + 3.9 5.4 * 2 – 13.6 + 18 / 2
Mixed Expressions (continued) • Evaluation rules: • If operator has same types of operands • Evaluated according to the type of the operands • If operator has both types of operands • Integer is changed to floating-point • Operator is evaluated • Result is floating-point • Entire expression is evaluated according to precedence rules
string Type • Programmer-defined type supplied in ANSI/ISO Standard C++ library • A series of zero or more characters in consecutive memory locations: "Hello" • Stored with the null terminator, \0, at the end • Enclosed in double quotation marks • Null: a string with no characters • Each character has relative position in string • Position of first character is 0
Input • Data must be loaded into main memory before it can be manipulated • Storing data in memory is a two-step process: • Instruct computer to allocate memory • Include statements to put data into memory
Allocating Memory with Constants and Variables • Named constant: memory location whose content can’t change during execution • The syntax to declare a named constant is: • In C++, const is a reserved word
Allocating Memory with Constants and Variables (continued) • Constant = named memory location that holds a non-changeable value • Must be declared • A variable name should represent the purpose of the variable. • Re-usable • MUST be initialized • Can not be modified after initialization int main () { const double pi = 3.14; double area, radius; radius = 12; area = pi * radius * radius; pi = 3.14159; /* but, this is wrong */ return 0; }
Allocating Memory with Constants and Variables • Variable: memory named storage location in the computer’s memory for holding a piece of data whose content may change during execution • The syntax to declare a named constant is:
Allocating Memory with Constants and Variables (continued) • In order to use a variable in our program we must first declare it. • HOW? • A declaration statement has the format: type variable_name; • type : what kind of data will be stored in that location (integer? character? floating point?) • variable_name : what is the name of the variable? • semi-colon : indicates this is a statement!
Variable types • There are four basic data types in C Type Integer Floating point Character C keyword to use: int float double char
Variable types • int • Integer variables hold signed whole numbers (i.e. with no fractional part), such as 10, – 4353, etc. • Integers typically take up 4 bytes ( = 32 bits, 1 for the sign, 31 for the number). • The range of integers is typically • from – 231 (approx –109) to + 231 (approx. 109)
Variable types • float and double • floating point variables hold signed floating point numbers (i.e. with a fractional part), such as 10.432, – 33.335, etc. • double provides twice the precision of float. • floats typically take up 4 bytes • doubles take up 8 bytes • The range of floats is approximately ±2127 (±1038) • The range of doubles is approximately ±21023 (±10308)
Variable types • char • character variables hold single characters, such as 'a', '\n', ' ', etc. • characters usually take 1 byte (8 bits). • IMPORTANT : Note that the value of a character is enclosed in single quotes.
Variable types • char(continued) • ASCII (American Standard Code for Information Exchange) is used to represent • the characters A to Z (both upper and lower case) • the digits 0 to 9 • special characters (e.g. @, <, etc) • special control codes • For example, • the character 'A' is represented by the code 65 • the character '1' is represented by the code 49
Variable values • After a variable has been declared, its memory location does not contain valid data. • Variables can be initialized when declared: • All variables must be initialized before they are used in any computations. • But not necessarily during declaration • There are two ways to initialize a variable: • by assigning a value using an assignment statement • by reading its value from the keyboard
Variable values Variable Initialization • To initialize a variable means to assign it a value when it is defined: int length = 12; • Can initialize some or all variables: int length = 12, width = 5, area;
Variable values • The basic syntax of an assignment statement is • variable = value; • Example • Assign the value on the right hand side to the variable on the left hand side • Expression is evaluated and its value is assigned to the variable on the left side • In C++, = is called the assignment operator int num_students; // declare num_students = 22; // initialize
Literals • Literals are fixed values written into a program. • Not declared, no memory location assigned • Not re-usable; just written directly into each statement • Example: char keypressed; keypressed = ‘y’; /* ‘y’ is a character literal */ • Example: double pi; pi = 3.14; /* 3.14 is a floating-point literal. */ • Example: int index; index = 17; /* 17 is an integer literal */
Example /* sample program that demonstrates variable declaration and initialization. */ #include <stdio.h> int main () { int num_students; num_students = 22; return 0; }
Example /* sample program that demonstrates variable declaration and initialization. */ #include <stdio.h> int main () { double rate, amount; /* declare two double variables */ amount = 12.50; rate = 0.05; return 0; }
Example /* sample program that demonstrates how to declare and initialize a variable at the same time */ #include <stdio.h> int main () { char grade = ‘A’; return 0; }
Example /* sample program that demonstrates how to declare and initialize a variable at the same time */ #include <stdio.h> int main () { char pass_grade = ‘A’, fail_grade = ‘F’; return 0; }
Increment & Decrement Operators • Increment operator: increment variable by 1 • Pre-increment: ++variable • Post-increment: variable++ • Decrement operator: decrement variable by 1 • Pre-decrement: --variable • Post-decrement: variable — — • What is the difference between the following? x = 5; y = ++x; x = 5; y = x++;
Increment & Decrement Operators (Continued) • postincrement operator • n++; can be used instead of n = n + 1; • postdecrement operator • n--; can be used instead of n = n - 1; • preincrement operator • ++n; can be used instead of n = n + 1; • predecrement operator • --n; can be used instead of n = n - 1;
Increment & Decrement Operators (Continued) • n++;++n and n--;--n are not equivalent in all cases • These operators as well as incrementing or decrementing the variable also return a value. i = n++; • Value of i ? Is it the oldvalue of n before it is incremented or the newvalue after it is incremented?
Increment & Decrement Operators (Continued) • Rule : • postincrement or postdecrement operator delivers the old value of the variable before incrementing or decrementing the variable. • A preincrement or predecrement operator carries out the incrementation first and then delivers the new value. • n = 5 ; i = n++; Give 5 to i and 6 to n • n = 5 ; i = ++n; Give 6 to i and 6 to n.