You are on page 1of 167

CSC-112

PROGRAMMING FUNDAMENTALS

DR. ABDUL ATTAYYAB KHAN


EMAIL ADDRESS: AAKHAN.BUKC@bahria.edu.pk
WEBSITE: https://sites.google.com/view/programming-
fundamentals/home

GENTLE REMINDER

“Switch Off” your Mobile Phone Or Switch Mobile Phone to


“Silent Mode”

1
COURSE ASSESSMENT

 Home/Assignment ----------------- 20%

 Quizzes ----------------------------- 10%

 Mid Term ------------------------------ 20%

 Final ------------------------50%

 Total -------------------------100%

An Overview of Programming
Languages and Problem
Solving Techniques

2
COMPUTER PROGRAM

 A program (also commonly called an application or software) is a set of


instructions that tells the computer what to do. The physical computer
machinery that executes the instructions is the hardware.
 Adobe Acrobat, Adobe Photoshop, FileZilla, Google Chrome, Microsoft Excel,
Microsoft PowerPoint, Microsoft Word, Mozilla and more.

PROGRAMMING LANGUAGES
 Various programming languages enable people to tell computers what to do.
 A vocabulary and set of grammatical rules for instructing a computer to
perform specific tasks. Computer programs are created by using
programming languages. Foundation for developing applications.
 Such as BASIC, C, C++, COBOL, FORTRAN, Ada, and Pascal.

Modern programming languages fall into following five categories.


 First generation Languages  Machine Language
 Second generation Languages assembly language
 Third generation Languages procedural
 Fourth generation Languages non procedural
 Fifth generation Languages  Natural Language Programming

3
PROGRAMMING LANGUAGES
Machine Language (first generation of programming languages)
 The computer’s ‘native language’ 11011101 1011011
01001100 1011100
 Composed of binary digits (0s, 1s)
11011100 1011011
 The only language that computers understand

Assembly Language (second generation of programming languages)

 One-to-one correspondence to machine language


 Somewhat more user-friendly than machine language (mnemonic rather than
binary digits)
 Assembler – program that translates an assembly language program into
machine language

PROGRAMMING LANGUAGES

Procedural Languages (High Level Languages) (third generation languages)


 write programs without having to be as concerned about what kind of
computer the program is being run on and are also closely resemble with
mathematical notations and human readable.
Sum = num1+num2;
 Examples: C, Fortran, QuickBasic
 Compiler - translates the entire program into machine language
 Interpreter - translates and executes one source program statement at a time.
Nonprocedural Language (fourth generation languages)
 Allows the user to specify the desired result without having to specify the
detailed procedures needed for achieving the result
 Example: data base query language - SQL
 Can be used by non technical users.

4
PROGRAMMING LANGUAGES
Represent the equation wages = rate · hours to calculate the weekly wages

Machine language
Assembly language
100100 stands for load
100110 stands for multiplication
100010 stands for store

Can be written as follows:


100100 010001
100110 010010
100010 010011
Can be written as follows:
LOAD rate
High level language MULT hour
STOR wages
In C++, can be written as follows:
wages = rate * hours;

PROGRAMMING LANGUAGES
Natural Language Programming Languages (fifth generation (intelligent)
languages)
 Translates natural languages into a structured, machine-readable form
 Are extremely complex and experimental

5
ELEMENTS OF PROGRAMMING:
Symbols include mathematical operates and
Each programming statement is made punctuations.
up of following elements. + Plus used for addition
- Hyphen for subtraction
 1. Symbols * Asterisk for multiplication
 2. Reserved words / Forward slash use for division
// backward slash use for comments
 3. Identifiers ; Semi-colon used for statement
termination
“” inverted commas
! Not operator

Identifiers
Special names created by programmer for.
• The name of the program
• Constants used in the program
• Variables used in the program

ELEMENTS OF PROGRAMMING:
Reserve words
 Reserve words are words that have special meaning in the programming language
and cannot used as identifier names.
 the reserved words, must not be used for any other purposes. The reserved words
already used are int and void. All reserved words are in lower-case letters.

Cout do goto signed unsigned

break double if sizeof void

Case else int static volatile

Char enum long struct while

cin extern register switch

default float return typedef

for short union const

6
ELEMENTS OF PROGRAMMING:

Symbols Reserve Words identifiers


 Activity:
# Include Main
Add two numbers. Find out the
<< Using Myname
identifiers, symbols and reserve words.
#include <iostream> <> Namespace

using namespace std; ; Std

int main() { ‘’ Return

string Myname='M . ALi Azeem'; }{ Int


cout <<"My name is " << Myname << endl;
() String
// your code goes here
= Cout
return 0;
// End1
}

ELEMENTS OF PROGRAMMING:

Symbols Reserve identifi


 Activity2: Words ers

#include <iostream>
using namespace std;
int main() {
int num1, num2, sum;
num1=5;
num2=7;
cout << "Enter two numbers to add\n";
sum = num1 + num2;
cout <<"Sum of entered numbers = " << sum
<<endl;
// your code goes here
return 0;
}

7
STEP IN PROGRAM DEVELOPMENT
Programming can be defined as the development of a solution to an identified problem, and the
setting up of a related series of instructions that will produce the desired results.

The program development process is a series of activities that are necessary for the successful
development of a computer program, however simple or complex. The program development
process can be divided into six stages.

1. Define the problem

2. Designing the program

3. Coding the program

4. Testing the program

5. Installing and maintain the program

6. Documentation the program

STEP IN PROGRAM DEVELOPMENT

 Define the Problem


To help with initial analysis, the problem should be divided into three separate
components:
 The inputs required by the program.
 The outputs or end result required.
 The processing steps to produce the required outputs.

 IPO Chart:
 IPO charts use to organize and summarize the results of a problem definition.
 The output is the first data added to the IPO chart, you can then ask what input
the program need to produce the required output.
 Processing is simply the series of actions you must perform on the input to get
the required output.

8
WRITE A PROGRAM CALCULATING THE SUM OF TWO
NUMBERS : ADDITION
Input Processing Output

5, 10 15

1) Declare variables 3) Process


num1 2) Assign values
num1 = 5 sum = num1 + num2
num2
sum num2 = 10

The computer (and so C) provides


basic arithmetic operations. If the
Names for our cells operation you want to use is not
provided, you have to compose it.

STEP IN PROGRAM DEVELOPMENT

Activity #3: Write a program calculating the sum of two numbers: Addition.
Suppose you were asked to add two numbers mentally. The first thing you would
do is ask for the two numbers. When you are given the two number.
You would add them. You would then communicate the result to the person who
asked you for it.

Input Process Output


IPO Chart Num1 Input Num1 Sum
Num2 Input Num2
Sum=num1+num2
print Sum;

9
STEP IN PROGRAM DEVELOPMENT

Activity #4: Write a program calculating the average of two numbers:


Suppose you were asked to add two numbers mentally. The first thing
you would do is ask for the two numbers. When you are given the two
number. You would add them, then divide the result by 2 to he get the
average.. You would then communicate the result to the person who
asked you for it.
Input Process Output

Input Num1
Input Num2
Num1 Average
Ipo Chart Sum=num1+num2
Num2
Average=sum/2
print average;

STEP IN PROGRAM DEVELOPMENT

Activity #5:Write a program that and prints the tax paid by a worker and
net pay received, given the hourly rate and the number of hours worked
for the week. Tax is equal to total pay minus tax.
For process
1. Compute the total pay. (hourlyrate*hoursworked)
2. Compute the tax paid.(taxrate*totalpay)
3. Compute the net pay.(totalpay-tax paid)

10
STEP IN PROGRAM DEVELOPMENT (DESIGNING )

 Designing the problem


 Once we have clearly define the problem, several programming tools are now
available to assist the programmer in designing a solution for the problem. One
should note that for a given problem, several solutions may exist. The
programmer must examine the alternative solutions and choose the best one.
 Pseudo codes
 Algorithms
 Flowcharts
 Decision tables
 Structure
 HIPO chart

PSEUDOCODE  WRITE A PROGRAM CALCULATING


THE SUM OF TWO NUMBERS
Pseudocode are English-like statements that follow a loosely defined syntax
and are used to convey the design of an algorithm.

A pseudocode is an informal programming language that’s is very similar to


the high level programming language but without the strictness of the syntax
of a high level language.
Version 1: Version 2:

PROGRAM Add Two Numbers PROGRAM Add Two Numbers


READ two numbers READ First
ADD the numbers READ Second
WRITE the sum Sum = First + Second
END PROGRAM WRITE Sum
END PROGRAM

11
WHAT IS AN ALGORITHM?
A step-by-step problem solving procedure, especially an established, recursive
computational procedure for solving a problem in a finite number of steps.

An algorithm has to
be clear
have a finite length
stop in finite time

 There are many models supporting the development of the code:

 Pseudocode
 Structure Diagram and finally in C++
 Flowcharts

All the models try to achieve something. What?

MODULAR DESIGN  WRITE A PROGRAM CALCULATING THE SUM OF


TWO NUMBERS
Pseudocode are more closely
to the programming language
and for the advanced programmer. Modular Design

Structure Diagrams are helpful We don’t break according


to break the algorithm into more to the sequence
manageable pieces. in which the parts are
following, but rather
Flowcharts show the workflow in its frequency of use and
of the algorithm and stress on similarity
structured programming. to other parts.

Every model has its advantages


and disadvantages. But all try to
help you to structure your code in
a top-down style and this is the
way you should implement your
algorithm.

12
STEP IN PROGRAM DEVELOPMENT(DESIGNING )
Flowchart Symbol Name Description
PROCESS An operation or
action
Flowchart Terminator A start or end
point in a
program
Flowchart is a graphic from of a
pseudocode or algorithm. Decision A question or
Programming instructions are branch in a
represented by symbols instead program
of alphanumeric phrases. Input/output Indicated data
input or output
to or form a
program
Flow line Indicates
direction of
program flow
connector A jump from
one point to
another

FLOWCHARTS SUM OF TWO NUMBERS

Addition of two numbers.

step 1. Start

step 2. Read num1, num2

step 3. Sum=num1+num2

step 4. write sum;

step 5. end

13
FLOWCHARTS SUM OF TWO NUMBERS

START Addition of two numbers.

READ First step 1. Start


READ Second
step 2. Read num1, num2

Sum = First + Second step 3. Sum=num1+num2

step 4. write sum;


WRITE Sum

Also involves
step 5. end
Repeating certain steps of a program
END Taking alternate sequence steps for some situations

BRANCHING
FLOWCHARTS
Also involves
Repeating certain steps of a program
Taking alternate sequence steps for some situations

BRANCHING
Process of following one of two or more alternate paths of program logic

14
BRANCHING
BRANCHING (EXAMPLE 1)
To find if a number is odd or even

Start

Read a number

Divide it by 2

No Yes
remainder=0
?
Display Odd Display Even

Stop

BRANCHING
BRANCHING (EXAMPLE 2)
To find the greatest of the three numbers

Start

Read a, b, c
Yes No
Is a>b

Yes No Yes No
Is a>c Is c>b

Display a Display c Display b

Stop

15
BRANCHING
BRANCHING
General form of flowcharts involve in branching

? ?

Compute Compute Compute

(i) (ii)

BRANCHING
LOOPING
• Refers to the repeated use of one or more steps
• Types of loops
• Fixed
• Variable

16
BRANCHING
LOOPING (EXAMPLE 1)
To calculate the sum of monthly expenditure for an entire year
Start
tot_exp – Total expenditure
no_mon – Number of months
tot_exp = 0
no_mon = 0

Read exp

Add exp to tot_exp

no_mon = no_mon +Yes


1

No
Is no_mon=12?
Yes
Display tot_exp

Stop

BRANCHING
LOOPING (EXAMPLE 2)
Given the information such as name and age and to maintain a list of people aged above
50

Start

Read name, age

Is age above No
50?
Yes
Add details of the person to list

Is he the last No
person?
Yes
Stop

17
BRANCHING
BASIC FLOWCHART FOR A LOOP

Yes
Condition

No

Compute

BRANCHING
CONNECTORS
• In preparing flowcharts for complex problems
• The flowchart may not fit in a single page
• It may be difficult to interconnect all boxes directly

