KEMBAR78
Programing Fundamental | PDF | Class (Computer Programming) | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
115 views109 pages

Programing Fundamental

Uploaded by

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

Programing Fundamental

Uploaded by

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

Introduction to Problem Solving

• Programming is a problem solving activity. When you


write a program, you are actually writing an
instruction for the computer to solve something for
you.

• Problem solving is the process of transforming the


description of a problem into a solution by using our
knowledge of the problem domain and by relying on
our ability to select and use appropriate problem-
solving strategies, techniques and tools.
Case Study: Yummy Cupcake
Problem: You are required to calculate the amount to be paid
by a customer buying cupcakes.

For programmer, we solve problems using Software


Development Method (SDM),
which is as follows:
1.Specify the problem requirements.
2.Analyze the problem.
3.Design the algorithm to solve the problem.
4.Implement the algorithm.
5.Test and verify the completed program.
6.Documentation
1.Requirement Specification
• Specifying the problem requirements requires you to state the
problem clearly and to gain the understanding of what to be solved
and what would be the solution.
• When specifying problem requirement, we ask ourselves the
following questions:
• What the problem is.
• What the solution should provide.
• What is needed to solve it.
• If there are constraints and special conditions.
2. Problem Analysis
• Analyzing the problem require us to identify the following:
• Input(s) to the problem, their form and the input media to be used
• Output(s) expected from the problem, their form and the output
media to be used
• Special constraints or conditions (if any)
• Any formulas or equations to be used
Problem Analysis
Input?
• Quantity of the cupcake purchased (integer)
• Price per cupcake (float)
Output?
• Total amount to be paid by the customer (float)
Constraint/condition?
• Quantity purchased must be more than zero
• Price per cupcake must be more than zero (it is not free)
• We assume that the price given is the standard price to all cupcakes

Formula/equation?
• Amount to pay = quantity of cupcake x price per cupcake
3. Designing algorithm
• Designing algorithm to solve the problem requires you to develop a
list of steps, arranged in a specific logical order which, when executed,
produces the solution for a problem.
• Using top-down design (also called divide and conquer):
• You first list down the major tasks
• For each major task, you further divide it into sub- tasks (refinement step)
• When you write algorithm, write it from the computer’s point of view.
Designing Algorithm cont..
• An algorithm must satisfy these requirements:
• It may have an input(s)
• It must have an output(s)
• It should not be ambiguous (there should not be different interpretations to
it. Every step in algorithm must be clear as what it is supposed to do)
• It must be general (it can be used for different inputs)
• It must be correct and it must solve the problem for which it is designed
• It must execute and terminate in a finite amount of time
• It must be efficient enough so that it can solve the intended problem using
the resource currently available on the computer
Major task
Major Task:
1. Read the quantity of cupcake purchased
2. Read the price per cupcake
3. Calculate total amount to pay
4. Display the total amount to pay
However, looking at the above algorithm, we can still further refine step 3, by
introducing the formula to calculate the amount to pay.
After refinement:
5. Read the quantity of cupcake purchased
6. Read the price per cupcake
7. Total amount to pay = quantity of cupcake x price per cupcake
8. Display the total amount to pay
Control Structure
 An algorithm can be represented using Pseudocode or Flowchart.
 In 1966, two researchers, C. Bohn and G. Jacopini, demonstrated that
any algorithm can be described using only 3 control structures:
sequence, selection and repetition.
• Sequence: A series of steps or statements that are executed in the
order they are written in an algorithm.
• Selection: Defines two courses of action depending on the outcome
of a condition. A condition is an expression that is, when computed,
evaluated to either true or false.
• Repetition: Specifies a block of one or more statements that are
repeatedly executed until a condition is satisfied.
Pseudocodes
 A pseudocode is a semiformal, English-like language with limited
vocabulary that can be used to design and describe algorithms.
 Criteria of a good pseudocode:
 Easy to understand, precise and clear
 Gives the correct solution in all cases
 Eventually ends
