PF Slides Lecture 2
PF Slides Lecture 2
Programming Fundamentals
#include <iostream>
using namespace std;
int main() {
double length, width, area, perimeter;
cout << ”Calculate and print perimeter and area of a rectangle." << endl;
length = 6.0;
width = 4.0;
perimeter = 2 * (length + width);
area = length * width;
cout << "Length = " << length << endl;
cout << "Width = " << width << endl;
cout << "Perimeter = " << perimeter << endl;
cout << "Area = " << area << endl;
return 0;
}
3
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Dissecting a C++ Program
// Program to compute and output perimeter and area of a rectangle Comments
#include <iostream>
using namespace std;
int main() {
double length, width, area, perimeter;
cout << ”Calculate and print perimeter and area of a rectangle." << endl;
length = 6.0;
width = 4.0;
perimeter = 2 * (length + width);
area = length * width;
cout << "Length = " << length << endl;
cout << "Width = " << width << endl;
cout << "Perimeter = " << perimeter << endl;
cout << "Area = " << area << endl;
return 0;
}
4
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Dissecting a C++ Program
// Program to compute and output perimeter and area of a rectangle
#include <iostream>
using namespace std;
int main() {
double length, width, area, perimeter; Variable declarations
cout << ”Calculate and print perimeter and area of a rectangle." << endl;
length = 6.0;
width = 4.0;
A statement such as double width;
perimeter = 2 * (length + width);
instructs the system to allocate memory
area = length * width;
space and name it width
cout << "Length = " << length << endl;
cout << "Width = " << width << endl;
cout << "Perimeter = " << perimeter << endl;
cout << "Area = " << area << endl;
return 0;
}
5
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Dissecting a C++ Program
// Program to compute and output perimeter and area of a rectangle
#include <iostream>
using namespace std;
int main() {
double length, width, area, perimeter;
cout << ”Calculate and print perimeter and area of a rectangle." << endl;
length = 6.0; Assignment statments
width = 4.0;
perimeter = 2 * (length + width);
area = length * width; Instructs the system to store values
cout << "Length = " << length << endl; in memory space (length, width)
cout << "Width = " << width << endl;
cout << "Perimeter = " << perimeter << endl;
cout << "Area = " << area << endl;
return 0;
}
6
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Dissecting a C++ Program
// Program to compute and output perimeter and area of a rectangle
#include <iostream>
using namespace std;
int main() {
double length, width, area, perimeter;
cout << ”Calculate and print perimeter and area of a rectangle." << endl;
length = 6.0;
width = 4.0;
perimeter = 2 * (length + width);
Calculations with arithmetic operators
area = length * width;
cout << "Length = " << length << endl;
cout << "Width = " << width << endl;
cout << "Perimeter = " << perimeter << endl;
cout << "Area = " << area << endl;
return 0;
}
7
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Dissecting a C++ Program
// Program to compute and output perimeter and area of a rectangle
#include <iostream>
using namespace std;
int main() {
double length, width, area, perimeter;
cout << ”Calculate and print perimeter and area of a rectangle." << endl;
length = 6.0;
width = 4.0; Instructs the system to display results
perimeter = 2 * (length + width);
area = length * width;
cout << "Length = " << length << endl;
cout << "Width = " << width << endl;
Output statments
cout << "Perimeter = " << perimeter << endl;
cout << "Area = " << area << endl;
return 0;
}
8
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Dissecting a C++ Program
● A sample run of the program:
9
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Basics of C++
● Variable, a named memory location whose contents can be changed
10
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Basics of C++
● Token, the smallest individual unit of a program which has a meaning
○ C++ tokens include special symbols, reserved words, and identifiers
● Reserved words, also called keywords, are words reserved for special purpose tasks
○ Cannot be redefined within program
○ Cannot be used for anything other than their intended use
○ Examples: int, float, double, char, const, void, return
● Identifier, the name of something that appears in a program
○ Consists of letters, digits, and the underscore character ‘ _ ’
○ Must begin with a letter or underscore
○ Examples: Two predefined identifiers are cout and cin
■ Unlike reserved words, predefined identifiers may be redefined (but not recommended)
11
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Basics of C++
● Examples of legal identifiers:
○ first
○ conversion
○ payRate
● Examples of illegal identifiers:
○ employee salary – (There can be no space between employee and salary)
○ Hello! – (The exclamation mark cannot be used in an identifier)
○ one + two – (The symbol + cannot be used in an identifier)
○ 2nd – (An identifier cannot begin with a digit)
12
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Basics of C++
● C++ is case sensitive
○ NUMBER is not the same as number
13
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Data Types
14
C++ Data Types
● Data type defines the type of data a variable can hold
15
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Data Types
● Primitive data type has further three categories:
○ Integer, numbers without a decimal point
■ Examples: char, int, bool
ü Can be modified using type modifiers: unsigned, short, long
○ Floating-point, numbers with a decimal point
■ Examples: float, double
○ Enumeration, user-defined data type
16
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Data Types
● Values and memory allocations for different simple data types
Data Type Size (in bytes) Range
short int 2 -32,768 to 32,767
unsigned short int 2 0 to 65,535
int 4 -2,147,483,648 to 2,147,483,647
unsigned int 4 0 to 4,294,967,295
long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 8 0 to 4,294,967,295
char 1 -128 to 127
unsigned char 1 0 to 255
float 4 -3.4E +38 to 3.4E +38 (7 digits)
double 8 -1.7E + 308 to 1.7E + 308 (15 digits)
bool 1 true or false
● It is important to note that different compilers may allow different ranges of values
17
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Data Types
● Examples of int data type: -6728, 0, 78, +763
○ Cannot use a comma within an integer (e.g., 26,000 is not a valid int value)
● Examples of bool data type: two (logical) values only, i.e., true and false
○ Manipulate logical (boolean) expression
● Examples of float data type: 6.0, 33.2, 753.900
○ Used to represent any real numbers
● Examples of char data type: ‘A’, ‘a’, ‘0’, ‘*’, ‘+’, ‘$’, ‘&’
○ Each character must be enclosed in single quotes
○ char is the smallest integral data type, used for single characters (letters, digits, and
special symbols)
○ A blank space is also a character, written as ' ' (a space left between the single quotes)
18
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Data Types
● string is a programmer-defined data type supplied in ANSI/ISO Standard C++ library
19
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Variables
20
C++ Variables
● Data must be loaded into main memory before it can be used (manipulated)
● Variable, is a named memory location whose content may change during execution
● In C++, a variable must be declared before using it
21
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Variables
● To declare a variable, must specify its data type and a name (identifier) of the variable
○ Syntax: DataType identifier;
● Examples:
int counter;
double interestRate;
char grade;
● Ways to place/replace data into a variable
○ Using C++ assignment statement
■ Example: counter = 7;
○ Using an input (read) statement
■ Example: cin >> counter;
22
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Variables
● A variable should be initialized explicitly, but not necessarily during declaration
○ Otherwise it contain a garbage value
● A variable is said to be initialized the first time a value is placed into it
○ Not all types of variables are initialized automatically
● Initializing variables with declaration:
int first = 13, second = 10;
● Initializing after declaration:
char ch;
char ch = ' ';
23
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Variables
● C++ assignment statement takes the form:
○ Syntax: variable = expression;
● = is called the assignment operator
● Expression (on the right) is evaluated and its value is assigned to the variable on the left side
n1 = 4;
n2 = 4 * 5 - 11;
sale = 0.02; Initializing variables using assignment operator
choice = 'Y';
str = "It is a sunny day";
24
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Variables
● Two forms of assignment operator, simple and compound
25
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Variables
● Constant, a named memory location whose content can’t change during execution
○ Syntax: const DataType identifier = value;
● const is a reserved word used to mark a variable as constant
● Examples:
const double CONVERTION = 2.54;
const int NO_OF_STUDENT = 20;
● Recommended to write the name of a constant in capital letters to differentiate it from other
variables
26
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Operators
27
C++ Operators
● C++ arithmetic operators
○ + addition, – subtraction, * multiplication, / division, % modulus (remainder) operator
■ +, –, *, and / can be used with integer and floating-point data types
■ % only with integer data types
● When / is used with integer data type(s), the result is truncated (no rounding), e.g., 5/2 = 2
28
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Operators
● Arithmetic operators 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
● Associativity, when operators are on the same level, they have left to right associativity
● 3*7-6+2*5/4+6 means (((3 * 7) – 6) + ((2 * 5) / 4 )) + 6
29
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Operators
● Integral expression, if all operands are integers, yields an integral result
○ Example: 5 / 2 + 3 * 5 = 17
● Floating-point expression, if all operands are floating-point, yields a floating-point result
○ Example: 5.0 / 2.0 + 12.8 * 7.5 = 98.50
● Mixed expressions, operands have different data types
○ Integer is changed to floating-point, operator is evaluated, result is floating-point
○ Precedence rules are always followed
○ Example: 5.4 * 2 - 13.6 + 18 / 2 = 6.2
30
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Operators
● Implicit type conversion, when value of one type is automatically changed to another type
31
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Operators
● Increment operator, increase variable by 1
○ Pre-increment (++variable_name), post-increment (variable_name++)
● Decrement operator, decrease variable by 1
○ Pre-decrement (--variable_name), post-decrement (variable_name--)
● Can you figure out the value of y and z?
x = 5;
y = x++;
x = 5;
z = ++x;
32
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Input/Output
33
C++ Input (Read)
● cin is used with >> to gather input, called as an input (read) statement
○ Syntax: cin >> variable_name >> variable_name;
○ >> is the stream extraction operator
● Examples:
int miles, x, y;
cin >> miles;
cin >> x >> y ;
34
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Output (Display)
● cout is used with a << to output to the screen, called an output (display) statement
○ Syntax: cout << expression or manipulator << expression or manipulator;
○ << is the stream insertion operator
● Examples: Output
cout << 28; // 28
cout << "Hello!"; // Hello!
cout << 'A’; // A
35
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Output (Display)
● cout can also be used to print result of an expression
36
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
C++ Output (Display)
● Manipulator is used with cout to format the output, e.g., endl causes insertion point to move to
beginning of next line
● Examples: Output
cout << "Hello!" << endl << "there."; // Hello!
// there.
● C++ commonly used escape sequences
\n Newline
\t Tab
\b Backspace
\r Return
\\ Backslash
\' Single Quotation
\ '' Double Quotation
37
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Creating C++ Programs
38
Preprocessor Directives
● Many functions and symbols needed to run a C++ program are provided as collection of libraries
39
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Preprocessor Directives
● cin and cout are declared in the header file iostream, but within std namespace
● To use cin and cout in a C++ program, the following two statements are required
#include <iostream>
using namespace std;
● To use the string datatype, include the following preprocessor directive
#include <string>
40
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Debugging C++ Programs
● C++ programs contain two types of statements:
○ Declaration statements: declare things, such as variables
○ Executable statements: perform calculations, manipulate data, create output, accept
input, etc.
● Preprocessor directives and program statements constitute C++ source code (.cpp file)
● Compiler generates object code (.obj file)
● Linker combines (one or more) object code file(s) and associated library file(s) into executable
code (.exe file)
41
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Debugging C++ Programs
● Understanding and fixing syntax errors
○ Compile a program to fix syntax errors
○ Compiler will identify the syntax errors and specifies the line numbers where the errors
occur
● Example:
c:\chapter 2 source code\example2_syntax_errors.cpp(9) : error C2146: syntax
error : missing ';' before identifier 'num'
c:\chapter 2 source code\example2_syntax_errors.cpp(11) : error C2065: syntax
error : ‘tempNum’ : undeclared identifier
42
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Functions
● Function (or subprogram) is a set of instructions, when activated, accomplishes a task
43
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Predefined Functions
● C++ function has:
○ Function name
○ None, one, or more parameters
○ Each parameter has a data type
● Each function is going to do (perform) a task
44
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Writing C++ Code
● Blanks (space charater) in C++ code are used to separate numbers, reserved words, and
identifiers from each other and from other symbols
○ Blanks must never appear within a reserved word or identifier
● All C++ statements must end with a semicolon (;), also called statement terminator
● { and } are not C++ statements , can be regarded as delimiters
● Prompt lines (messages printed on screen using cout) are executable statements that inform
the user what to do
○ Always include prompt lines when input is needed from users
● Example:
cout << "Please enter a number between 1 and 10" << endl;
cin >> num;
45
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Writing C++ Code
● Semantics, set of rules that gives meaning to a language
○ Possible to remove all syntax errors in a program and still not have it run
○ Even if it runs, it may still not do what you meant it to do
○ Such type of errors in a program are called semantic errors (logical errors)
● Example:
46
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Writing C++ Code
● Always use comments to document C++ programs
○ A well-documented program is easier to understand and modify
● Comments should appear in a program to:
○ Explain the purpose of the program
○ Identify who wrote it
○ Explain the purpose of C++ statements
47
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Thanks
48