18
BRANCHING
CONNECTORS (EXAMPLE)
To find the largest of the three numbers a , b and c

Start 1 2

Read a, b, c
Yes No Yes No
Is a>c Is
c>b

Yes No Display
Display Display
Is a>b
a c b

1 2 Stop

STEP IN PROGRAM DEVELOPMENT

3. Coding the program


 Code the Algorithm into a Specific Programming Language
 Only after all design considerations have been met

4. Testing the program


 Test the Algorithm for Correctness
 Most important in the development of a program
 To identify major logic errors early, so that they may be easily corrected.

19
STEP IN PROGRAM DEVELOPMENT

5. Installing and maintain the program


The first version of program is ready and now allow user to use and test it.
6. Documentation the program
 Document and Maintain the program
 It is an ongoing task from the initial definition of the problem to the final test
result.
 Documentation involves both external and internal documentation that may
have been coded in the program.
 Maintenance requires using and modifying the program if the problem domain
changes.

PROGRAMMING WITH THE PROBLEM ANALYSIS –


CODING – EXECUTION CYCLE
Problem solving process

First step
 Define the problem.
 Outline the solution.
 Design an algorithm.
 Test the algorithm for correctness.

Second step
 Implement the algorithm in programming
language, such as C++.
 Run the program on the computer

Last step
 Document and maintain the program.

20
PROCEDURAL VS. OBJECT-ORIENTED PROGRAMMING

 Procedural programming
 is based on a structured, top-down approach to writing effective programs.
 concentrates on ‘what’ a program has to do and involves identifying and
organizing the ‘processes’ in the program solution
 Decomposed into separate tasks or functions and includes
 top-down development broken down problem into more detailed steps
 modular design  grouping task together because they all perform the
same function; connected to top-down development

 Object-Oriented Programming
 OOP is also based on decomposing the problem.
 The primary focus is on the things that make up the program.

TOP-DOWN DEVELOPMENT

 If we look at a problem as a whole, it may seem impossible to solve because it is so


complex.
Examples:
 writing a tax computation program
 Writing a library system
 Writing a Bank System

 Complex problems can be solved using top-down design, also known as stepwise
refinement, where
 We break the problem into parts
 Then break the parts into smaller parts
 Soon, each of the parts will be easy to solve

21
ADVANTAGES OF TOP-DOWN DEVELOPMENT

 Breaking the problem into parts helps us to clarify what needs to be


done.
 At each step of refinement, the new parts become less complicated and,
therefore, easier to figure out.
 Parts of the solution may turn out to be reusable.
 Breaking the problem into parts allows more than one person to work on
the solution.

 Problem:
You own a home improvement company providing painting, roofing,
and basement waterproofing service. A section of the town has
recently flooded (zip code 43100). You want to send out pamphlets to
our customers in that area.

THE TOP LEVEL

 Get the customer list from a file.


 Sort the list according to zip code.
 Make a new file of only the customers with the zip code 43100
from the sorted customer list.
 Print an envelope for each of these customers.

Main

Read Sort Select Print

22
ANOTHER LEVEL?
 Should any of these steps be broken down further? Possibly!
 How do I know? Ask yourself whether or not you could easily write the
algorithm for the step. If not, break it down again.
 When you are comfortable with the breakdown, write
the pseudocode for each of the steps (modules) in the hierarchy.
 Typically, each module will be coded as a separate function.

Another Example:
 A Top-down analysis of a simple cooking task

Cook Breakfast

Bring out Take out


Cook food Serve food
cook ware Uncooked food

Get Get Get


Get fork
Coffee Pot Frying pan Serving dishes

WRITE A PROGRAM CALCULATING THE SUM OF


TWO NUMBERS : ADDITION
Input Processing Output

5, 10 15

1) Declare variables 3) Process


input_1 2) Assign values
input_1 = 5 sum = input_1 + input_2
input_2
sum input_2 = 10

The computer (and so C) provides


basic arithmetic operations. If the
Names for our cells operation you want to use is not
provided, you have to compose it.

23
STRUCTURE DIAGRAM  WRITE A PROGRAM CALCULATING
THE SUM OF TWO NUMBERS

Version 1: Version 2:

Add Two
Add Two Numbers
Numbers

READ Two ADD Two


Numbers Write The
Numbers Sum

READ Sum = Input_1


ADD Two Write Read Num1 +Input_2
Two
Numbers The Sum
Numbers
Read Num2

Take note:
We develop software iteratively (meaning version by version), but
the code itself is broken in top-down manner!!

C++ CODING  WRITE A PROGRAM CALCULATING THE SUM


OF TWO NUMBERS
/* Addition of 2 numbers */

#include <iostream> Where do you find now in


using namespace std; the code the steps we
have developed?
int main()
{ 1. Declaration of the
int first, second, sum; structure

cin>>first; 2. Reading the input


cin>>second;
3. Processing the data
sum = first + second;
cout<<sum<<endl; 4. Writing the output

return 0;
}

24
PROGRAMMING GUIDELINE

The following rules are intended


to avoid some mistakes students
normally do. Even, if you have not
programmed much until now and
some of the given rules may still
be a little bit cryptic, you can
capture the idea and apply the
rules right from the start.
Programming can be fun, but also
a torture.

PROGRAMMING GUIDELINE
Rule 2: You cannot program, what
Rule 1: Think about your strategy you cannot do with paper and pencil.
twice! Choose a strategy possibly
coming out with less program
lines.

It is worth to rethink your strategy.


- Do I really have chosen the best?
- Can I reformulate my problem to Play with your data. Play to be the
make it more simple? computer. You are only allowed to
perform actions a computer can.
Can you solve your problem this
way?

Even after having No? Then do not touch a computer


an algorithm ready and think about your problem
in mind. again.

25
PROGRAMMING GUIDELINE
Rule 3: The compiler must be
easy and in short time accessible.
Rule 4: (Data) Structure before
functionality!
First declare all the
variables you will
need. (Later you will
use more advanced
structures like
objects, trees,
You can still use old DOS- graphs,..)
shells, if you want. But open
at least two windows, one for
editing, one for compiling the
code. But in all cases: The
data structure you
need has to be ready
Prepare your programming
first.
environment, save your files,
that it is fun to program.

PROGRAMMING GUIDELINE
Rule 5: Name your variables Rule 6: Write code using a divide
appropriate and format your code and conquer approach. (Top-down)
in a way, that the structure is
easily detectable.
while (counter < 100)
{
if (no > 1) Express Test Cycle
{
...
}
}

while (counter < 100){


 PROGRAM
if (no > 1) Add Two Numbers
{
...
}
}  READ
Two
Numbers
ADD
Two
Numbers
WRITE
The
Sum

26
PROGRAMMING GUIDELINE
Rule 7: Compile every three lines. Rule 8: Do your best in writing the
Write code in such a way, that it documentation, learn from your
Compiles and executes at every code.
moment of the code development! Make sure you do not do the same
mistakes again.
/* Addition of 2 numbers */

#include <iostream>
using namespace std;
Express Test Cycle
int main()
{
/* The input numbers */
int first, second; Comment
clearly
/* The output number */
Whatever we do, our code always int sum;
compiles and executes!!
....
Compile very often! Detect a
mistake as soon as possible!

SUMMARY
• A program (also commonly called an application or software) is a set of
instructions that tells the computer what to do.

• A vocabulary and set of grammatical rules for instructing a computer to perform


specific tasks. Computer programs are created by using programming languages.
Foundation for developing applications.

• Elements of programming are :Symbols ,Reserved words and Identifiers.

• IPO charts use to organize and summarize the results of a problem


definition.

• Pseudocode are English-like statements that follow a loosely defined


syntax and are used to convey the design of an algorithm.

• Flowcharts show the workflow of the algorithm and stress on structured


programming.

27
Computer Programming Bukc

Pointers

POINTER DATA TYPE AND POINTER VARIABLES

• C++’s data types are classified into


three categories:
▫ Simple
▫ Structured
▫ Pointers

1
Computer Programming Bukc

VARIABLE AND MEMORY

identifier

int main ()
{ int a int b int c
int a;
int b; 1000 2000 3000
int c;

a = 1000; value
b = 2000;
c = 3000;
}

VARIABLE AND MEMORY

int main ()
{
int a; int a int b int c
int b;
int c; 1000 2000 3000

a = 1000; 1004 1008 1012 1016


b = 2000;
c = 3000; address
}

2
Computer Programming Bukc

WHAT IS THE POINTER?


‘Pointer’ is a variable that contains a memory
address of other variable (does not contain a
actual data).This is why we call it “Pointer” since it
is used to POINT other variable.

POINTER

int a int b int c


int main ()
{
int a; 1000 2000 3000
int b;
int c;
1004 1008 1012 1016

int* ptr;
int* ptr
a = 1000;
b = 2000; NUL
c = 3000;
} 3004 3008

3
Computer Programming Bukc

POINTER

int a int b int c


int main ()
{
int a; 1000 2000 3000
int b;
int c;
1004 1008 1012 1016
int* ptr;

memory int* ptr


a = 1000; address of ‘a’
b = 2000;
c = 3000; 1004
ptr = &a;
} 3004 3008

POINTER DECLARATION

 Thus, the character * can appear anywhere between the


data type name and the variable name.

4
Computer Programming Bukc

POINTER DECLARATION

 int* p, q;

 In this statement:
 only p is the pointer variable, not q.
 Here, q is an int variable.

 we prefer to attach the character * to the variable


name. So the preceding statement is written as:
int *p, q;

POINTER OPERATOR

 C++ provides two operators to work with pointers.

 (&) the address of operator

 (*) the dereferencing

5
Computer Programming Bukc

ADDRESS OF OPERATOR (&)

 is a unary operator that returns the address of its operand.


 For example, given the statements:

int x;
int *p;
 The statement:
p = &x;
 assigns the address of x to p. That is, x and the value of p refer
to the same memory location

DEREFERENCING OPERATOR (*)

 referred to as indirection operator


 refers to the object to which its operand (that is, the pointer)
points.
 For example, given the statements:

p X
25

6
Computer Programming Bukc

DEREFERENCING OPERATOR (*)

 Let us consider the following statements:

In these statements:
 p is a pointer variable of type int
 num is a variable of type int.

 Let us assume that memory location 1200 is


allocated for p, and memory location 1800 is
allocated for num.

DEREFERENCING OPERATOR (*)


• Consider the following statements

1. num = 78;

2. p = &num;

3. *p = 24;

7
Computer Programming Bukc

EXAMPLE

OPERATIONS ON POINTER VARIABLES


 The value of one pointer variable can be assigned to another
pointer variable of the same type.

 Two pointer variables of the same type can be compared for


equality, and so on.

 Integer values can be added and subtracted from a pointer


variable.

 The value of one pointer variable can be subtracted from


another pointer variable.

8
Computer Programming Bukc

OPERATIONS ON POINTER VARIABLES

 copies the value of q into p. After this statement


executes, both p and q point to the same memory
location.
 Any changes made to *p automatically change the
value of *q, and vice versa.

COMPARISON

The expression:
 p == q
evaluates to true if p and q have the same value—that is, if they
point to the same memory location.

Similarly, the expression:


 p != q
evaluates to true if p and q point to different memory locations.

9
Computer Programming Bukc

DECREMENT AND INCREMENT


 ++ increments the value of a pointer variable by the size of the
memory to which it is pointing.
 Similarly, -- the value of a pointer variable by the size of the
memory to which it is pointing.
 Recall that the size of the memory allocated for an
 int variable is 4 bytes
 a double variable is 8 bytes
 a char variable is 1 byte.
 studentType is 39 bytes.

DECREMENT AND INCREMENT


The statement:
 p++; or p = p + 1;
increments the value of p by 4 bytes because p is a pointer of type int.
Similarly, the statements:
 q++;
 chPtr++;
increment the value of q by 8 bytes and the value of chPtr by 1 byte,
respectively.
The statement:
 stdPtr++;
increments the value of stdPtr by 39 bytes.

10
Computer Programming Bukc

FUNCTIONS AND POINTERS


 A pointer variable can be passed as a parameter to a function
either by value or by reference.

 In the function pointer Parameters, both p and q are pointers.


The parameter p is a reference parameter; the parameter q is
a value parameter.
 Furthermore, the function pointer Parameters can change the
value of *q, but not the value of q. However, the function
pointer Parameters can change the value of both p and *p.

11
Computer Programming Bukc

POINTERS AND FUNCTION RETURN VALUES

 In C++, the return type of a function can be a pointer.


For example, the return type of the function:

12
Computer Programming Bukc

POINTERS TO ARRAYS

same
a &a[0]
‘a’ is a pointer only to the first element, not the whole array

ARRAY NAME AS A POINTER

a[0] a[1] a[2]

int main () 1000 2000 3000


{
int a[3];
1004 1008 1012 1016
cout << &a[0];
// → 1004 The name of an array is a pointer
constant to its first element

cout << a;
// → 1004
}
a

13
Computer Programming Bukc

DEREFERENCE OF ARRAY NAME

ARRAY NAMES AS POINTERS

14
Computer Programming Bukc

POINTER ARITHMETIC AND DIFFERENT TYPES

DEREFERENCING ARRAY POINTERS

15
Computer Programming Bukc

DEREFERENCING ARRAY POINTERS

#include <iostream>
using namespace std;

int main()
{
int a[5]={2,4,6,8,22};
int *p=a+1;
int i=2;

cout<<a[i]<<" "<<*p;

system("pause");
return 0;
}

16
Computer Programming Bukc

An Overview of Functions

RECALL

 A function is a special relationship where each input has a single output. It is often
written as "f(x)" where x is the input value.

Example:
f(x) = x/2 ("f of x is x divided by 2") is a function, because each input "x" has a
single output "x/2“.

 A function groups a number of statements into a unit and gives it a name. this
unit can then be invoked from other parts of a program.
Computer Programming Bukc

OBJECTIVES

 Create a function that return a value

 Invoke a function that return a value

 Create a function that does not return a value

 Invoke a function that does not return a value

 Pass information, by reference, to a function

ABOUT FUNCTIONS IN C++


 Dividing a program into functions is one of the major principals of
structure programming.
 Boss To Worker Analogy
 A Boss (the calling/caller function) asks a worker (the called
function) to perform a task and return result when it is done.
Boss
Main

Worker
Worker Worker

Function A Function B Function Z

Worker Worker
Note: usual main( ) Calls other
Function B1 Function B2 functions, but other functions
can call each other
Computer Programming Bukc

FUNCTIONS IN C++

 Some of the functions used in a program are built into the C++ language.
The code for these built-in functions resides in C++ libraries, which are
special files that come with the C++ language.

 some built-in functions: setw(n) ,sqrt(n).

 Other functions, like main, are created by the programmer.

 These functions are often referred to as program-defined functions


because the function definitions are typically contained in the program
itself rather than in a different file.

FUNCTION
Function declaration (Function prototype )
 Gives the “full name” of the function to be called.
 Function prototype must precede any call or definition of a function
 - Compiler must know of a function's existence Else a compiler error will occur
undeclared

Function definition (function implementation )


 Contains statements that specify its behaviour when it is called.
 Function must be defined in order to be called ,Else a linker error will occur
undefined reference to.
Calling A Function
 For a function to perform its task, it must be called (or invoked).
 The main function in a C++ program is invoked automatically when the program is
executed. Functions other than main, must be called by a function Name.
Computer Programming Bukc

VOID FUNCTIONS
void functions cannot be used in an expression; they must be a separate
statement.function1();

Functions without Parameters Functions with Parameters


Syntax Declare a function Syntax Declare a function

void FunctionName (); void FunctionName(DataType identifier);

Define a function Define a function


void FunctionName () void FunctionName (DataType identifier)
{ {
Statements Statements e.g cout , cin , for , while ,
e.g cout , cin , for , while , dowhile dowhile
and if else and if else
} }

Call a function Call a function

FunctionName (); FunctionName ( identifier);

VALUE RETURNING FUNCTIONS


Functions that return a value may be used in an expression or as a separate statement.
int sum = function2();
Functions without Parameters Functions with Parameters
Syntax Declare a function Syntax Declare a function

Data Type FunctionName (); DataType FunctionName (DataType Parameters);

Define a function OR function header Define a function OR function header

Data Type FunctionName () Data Type FunctionName (Data Type Parameters)


{ {
Statements e.g cout , cin , for , while , Statements e.g cout , cin , for , while , dowhile
dowhile and if else and if else
Return; Return Value;
} }
Call a function Call a function

Variable = FunctionName (); Variablea = FunctionName (Parameters);


Computer Programming Bukc

FUNCTIONS

Recall
Identifiers allow us to
name variables, constant
names, functions and
objects in the program

 Rules For Function Names


Datatypes
 First character must be an alphabet int, float , double, char
or an underscore ,enumeration,array
 Can consist of alphabets, digits and
underscore
 C++ is case sensitive language

FUNCTIONS
Computer Programming Bukc

WRITE A PROGRAM CALCULATING THE SUM OF TWO


NUMBERS : ADDITION
Input Processing Output

5, 10 15

1) Declare variables 3) Process