Flowcharts
• Flowcharts is a graph used to depict or show a step by step solution
using symbols which represent a task.
• The symbols used consist of geometrical shapes that are connected
by flow lines.
• It is an alternative to pseudo coding; whereas a pseudocode
description is verbal, a flowchart is graphical in nature.
4. Implementation
• The process of implementing an algorithm by writing a computer
program using a programming language (for example, using C
language)
• The output of the program must be the solution of the intended
problem
• The program must not do anything that it is not supposed to do
(Think of those many viruses, buffer overflows, trojan horses, etc. that we
experience almost daily. All these result from programs doing more than they
were intended to do)
5. Testing and Verification
• Program testing is the process of executing a program to demonstrate
its correctness
• Program verification is the process of ensuring that a program meets
user- requirement
• After the program is compiled, we must execute the program and
test/verify it with different inputs before the program can be released
to the public or other users (or to the instructor of this class)
6. Documentation
• Writing description that explain what the program does.
• Can be done in 2 ways:
 Writing comments between the line of codes
 Creating a separate text file to explain the program
• Important not only for other people to use or modify your program,
but also for you to understand your own program after a long time
(believe me, you will forget the details of your own program after
some time...)
Von Neumann Architecture
Cont.……
Cont.
Introduction to Programing
Object Oriented Programming
Concept Of Object Oriented
Programming
oop is an approach or a Programming pattern where the programs are
structured around objects rather than functions and logic. It makes the
data partitioned into two memory areas, i.e., data and functions, and
helps make the code flexible and modular.
Object-oriented programming mainly focuses on objects that are
required to be manipulated. In OOPs, it can represent data as objects
that have attributes and functions.
Basic Object-Oriented
Programming
 Object-An O Object can be defined as an entity that has a state and
behavior, or in other words, anything that exists physically in the
world is called an object. It can represent a dog, a person, a table,
etc. An object means the combination of data and programs, which
further represent an entity.
 Classes-Class can be defined as a blueprint of the object. It is basically
a collection of objects which act as building blocks.

Abstraction- Abstraction helps in the data hiding process. It helps in
displaying the essential features without showing the details or the
functionality to the user. It avoids unnecessary information or
irrelevant details and shows only that specific part which the user
wants to see.
Basic Object-Oriented Programming
 Encapsulation- The wrapping up of data and functions together in a single unit is known as
encapsulation. It can be achieved by making the data members' scope private and the member
function’s scope public to access these data members. Encapsulation makes the data non-
accessible to the outside world.
 Inheritance- Inheritance is the process in which two classes have an is-a relationship among
each other and objects of one class acquire properties and features of the other class. The class
which inherits the features is known as the child class, and the class whose features it inherited
is called the parent class. For example, Class Vehicle is the parent class, and Class Bus, Car, and
Bike are child classes.
 Polymorphism- It means many forms. It is the ability to take more than one form. It is a feature
that provides a function or an operator with more than one definition. It can be implemented
using function overloading, operator overload, function overriding, virtual function.
Advantages of OOPs
There are various advantages of object-oriented programming.
 OOPs provide reusability to the code and extend the use of existing
classes.
 In OOPs, it is easy to maintain code as there are classes and objects,
which helps in making it easy to maintain rather than restructuring.
 It also helps in data hiding, keeping the data and information safe
from leaking or getting exposed.
 Object-oriented programming is easy to implement.
C++ Keywords
Console Input and Output
Console Input / Output
• I/O objects cin, cout
• Defined in the C++ library called <iostream>
• Must have these lines (called pre- processor directives) near start of
file:
• #include <iostream>
using namespace std;
• Tells C++ to use appropriate library so we can
use the I/O objects cin, cout
Console Output

Output using Insertion Operator


**cout: Standard Output Stream
Console Output
• What can be outputted?
• Any data can be outputted to display screen
• Variables
• Constants
• Literals
• Expressions (which can include all of above)
• cout << numberOfGames << " games played.";
2 values are outputted:
"value" of variable numberOfGames,
literal string " games played."
• Cascading: multiple values in one cout
Separating Lines of Output
• New lines in output
• Recall: "\n" is escape sequence for the
char "newline"
• A second method: object endl
• Examples:
cout << "Hello World\n";
• Sends string "Hello World" to display, & escape sequence "\n", skipping to next line
cout << "Hello World" << endl;
• Same result as above
Input Using cin
• cin for input, cout for output
• Differences:
• ">>" (extraction operator) points opposite
• Think of it as "pointing toward where the data goes"
• Object name "cin" used instead of "cout"
• No literals allowed for cin
• Must input "to a variable"
• cin >> num;
• Waits on-screen for keyboard entry
• Value entered at keyboard is "assigned" to num
Console Input

Input using Extraction Operator


**cin: Standard Input Stream
Prompting for Input: cin and cout
• Always "prompt" user for input
cout << "Enter number of dragons: ";
cin >> numOfDragons;
• Note no "\n" in cout. Prompt "waits" on same
line for keyboard input as follows:

