0% found this document useful (0 votes)
6 views

Lecture 2(Basics)

Uploaded by

Abdul Basit AB
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lecture 2(Basics)

Uploaded by

Abdul Basit AB
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 38

Steps in Problem Solving

1. Problem specification
- understand problem
- identify input/output

2. Solution design
- work problem out by hand for specific case.
- design general algorithm

3. Implementation, coding and documentation


- write program in programming language

4. Testing and debugging


- test program for specific example used in step 2.
- test with other values.
Example of steps in problem solving

Problem:
Write a program that converts from miles (m) to kilometers (km).

1. Problem Specification
 need to know that 1 mile is equivalent to 1.6093 Kilometers.
 x miles is equivalent to (x  1.6093) km
 input miles --> output kilometers
Example of steps in problem solving

2. Solution design

Display message:
“Please enter distance in miles:__”
Read the miles (m)
Compute the number of kilometers (km)
Display message:
“Equivalent distance in kilometers is:__”
Example of steps in problem solving …

3. Implementation
// Miles2km.cpp
// Convert miles to kilometers.
#include <iostream>
using namespace std;
int main()
{
double miles, km;
cout << “Please enter distance in miles:”;
cin >> miles;
km = miles * 1.6093;
cout<<“Equivalent distance in km is :” << km << endl;
return 0;
}
Example of steps in problem solving …

3. Implementation
// Miles2km.cpp
// Convert miles to kilometers.
#include <iostream>
using namespace std;
int main()
{
double miles, km;
cout << “Please enter distance in miles:”;
cin >> miles; <- - - - - - - - - - - - - - - -
km = miles * 1.6093;
cout << “Equivalent distance in km is :” << km << endl;
return 0;
}
Example of steps in problem solving …

3. Implementation
// Miles2km.cpp
// Convert miles to kilometers.
#include <iostream>
using namespace std;
int main()
{
double miles, km;
cout << “Please enter distance in miles:”;
cin >> miles;
km = miles * 1.6093;
cout<<“Equivalent distance in km is :” << km << endl;
return 0;
}
Namespaces
Namespaces allow to group entities like classes,
objects and functions under a name. This way the
global scope can be divided in "sub-scopes", each
one with its own name.

The format of namespaces is:


namespace identifier
{
entities
}
Namespaces
Preprocessor Directives
• Include Directives
#include <iostream>
– Tells compiler where to find information about items used in the program
– iostream is a library containing definitions of cin and cout

#include <iostream>
It instructs the preprocessor to read a file from disk and insert its contents
into the source code file. In this case it reads the general I/O streams
header from the compiler's standard header directory.

#define PI (3.14159)
cout << (2.0 * PI) << endl;
Standard Input and Output Objects
• C++ does not directly define any statements to do input
or output (IO). Instead, IO is provided by the standard
library.
• iostream istream, ostream
• ? Stream:
• A stream is a sequence of characters intended to be
read from or written to an IO device of some kind. The
term "stream" is intended to suggest that the
characters are generated, or consumed, sequentially
over time.
IO objects
• cin (standard input)
• cout (standard output)
Running a C++ Program
• C++ source code is written with a text
editor
• The compiler on your system converts
source code to object code.
• The linker combines all the object code into
an executable program.
Three C++ Program Stages

myprog.cpp myprog.obj myprog.exe


SOURCE OBJECT EXECUTABLE
written
written in
in
written
written in
in written
written in
in machine
machine
C++
C++ machine
machine language
language
language
language

via compiler via linker

other
other code
code
from
from libraries,
libraries,
etc.
etc.
Errors
There are three general categories of errors:
1) Syntax Errors
- violations of the C++ grammar rules
- caught by the compiler
2) Run-Time Errors
- also called an execution error
- caught during the running of the
program (peripheral devices may not be turned on)
3) Logical Errors
- error in design of program
- do not produce an error message
- produce incorrect output
using namespace std;
Syntax and Semantics
Syntax: The formal rules governing how valid
instructions are written in a programming
language.

Semantics: The set of rules that determines


the meaning of instructions written in a
programming language.
What is an object?

Objects are key to understanding object-oriented technology

Real world examples: Dog, Car, Table, Bicycle

Real-world objects share two characteristics:


a) State (Attributes) b) and behavior (Actions).

Dogs have state (name, color, breed, hungry) and behavior


(barking, wagging tail).

Bicycles also have state (current gear, current pedal cadence,


current speed) and behavior (changing gear, changing pedal
cadence, applying brakes).

Identifying the state and behavior for real-world objects is a


great way to begin thinking in terms of object-oriented
programming.
Objects

Components in problem solving are called objects.

Objects made up of:


Attributes: describe what it is
Actions: describes what it can do.
Integer Object - Declaration
- Several kinds of integer objects.
- The most commonly used one is int which ranges from -
2,147,483,648 to 2,147,483,647
Short int signed: -32768 to 32767
unsigned: 0 to 65535

Declaration statement
Example int k;
int classSize;
can also be written as
int k, classSize;

What are the values of the variables k and classSize?


Integer Object- Assignment
Three ways to assign a value to a variable

1. Assignment statement
Assigns a value to a variable.
Ex: k = 65;
classSize = 50;
Syntax : variable = expression;