num1 2) Assign values
num1 = 5 sum = num1 + num2
num2
sum num2 = 10

The computer (and so C) provides


basic arithmetic operations. If the
Names for our cells operation you want to use is not
provided, you have to compose it.

EXAMPLE#1

Write a program calculating the sum of two numbers: Addition.


Suppose you were asked to add two numbers mentally. The first thing you would
do is ask for the two numbers. When you are given the two number.
You would add them. You would then communicate the result to the person who
asked you for it.

Input Process Output


IPO Chart Num1 Input Num1 Sum
Num2 Input Num2
Sum=num1+num2
print Sum;
Computer Programming Bukc

VALUE RETURNING FUNCTIONS WITHOUT PARAMETERS


#include <iostream>
#include <iomanip> setw() : Setting field
using namespace std; width Using Cout in
C++ Programming
int main () {
int num1 =5,num2 =10,sum =0;
sum= num1+num2;
cout<<"Sum of Two Numbers\n";
cout<< "Num1" <<setw(9)<< "=“
<<setw(10)<<num1<<endl ; Key Point
cout<< "Num2"<<setw(9) << "="<<setw(10) Function name is
<<num2<<endl; SAME for
cout<<"Sum"<<setw(10)<<"=" declarations,
Calling, and
<<setw(10)<<sum<<endl;
definition.
return 0;
}

VALUE RETURNING FUNCTIONS WITHOUT PARAMETERS


Without functions With functions
#include <iostream>
#include <iomanip>
#include <iostream>
using namespace std;
#include <iomanip>
int addition ();//function declaration
using namespace std;
int main () {
int main () {
int Result =0;
int num1 =5,num2 =10,sum =0;
Result= addition ();//function calling
sum= num1+num2;
cout<<"Sum"<<setw(10)<<"=" <<setw(10)<<Result<<endl;
return 0;
cout<<"Sum of Two Numbers\n";
}
cout<< "Num1" <<setw(9)<< "=“ <<setw(10)<<num1<<endl ;
int addition () //function definition
{//start function
cout<< "Num2"<<setw(9) << "="<<setw(10) <<num2<<endl;
int num1 =5,num2 =10,sum =0;
sum= num1+num2;
cout<<"Sum"<<setw(10)<<"=" <<setw(10)<<sum<<endl;
cout<<"Sum of Two Numbers\n";
return 0;
cout<< "Num1" <<setw(9)<< "=" <<setw(10)<<num1<<endl ;
}
cout<< " " <<setw(9)<< "+" <<endl ;
cout<< "Num2"<<setw(9) << "="<<setw(10) <<num2<<endl;

return sum;
} //end function
Computer Programming Bukc

VALUE RETURNING FUNCTIONS WITHOUT PARAMETERS


#include <iostream>
#include <iomanip>  Function addition return the sum of
using namespace std; Two numbers which is in sum variable.
int addition ();//function declaration
int main () {  Then assign the value to result variable.
int Result =0;
Result= addition();//function calling Result=0 sum=15
cout<<"Sum"<<setw(10)<<"="
<<setw(10)<<Result<<endl; Assign to
Return sum
return 0; Result
}
int addition() //function definition
{//start function
int num1 =5,num2 =10,sum =0; Result=15
sum= num1+num2;
cout<<"Sum of Two Numbers\n";
cout<< "Num1" <<setw(9)<< "="
<<setw(10)<<num1<<endl ;
cout<< " " <<setw(9)<< "+" <<endl ; In this program we have
cout<< "Num2"<<setw(9) << "="<<setw(10) neither a parameter nor a
<<num2<<endl; argument!!
return sum;
} //end function

EXAMPLE#2
Write a C++ Program that contains four user defined function(s) addition(),
subtraction(), division(), multiplication(). Develop a calculator as follows:
In main() function:
1. A menu with choices addition,subtraction,division and multiplication must be
displayed.
2. Get two numbers and a choice from user
3. Call the respective functions with user given number as parameter using
switch statement
4. Print the result from addition(), subtraction, division(), multiplication().
In user defined functions:
5. Plus and Minus function get two interger values and return interger.
6. Multiply and Divide functions get two interge values and return float

Input Process Output


IPO Chart Num1 Input Num1 Result
Num2 Input Num2
choice print Result;
Computer Programming Bukc

EXAMPLE
int main () {
int num1 =5,num2 =10;float Result
=0;char option; Function Declaration
cout<<"Enter a Character + - / OR int addition(int num1,int num2);
*"<<endl; int subtraction(int num1,int num2);
cin>>option; float division(int num1,int num2);
if(option=='*'){ float multiplication (int num1,int
cout<<"Product of Two Numbers\n"; num2);
Result= num1*num2;
cout<< num1<< "*"<<num2<< " = "
<<Result;
}else if(option=='-'){
Function Definition addition
cout<<"Diffrence of Two Numbers\n";
int addition(int num1,int num2)
Result= num1-num2;
{
cout<< num1<< " - " <<num2<< " = "
cout<<"sum of Two Numbers\n";
<<Result;
}else if(option=='/'){
cout<< num1<< "+"<<num2<< " = ";
cout<<"Division of Two Numbers\n"; return num1+num2;
Result= num1/num2; }
cout<< num1<< " / " <<num2<< " = "
<<Result;
}else if(option=='+'){
cout<<"sum of Two Numbers\n";

EXAMPLE

Step 1. Function Declare Function Declaration


Step 2. Function definition int addition(int num1,int num2);
Step 2. Function calling int subtraction(int num1,int num2);
float division(int num1,int num2);
float multiplication (int num1,int
num2);
arguments
parameters

Function Definition addition


Function Calling addition int addition(int num1,int num2)
if(option=='+') {
{ cout<<"sum of Two Numbers\n";
Result= addition(num1,num2); cout<< num1<< "+"<<num2<< " = ";
} return num1+num2;
}
Computer Programming Bukc

EXAMPLE
Function Definition subtraction
Function Definition addition
int subtraction (int num1,int num2)
int addition(int num1,int num2)
{
{
cout<<"subtraction of Two
cout<<"sum of Two Numbers\n";
Numbers\n";
cout<< num1<< "+"<<num2<< " = ";
cout<< num1<< “-"<<num2<< " = ";
return num1+num2;
return num1-num2;
}
}

Function Definition multiplication Function Definition division


float multiplication(int num1,int num2) float division(int num1,int num2)
{cout<<"Product of Two Numbers\n"; {cout<<"division of Two Numbers\n";
cout<< num1<< "*"<<num2<< " = "; cout<< num1<< “/"<<num2<< " = ";
return num1*num2; return num1/num2;
} }

EXAMPLE
int main () {
int addition(int num1,int num2); int num1 =10,num2 =5;
int subtraction(int num1,int num2); float Result =0;
float division(int num1,int num2); char option;
float multiplication (int num1,int num2); cout<<"Enter a Character + - / OR *"<<endl;
int addition(int num1,int num2) cin>>option;
{cout<<"sum of Two Numbers\n"; if(option=='*')
cout<< num1<< "+"<<num2<< " = ";
{
return num1+num2;
} Result= multiplication(num1,num2);
float multiplication(int num1,int num2) }else if(option=='-')
{cout<<"Product of Two Numbers\n"; {
cout<< num1<< "*"<<num2<< " = "; Result= subtraction(num1,num2);
return num1*num2; }else if(option=='/')
} {
int subtraction(int num1,int num2)
Result= division(num1,num2);
{cout<<"Difference of Two Numbers\n";
cout<< num1<< "-"<<num2<< " = "; }else if(option=='+')
return num1-num2; {
} Result= addition(num1,num2);
float division(int num1,int num2) }else cout <<"invalid operator";
{cout<<"Division of Two Numbers\n"; cout<< Result;
cout<< num1<< "-"<<num2<< " = ";
return num1/num2;
return 0;
}
}
Computer Programming Bukc

EXAMPLE#3
Write a C++ Program that contains one user defined function cal_grades().
• In main() function:
• Prompt user to enter obtained(0 - 100) marks for one subject.
• Call cal_grades(marks_subject).
• Print the corresponding Grade with respect to Marks.
• In user defined function:
• Perform conditioning with else if statement return char value.
• Function must return value.

Input Process Output


IPO Chart marks print Grades; Grades

EXAMPLE#3
Computer Programming Bukc

EXAMPLE#4
Write a C++ Program that contains one user defined function month().
In main() function:
Read an integer input in between (1 to 12) and store it month_of_year.
Call month(month_of_year)
In month() function:
Print the corresponding month of year in month().
Example: Value of parameter is 4… Print “April”.

Input Process Output


IPO Chart month_of_year Print the corresponding corresponding month
month of year ;

Recall if else lab


tasks!!
Computer Programming Bukc
Computer Programming Bukc
Computer Programming Bukc

VOID FUNCTIONS
Syntax Declare a function
 void means EMPTY.
 void data type means function does not void FunctionName ();
return anything.
 A void function does not have a return
Define a function
type
void FunctionName ()
 return statement without any value is {
typically used to exit the function early Statements
e.g cout , cin , for , while , dowhile
and if else
 Formal parameters are optional }
 A call to a void function is a stand-alone
statement Call a function
 Function will just execute some
FunctionName ();
statements .
Computer Programming Bukc

WRITE A PROGRAM CALCULATING THE SUM OF TWO


NUMBERS : ADDITION
Input Processing Output

5, 10 15

1) Declare variables 3) Process


