0% found this document useful (0 votes)
14 views48 pages

PF Slides Lecture 2

Uploaded by

Raza Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views48 pages

PF Slides Lecture 2

Uploaded by

Raza Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

CSC103

Programming Fundamentals

Dr. Muhammad Sharjeel


Lecture 2
Basic Elements of C++
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);
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:

Calculate and print perimeter and area of a rectangle.


Length = 6.0
Width = 4.0
Perimeter = 20.0
Area = 24.0

9
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Basics of C++
● Variable, a named memory location whose contents can be changed

● Function (or subprogram), collection of statement, when executed, accomplishes something


○ Predefined or programmer-defined
● Programming language is set of rules, symbols, and special words
○ Syntax rules specify which statements (instructions) are legal or valid
○ Semantic rules determine the meaning of the instructions
● Comments are for the reader, not the compiler (they are not executed)
○ Two types, single line (starts with //), multiple lines (enclosed between /* and */)

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

● Special symbols, + – * / . ; ? , <= != == >=

● 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

● Every C++ program contains whitespaces


○ Examples are blanks, tabs, and newline characters
○ Used to separate special symbols, reserved words, and identifiers
● Proper utilization of whitespaces is important
○ Used to make the program more readable

13
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Data Types

14
C++ Data Types
● Data type defines the type of data a variable can hold

● C++ data types fall into three categories:


○ Simple (primitive) data type
○ Structured data type
○ Pointers

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

● It is a sequence of zero or more characters enclosed in double quotation marks


○ Null (or empty) string has no characters
● Each character within a string has a relative position in that string
○ The position of first character is 0
○ Length of a string is number of characters in it
● Example: “Hello World” is a string and its length is 11

19
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Variables

20
C++ Variables
● Data must be loaded into main memory before it can be used (manipulated)

● Loading (or storing) data in main memory is a two-step process:


○ Instruct computer to allocate (reserve) main memory
■ In a C++ program, this is accomplished by ‘declaring a variable’
○ Include statements to put data into main memory
■ In a C++ program, this is accomplished by ‘assigning value to a variable’

● 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

int n1, n2;


float sale; Variables declarations
char choice;
string str;

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

● Compound operators provide more concise notation


● Compound operators: +=, -=, *=, /=, %=
● Examples:
x = x * y; // Simple assignment
x *= y; // Compound assignment

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

● Arithmetic expressions, contain values and arithmetic operators


○ Operands, the number of values on which the operators will work
● Operators can be unary (one operand) or binary (two operands)
○ Examples: -5 (unary) or ++5 (binary)

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

● Cast operator, provides explicit type conversion


○ Syntax: static_cast<dataTypeName>(expression)
● Examples:
static_cast<double>(x/y)
static_cast<int>(7.9) // evaluates to 7
static_cast<int>(3.3) // evaluates to 3
static_cast<double>(5) // evaluates to 5.0
static_cast<double>(7/2) // evaluates to 3.0

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

● Expression is first evaluated, its value is then printed


● Examples: Output
cout << 28 / 4; // 7
cout << "sum = " << 4 + 7; // sum = 11

● What will be the output of the following statement

cout << "4 + 7”;

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

● Every library has a name and is referred to by a header file


● C++ program has two parts, (i) preprocessor directives and (2) the program
● Preprocessor directives are commands supplied to the preprocessor program
○ All preprocessor commands begin with #
○ No semicolon at the end of these commands
○ Example:
#include <iostream>
■ Instructs the preprocessor to include the header file iostream into the C++ program
● Preprocessor commands are processed before the program goes through the compiler

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

● Syntax rules indicate what is legal and what is not legal

42
CSC103 – Programming Fundamentals Dr Muhammad Sharjeel
Functions
● Function (or subprogram) is a set of instructions, when activated, accomplishes a task

● C++ program is a collection of functions, one of them is the function main


○ main function executes (automatically) when a program is run
○ Other functions execute only when called
● The first line of the function main is called the heading of the function
● The statements enclosed between the curly braces { and } form the body of the function
int main() { body of the function }
● C++ includes a wealth of functions
● Predefined functions are organized as a collection of libraries called header files
○ Header file may contain several functions, to use a predefined function, include
the appropriate header file

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

● To find power of a value, use the pow function


○ It is defined in cmath header file, so must include cmath before using pow function
● pow function takes two numeric parameters, pow(x,y) which is equal to (xy)
○ x and y are the arguments (or parameters)
■ Example: pow(7,2), the parameters are 7 and 2, and it is equal to 72

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:

2 + 3 * 5 will give a different result than (2 + 3) * 5


● Both of the above expressions are syntactically correct, but have different meanings

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

You might also like