Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 2: Basic Elements of C++

Similar presentations


Presentation on theme: "Chapter 2: Basic Elements of C++"— Presentation transcript:

1 Chapter 2: Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++ Slides borrowed from Instructor: Wajih Alouini

2 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

3 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

4 What Is a Program Made Of?
Common elements in programming languages: Keywords Programmer-Defined Identifiers Operators Punctuation Syntax Slide 1- 4

5 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

6 Structure of a C program
Statement = Command or instruction

7 Parts of a C++ Program // sample C++ program #include <iostream>
comment // sample C++ program #include <iostream> using namespace std; int main() { cout << "Hello, there!"; return 0; } preprocessor directive which namespace to use beginning of function named main beginning of block for main output statement - Return 0 means program has executed main function (int ) successfully string literal send 0 to operating system end of block for main

8 Comments Single line Multiple line
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. */

9 Special Symbols Special symbols + - * / . ; ? , <= != == >=

10 Punctuation Characters that mark the end of a statement, or that separate items in a list Example: , and ;

11 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.

12 Identifiers Names made up by the programmer
Not part of the C++ language Used to represent various things: variables (memory locations), functions, etc. - How to write identifiers

13 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

14 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

15 Identifiers (cont) The following are legal identifiers in C++: first
conversion payRate

16 Identifiers (cont) Valid OR Invalid ? A $a Student8 3name student_name
person name _person_name int TRUE what? FALSE

17 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

18 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 - integral: no decimal part

19 Binary Arithmetic Operators
C++ has unary, binary, and ternary operators: unary (1 operand) binary (2 operands) ternary (3 operands) exp1 ? exp2 : exp3 SYMBOL OPERATION EXAMPLE VALUE OF ans + addition ans = 7 + 3; 10 - subtraction ans = 7 - 3; 4 * multiplication ans = 7 * 3; 21 / division ans = 7 / 3; 2 % modulus ans = 7 % 3; 1 - Modulo is the reminder of the division after getting the result 1-19

20 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

21 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

22 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

23 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 * * 5 / means (((3 * 7) – 6) + ((2 * 5) / 4 )) + 6

24 Expressions If all operands are integers
Expression is called an integral expression Yields an integral result Example: * 5 If all operands are floating-point Expression is called a floating-point expression Yields a floating-point result Example: 12.8 *

25 Mixed Expressions Mixed expression: Examples of mixed expressions:
Has operands of different data types Contains integers and floating-point Examples of mixed expressions: 6 / 5.4 * 2 – / 2

26 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

27 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 - Location for string start from 0 to …etc whit spaces should be included

28 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

29 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

30 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 = ; /* but, this is wrong */ return 0; }

31 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:

32 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!

33 Variable types There are four basic data types in C Type Integer
Floating point Character C keyword to use: int float double char

34 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 (approx. 109)

35 Variable types float and double
floating point variables hold signed floating point numbers (i.e. with a fractional part), such as , – , 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)

36 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.

37 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 <, etc) special control codes For example, the character 'A' is represented by the code 65 the character '1' is represented by the code 49 IMPORTANT: the integer 1, the character '1' and the ASCII code 1 represent three different things!

38 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

39 Variable Initialization
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;

40 Variable values The basic syntax of an assignment statement is
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

41 Variable values

42 Literals Literals are fixed values written into a program. Example:
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 */ double pi; pi = 3.14; /* 3.14 is a floating-point literal. */ int index; index = 17; /* 17 is an integer literal */

43 Example /* sample program that demonstrates variable declaration and
initialization. */ #include <stdio.h> int main () { int num_students; num_students = 22; return 0; }

44 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; }

45 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; }

46 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; }

47 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++;

48 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;

49 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 old value of n before it is incremented or the new value after it is incremented?

50 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.

51 Specialised Assignment Statements
sum = sum + x; can be represented in C++ by: sum += x; This notation can be used with the arithmetic operators +, -, *, / and %.  General form : variable op= expression which is interpreted as being equivalent to: variable = variable op ( expression )

52 Specialised Assignment Statements (Continued)
total += value; or total = total + value; prod *= 10; prod = prod * 10; x /= y + 1; x = x/(y + 1); n %= 2; n = n % 2;


Download ppt "Chapter 2: Basic Elements of C++"

Similar presentations


Ads by Google