You are on page 1of 70

1

Introduction To Computer
Programming

Saqib Rizwan

COMSATS Institute of Information Technology, Sahiwal


2

Introduction to C++ Programming


3
Pseudo-code vs. Assembly Language
(Sum of first 5 natural numbers)
Use a Loop to calculate
1+2+3+4+5
Set sum to 0
LOAD DIRECT 1 (always 1)
Set i to 1 MOV R1 ACC
While i 5 do LOAD DIRECT 0 (running total)
MOV R2 ACC
Set sum to sum+i LOAD DIRECT 5 (N=5)
Set value of i to i+1 MOV R3 ACC
End of While loop L1: Add ACC R2 (add in N)
MOV R2 ACC
Print the value of sum Sub R3 R1 (N = N-1)
MOV R3 ACC
Jump if positive L1 (Jump to L1 if ACC>0)
HALT (R2 = 1+2+3+4+5)
4

Disadvantages of Machine Language

• The programmer must manage movement of data


items between memory locations and the ALU.
• Programmer must take a “microscopic” view of a
task, breaking it down to manipulate individual
memory locations.
• Statements are not English-like (Pseudo-code)
5
Pseudo-code vs. High-Level Language
Program

int i, sum;
Set sum to 0 sum = 0;
Set i to 1 i = 1;
While i 5 do Wouldn’t
while ( i <=it5be
) nice if we
Set sum to sum+i { could instead write
Set i to i+1 sum = sum + i;
End of While loop
our program
i = i + 1; in a
Print the value of sum } language more similar
to a<<pseudo-code?
cout sum;
6

High-level Programming Languages

• The programmer need not manage the details of the


movement of data items between memory and CPU.
– Doesn’t even have to know that there is a register in the CPU for
performing arithmetic.
• The programmer has more macroscopic view of a task,
using less primitive building blocks
– E.g. doesn’t work with individual memory locations anymore.
• More English (pseudo-code) like!
7

Why C++

• C is a language designed by and for programmers


• C++ is an expanded and enhanced version of C
Programming Language
• It is the language of choice for professional programmers
worldwide
• Once mastered, C++ will give you complete control over
the computer
• C++ is, above all, the most powerful programming
language ever invented!!!
8

Compiler