Enter number of dragons: ____

• Underscore above denotes where keyboard entry


is made
Namespaces
• Namespaces defined:
• Collection of name definitions
• For now: interested in namespace "std"
• Has all standard library definitions we need
• Examples:
#include <iostream>
using namespace std;
• Includes entire standard library of name definitions
• #include <iostream>using std::cin;
using std::cout;
• Can specify just the objects we want
C++ Tokens
Tokens are the minimal chunk of program that have meaning to the
compiler – the smallest meaningful symbols in the language.
Some Escape Sequences (1 of 2)
Usage of Named Constant
Different Types of Operators
Precedence of Operators (1 of 4)
Precedence of Operators (2 of 4)
Precedence of Operators (3 of 4)
Precedence of Operators (4 of 4)
Precedence Examples
• Arithmetic before logical
• x + 1 > 2 || x + 1 < -3 means:
• (x + 1) > 2 || (x + 1) < -3

• Short-circuit evaluation
• (x >= 0) && (y > 1)
• Be careful with increment operators!
• (x > 1) && (y++)

• Integers as boolean values


• All non-zero values  true
• Zero value  false
Control Structures
Control Structures
Branching Mechanisms
• if-else statements
• Choice of two alternate statements based
on condition expression
• Example:
if (hrs > 40)
grossPay = rate*40 + 1.5*rate*(hrs-40);
else
grossPay = rate*hrs;
if-else Statement Syntax
• Formal syntax:
if (<boolean_expression>)
{
<yes_statement>
}
else
{
<no_statement>
}
Common Pitfalls
• Operator "=" vs. operator "=="
• One means "assignment" (=)
• One means "equality" (==)
• VERY different in C++!
• Example:
if (x = 12) Note operator used!
Do_Something
else
Do_Something_Else
Conditional Operator
• Also called "ternary operator"
• Allows embedded conditional in expression
• Essentially "shorthand if-else" operator
• Example:
if (n1 > n2)
max = n1;
else
max = n2;
• Can be written:
max = (n1 > n2) ? n1 : n2;
• "?" and ":" form this "ternary" operator
Nested Statements
• if-else statements contain smaller statements
• Can also contain any statement at all, including another if-else stmt!
• Example:
if (speed > 55)
if (speed > 80)
cout << "You’re really speeding!";
else
cout << "You’re speeding.";
• Note proper indenting!
Multiway if-else Example
The switch Statement
• A new stmt for controlling multiple branches
• Uses controlling expression which returns bool data type (true or
false)
switch Statement Syntax
The switch Statement in Action
The switch: multiple case labels
• Execution "falls thru" until break
• switch provides a "point of entry"
• Example:
case ‘A’:
case ‘a’:
cout << "Excellent: you got an \" A \" ! \n";
break;
case ‘B’:
case ‘b’:
cout << "Good: you got a \" B \" ! \n";
break;
• Note multiple labels provide same "entry"
Loops
• 3 Types of loops in C++
• while
• Most flexible
• No "restrictions"
• do-while
• Least flexible
• Always executes loop body at least once
• for
• Natural "counting" loop
while Loops Syntax
do-while Loop Syntax
while Loop Example
• Consider:
count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}
• Loop body executes how many times?
do-while Loop Example
count = 0; // Initialization
do
{
cout << "Hi "; // Loop Body
count++; // Update expression
} while (count < 3); // Loop Condition

• Loop body executes how many times?


• do-while loops always execute body at least once!
for Loop Syntax
for (Init_Action; Bool_Exp; Update_Action)
Body_Statement
OR
for (Init_Action; Bool_Exp; Update_Action)
{
Body_Statements
}
for Loop Example
• for (count=0;count<3;count++)
{
cout << "Hi "; // Loop Body
}
• How many times does loop body execute?
• Initialization, loop condition and update all "built into" the for-loop
structure!
• A natural "counting" loop
Nested Loops
• Recall: ANY valid C++ statements can be
inside body of loop
• This includes additional loop statements!
• Called "nested loops"
• Requires careful indenting:

for (outer=0; outer<5; outer++)


for (inner=7; inner>2; inner--)
cout << outer << inner;

• Notice no { } since each body is one statement


The break and continue Statements
• Flow of Control
• Recall how loops provide "graceful" and clear flow of control in and out
• In RARE instances, can alter natural flow
• break;
• Forces loop to exit immediately.
• continue;
• Skips rest of loop body
• These statements violate natural flow
• Only used when absolutely necessary!

You might also like