num1 2) Assign values
num1 = 5 sum = num1 + num2
num2
sum num2 = 10

The computer (and so C) provides


basic arithmetic operations. If the
Names for our cells operation you want to use is not
provided, you have to compose it.

EXAMPLE

Activity #2: Write a program calculating the sum of two numbers: Addition.
Suppose you were asked to add two numbers mentally. The first thing you would
do is ask for the two numbers. When you are given the two number.
You would add them. You would then communicate the result to the person who
asked you for it.

Input Process Output


IPO Chart Num1 Input Num1 Sum
Num2 Input Num2
Sum=num1+num2
print Sum;
Computer Programming Bukc

VOID FUNCTIONS WITHOUT PARAMETERS


#include <iostream>
#include <iomanip>
using namespace std;
int main () {
int num1 =5,num2 =10,sum =0;
sum= num1+num2;
cout<<"Sum of Two Numbers\n";
cout<<"======================\n";
cout<< "Num1" <<setw(9)<< "=“
<<setw(10)<<num1<<endl ;
cout<< "Num2"<<setw(9) << "="<<setw(10)
<<num2<<endl;
cout<<"Sum"<<setw(10)<<"="
<<setw(10)<<sum<<endl;
return 0;
}

VOID FUNCTIONS WITHOUT PARAMETERS


#include <iostream>
#include <iostream> using namespace std;
#include <iomanip> void sum ();//function declaration
using namespace std; int main () {
int main () { sum();//function calling
int num1 =5,num2 =10,sum =0; return 0;
sum= num1+num2; }
cout<<"Sum of Two Numbers\n"; void sum () //function definition
cout<<"======================\n"; {//start function
cout<< "Num1" <<setw(9)<< "=“ int num1 =5,num2 =10,sum =0;
<<setw(10)<<num1<<endl ; sum= num1+num2;
cout<< "Num2"<<setw(9) << "="<<setw(10) cout<<"Sum of Two Numbers\n";
<<num2<<endl; cout<<"=====================
cout<<"Sum"<<setw(10)<<"=" =\n";
<<setw(10)<<sum<<endl; cout<< "Num1" <<setw(9)<< "="
return 0; <<setw(10)<<num1<<endl ;
} cout<< "Num2"<<setw(9) <<
"="<<setw(10) <<num2<<endl;
cout<<"Sum"<<setw(10)<<"="
<<setw(10)<<sum<<endl;
} //end function
Computer Programming Bukc

VOID FUNCTIONS WITHOUT PARAMETERS


#include <iostream>
#include <iomanip>
using namespace std; Key Point
void sum ();//function declaration Function name is
int main () {
sum();//function calling SAME for
return 0; declarations,
} Calling, and
void sum () //function definition
definition.
{//start function
int num1 =5,num2 =10,sum =0;
sum= num1+num2;
cout<<"Sum of Two Numbers\n";
cout<<"======================\n";
cout<< "Num1" <<setw(9)<< "="
<<setw(10)<<num1<<endl ;
cout<< "Num2"<<setw(9) <<
"="<<setw(10) <<num2<<endl;
cout<<"Sum"<<setw(10)<<"="
<<setw(10)<<sum<<endl;
} //start function

VOID FUNCTIONS WITH PARAMETERS


#include <iostream>
#include <iomanip>
using namespace std; Key Point
void sum (int num1, int num2);//function Function name is
declaration
int main () { SAME for
Int a=5, b=10; declarations,
sum(a,b);//function calling Calling, and
return 0;
definition.
}
void sum (int num1, int num2) //function
definition
{//start function
int sum=0;
sum= num1+num2;
cout<<"Sum of Two Numbers\n";
cout<<"======================\n";
cout<< "Num1" <<setw(9)<< "="
<<setw(10)<<num1<<endl ;
cout<< "Num2"<<setw(9) <<
"="<<setw(10) <<num2<<endl;
cout<<"Sum"<<setw(10)<<"="
<<setw(10)<<sum<<endl;
} //start function
Computer Programming Bukc

SUMMARY

SUMMARY
Computer Programming Bukc

SUMMARY
Pass by Value OR Passing Parameters

Different local
variables

SUMMARY
EXAMPLES OF FUNCTION CALLS
Computer Programming Bukc

PREVIOUS LECTURE
Functions

with arguments without arguments


 No parameters List
 Declare and define with
 No Values passed during
parameters
function calling
 Values for parameters passed
 Eg
during function calling
Int sum();//declare
 Eg
Sum();//calling
Int sum(int x , int y);//declare
Sum(4,5);//calling

WHILE CALLING A FUNCTION, THERE ARE TWO WAYS THAT


ARGUMENTS CAN BE PASSED TO A FUNCTION:
Computer Programming Bukc

PASS BY VALUE

Different local
variables

PASS BY VALUE

By default, C++ uses call by value to pass arguments. In general, this


means that code within a function cannot alter the arguments used to call
the function. Consider the function swap() definition as follows.
Computer Programming Bukc

NOW LET US CALL THE FUNCTION SWAP() BY PASSING


ACTUAL VALUES AS IN THE FOLLOWING EXAMPLE:

REFERENCE VARIABLES
 A reference variable is a nickname, or alias, for
some other variable.
int n = 5; //declares a variable, n
 To declare a reference variable, we use the
int & r = n; //declares r as a reference to n
unary operator & address operator
cout<<"r= "<<r<<endl;
 To declare a reference variable, add the & n=9;//change the value of r and makes 9
operator after the type. cout<<"r= "<<r<<endl;
 Note: The notation can become confusing
when different sources place the & differently.
The following three declarations are output:
equivalent: r=5
int &r = n;
r=9
int& r = n; equivalent:
In this example, r is now a
int & r = n;
reference to n.
 The spacing between the "int" and the "r" is (They are both referring to the
irrelevant. All three of these declare r as a SAME storage location in
reference variable that refers to n.
memory).
Computer Programming Bukc

PASS BY REFERENCE VS. PASS BY VALUE


Pass By Value Pass By Reference
 Pass By Value function
 Pass By Reference the local
parameters receive copies of the
data sent in. parameters are references to the
storage locations of the original
 The local parameters are copies
of the original arguments passed arguments passed in.
in  Changes to these variables in the
 Changes made in the function to function will affect the originals.
these variables do not affect
originals  No copy is made, so overhead of
copying (time, storage) is saved.

EXCHANGE
Computer Programming Bukc

PASS BY REFERENCE

REFERENCE VARIABLES

 Write a program using function that adds two integers and stores the result in a
variable that is referenced.

 Hint: addnumbers(int, int, int&)


Computer Programming Bukc

REFERENCE VARIABLES
#include <iostream>
using namespace std;
Explanation
void addnumbers(int , int , int&);
int main() Main() a b sum
{ addnumbers(a,b,sum) Num1=a Num2=b Result
int a =10, b=5,sum=0;
output
addnumbers(a,b,sum);
cout <<a<<"+"<<b<<"="<<sum;
}
void addnumbers(int num1, int
num2, int&result)
{
result=num1+num2;
}

REFERENCE VARIABLES

 Write a program that doubles the values of the initialized variables using a user
defined function by reference.

 Hint: void Twice(int&, int&)


Computer Programming Bukc

REFERENCE VARIABLES
#include <iostream>  Note that when it is run, the variables
using namespace std;
void Twice(int&, int&);// DECLARE before use
passed into Twice from the main() function
int main() DO get changed by the function.
{
int x = 5, y = 8;  The parameters a and b are still local to the
cout << "Initial values of variables:\n"; function, but they are reference variables.
cout << "\tx = " << x;
cout << "\ty = "<< y;  When reference variables are used as
cout << '\n';
cout << "Calling the function Twice(x,y)\n"; formal parameters, this is known as Pass
Twice(x,y);// x=5 , y =8 By Reference.
cout << "The new values of x and y are:\n";
cout << "\tx = " << x << "\ty = " << y << '\n';  When a function expects strict reference
cout << "Goodbye!\n"; types in the parameter list, a Local-value
}
void Twice(int& a, int& b) (i.e. a variable, or storage location) must
{//a=5 b=8 be passed in.
a *= 2;
b *= 2;
//a=10 means x=10
//b=16 mean b=16
}

EXAMPLE
Write a C++ Program that contains four user defined function(s) _plus(int, int,
int&), _minus(int, int, int&), _multiply(int, int, int&), _divide(int, int, float&).
In main() function:
1. Get two numbers from user
2. Call four user defined functions
3. Variable to contain result should be declared in main function and passed as
reference to the user defined function.
4. Calculation must be done in the user defined function according to their names,
e.g. plus() should perform addition of the two variables. Variable to contain
result should be updated in user defined function.

Input Process Output


IPO Chart Num1 Input Num1 Result
Num2 Input Num2
choice print Result;
Computer Programming Bukc

EXAMPLE
void addition(int ,int,float&);
void subtraction(int ,int,float&);
void division(int ,int,float&);
void multiplication (int ,int,float&);
void addition(int num1,int num2,float&answer)
{cout<<"sum of Two Numbers\t"; int main () {
cout<< num1<< "+"<<num2<< " = "; int num1 =10,num2 =5;
answer= num1+num2; float Result =0;
} multiplication(num1,num2 , Result);
void multiplication(int num1,int num2,float&answer)
cout<< Result<<endl;
{cout<<"Product of Two Numbers\t";
subtraction(num1,num2 , Result);
cout<< num1<< "*"<<num2<< " = ";
cout<< Result <<endl;
answer= num1*num2;
division(num1,num2, Result);
}
void subtraction(int num1,int num2,float&answer)
cout<< Result <<endl;
{cout<<"Difference of Two Numbers\t"; addition(num1,num2, Result);
cout<< num1<< "-"<<num2<< " = "; cout<< Result <<endl;
answer= num1-num2; return 0;
} }
void division(int num1,int num2,float&answer)
{cout<<"Division of Two Numbers\t";
cout<< num1<< "/"<<num2<< " = ";
answer= num1/num2;
}