C++
C++ Program
Program C++
C++ Compiler
Compiler Machine
Machine
Language
Language
(e.g.
(e.g. g++)
g++) Program
Program
int
int main()
main() {{
int
int i=1;
i=1;
.. .. .. 01001001
01001001
10010100
10010100

Created with text editor or


development environment
9

Basics of a Typical C++ Environment

• C++ systems
– Program-development environment
– Language
– C++ Standard Library
10

The C++ Standard Library

• C++ programs consist of pieces/modules called functions


– A programmer can create his own functions
• Advantage: the programmer knows exactly how it works
• Disadvantage: time consuming (if it exists already)
– Programmers will often use the C++ library functions
• Use these as building blocks
– Avoid re-inventing the wheel
• If a pre-made function exists, generally best to use it rather than write
your own
• Library functions carefully written, efficient, and portable
11

Basics of a Typical C++ Environment


Program is created in
Editor
Phases of C++ Programs: Disk the editor and stored
on disk.

Preprocessor Preprocessor program


1. Edit
Disk
processes the code.
Compiler creates
Compiler Disk object code and stores
2. Preprocess it on disk.
Linker links the object
Linker Disk code with the libraries,
3. Compile Primary
creates a.out and
stores it on disk
Memory
Loader
4. Link Loader puts program
in memory.
Disk
5. Load ..
..
..

Primary
6. Execute CPU
Memory

CPU takes each


 
instruction and
executes it, possibly
storing new data
..
.. values as the program
..
executes.
12
1.12 Basics of a Typical C++
Environment
• Input/output
– cin
• Standard input stream
• Normally keyboard
– cout
• Standard output stream
• Normally computer screen
13
A Simple Program:
Printing a Line of Text
• Comments
– Document programs
– Improve program readability
– Ignored by compiler
– Single-line comment
• Begin with //
– Multiple-line comment
• Everything between /* and */ is ignored.
• Preprocessor directives
– Processed by preprocessor before compiling
– Begin with #
• # include
• # define
14

C++ Preprocessor

• C++ Compilers automatically invoke a


preprocessor that takes care of #include
statements and some other special directives.
• You don't need to do anything special to run the
preprocessor - it happens automatically.
15

Preprocessing

Temporary
Temporary file
file
C++
C++ (C++
(C++ program)
program) C++
C++
Preprocessor
Preprocessor Compiler
Compiler

Executable
Executable
C++
C++ Program
Program Program
Program
16
1 // code1.cpp
2 // A first program in C++.
Single-line comments.
3 Function main
#include <iostream> returns an
4 integer { begins Preprocessor
value.
Left brace function directive to
5 // function main body. program
begins Function include input/output Statements
main appears
execution stream end with a
6 int main() header file <iostream>.
exactly once in every C++ semicolon ;.
7 { program..
8 cout << "Welcome to C++!\n";
9 Corresponding right brace }
10 return 0; //ends function
indicate body.
that program ended successfully
11 Stream insertion operator.
12 } // end function main

Keyword return is one of


Welcome to C++!
several means to exit
function; value 0 indicates
program terminated
successfully.
17
A Simple Program:
Printing a Line of Text
• Standard output stream object
– std::cout
– “Connected” to screen
– A stream is an abstraction that represents a device on which input and
output operations are performed
– <<
• Stream insertion operator
• Value to right (right operand) inserted into output stream
• Namespace
– std:: specifies using name that belongs to “namespace” std
– std:: removed through use of using statements
using namespace std;
• Escape characters
– \
– Indicates “special” character output
18
A Simple Program:
Printing a Line of Text

Escape Sequence Description

\n Newline. Position the screen cursor to the


beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next
tab stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote
character.
19
1 // code2.cpp
2 // Printing a line with multiple statements.
3 #include <iostream>
4
5 // function main begins program execution Multiple stream insertion
6 int main() statements produce one line of
7 { output.
8 std::cout << "Welcome ";
9 std::cout << "to C++!\n";
10
11 return 0; // indicate that program ended successfully
12
13 } // end function main

Welcome to C++!
20
1 // code3.cpp
2 // Printing multiple lines with a single statement
3 #include <iostream>
4
5 // function main begins program executionUsing newline characters to
6 int main() print on multiple lines.
7 {
8 std::cout << "Welcome\nto\n\nC++!\n";
9
10 return 0; // indicate that program ended successfully
11
12 } // end function main

Welcome
to
 
C++!
21

The Preprocessor

• Lines that start with the character '#' are special


instructions to a preprocessor.
• The preprocessor can replace the line with
something else:
– include: replaced with contents of a file
• Other directives tell the preprocessor to look for
patterns in the program and do some fancy
processing.
22

#define (macro) Example

#define square(a) (a * a)

y = square(x);

z = square(y*x);
becomes y = (x * x);

becomes z = (y*x * y*x);


23
Another Simple Program:
Adding Two Integers
• Variables
– Location in memory where value can be stored
– Common data types
• int - integer numbers
• char - characters
• double - floating point numbers
– Declare variables with name and data type before use
int integer1;
int integer2;
int sum;
– Can declare several variables of same type in one declaration
• Comma-separated list
int integer1, integer2, sum;
24
Another Simple Program:
Adding Two Integers
• Variables
– Variable names
• Valid identifier
– Series of characters (letters, digits, underscores)
– Cannot begin with digit
– Case sensitive
25
Another Simple Program:
Adding Two Integers
• Input stream object
– >> (stream extraction operator)
• Used with std::cin
• Waits for user to input value, then press Enter (Return) key
• Stores value in variable to right of operator
– Converts value to variable data type
• = (assignment operator)
– Assigns value to variable
– Binary operator (two operands)
– Example:
sum = variable1 + variable2;
26
1 // code4.cpp
2 // Addition program.
3 #include <iostream>
4
5 // function main begins program execution
6 int main()
7 { Declare integer variables.
8 int integer1; // first number to be input by user
9 int integer2; // second number to be input by user
10 int sum;
Use stream extraction
// variable in which sum will be stored
11 operator with standard input
12 std::cout << "Enter first stream to obtain
integer\n"; // user input.
prompt
13 std::cin >> integer1; // read an integer
14
15 std::cout << "Enter second integer\n"; // prompt
16 std::cin >> integer2; Calculations can
// be performed
read in output
an integer statements: alternative for
Stream manipulator
17 lines 18 and 20: std::endl outputs a
18 sum = integer1 + integer2; // assign result to sum
19
newline, then “flushes output
std::cout << "Sum is " << integer1 + integer2 << std::endl;
20 std::cout << "Sum is " << sum << std::endl; // print sumbuffer.”
21
22 return 0; // indicate that program ended successfully
23
24 } // end function main Concatenating, chaining or
cascading stream insertion
operations.
27
Enter first integer
45
Enter second integer
72
Sum is 117
28

Memory Concepts

• Variable names
– Correspond to actual locations in computer's memory
– Every variable has name, type, size and value
– When new value placed into variable, overwrites previous
value
– Reading variables from memory, nondestructive
29

Memory Concepts

std::cin >> integer1; integer1 45


– Assume user entered 45

std::cin >> integer2; integer1 45


– Assume user entered 72 integer2 72

sum = integer1 + integer2; integer1 45


integer2 72
sum 117
30

Arithmetic

• Arithmetic calculations
– *
• Multiplication
– /
• Division
• Integer division truncates remainder
– 7 / 5 evaluates to 1
– %
• Modulus operator returns remainder
– 7 % 5 evaluates to 2
31

Arithmetic

• Rules of operator precedence


– Operators in parentheses evaluated first
• Nested/embedded parentheses
– Operators in innermost pair first
– Multiplication, division, modulus applied next
• Operators applied from left to right
– Addition, subtraction applied last
Operator(s) • Operators
Operation(s)
applied fromOrder
leftoftoevaluation
right (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Evaluated second. If there are several, they re
Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.
32
Decision Making: Equality and
Relational Operators
• if structure
– Make decision based on truth or falsity of condition
• If condition met, body executed
• Else, body not executed
• Equality and relational operators
– Equality operators
• Same level of precedence
– Relational operators
• Same level of precedence
– Associate left to right
33
Decision Making: Equality and
Relational Operators

Standard algebraic C ++ equality Example Meaning of


equality operator or or relational of C ++ C ++ condition
relational operator operator condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y

 >= x >= y x is greater than or equal to y

 <= x <= y x is less than or equal to y

Equality operators
= == x == y x is equal to y

 != x != y x is not equal to y
34
Decision Making: Equality and
Relational Operators
• using statements
– Eliminate use of std:: prefix
– Write cout instead of std::cout
35
1 // code5.cpp
2 // Using if statements, relational
3 // operators, and equality operators.
4 #include <iostream>
5
6 using std::cout; // program uses cout
7 using std::cin; // program uses cin using statements eliminate
8 using std::endl; // program uses endl need for std:: prefix.
9
10 Declare
// function main begins program variables.
execution
11 int main()
12 {
13 Can write
int num1; // first number to be readand
cout cinuser
from
14 without to
int num2; // second number std:: prefix.
be read from user
15
16 cout << "Enter two integers, and I will tell you\n"
17
if structure compares values
<< "the relationships they satisfy: ";
18 cin >> num1 >> num2;
of num1 and num2
// read two integers
to test for
If condition is true (i.e.,
19 equality. values are equal), execute this
20 if ( num1 == num2 )
if structure compares
statement.values
21 cout << num1 << " is of num1
equal to " and If condition
num2
<< num2 <<toendl; is true (i.e.,
test for
22 inequality. values are not equal), execute
23 if ( num1 != num2 ) this statement.
24 cout << num1 << " is not equal to " << num2 << endl;
25
36
26 if ( num1 < num2 )
27 cout << num1 << " is less than " << num2 << endl;
28
29 if ( num1 > num2 )
30 cout << num1 << " is greater than " << num2 << endl;
Statements may be split over
31
32 if ( num1 <= num2 )
several lines.
33 cout << num1 << " is less than or equal to "
34 << num2 << endl;
35
36 if ( num1 >= num2 )
37 cout << num1 << " is greater than or equal to "
38 << num2 << endl;
39
40 return 0; // indicate that program ended successfully
41
42 } // end function main

Enter two integers, and I will tell you


the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
37
Enter two integers, and I will tell you
the relationships they satisfy: 7 7
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7
38
Confusing Equality (==) and
Assignment (=) Operators
• Common error
– Does not typically cause syntax errors
• Aspects of problem
– Expressions that have a value can be used for decision
• Zero = false, nonzero = true
– Assignment statements produce a value (the value to be
assigned)
39
Confusing Equality (==) and
Assignment (=) Operators
• Example
if ( payCode == 4 )
cout << "You get a bonus!" << endl;
– If paycode is 4, bonus given

• If == was replaced with =


if ( payCode = 4 )
cout << "You get a bonus!" << endl;
– Paycode set to 4 (no matter what it was before)
– Statement is true (since 4 is non-zero)
– Bonus given in every case
40

C++ Data Types

Simple address Structured

Integral enum Floating pointer array


reference struct
char float union
short signed double class
int unsigned long double
long
bool
41

Integral Types

• char, short, int, long


• Different sizes of integers - different memory size
• Dependent upon the compiler
• Integer values: Sequence of one or more digits
22 129 -67 0
• commas are not allowed: 100,000
Type Name Bytes Other Names Range of Values 42
int 4 signed –2,147,483,648 to 2,147,483,647

unsigned int 4 unsigned 0 to 4,294,967,295

bool 1 none false or true

char 1 none –128 to 127

signed char 1 none –128 to 127

unsigned char 1 none 0 to 255

short 2 short int, signed short int –32,768 to 32,767

unsigned short 2 unsigned short int 0 to 65,535

long 4 long int, signed long int –2,147,483,648 to 2,147,483,647

unsigned long 4 unsigned long int 0 to 4,294,967,295

long long 8 none –9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

unsigned long long 8 none 0 to 18,446,744,073,709,551,615

enum varies none

float 4 none 3.4E +/- 38

double 8 none 1.7E +/- 308

long double same as double none same as double


43

Expressions

• C++ expressions are used to express computation.


• Expressions include operations and the operands
on which the operations are applied.
• Operands can be variables, literals or constants.
44

Precedence

• Precedence controls the order of evaluation of


operators.
– A high precedence means an operator is evaluated (applied)
before any lower precedence operators.
• Operators that have the same precedence can
happen in either order, but in C++ the one on the
left is evaluated first.
45

Precedence

Operators Precedence
() highest (applied first)
* / %
+ -
< <= > >=
== !=
= lowest (applied last)
46

const

• You can add the const modifier to the declaration


of a variable to tell the compiler that the value
cannot be changed:

const double factor = 5.0/9.0;


const double offset = 32.0;
celcius = (fahr - offset)*factor;
47

What if you try to change a const?

• The compiler will complain if your code tries to


modify a const variable:

const int temp = 100;



temp = 21;

Error: l-value specifies const object

• Const tells the compiler that a variable should never be changed.


48

Unary and Binary Operators

• Unary Operator – one operand: a++

• Binary Operator – two operands: a - b


49

Integer vs. floating point math

• How does C++ know whether to use floating point


or integer math operators?
• If either operand is floating point, a floating point
operation is done (the result is a floating point
value).
• If both operand are integer the result is an integer
(even division).
50

Division

• Floating point division


– when at least one of the operands is FP
• Integer division
– when both operands are integer

7/2  3
7.0 / 2.0  3.5
7.0 / 2  3.5
7 / 2.0  3.5
51

Expression Value
3+6 9
3.4 - 6.1 -2.7
2*3 6
2 * 3.0 6.0
8/2 4
8.0 / 2.0 4.0
Mixed Mode Expressions
An expression that takes operands of different types.
52

Compound Expressions

avgTemp = FREEZE_PT + BOILING_PT;


avgTemp = avgTemp / 2.0;


avgTemp = FREEZE_PT + BOILING_PT / 2.0;

avgTemp = (FREEZE_PT + BOILING_PT) / 2.0;


53

Type Coercion and Type Casting

• Coercion – automatic conversion of a value from


one type to the other.
• Casting – explicit conversion of a value from one
type to the other.
54
Type Coercion and Type Casting

int int1, int2;


float float1, float2; Type
Coercion
casting

Expression LHS Value


float1 = 5; 5.0
int1 = 3.8; 3
int1 = 7; int2 = 2;
float1 = int1 / int2 + 5; 8.0
float2 = float(int1)/int2 +5 8.5
55
Type Coercion and Type Casting
int int1;
float float1 = 2.0;

Expression int1
int1 = float1 + 8.2 ; 10
int1 = int (float1 + 8.2) ; 10
What’s the difference?
Any advantages?

CLARITY!
56

Type Casting

int total, count;


float average;
… // some values assigned to total and count


average = total / count ;

average = float(total) / float(count) ;


57

Literals (fixed values)

• Literals are fixed values used by a program.


• Some examples of literals:
22 3.14159
false "Hi Kurt" 'c'

• You can initialize a variable in the declaration by


assigning it a value:
int temp = 17;
double PI = 3.14159;
char alpha = ‘a';
58

Control Structures
59

• Before writing a program


– Have a thorough understanding of problem
– Carefully plan your approach for solving it
• While writing a program
– Know what “building blocks” are available
– Use good programming principles
60

Control Structures

• Sequential execution
– Statements executed in order
• Transfer of control
– Next statement executed not next one in sequence
• 3 control structures
– Sequence structure
• Programs executed sequentially by default
– Selection structures
• if, if/else, switch
– Repetition structures
• while, do/while, for
61

Control Structures

• C++ keywords
– Cannot be used as identifiers or variable names
C ++ Keywords

Keywords common to the


C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
62

Control Structures

• Flowchart
– Graphical representation of an algorithm
– Special-purpose symbols connected by arrows (flowlines)
– Rectangle symbol (action symbol)
• Any type of action
– Oval symbol
• Beginning or end of a program, or a section of code (circles)
• Single-entry/single-exit control structures
– Connect exit point of one to entry point of the next
63

if Selection Structure

• Selection structure
– Choose among alternative courses of action
– Pseudocode example:
If student’s grade is greater than or equal to 60
Print “Passed”
– If the condition is true
• Print statement executed, program continues to next statement
– If the condition is false
• Print statement ignored, program continues
– Indenting makes programs easier to read
• C++ ignores whitespace characters (tabs, spaces, etc.)
64

if Selection Structure

• Translation into C++


If student’s grade is greater than or equal to 60
Print “Passed”

if ( grade >= 60 )
cout << "Passed";

 
• Diamond symbol (decision symbol)
– Indicates decision is to be made
– Contains an expression that can be true or false
• Test condition, follow path
• if structure
– Single-entry/single-exit
65

if Selection Structure

• Flowchart of pseudocode statement

A decision can be made on


any expression.

true zero - false


grade >= print “Passed”
60 nonzero - true
Example:
false
3 - 4 is true
66

if/else Selection Structure

• if
– Performs action if condition true
• if/else
– Different actions if conditions true or false
• Pseudocode
if student’s grade is greater than or equal to 60
print “Passed”
else
print “Failed”
• C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
67

if/else Selection Structure

• Ternary conditional operator (?:)


– Three arguments (condition, value if true, value if false)
• Code could be written:
cout << ( grade >= 60 ? “Passed” : “Failed” );

Condition Value if true Value if false

false true
grade >= 60

print “Failed” print “Passed”


68

if/else Selection Structure

• Nested if/else structures


– One inside another, test for multiple cases
– Once condition met, other statements skipped
if student’s grade is greater than or equal to 90
Print “A”
else
if student’s grade is greater than or equal to 80
Print “B”
else
if student’s grade is greater than or equal to 70
Print “C”
else
if student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
69

if/else Selection Structure

• Example
if ( grade >= 90 ) // 90 and above
cout << "A";
else if ( grade >= 80 ) // 80-89
cout << "B";
else if ( grade >= 70 ) // 70-79
cout << "C";
else if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";
70

if/else Selection Structure

• Compound statement
– Set of statements within a pair of braces
if ( grade >= 60 )
cout << "Passed.\n";
else {
cout << "Failed.\n";
cout << "You must take this course again.\n";
}
– Without braces,
cout << "You must take this course again.\n";
always executed
• Block
– Set of statements within braces

You might also like