Professional Documents
Culture Documents
PROGRAMMING FUNDAMENTALS
GENTLE REMINDER
1
COURSE ASSESSMENT
Final ------------------------50%
Total -------------------------100%
An Overview of Programming
Languages and Problem
Solving Techniques
2
COMPUTER PROGRAM
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.
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
PROGRAMMING LANGUAGES
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
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.
6
ELEMENTS OF PROGRAMMING:
ELEMENTS OF PROGRAMMING:
#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.
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
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.
9
STEP IN PROGRAM DEVELOPMENT
Input Num1
Input Num2
Num1 Average
Ipo Chart Sum=num1+num2
Num2
Average=sum/2
print average;
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 )
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
Pseudocode
Structure Diagram and finally in C++
Flowcharts
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
step 1. Start
step 3. Sum=num1+num2
step 5. end
13
FLOWCHARTS SUM OF TWO NUMBERS
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
Stop
15
BRANCHING
BRANCHING
General form of flowcharts involve in branching
? ?
(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
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
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
19
STEP IN PROGRAM DEVELOPMENT
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
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
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.
Main
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
5, 10 15
23
STRUCTURE DIAGRAM WRITE A PROGRAM CALCULATING
THE SUM OF TWO NUMBERS
Version 1: Version 2:
Add Two
Add Two Numbers
Numbers
Take note:
We develop software iteratively (meaning version by version), but
the code itself is broken in top-down manner!!
return 0;
}
24
PROGRAMMING GUIDELINE
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.
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
{
...
}
}
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.
27
Computer Programming Bukc
Pointers
1
Computer Programming Bukc
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;
}
int main ()
{
int a; int a int b int c
int b;
int c; 1000 2000 3000
2
Computer Programming Bukc
POINTER
3
Computer Programming Bukc
POINTER
POINTER DECLARATION
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.
POINTER OPERATOR
5
Computer Programming Bukc
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
p X
25
6
Computer Programming Bukc
In these statements:
p is a pointer variable of type int
num is a variable of type int.
1. num = 78;
2. p = #
3. *p = 24;
7
Computer Programming Bukc
EXAMPLE
8
Computer Programming Bukc
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.
9
Computer Programming Bukc
10
Computer Programming Bukc
11
Computer Programming Bukc
12
Computer Programming Bukc
POINTERS TO ARRAYS
same
a &a[0]
‘a’ is a pointer only to the first element, not the whole array
cout << a;
// → 1004
}
a
13
Computer Programming Bukc
14
Computer Programming Bukc
15
Computer Programming Bukc
#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
Worker
Worker Worker
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.
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
VOID FUNCTIONS
void functions cannot be used in an expression; they must be a separate
statement.function1();
FUNCTIONS
Recall
Identifiers allow us to
name variables, constant
names, functions and
objects in the program
FUNCTIONS
Computer Programming Bukc
5, 10 15
EXAMPLE#1
return sum;
} //end function
Computer Programming Bukc
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
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
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;
}
}
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.
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”.
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
5, 10 15
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.
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
PASS BY VALUE
Different local
variables
PASS BY VALUE
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
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.
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.
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.
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():
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
SCOPE OF AN IDENTIFIER
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
61
62
Computer Programming Bukc
1. void print();
Syntax error:
64
Computer Programming Bukc
65
69
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;
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
• 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
2
10/18/2021
Loop Control
Operation
3
10/18/2021
4
10/18/2021
5
10/18/2021
• 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
6
10/18/2021
Loops in C++
7
10/18/2021
8
10/18/2021
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
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
5 0
5 True
7 12 True
3 15 True
0 False 15
10
10/18/2021
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
11
10/18/2021
12
10/18/2021
13
10/18/2021
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; }
}
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
16
10/18/2021
2 endl
2 1 1
2 2
3 endl
3 1 1
2 2
3 3
4 endl
17
10/18/2021
break Statement
Unconditional loop exit
for(…;…;…) or while(…)
{
…
break;
… Terminate the loop and
} execution jumps to here
…
18
10/18/2021
break - example
// break loop example
#include <iostream>
using namespace std; 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
int main () {
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";
}
Result:
Adam
Result:
Adam
Adam
Adam
Adam
Adam
21
10/18/2021
43
22
10/18/2021
CSC-112
COMPUTER PROGRAMMING
C++ Fundamentals
1
10/18/2021
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
ARITHMETIC OPERATORS
+ 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
Logical NOT !expr Returns false if its single operand can be converted
(!) to true; otherwise, returns true.
NOT(!)
X !x
True False
false true
4
10/18/2021
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
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
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.
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)
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
Arrays
• Multiple values group together that have
same data type.
• Multiple values together as one unit that
have same data type.
3
10/18/2021
Arrays
Int arr[4];
Arrays
4
10/18/2021
An Array of Scores
10
5
10/18/2021
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
12
6
10/18/2021
13
14
7
10/18/2021
Initializing arrays
15
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
0 True 15
1 True 16
True
2 21
True
3 45
True
4 65
True
5 24
True
..
False
10 17
18
9
10/18/2021
19
20
10
10/18/2021
Dry Run
0 True 0 0
1 True 1 1
True
2 2 4
True
3 3 9
True
4 4 16
5 False
21
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
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.
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
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];
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} };
19
10/18/2021
...
int vals[NUM_ROW][NUM_COL] = { {11, 12, 13, 14},
{21, 22, 23, 24},
{31, 32, 33, 34} };
> 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} };
20
10/18/2021
Matrix.cpp
int main()
{
const int NUM_ROWS(3); // number of matrix rows
const int NUM_COLS(2); // number of matrix columns
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
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:
23
10/18/2021
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
}
}
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
52
26
10/18/2021
CSC-112
COMPUTER PROGRAMMING
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)
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++ */
PREPROCESSOR DIRECTIVES
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
4
10/18/2021
COMMENTS
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
There are rules for both syntax (grammar) and semantics (meaning).
Syntax: The formal rules governing how one writes valid
instructions in a 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.
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
7
10/18/2021
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
8
10/18/2021
DATA TYPE
9
10/18/2021
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.
10
10/18/2021
11
10/18/2021
NAMED CONSTANT
The syntax to declare a named constant is
int main ()
{
const int noOfStudents = 20;
const char blank = ' ';
const double payRate = 15.75;
return 0;
}
12
10/18/2021
VARIABLES
cin>>…
cout<<…
13
10/18/2021
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
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.
NAMING IDENTIFIERS
x = y * a;
Consider the following
const double conversion = 2.54;
double centimeters;
double inches;
Run-together-word
inchperfoot inchPerFoot inch_per_foot.
15
10/18/2021
PROMPT LINES
When these two statements execute in the order given, first the cout statement causes
the following line of text to appear on the screen:
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
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
Functions in C++
1
10/18/2021
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
+ 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
Logical NOT !expr Returns false if its single operand can be converted
(!) to true; otherwise, returns true.
3
10/18/2021
NOT(!)
X !x
True False
false true
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
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
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.
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)
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