EXAMPLE
Write a C++ that calculate price of purchased items.
• A shopkeeper supplies following items.
• notebooks, English novels and stationary
• notebooks = 160
• English novels = 1200
• stationary = 110
Ask user to enter purchased quantity of each item. Store values in variables.
Write a function Cal_Price (int, int, int& total) that calculate the price for each item.
For example Cal_Price(160,2,total) saves 320 in variable total.
Print the results from main():

Input Process Output


IPO Chart notebooks, Calculate price for each Per item price
English novels item And
and stationary Total Price
Computer Programming Bukc

REFERENCE VARIABLES
int Cal_Price (int , int,int&); cout<< "How many stationary did you buy:";
void diplaylines(); cin>>Quantity_stationary;
void diplaystars(); diplaylines();
int Cal_Price (int price , int Quantity,int& Total) peritem_total=Cal_Price(Price_books,Quantity_b
{int p =price*Quantity; ooks,Total_Price);
Total=p+Total; cout <<"Price for notebooks:"<< Quantity_books
return p;} <<"*"<< Price_books<< " =
void diplaylines() "<<peritem_total<<endl;
{cout<<"========================================" peritem_total=Cal_Price(Price_novels,
<<endl; } Quantity_novels,Total_Price);
void diplaystars() cout <<"Price for novels:"<< Quantity_novels
{cout<<"****************************************" <<"*"<< Price_novels<< " =
<<endl;} "<<peritem_total<<endl;
int main () { peritem_total=Cal_Price(Price_stationary,Quantit
int Quantity_stationary , Quantity_books, y_stationary,Total_Price);
Quantity_novels; cout <<"Price for stationary:"<<
int Price_stationary=110 , Price_books=160, Quantity_stationary <<"*"<< Price_stationary<< "
Price_novels=1200; = "<< peritem_total<<endl;
int Total_Price=0,peritem_total=0; diplaystars();
diplaylines(); cout <<"Total Price of your purchase is:"
cout<< "How many notebooks did you buy:"; << Total_Price<<endl;
cin>>Quantity_books; diplaystars();
cout<< "How many novels did you buy:";
cin>>Quantity_novels; return 0;
}

LECTURE OUTLINE

 Overloading Functions
 What is function overloading
 How to perform function overloading
 Examples of function overloading

 Recursion
 What Overview of Recursion
 Factorial example
 Some benchmark examples of recursion

58
Computer Programming Bukc

Calling Function
2 ways of calling any function

Functions

Call by Value Call by Reference

SCOPE OF AN IDENTIFIER

 Rules when an identifier accessed:


 Global identifiers
 Declared before function definition
 Function name different from identifier
 Parameters to function have different names
 All local identifiers have different names

 Nested block
 Identifier accessible from declaration to end of block
 Within nested blocks if no identifier with same name exists
60
Computer Programming Bukc

FUNCTION OVERLOADING

 In a C++ program, several functions can have the same name

 This is called function overloading or overloading a


function name
 Two functions are said to have different formal parameter lists if both functions
have:

 A different number of formal parameters, or


 If the number of formal parameters is the same, then the
data type of the formal parameters, in the order you list
them, must differ in at least one position

61