2. Initialized declaration
Combines declaration and assignment
int k = 65;
int classSize = 50;
Integer Object ….

Sometimes want an integer object that will not change values during
execution of program.
const int WEEK_DAYS = 7;
const int WKS_IN_YR= 52;

Integer Operations:

int a = 1, b = 2, c = 3;
- addition: a + 4 value is 1+ 4 = 5
- subtraction: c - 1 value is 3 - 1 = 2
- multiplication: b * c value is 2 * 3 = 6
- negation: -a value is -1
Integer Object ….

int a = 17, b = 3;
- integer division: a/b value is 17/3 = 5
- remainder: a%b value is 17 % 3 = 2

Example of uses:
1) Convert 100 inches into feet and inches
100/12 = 8
100 % 12 = 4
So 100 inches is equivalent to 8 feet, 4 inches
2) How do you know if a number is odd or even?
Assignment operator ( = )
Syntax object = expression;

- The value of the expression is assigned to the object.


- Original value is destroyed.

Ex: int a=1, b=2;


a = 12;
a = b;
a = b + 1;
Assignment operator ( = ) …

Ex: a = a + 1; (counter)
a = b = 100; (multiple
assignment)

Not valid! Why? a + 1 = b + 4;


Input and Output

Can use cout to display the value of integer


expressions and cin to assign a value to an integer
variable.
Example:
cout << “ What is the size? “;
cin >> size;
cout << “Size is: “ << size;
Program which uses integers
int main()
{
int quarters, dimes, nickels, pennies;
cout << “Enter number of quarters: “;
cin >> quarters;
cout << “Enter number of dimes: “;
cin >> dimes;
cout << “Enter number of nickels: “;
cin >> nickels;
cout << “Enter number of pennies: “;
cin >> pennies;
int total = 25 * quarters + 10 * dimes + 5 * nickels + pennies;
cout << “The total amount is”<< (total/100)<<“dollars and “
<< (total % 100) << “cents.” << endl;
return 0;
}
Identifiers/Variable Names
Identifiers used to name constants, variables and various
other things as well.

Have seen:
quarters, dimes, nickels, pennies, total, size,…

Three factors affect the choice of names


1. Rules of C++
2. Conventions adopted by C++ programmers
3. Good style
Identifiers/Variable Names
Rules
An identifier may contain:
- upper case letters (A, B, …, Z)
- lower case letters (a,b,c,…,z)
- digits (0,1,2,…,9)
- underscore ( _ )

Identifier must begin with a letter


(can start with _ but not good style)

Case sensitive: QUARTER, Quarter, quarter


are three different names
Identifiers/Variable Names
Conventions
Use lower case names for variables
Ex: quarters, pennies, size

If variable name consists of more than one word, start each new word
with an upper case letter
Ex: bookPrice, studentId

An alternate method for multi-word names is to separate each word with


an underscore
Ex: book_price, student_id

Use upper case letters for constant identifiers


Ex: const int MAX_LENGTH = 80;
Identifiers/Variable Names
Good Style
What does the following program do?

const double BTR_1 = 0.15;


const double STR_2 = 0.10;
const double LXVRW = 40000.0;
void main()
{
cout <<“ ?”;
double stuff;
cin >> stuff;
double theAnswer;
if (stuff < LXVRW)
theAnswer = stuff * BTR_1;
else
theAnswer =stuff * (BTR_1 + STR_2);
cout<< “Answer = “ << theAnswer << endl;
}
Identifiers/Variable Names
Easier to understand

const double BASE_TAX_RATE = 0.15;


const double SUPER_TAX_RATE = 0.10;
const double SUPER_LEVEL= 40000.0;
void main()
{
cout <<“ Enter income: ”;
double income;
cin >> income;
double tax;
if (income < SUPER_LEVEL)
tax = income * BASE_TAX_RATE;
else
tax =income * (BASE_TAX_RATE + SUPER_TAX_RATE);
cout<< “Tax = “ << tax << endl;
}
Identifiers/Variable names
Good Style …

Sometimes you will see


int count; // Number of coffees

Better style do do
int numCoffees; // Number of coffees
Output Statements

The cout statement produces output on the screen.


Items in double quotes (“) are treated as a message, and
shown exactly as they appear.
Items not in double quotes must therefore be variables or
expressions.
Each item is separated by the output operator <<
Need to include library iostream as cout is predefined
there.
Output Statements …
What will be the output of the following statements?

1) x = 8; y = 6;
cout << x << y;
cout << “ “ << y;

Conclusion: Separate cout statements do not necessarily


produce separate lines of output.

To begin a new line of output, use the endl manipulator.


Causes printing cursor to go to the beginning of the next
line.
Output Statements …
What will be output of each of these program fragments?
2) yards = 8;
feet = 3 * yards;
cout << yards << “ yd. is”;
cout << feet << “ ft.”;
Output Statements …
What will be output of each of these program fragments?

3) yards = 8;
feet = 3 * yards;
cout << yards << “ yd. is”;
cout << endl;
cout << feet << “ ft.”;
Output Statements …
What will be output of each of these program fragments?
4) cout << “Yes”;
cout << endl << “No.”;

5) cout << “Yes” << endl;


cout << endl;
cout << “No”;

6) cout << “Yes”;


cout << “No”;

You might also like