FUNCTION OVERLOADING (CONT'D.)

 Function overloading: creating several functions with the same


name
 The signature of a function consists of the function name and
its formal parameter list
 Two functions have different signatures if they have either
different names or different formal parameter lists
 Note that the signature of a function does not include the
return type of the function

62
Computer Programming Bukc

FUNCTION OVERLOADING (CONT'D.)

1. void print();

 An overloaded function must have: 2. void print(int a);

 Different type of parameters. 3. void print(float a);


 Different number of parameters. 4. void print(int a, int b);
 Different sequence of parameters. 5. void print(int a, double b);
6. void print(double a, int b);

FUNCTION OVERLOADING (CONT'D.)

 Correct function overloading:

 Syntax error:

64
Computer Programming Bukc

FUNCTION OVERLOADING - EXAMPLE

65

DIFFERENT NUMBERS OF ARGUMENTS


Computer Programming Bukc

DIFFERENT KINDS OF ARGUMENTS

FUNCTION OVERLOADING (CONT'D.)

 printOnNewLine(3) prints “1 Integer: 3”


 printOnNewLine(2, 3) prints “2 Integers: 2 and 3”
68
Computer Programming Bukc

FUNCTION OVERLOADING (EXAMPLE)


Write a C++ that contains following functions:
int main():
• prompt user to enter numbers for comparison.
• Minimum numbers user can enter are 2 and maximum up to 4.
• call comparison() method with two, three and four parameters.
int comparison():
• this function determine the smallest and largest number
• print the smallest and largest number
• this function(s) must be overloaded

69

PASSING ARRAYS TO FUNCTIONS


 An array name actually represents a memory address

 Thus, an array name is a pointer

 The subscript used to access an element of an array


indicates how much to add to the starting address to locate
a value

 When you pass an array to a function, you are actually


passing an address

 Any changes made to the array within the function also


affect the original array
Computer Programming Bukc

PASSING ARRAYS TO FUNCTIONS


 C++ does not allow to pass an entire array as an
argument to a function.

 However, You can pass a pointer to an array by


specifying the array's name without an index.

 If you want to pass a single-dimension array as an


argument in a function, you would have to declare
function formal parameter in one of following three
ways and all three declaration methods produce similar
results because each tells the compiler that an integer
pointer is going to be received.
71

Passing arrays to functions

 Formal parameters as a pointer as follows:


Void myfunc(int *param)
{ Statements }

 Formal parameters as a sized array as follows:


Void myfunc(int param[10])
{ Statements }

 Formal parameters as an unsized array as follows:


Void myfunc(int param[])
{ Statements }
Computer Programming Bukc

Passing arrays to functions

 Write down a program that initializes a pre-defined array in


the main function and passes this array along with its size
in another function that calculates the average using these
two parameters.

Calculating average
double getaverage(int arr[], int
#include<iostream> size)
using namespace std; {
int i ,sum =0;
double getaverage(int arr[] , int
size); double avg;

int main() for(i =0;i<size;i++)


{ {
int balanc[5] = {12,34,56,21,6}; sum +=arr[i];
double avg; }
avg = getaverage(balanc,5);
//arrary and array size avg = (double)sum/size;
cout<<"average value
is"<<avg<<endl; return avg;
return 0; }
}
OUTPUT
Average value is 25.8
Computer Programming Bukc
10/18/2021

CSC-112
Programming
Fundamentals
Lecture 4

Lecture Outline
• Control Structures
• The while Statement
• The for Statement
• Nested Loops
• The do. . . while Statement
• The break and continue Statements

1
10/18/2021

Why Do We Need Repetition?

• Sometimes we want to do things more than once.


• E.g., Calculate the grades of 160 students
• E.g., Calculate the sum of 1~100

• How?
1.Cut and paste the codes 160 times?
2.cout << 1 + 2 + ……+100 << endl; ??
3.Then, what about summing up 1~10000?

Concept of Loop

Loop: The real power of computers!

2
10/18/2021

Loop Control Operation: Stopping the


Loop

Loop Control
Operation

Question: When to Check Loop-End


Condition?

3
10/18/2021

Two Different Strategies for Starting


Exercise

Minimum Number of Iterations in Two


Loops

4
10/18/2021

Loop Initialization and Updating

Initialization and Updating for Exercise

5
10/18/2021

Question: When to Stop a Loop?

• Counter-Controlled Loop
• Know how many times to loop when a loop begins
• E.g., do the summing calculation 100 times.

• Event-Controlled Loop
• Don’t know how many times, but knows how world will
be when done
• E.g., end the exercise when energy runs out

Event-Controlled Loop Concept

6
10/18/2021

Counter-Controlled Loop Concept

Loops in C++

Usually used Usually used Usually used


for event- for counter- for event-
controlled loop controlled loop controlled loop

7
10/18/2021

The while Statement

The Compound while Statement

8
10/18/2021

Examples of while Loop


#include<iostream>
using namespace std;

int main(){
int count=0;

while(count<2)
{
cout<<“Welcome the count is ”<< count << endl;
count++;
} Dry Run
return 0;
Count Condition Print
}
/* Output Welcome the
0 True
Welcome the count is 0 count is 0
Welcome the count is 1 Welcome the
*/ 1 True count is 1

Loop
2 False
Terminate

Examples of while Loop


#include<iostream>
using namespace std;

int main(){
int j; Dry Run
j=-5;
while(j<0) J Condition Print
{
cout<<j<<endl; -5 True -5
j=j+1;
} -4 True -4
return 0;
} -3 True -3
/* Output
-5 -2 True -2
-4
-3 -1 True -1
-2
Loop
-1 0 False
*/ Terminate

9
10/18/2021

Dry Run
ival Condition Print
10 True 10/2 = 5
5 True 5/2 = 2
2 True 2/2 = 1
1 True 0

Loop
0 False
Terminate

ival sum Condition Print

5 0
5 True
7 12 True

3 15 True

0 False 15

10
10/18/2021

num lineCount Print

15 0
15 1 15
14 2 14
13 3 13
12 4 12
11 5 11
10 6 10
9 7 9
8 8 8
7 9 7
6 10 6
5 1 5
4 2 4
3 3 3
2 4 2
1 5 1

Enter an integer: 12345


• Your number is: 12345

The number of digits is: 5


The sum of the digits is: 15

Count Sum Number


0 0 12345
1 5 1234
2 9 123
3 12 12
4 14 1
5 15 0

11
10/18/2021

The for Loop

A for loop is used when your loop is to be


executed a known number of times. You can
do the same thing with a while loop, but the
for loop is easier to read and more natural for
counting loops.

The for Statement

12
10/18/2021

The Compound for Statement

Comparing for and while Loops

13
10/18/2021

Step by Step Trace


int main()
{
int j;
for(j = -4; j <= 0 ; j = j + 1)
{
cout << j << endl;
}
return 0;
}

Loop counts Steps J J<=0 print J+1


1st 1 -4
iteration/loo
2 T
p
int main() 3 -4
{ int j; 4 -3
for(j = -4; j <= 0 ; j = j + 1) 2nd 5 -3
{ iteration/loo
6 T
p
cout << j << endl; 7 -3
} 8 -2
return 0; 3rd 9 -2
} 10 T
11 -2
12 -1
4th 13 -1
14 T
15 -1
16 -0
5th 17 0
18 T
19 0
20 1
6th iteration 21 1 F
21

14
10/18/2021

int main()
{ int main()
int j; {
j = -4; int j;
while(j <= 0) for(j= -4; j <= 0 ;j++ )
{ {
cout << j << endl; cout << j << endl;
j = j + 1; }
} return 0;
return 0; }
}

Conversion from while to for Loop

int main() int main()


{ {
int j = -4; int j;
for( ; j <= 0 ; ) for(j = -4; j <= 0 ; )
{ {
cout << j << endl; cout << j << endl;
j = j + 1; j = j + 1;
} }
return 0; return 0;
} }

15
10/18/2021

Examples!
• for(i = 2; i <= 6; i = i + 2)
cout << i+1 << ‘\t’;

• for(i = 2; i != 11; i = i + 3)
cout << i+1 << ‘\t’;

• cout << "\nPlease enter a limit: "; Please enter the limit: 3
cin >> limit; 1
for (i = 1; i <= limit; i++) 2
cout << "\t" << i << endl; 3

0 10
• for (n=0,i=10;n!=i;n++,i--) 1 9
cout << n <<"\t" << i << endl; 2 8
3 7
4 6

Nested for Loop


i j Print
1 1 $
2 $
3 $
4 $
5 $
.. 20 $
2 1 $
2 $
3 $
4 $
5 $
.. 20 $
3 1 $
2 $

16
10/18/2021

Limit LineCtrl numCtrl Print


5 1 1 1

2 endl

2 1 1

2 2

3 endl

3 1 1

2 2

3 3

4 endl

Format of the do…while Statement

17
10/18/2021

while vs. do … while

Print nothing because the i<0 is


checked prior to the cout

Print 0. cout is executed at least once


Before checking the i<0

break Statement
Unconditional loop exit

for(…;…;…) or while(…)
{

break;
… Terminate the loop and
} execution jumps to here

18
10/18/2021

break in Nested Loop

break - example
// break loop example
#include <iostream>
using namespace std; 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
int main () {

for (int n=10; n>0; n--)


{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
}

19
10/18/2021

continue Statement
Skip the rest of the loop body without
exiting the loop

Continue - example
// continue loop example
#include <iostream> 10, 9, 8, 7, 6, 4, 3, 2, 1, liftoff!
using namespace std;
int main () {
for (int n=10; n>0; n--)
{
if (n==5)
continue;
cout << n << ", ";
}
cout << "liftoff!\n";
}

20
10/18/2021

Continue - example
// continue loop example
#include <iostream> 10, 9, 8, 7, 6, 4, 3, 2, 1, liftoff!
using namespace std;
int main () {
for (int n=10; n>0; n--)
{
if (n==5)
continue;
cout << n << ", ";
}
cout << "liftoff!\n";
}

break vs. continue

Result:
Adam

Result:
Adam
Adam
Adam
Adam
Adam

21
10/18/2021

43

22
10/18/2021

CSC-112
COMPUTER PROGRAMMING

DR. ABDUL ATTAYYAB KHAN


EMAIL ADDRESS: aakhan.bukc@bahria.edu.pk

C++ Fundamentals

1
10/18/2021

SO FAR WE HAVE STUDY

 Fundamentals of C++
 Structure of C++ Program C++
 Data types
 Variables
 Escape Sequences
 I/O Statements (cin/cout)

LECTURE OUTLINE

 Operators
 Precedence of Operators
 Expression

2
10/18/2021

OPERATORS

Operators are symbols representing operations that can be performed on


variable and constants. There are four operations available in C++
programming.
1. Assignment Operations =
2. Arithmetic Operations (*,^,/,+,-,%)
3. Relational Operations (<,>,<=,>=,==)
4. Logical Operations (&&,||,!)

ARITHMETIC OPERATORS

Operators Meanings Syntax

+ Addition A+B

- Subtraction A-B

* Multiplication A*B

/ Division A/B

^ Power A^B
Return the reminder
Mod after integral division
A%B

= Assignment A=10;

3
10/18/2021

LOGICAL OPERATOR

Operator Usage Description


Logical AND expr1&&expr2 Returns expr1 if it can be converted to false;
(&&) otherwise, returns expr2. Thus, when used with
Boolean values, && returns true if both operands
can be converted to true; otherwise, returns false.

Logical OR expr1||expr2 Returns expr1 if it can be converted to true;


(||) otherwise, returns expr2. Thus, when used with
Boolean values, || returns true if either operand
can be converted to true; if both can be converted
to false, returns false.

Logical NOT !expr Returns false if its single operand can be converted
(!) to true; otherwise, returns true.

LOGICAL OPERATORS TRUTH TABLE


AND (&&) OR (||)
Bool OPR Bool OPR Result (&&)
Bool OPR Bool OPR Result (||)
True true True
True true True
true false False true false True
false false False false False False
false true False false true True

NOT(!)
X !x

True False

false true

4
10/18/2021

Compound Boolean Expression


1. (A And B )OR (NOT C)
2. NOT (A AND B) OR C
(A And B )OR
A B C A &&B !C (NOT C)

T T T

T T F

T F T

T F F

F T T

F T F

F F T

F F F
9

COMPOUND ASSIGNMENT
Compound expression Equivalent simple expression
X*=y X=x*y
x/=y X=x/y
X%=y X=x%y
X+=y X=x+y
X-=y X=x-y
X++ X=x+1
X-- X=x-1

Content of Content of Value of


expression Result of expression
variable x variable y expression

X*=y 10 5

x/=y 10 5

X%=y 10 5

X+=y 10 5

X-=y 10 5

5
10/18/2021

POSTFIX EXPRESSIONS
Remember!

(a++) is (a = a + 1)
(a– –) is (a = a – 1)

POSTFIX EXPRESSIONS
#include <iostream>
using namespace std;
Remember!
int main()

{ (a++) is (a = a + 1)
int a=5, x,y; (a– –) is (a = a – 1)

x=a++;
y=x+1;
cout << x << endl;
cout << y << endl;
cout << a << endl;
return 0;
}
OUTPUT:

5
6
6

6
10/18/2021

UNARY EXPRESSIONS
Remember!

(++a) is (a = a + 1)
(– –a) is (a = a – 1)

UNARY EXPRESSIONS
#include <iostream>
using namespace std; Remember!
int main()

{ (++a) is (a = a + 1)
int a=5, x,y; (– –a) is (a = a – 1)

x=++a;
y=x+1;
cout << x << endl;
cout << y << endl;
cout << a << endl;
return 0;
}
OUTPUT:

6
7
6

7
10/18/2021

OPERATOR PRECEDENCE

 Which operator will be


evaluated first?

 Each operator has one


of 18 precedence levels

ORDER OF PRECEDENCE

 Consider the logical expression:  Because relational and logical operators are
11 > 5 || 6 < 15 && 7 >= 8 evaluated from left to right, the
associativity of these operators is said to be
from left to right.

 This logical expression will yield


different results if || is evaluated
first or && is evaluated first.

 If || is evaluated first, this logical


expression evaluates to 0 (false).

 If && is evaluated first, this logical


expression evaluates to 1(true).

8
10/18/2021

PRECEDENCE OF OPERATORS
 You can insert parentheses into an expression to clarify its meaning.
 The expression

1 (true)
11 > 5 || 6 < 15 && 7 >= 8 11 > 5 || (6 < 15 && 7 >= 8)

 Evaluate the following expression:

(17 < 4*3+5) || (8*2 == 4*4) && !(3+3 == 6)


= (17 < 12+5) || (16 == 16) && !(6 == 6)
= (17 < 17) || true && !(true)
= false || true && false
= false || false
= false

STATEMENTS
 A statement causes an
action to be performed by
the program.
 A block of instructions
 Types of statements
 An is terminated expression
statement with a
semicolon (;). The
semicolon is a terminator,
and it tells the compiler that
the statement is finished.

9
10/18/2021

RELATIONAL OPERATIONS
 A relational operator allows you to make comparisons in a program.
 They are all binary operators and can accept two operands.

 Equality of real numbers is usually machine dependent. It is quite possible that on a particular
machine
 6.8 + 3.1 == 2.7 + 7.2 is false

19

10
10/18/2021

CSC-112
Programming
Fundamentals
Lecture 5

Lecture Outline

• Arrays
• One Dimension Array
• Sorting
• Searching

1
10/18/2021

Derived Types

Ten Variables

2
10/18/2021

Processing Ten Variables

Arrays
• Multiple values group together that have
same data type.
• Multiple values together as one unit that
have same data type.

• Store values Sequentially

• Like normal variable array must be initialized


before they can be used.
6

3
10/18/2021

Arrays

•To declare an empty integer array


named arr of four elements, we
write

Int arr[4];

Arrays

•To declare an integer array named


arr of four elements (3,5,7,0), we
write
Int arr[]={3,5,7,0};

4
10/18/2021

What are arrays…


• An array is the collection of similar elements. These
similar elements could be all int , float ,or all chars etc.
• Consecutive group of memory locations
• Same name and type (int, char, etc.)
• To refer to an element
• Specify array name and position number (index)
• Format: arrayname[ position number ]
• First element at position 0
• N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
• Nth element as position N-1

An Array of Scores

10

5
10/18/2021

The Scores Array

11

Declaring Arrays
• When declaring arrays, specify
• Name
• Type of array
• Any data type
• Number of elements
• type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats

• Declaring multiple arrays of same type


• Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];

12

6
10/18/2021

Examples Using Arrays


• Initializing arrays
• For loop
• Set each element
• Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements 0
• If too many syntax error
• To set every element to same value
int n[ 5 ] = { 0 };
• If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array

13

Declaring and defining arrays

14

7
10/18/2021

Initializing arrays

15

Loop for Ten Scores


Dry Run

i Condition Read Score[i]

0 True 15

1 True 16
True
2 21
True
3 45
True
4 65
True
5 24
True
..
False
10 16

8
10/18/2021

Loop for Ten Scores


Dry Run

i Condition Print Score[i]

0 True 15

1 True 16
True
2 21
True
3 45
True
4 65
True
5 24
True
..
False
10 17

Sample Program Using Arrays.

18

9
10/18/2021

Exchanging/ swapping scores-the


wrong way

19

Exchanging / swapping scores with


temporary variable

20

10
10/18/2021

Dry Run

i Condition sqrAry[i] sqrAry[i]

0 True 0 0

1 True 1 1
True
2 2 4
True
3 3 9
True
4 4 16

5 False

21

Print Input Reversed

22

11
10/18/2021

SORTING IN ARRAY
• Most common application is sorting.
• Process through which data are arranged according
to their values.
• Three sorting algorithms
• Selection sort
• Bubble sort
• Insertion sort
• Common concept : swapping of data between two
elements.
23

SEARCHING IN ARRAY

24

12
10/18/2021

Search concept

Sequential Search

13
10/18/2021

Unsuccessful search

Binary search example

Note that the list is


already sorted

14
10/18/2021

Lecture Outline
• Arrays
• Two Dimension Array
• Three Dimension Array
• Examples
• Multi Dimensional Array

Two-dimensional array
• Many applications require data be stored in more then
one dimension.

• A two-dimensional array consists of both rows and


columns of elements. It is essentially a matrix.

• To declare a two-dimensional array, we merely use two


sets of square brackets.
• The first contains the number of rows
• The second contains the number of columns
//Creates a 2D array with 3 rows and 4 columns
int vals[3][4];

15
10/18/2021

Two-dimensional array

Array of arrays

16
10/18/2021

Memory layout

Indices in 2D arrays
• Assume that the two dimensional array called val
is declared and looks like the following:
Val C1 C2 C3 C4
R1 8 16 9 52
R2 3 5 8 9
R3 21 17 13 12

• To access the cell containing 13, we reference


val[2][2], that is, row 3, column 3.

17
10/18/2021

Using 2D arrays
• Just like 1D arrays, once you have specified the
index, you are just working with a single variable of
the given data type.
• Assignments and usage is still the same:
sumRow0 = val[0][0] + val[0][1] + val[0][2] +
val[0][3];

//assigns 72 to cell at row 2, column 3


val[2][3] = 72;

Initializing 2D arrays
• You can use additional braces to indicate when rows start
and end, but you don’t have to do that.
int val[3][4] = { {8,16,9,52},
{3,15,27,6},
{14,25,2,10}
};
• Or
int val[3][4] = {8,16,9,52,
3,15,27,6,
14,25,2,10};
• Or (correct, but not as clear as the first two):
int val[3][4] =
{8,16,9,52,3,15,27,6,14,25,2,10};

18
10/18/2021

Dry Run
row Column table[row][column]
0 0 Table[0][0] = 0
0 1 Table[0][1] = 1
0 2 Table[0][2] = 1
0 3 Table[0][3] = 1
0 4 Table[0][4] = 1
0 5 Table[0][5] = 1
1 0 Table[1][0] = -1
1 1 Table[1][1] = 0
1 2 Table[1][2] = 1
1 3 Table[1][3] = 1
1 4 Table[1][4] = 1
1 5 Table[1][5] = 1
… … ………………………..
5 5 Table[5][5] = 0

EXAMPLE PROGRAM
...
int main()
{
const int NUM_ROW(3);
const int NUM_COL(4);
int vals[NUM_ROW][NUM_COL] = { {11, 12, 13, 14},
{21, 22, 23, 24},
{31, 32, 33, 34} };

// output the array


for (int row = 0; row < NUM_ROW; row++)
{
for (int col = 0; col < NUM_COL; col++)
{
cout << vals[row][col] << " ";
}
cout << endl;
}
...

19
10/18/2021

...
int vals[NUM_ROW][NUM_COL] = { {11, 12, 13, 14},
{21, 22, 23, 24},
{31, 32, 33, 34} };

// output the array


for (int row = 0; row < NUM_ROW; row++)
{
for (int col = 0; col < NUM_COL; col++)
{
cout << vals[row][col] << " ";
}
cout << endl;
}
...

> array2DExample.exe
11 12 13 14
21 22 23 24
31 32 33 34

EXAMPLE(2)
...
int main()
{
const int NUM_ROW(3);
const int NUM_COL(4);
int vals[NUM_ROW][NUM_COL] = { {11, 12, 13, 14},
{21, 22, 23, 24},
{31, 32, 33, 34} };

// output the transpose of the array


for (int col = 0; col < NUM_COL; col++)
{
for (int row = 0; row < NUM_ROW; row++)
{
cout << vals[row][col] << " ";
}
cout << endl;
}
...

20
10/18/2021

Matrix Addition Algorithm


• Add two n x m matrices A, B;

• for each row i of A do


• for each column j of A do
° C[i][j] = A[i][j] + B[i][j];
• Output matrices A, B and C.

Matrix.cpp
int main()
{
const int NUM_ROWS(3); // number of matrix rows
const int NUM_COLS(2); // number of matrix columns

// Note: A, B and C have the same dimensions


double A[NUM_ROWS][NUM_COLS] = { {3, 3}, {1, 1}, {2, 0} };
double B[NUM_ROWS][NUM_COLS] = { {3, 0}, {3, 0}, {0, 1} };
double C[NUM_ROWS][NUM_COLS];
// C = A + B
for (int i=0; i<NUM_ROWS; i++)
{
for (int j=0; j<NUM_COLS; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}

21
10/18/2021

Matrix.cpp
// display C
cout << "C =" << endl;
for (int i=0; i<NUM_ROWS; i++)
{
for (int j=0; j<NUM_COLS; j++)
{
cout << " " << C[i][j] << " ";
}
cout << endl;
}
cout << endl;

system("pause");
return 0;
}

A three-dimensional array (3 x 5 x 4)

22
10/18/2021

C++ view of three-dimensional array

Multi-Dimensional Arrays
• Arrays can have higher dimensions.
• Definitions, intialization, indexing, function
parameters are similar to 2D arrays.
• Note multidimensional arrays can have quite a few
elements so you must be mindful of your memory
capacity:

int big[1000][1000][1000]; //a billion ints

23
10/18/2021

Initializing a three-dimensional array

3D Array

int arr[3][3][3]=
{
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23}, arr[0][0][0]=11;
{24, 25, 26}, Arr[0][0][1]=12;
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};

24
10/18/2021

3D Array
#include <iostream>
using namespace std;
OUTPUT:
int main()
{
// This array can store upto 12 elements (2x3x2) Element at x[0][0][0] = 0
int test[2][3][2]; Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
cout << "Enter 12 values: \n";
Element at x[0][1][1] = 3
// Inserting the values into the test array Element at x[0][2][0] = 4
// using 3 nested for loops. Element at x[0][2][1] = 5
for(int i = 0; i < 2; ++i)
{
Element at x[1][0][0] = 6
for (int j = 0; j < 3; ++j) Element at x[1][0][1] = 7
{ Element at x[1][1][0] = 8
for(int k = 0; k < 2; ++k ) Element at x[1][1][1] = 9
{
cin >> test[i][j][k]; Element at x[1][2][0] = 10
} Element at x[1][2][1] = 11
}
}

cout<<"\nDisplaying Value stored:"<<endl;

3D Array
#include<iostream> // Displaying the values with proper index.
using namespace std; for(int i = 0; i < 2; ++i)
int main() {
{ for (int j = 0; j < 3; ++j)
// initializing the 3-dimensional array {
int x[2][3][2] = for(int k = 0; k < 2; ++k)
{ {
{ {0,1}, {2,3}, {4,5} }, cout << "test[" << i << "][" << j << "][" << k << "] = " << test[i][j][k] << endl;
{ {6,7}, {8,9}, {10,11} } }
}; } OUTPUT:
}
// output each element's value Enter 12 values:
for (int i = 0; i < 2; ++i) system("pause"); 1 2 3 4 5 6 7 8 9 10 11 12
{ return 0;
for (int j = 0; j < 3; ++j) } Displaying value stored:
{ test[0][0][0] = 1
for (int k = 0; k < 2; ++k) test[0][0][1] = 2
{ test[0][1][0] = 3
cout << "Element at x[" << i << "][" << j test[0][1][1] = 4
<< "][" << k << "] = " << x[i][j][k] test[0][2][0] = 5
<< endl; test[0][2][1] = 6
} test[1][0][0] = 7
} test[1][0][1] = 8
} test[1][1][0] = 9
system("pause"); test[1][1][1] = 10
return 0; test[1][2][0] = 11
} test[1][2][1] = 12

25
10/18/2021

COMMON PROGRAMMING ERRORS


• Addressing indices that are out of bounds of the
array range. This will run-time crash or at the very
least a logical error. Be careful especially when
using expressions to compute the indices.
• Remember, indexing starts with 0, not 1!!!

• Forgetting to declare the array (either altogether or


forgetting the [])
• Assuming the array is initialized (to zero.)

52

26
10/18/2021

CSC-112
COMPUTER PROGRAMMING

DR. ABDUL ATTAYYAB KHAN


EMAIL ADDRESS: aakhan.bukc@bahria.edu.pk

C++ Fundamentals

1
10/18/2021

LECTURE OUTLINE

 Fundamentals of C++
 Structure of C++ Program C++
 Data types
 Variables
 Escape Sequences
 I/O Statements (cin/cout)

STRUCTURE OF A C++ PROGRAM Preprocessor directives


are lines included in a
program that being with
the character #, which
make them different
from a typical source
code text. They are
invoked by the compiler
to process some
Opening brace programs before
compilation.

Closing brace

Opening brace

Closing brace

2
10/18/2021

PREPROCESSOR DIRECTIVES
 A libraries that contain /* A program to print the string
functions and symbols that are Welcome to C++ to the screen
necessary to run a C++ */

program. #include <iostream>

 Every library has a name and is int main()


referred as a header file. {
/* print out the message */
 All preprocessor commands cout<<"Welcome to C++"<<endl;
begin with #. return 0;
}
 In Standard C++, header files
have the file extension .h
 There is no semicolon at the
end of these commands. #include <headerFileName>

 The general syntax to include a


#include <iostream.h>
header file

PREPROCESSOR DIRECTIVES

 Another option to use to perform /* A program to print the string


I/O in a program: Welcome to C++ to the screen
*/
#include <iostream>
equivalent
#include <iostream>
#include <iostream.h> using namespace std;

int main()
 To use the string data type in a
{
program, you must include the
/* print out the message */
following preprocessor directive:
cout<<"Welcome to C++"<<endl;
#include <string> return 0;
 The descriptions of some very }
useful mathematics functions such
as power, absolute, sine, etc., are
contained in the header file
cmath.
#include <cmath>

3
10/18/2021

THE PROGRAM PART: THE HEADING

The heading part has the following form


 Every C++ program has a function
main.
typeOfFunction main(argument list)
 The basic parts of the function main
are:
1. The heading
2. Body of the function int main()
{
/* print out the message */
cout<<"Welcome to C++"<<endl;
return 0;
}
 The statement

int main(void) int main()


means that the function main equivalent It is not necessary to put word
returns a value of the type int the void in parentheses, but
and it has no arguments. the parentheses are still
needed.

THE PROGRAM PART: BODY OF THE FUNCTION


 The body of the function is enclosed
between { and } and has two types of int main()
statements. {
 Declaration Statements /* assignment statements */
int a, b, c; int a = 10;
int b = 2;
double x, y; int c;
Variables (or identifies) can be int sum;
declared anywhere in the program,
but they must be declared before
they can be used. /* print out the message */
cout<<"Welcome to C++"<<endl;
 Executable Statements
// input statement
a = 10; cin>>c;
//assignment statement sum=a+b+c;
cin>>c; /* output statement */
cout<<sum<<endl;
//input statement
cout<<a+b+c<<endl; return 0;
//output statement }

4
10/18/2021

COMMENTS

 Multiple line comments are


enclosed between /* and */ /* A program to print the string
Welcome to C++ to the screen
 Single line comments begin */
with //
#include <iostream>
 Statements that have no using namespace std;
effect on the execution of
int main()
the program
{
 The Compiler neglects these // print out the message
comments when translating cout<<"Welcome to C++"<<endl;
the program to machine return 0;
code
}
 Comments can be place
before each of the functions
Output:
and inside the function
Welcome to C++ Programming

THE HELLO WORLD PROGRAM


Indicates the beginning of the
functions body  < iostream> is included
in this program because it
#include <iostream> provides information to the
using namespace std; compiler about cout
int main (void) function
{
cout<<“hello world\n”; Block  cout is a function from a
return 0; standard library that prints
} on the screen

End of function’s body 0 is returned to the OS when


main is terminated

 The string “hello world\n” is sent to the cout function and the
function will display the message on the screen
 The \n that appears in the cout function call will cause the message
to be printed on the screen then moves the printing to the next line

5
10/18/2021

SYNTAX

 A programming language is a set of rules, symbols, and special words used


to construct a program.

 There are rules for both syntax (grammar) and semantics (meaning).
 Syntax: The formal rules governing how one writes valid
instructions in a language

 Semantics: The set of rules that gives the meaning of


instructions written in a programming language.

 The syntax rules tell us which statements (instructions) are legal, that is,
accepted by the programming language and which are not.

TOKEN
 The smallest individual unit of a program written in any language is called a token.
 A token is one or more symbols understood by the compiler that help it interpret code.

 A token is the basic vocabulary of the language.

 Tokens in C++
 keywords
 identifiers
 constants
 string constants
 operators
 punctuators

 Language syntax specifies the valid combinations of tokens in the language into legal
strings.

6
10/18/2021

TOKEN TYPES

 Identifiers
main, payRate, score_1, conversion

 Operators
+ - * / ( )

 Keywords
int, float, double, char, void, return

 Punctuators
. ; ? , {

 Others
<= != == >=

 Comments are not tokens (remember they are removed from the program)

IDENTIFIERS

 Identifiers allow us to name variables, constant names, functions and


objects in the program
 Each piece of data in the computer is stored at a unique memory address
 Identifier names allow us to symbolically deal with the memory locations so
that we don’t have to deal directly with these addresses
 A C++ identifier are formed using the following symbols
 Capital letters A to Z
 Small letters a to z
 Digits 0 to 9
 Underscore _ “shift key with minus key in the keyboard”

7
10/18/2021

IDENTIFIERS A Syntax diagram of the identifier


 Rules to form and Identifier
 First character must be an alphabet
Letter
or an underscore
 Can consist of alphabets, digits and Letter digit
underscore
underscore underscore
 C++ is case sensitive language

Some of the predefined identifiers are cout and cin.


Unlike reserved words, pre-defined identifiers may be redefined, but it would
not be wise to do so.

Valid Identifiers Invalid Identifiers

A _a a123
ABcDf99_ sum average a+2 a$1
Mark1 Mark_2 xy_1_4
A”bc -abc aa.bb
Sum_of_values avg_plus_sum
A abc a9!c
these are not the same
Why they are invalid ?.
Aa aa aA AA aa

KEYWORDS (reserve words)

 Keywords are words (like identifiers) that have a special meaning


to the compiler and cannot be used in your programs for other
purposes.

auto do goto signed unsigned


break double if sizeof void
case else int static volatile
char enum long struct while
continue extern register switch
default float return typedef
for short union const

8
10/18/2021

DATA TYPE

 A set of values together with a set of operations is called a


data type.

C++’s Data Types


 C++ data types fall into three categories
 Simple Data Type.
Simple Structured Pointers
 Structured Data Type.
 Pointers.
Integral Floating-Point Enumeration

Simple Data Type

 C++ simple data can be classified into three categories


1. Integral, which is a data type that deals with integers, or numbers
without a decimal part.
2. Floating-point, which is a data type that deals with decimal numbers.

3. Enumeration type, which is a user-defined data type.

Simple Data Type

Integral Floating-Point Enumeration

9
10/18/2021

THE INT DATA TYPE


 The type defines the size of the field in which
data can be stored
-6728, -67, 0, +78, 36782, ...
 C++ language supports three different types
of integer data type.

short int Int 2 long int


2 bytes or 4 bytes 4 bytes

The bool Data Type


 The data type bool has two values, true and
false. The central purpose of this data type
is to manipulate logical (Boolean) expressions.

 In C++, bool, true, and false are reserved


words.

FLOATING – POINT DATA TYPES

float: The data type float is used in C++ to represent any real number
between -3.4E+38 and 3.4E+38.The memory allocated for the float data
type is 4 bytes.

double: The data type double is used in C++ to represent any real number
between -1.7E+308 and 1.7E+308.The memory allocated for the double
data type is 8 bytes.

 On most newer compilers, the data types double and long double are
the same.
 The maximum number of significant digits—that is, the number of decimal
places—in float values is 6 or 7 and double is 15.

Floating-Point Data Type

float double long double

10
10/18/2021

THE CHAR DATA TYPE


 To the computer, a character is any value that can be represented in the
computer’s alphabets
 Most computers use American Standard Code for Information Interchange
(ASCII) as computer alphabets
 A character requires one byte for the representations (28=256 characters,
extended ASCII table shown next slide)
 Characters are stored in memory as numbers (ASCII number)

Valid character literals (ASCII values) Invalid character literals


‘A’=65,‘B’=66,‘C’=67, … “a” a
‘a’=97,‘b’=98,‘c’=99, … ‘ab’ ‘a11111’
‘0’=48,‘1’=49,‘2’=50, … Why ?

THE STRING TYPE


 The data type string is a programmer-defined type and is not part of the C++
language. The C++ standard library supplies it.
 A string is a sequence of zero or more characters.
 Strings in C++ are enclosed in double quote marks.
 A string with no characters is called a null or empty string.
Null or empty string

Valid string constants Invalid string constants


“” ‘ mary’ Use single quotes for
“mary” “ hgshd hfd h” jsdjasdhajdk” character constants
and Double quotes
“Hello world\n” for strings
“How are you John?” How to fix the problem?
“I have #1 pc costs 15$”
“……………….”
“\n\t\r\r\r\t\thi *&^%$%$###”

11
10/18/2021

CONSTANTS AND VARIABLES

 Storing data in the computer’s memory is a two step process.


 Instruct the computer to allocate memory.
 Include statements in the program to put data into the
allocated memory.

 Allocating Memory with Constants and Variables


 Named Constant: A memory location whose content is not
allowed to change during program execution.
 Variable: A memory location whose content may change during
program execution.

NAMED CONSTANT
 The syntax to declare a named constant is

const dataType identifier = value;

const double conversion = 2.54;


 This mean that conversion has a value of 2.54 and cannot be changed throughout
the program execution.
 In C++, const is a reserved word.

int main ()
{
const int noOfStudents = 20;
const char blank = ' ';
const double payRate = 15.75;
return 0;
}

12
10/18/2021

VARIABLES

 Variables don’t have fixed values


throughout the program dataType identifier;
 In C++ language there are a set of
operations to change and manipulate
the value stored in these variables int conversion = 2.54;
 Every variable used in the program
must be declared before its use
= Literal
 Variable names are valid identifiers and
cannot be the same as any of the
reserved words (keywords) type identifier ;
 When variables are created there is a
need to assign them initial values ,
 In order to do that an assignment
operator is used (=)
int sum =
0;

INPUT AND OUTPUT FUNCTIONS IN C++ LANGUAGE


 C++ uses two functions for formatted input/output
 cin reads data from the keyboard and stores it to a buffer
 cout prints out data to the monitor

 Keyboard is known as the standard input device (stdin).


 The monitor is known also as the standard output device (stdout)

cin>>…

cout<<…

13
10/18/2021

INPUT (READ) STATEMENT: CIN Output : cout


 The syntax of cout together with <<
 Syntax of cin together with is
>>:
cout<< variable;
cin>>variable;
 In C++, << is called the insertion
 In C++, >> is called the operator.
extraction operator.  expression is evaluated and its
Suppose miles is a variable value is printed at the current
of the type double. cursor position on the screen.
 manipulator manipulates the
The statement output. The simplest manipulator is
cin>>miles; endl (the last character is the letter
el), which causes the cursor to
move to the beginning of the next
causes the computer to get a line.
value of the type double and
 Strings and expressions involving
place it in the memory cell only one variable or a single value
miles. are evaluated to itself.

OUTPUT : COUT
Statement Output
1. cout<<29/4; 7
2. cout<<"Hello there. "; Hello there.
3. cout<<12; 12
4. cout<<"4+7"; 4+7
5. cout<<4+7; 11
6. cout<<"A"; A
7. cout<<"4 + 7 = "<<4 + 7; 4 + 7 = 11
8. cout<<2+3*5; 17
9. cout<<"Hello \nthere. "; Hello
there.
 \n is called new line escape sequence.
 \ (back slash) is called the escape character.

14
10/18/2021

USE OF BLANKS, SEMICOLONS, BRACKETS AND COMMAS

 In C++, one or more blanks are used to separate numbers when data is input.
 Blanks are also used to separate reserved words and identifiers from each other
and other symbols.
int a,b,c;
int a, b, c;
The blanks between the identifiers in the second statement
are meaningless.

inta,b,c;
no blank between the t and a changes the reserved word
int and the identifier a into a new identifier inta.

 Commas are used to separate items in a list.


 All C++ statements terminate with a semicolon  statement terminator
 Brackets{ and } are not C++ statements.

NAMING IDENTIFIERS

const double a = 2.54; //conversion constant


double x; //variable to hold centimeters
double y; //variable to hold inches

x = y * a;
Consider the following
const double conversion = 2.54;
double centimeters;
double inches;

centimeters = inches * conversion;

 Run-together-word
inchperfoot inchPerFoot inch_per_foot.

15
10/18/2021

PROMPT LINES

cout<<"Please enter a number between 1 and 10 and"


<<" press ENTER"<<endl;
cin>>num;

When these two statements execute in the order given, first the cout statement causes
the following line of text to appear on the screen:

Please enter a number between 1 and 10 and press ENTER

After seeing this line, users know that they must enter a number and press the return key.

ESCAPE SEQUENCE

Escape
Description
sequence
\' single quote
\" double quote
 Escape sequences are used to
\? question mark
represent certain special
\\ backslash
characters within string \a audible bell
literals and character literals. \b backspace
\n line feed - new line
\r carriage return
\t horizontal tab

16
10/18/2021

Examples
33

MORE ABOUT COUT

 precision (int) sets the number of significant digits of float type


numbers

float y = 23.1415;
cout.precision(1);
cout << y << '\n'; // Outputs 2e+01
cout.precision(2);
cout << y << '\n'; // Outputs 23
cout.precision(3);
cout << y << '\n'; // Outputs 23.1

17
10/18/2021

SUMMARY

 The body of the function is enclosed between { and } and has two types of
statements.
 Statements enclosed in // have no effect on the execution of the program.
 Identifiers allow us to name variables, constant names, functions and objects in the
program.
 C++ data types fall into three categories: Simple Data Type. ,Structured Data Type.,
Pointers
 Named Constant: A memory location whose content is not allowed to change
during program execution.
 Variable: A memory location whose content may change during program execution.
 cin reads data from the keyboard and stores it to a buffer
 cout prints out data to the monitor
 In C++, >> is called the extraction operator
 In C++, << is called the insertion operator 35

18
10/18/2021

CSC-112
COMPUTER PROGRAMMING

DR. ABDUL ATTAYYAB KHAN


EMAIL ADDRESS: aakhan.bukc@bahria.edu.pk

Functions in C++

1
10/18/2021

SO FAR WE HAVE STUDY

 Fundamentals of C++
 Structure of C++ Program C++
 Data types
 Variables
 Escape Sequences
 I/O Statements (cin/cout)

FUNCTIONS

In C++, a program is made of one or more functions, one and only one of
which must be named main. The execution of the program always starts with
main, but it can call other functions to do some part of the job.

2
10/18/2021

ARITHMETIC OPERATORS

Operators Meanings Syntax

+ Addition A+B

- Subtraction A-B

* Multiplication A*B

/ Division A/B

^ Power A^B
Return the reminder
Mod after integral division
A%B

= Assignment A=10;

LOGICAL OPERATOR

Operator Usage Description


Logical AND expr1&&expr2 Returns expr1 if it can be converted to false;
(&&) otherwise, returns expr2. Thus, when used with
Boolean values, && returns true if both operands
can be converted to true; otherwise, returns false.

Logical OR expr1||expr2 Returns expr1 if it can be converted to true;


(||) otherwise, returns expr2. Thus, when used with
Boolean values, || returns true if either operand
can be converted to true; if both can be converted
to false, returns false.

Logical NOT !expr Returns false if its single operand can be converted
(!) to true; otherwise, returns true.

3
10/18/2021

LOGICAL OPERATORS TRUTH TABLE


AND (&&) OR (||)
Bool OPR Bool OPR Result (&&)
Bool OPR Bool OPR Result (||)
True true True
True true True
true false False true false True
false false False false False False
false true False false true True

NOT(!)
X !x

True False

false true

Compound Boolean Expression


1. (A And B )OR (NOT C)
2. NOT (A AND B) OR C
(A And B )OR
A B C A &&B !C (NOT C)

T T T

T T F

T F T

T F F

F T T

F T F

F F T

F F F
8

4
10/18/2021

COMPOUND ASSIGNMENT
Compound expression Equivalent simple expression
X*=y X=x*y
x/=y X=x/y
X%=y X=x%y
X+=y X=x+y
X-=y X=x-y
X++ X=x+1
X-- X=x-1

Content of Content of Value of


expression Result of expression
variable x variable y expression

X*=y 10 5

x/=y 10 5

X%=y 10 5

X+=y 10 5

X-=y 10 5

POSTFIX EXPRESSIONS
Remember!

(a++) is (a = a + 1)
(a– –) is (a = a – 1)

5
10/18/2021

POSTFIX EXPRESSIONS
#include <iostream>
using namespace std;
Remember!
int main()

{ (a++) is (a = a + 1)
int a=5, x,y; (a– –) is (a = a – 1)

x=a++;
y=x+1;
cout << x << endl;
cout << y << endl;
cout << a << endl;
return 0;
}
OUTPUT:

5
6
6

UNARY EXPRESSIONS
Remember!

(++a) is (a = a + 1)
(– –a) is (a = a – 1)

6
10/18/2021

UNARY EXPRESSIONS
#include <iostream>
using namespace std; Remember!
int main()

{ (++a) is (a = a + 1)
int a=5, x,y; (– –a) is (a = a – 1)

x=++a;
y=x+1;
cout << x << endl;
cout << y << endl;
cout << a << endl;
return 0;
}
OUTPUT:

6
7
6

OPERATOR PRECEDENCE

 Which operator will be


evaluated first?

 Each operator has one


of 18 precedence levels

7
10/18/2021

ORDER OF PRECEDENCE

 Consider the logical expression:  Because relational and logical operators are
11 > 5 || 6 < 15 && 7 >= 8 evaluated from left to right, the
associativity of these operators is said to be
from left to right.

 This logical expression will yield


different results if || is evaluated
first or && is evaluated first.

 If || is evaluated first, this logical


expression evaluates to 0 (false).

 If && is evaluated first, this logical


expression evaluates to 1(true).

PRECEDENCE OF OPERATORS
 You can insert parentheses into an expression to clarify its meaning.
 The expression

1 (true)
11 > 5 || 6 < 15 && 7 >= 8 11 > 5 || (6 < 15 && 7 >= 8)

 Evaluate the following expression:

(17 < 4*3+5) || (8*2 == 4*4) && !(3+3 == 6)


= (17 < 12+5) || (16 == 16) && !(6 == 6)
= (17 < 17) || true && !(true)
= false || true && false
= false || false
= false

8
10/18/2021

STATEMENTS
 A statement causes an
action to be performed by
the program.
 A block of instructions
 Types of statements
 An is terminated expression
statement with a
semicolon (;). The
semicolon is a terminator,
and it tells the compiler that
the statement is finished.

RELATIONAL OPERATIONS
 A relational operator allows you to make comparisons in a program.
 They are all binary operators and can accept two operands.

 Equality of real numbers is usually machine dependent. It is quite possible that on a particular
machine
 6.8 + 3.1 == 2.7 + 7.2 is false

18

9
10/18/2021

10

You might also like