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

Lecture 2

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

Lecture 2

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

Programming Techniques

Lecture 2
Lecture Outline
• Basic Programming Concepts: Input, Processing and Output
• Data Types
• Variables
• Identifier Naming Conventions
• Reserved Words
• Algorithms
• Pseudocode
• Flowcharts
Introduction
• Programming is the process of designing and implementing
logic to accomplish a specific computer task.
• It involves analyzing, generating algorithms, implementing
algorithms in a particular programming languages, and
testing to make sure the program works correctly.
• Every task that happens inside a computer system involves
processing some input data into a form of output using an
algorithm (instructions)
• We shall discuss what happens during input, processing , and
output process.
Syntax
• The ways that specific words and symbols are used by each
language is called its syntax.
• The actual code depends on what language you are using.
• Every language has its specific syntax
#include <iostream>
using namespace std;
• In C++ the syntax is as follows:
int main( ) {
cout << "Hello World!";
return 0;
}
Syntax
• Line 1: #include <iostream>
#include <iostream> • Is a header file library that lets
using namespace std; us work with input and output
objects, such as cout.
• Header files add functionality
int main( ) { to C++ programs.
cout << "Hello World!"; • Line 2: using namespace std
• Allows us to use names for
return 0; objects and variables from the
} standard library.
Syntax
• Line 3: A blank line.
#include <iostream> • C++ ignores white space.
• But we use it to make the code
using namespace std; more readable.
• Line 4: int main().
int main( ) { • This is called a function. Any
cout << "Hello World!"; code inside its curly brackets {}
will be executed.
return 0;
• Line 5: cout is an object used
} together with the insertion
operator (<<) to output/print
text.
Syntax

#include <iostream> • Every C++ statement ends


using namespace std; with a semicolon (;)
• Line 6: return 0 ends the main
function.
int main( ) {
• Line 7: Do not forget to add
cout << "Hello World!"; the closing curly bracket } to
return 0; actually end the main
} function.
Data Input
• The data input operation enables us to enter data into the
computer system in different forms. (i.e. text, sound, light,
video, …).
• When you want the user to input data to a program, you should
always provide a prompt.
• We will use a statement that begins with the word cin to
allow the user to enter data from the keyboard.
cout << “This is a prompt:”;
cin >> amount;
Data Processing
• The processing operation in a program executes the statements
that cause the program to do something.
• Consider the statement:
sum = varNumber1 + varNumber2
• Consider
profit = sellingPrice - costPrice
Data Output
• The output of a program is the data sent by the program to the
screen, printer, or another destination such as a file.
• The output normally consists, at least in part, of the results of the
program’s processing component.
• We will use the cout statement to display messages on the
screen.
• A statement like the following to display the value of a variable:
cout << circumference;
cout << “Enter you name:”;
Variables
• When we write programs most times we don’t know the actual
numbers that the user will enter while running (executing) the
program.
• A computer program should always be written so that the user
doesn’t have to reenter all the steps to get another result.
• A variable is quantity that can change value during execution of
a program.
• It is a named memory location whose contents can vary or differ
over time.
• Example: myNumber, NAME, amount, … are variables
Variables
• Whenever we need to refer to that data in a subsequent
program statement, we simply refer to its variable name
• Technically, a variable is the name for a storage location in the
computer’s memory, and the value of a variable is the contents
of that location.
Variables
• In most programming languages before you can use a variable,
it must be first declared.
• A variable declaration is a statement that provides a data type
and identifier for a variable.
• An identifier is a variable’s name
• The data type of a variable describes:
• The data the variable can hold
• How the data is stored in memory
• What operations can be performed on the data item
Identifier Names
• Identifiers are names of things, such as variables, constants,
and methods, that appear in programs.
• All identifier names must obey the programming language
rules for identifiers.
• These rules are different for every language but the
following is generally accepted:
• An identifier name consists of letters, digits, the
underscore character (_), and the dollar sign ($) and must
begin with a letter, underscore, or the dollar sign.
• Identifier names can be any length but should be
meaningful.
Identifier Names
• Identifiers can be made of only letters, digits, the underscore,
and the dollar sign, no other symbols are permitted to form an
identifier.

• Legal/acceptable identifier names include:


• first, NUMBER, Conversion, NaMe, …
• payRate, ComputeAverage, FIRSTname, Lastname, …
• count1, n1room, f2name, item_number, …
• $Amount, _amount, _Amount, _2place, …
• _house, _20, var, …
Reserved Words
• Reserved words are also called keywords.
• Reserved words cannot be redefined by the user within any
program, i.e. they cannot be used for anything other than
their intended use.
• A named constant is an identifier that represents a permanent
value that never changes.
• Example: float PI = 22/7
int INTEREST_RATE = 30
float SALES_TAX = 0.07
Data Types
• The computer allocates a certain amount of space in its
memory for data.
• But some data requires more space than other data
• All data requires memory space and the type of data
determines how much memory is needed.
• For this reason, when we write programs, we must tell the
computer what type of data we are dealing with.
• The programmer must define the data type of the variables
being used.
Data Types
• Computer languages make use of two categories of data types,
namely: primitive and derived data or reference types.

• Primitive data types are the most basic types of data available
within any programming language.
• They may include types such as integer, double, float, character, byte,
long, short, signed, unsigned, and Boolean.

• Derived data types are an aggregation of the basic data types.


• They include types like string, list/arrays, structures, dictionaries,
tuples, pointers, queues, stacks, objects, unions, …
Data Types
• Four (4) basic data types will be used in our course, namely:
• integer
• floating-point
• character
• Boolean

• Two (2) derived data types will also be studied in this course,
namely:
• String
• Array
Declare Statement
• When we declare variables using statements like the following:
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String
• Many programming languages allow you to declare several variables
in one statement, all variables must have the same data type.
int num1, num2;
string firstName, lastName, fullName;
Basic Data Types

Data Type Size Description


Boolean 1 byte True or False values
char 1 byte single character/letter/number, or ASCII values
int 4 bytes whole numbers, without decimals
float 4 bytes fractions containing a decimal. Can store 6-7
decimal digits
double 8 bytes fractions containing a decimal. Sufficient for
storing 15 decimal digits
String Data Type
• The string type is used to store a sequence of characters (text).
• Strings must be surrounded by double quotes (“ ”)
• Example: string val = "Enter the first number:”;
string name;
name = “My name is Peter.”;
• To use strings, you must include an additional header file in the
source code, the <string> library:
//Include the string library
#include <string>
Operations on Strings
• In many programming languages, concatenation, takes two or
more strings and joins them to produce a single string result.
• The symbol that is often used to concatenate two strings is the
plus sign, +.
• For example, if String1 = "Part" and String2 = "Time", then the
statement
newString = String1 + String2

• The value of NewString is “Part Time”


Example
• What is displayed on the screen when the following is
executed:
string ItemName, TextString, ItemCost;
ItemName = "Cashmere sweater ”;
TextString = "will cost $ ”;
ItemCost = “125”
cout << ItemName << TextString << ItemCost << endl;
Algorithms
• An algorithm is a sequence of steps for solving a specific
problem given its input data and the expected output data.
• When we write a computer program, we are generally
implementing a method that has been devised previously to
solve some problem.
• Algorithms can be expressed in one of these ways: words,
pseudocodes, flowchart and a programming language.
Pseudocode
• Pseudocode uses short, semi-formal English-like phrases to
describe the outline of a program.
• It’s not actual code from any specific programming
language, but sometimes it strongly resembles the actual
code.
• Pseudo is a prefix that means “false”, hence it simply
means “false code”
• It uses limited vocabulary to design and describe algorithms
• It is a "text-based" (algorithmic) detail design tool.
Pseudocode
• Using pseudocode involves writing down all the steps used
in your program
• Statements can begin with start/begin and can end with
stop/halt/end/terminate
• The statements between the start and end look like ordinary
English but can be somewhat formal
Example 1: Number Doubling Program
// This is a comment – Single Line Comments
/*This is also a comment – Multiple Line comment*/

1) Start
2) Write “Enter number: ”
3) Input myNumber
4) Set myAnswer = myNumber * 2
5) Write myAnswer
6) End
Example 1: Number-doubling program
// This is a comment – Single Line #include <iostream>
Comments using namespace std;

/*This is also a comment – Multiple


int main( ) {
Line comment*/
// Single Line Comments
1) Start /*This is a Multiple Line comment*/
2) Write “Enter number: ” int myNumber, myAnswer;
3) Input myNumber cout << “Enter number:”<< endl;
cin >> myNumber;
4) Set myAnswer = myNumber * 2
myAnswer = myNumber * 2;
5) Write myAnswer cout << myAnswer;
6) End return 0;
}
Example 2
• Pseudocode for addition program might look as:

1) Start
2) //Prompt for first and second number
3) Write “Enter first and second numbers”
4) Input num1, num2
5) Calculate sum = num1 + num2
6) Write “The results is “ + sum
7) End
Example 2
1) Start #include <iostream>

2) //Prompt for first and second number using namespace std;

3) Write “Enter first and second numbers”


int main( ) {
4) Input num1, num2
/*Addition program*/
5) Calculate sum = num1 + num2 int num1, num2, sum;
6) Write “The results is “ + sum cout<<“Enter first and second numbers”;
7) End cin >> num1 >> num2;
sum = num1 + num2;
cout << “The results is ”<< sum;
return 0;
}
Try
1. Write an algorithm in pseudocode to find the profit on
each item bought in a shop.
2. Write an algorithm in pseudocode to find the area and
perimeter of a rectangle.
Flow charts
• This is a diagram that uses special symbols to display
pictorially the flow of execution within a program or a
program module.
• It is a formalized graphic representation of a program’s logic
sequence, a work or manufacturing process, or any similar
structure.
• It provides an easy, clear way to see which pieces of code
follow the various programming structures that all programs
are constructed from.
Creating flow charts
• A programmer would create a flow-chart to aid in
understanding the flow of a program.
• Herman Goldstine (developers of ENIAC) first developed flowcharts
with John von Neumann at Princeton University in the late 1946 and
early 1947.
• Interactive flowcharting programs are available for creating
flow charts
• Raptor, MS word templates, etc
Flow Chart Symbols
• A typical flowchart will include some or all of the following
symbols;
• Start and End symbols are represented as ovals or
rounded rectangles.
• Arrows show the flow of control. An arrow coming from
one symbol and ending at another symbol represents that
control passes to the symbol to which the arrow points.
• Processing steps are represented as rectangles.
Flow Chart Symbols
• Input/Output steps are represented as parallelograms.
• Conditional (or decision or selection) segments are
represented as diamond shapes. These typically contain a
Yes/No question or a True/False test.
• This symbol has two arrows coming out of it.
Flow
Chart
Symbols
Example 1
Pseudocode: Flowchart:
1) start start

2) input myNumber
3) set myAnswer = myNumber * 2 Input myNumber

4) write myAnswer
Set myAnswer = myNumber * 2
5) end

write myAnswer

end
Example 2
Pseudocode:
1) Start
2) Prompt for user temperature in Fahrenheit
3) Input temperature
4) Calculate temperature in Celsius by subtracting 32 from
Fahrenheit and multiplying by 5 and dividing the result by 9
5) Display the temperature in Celsius
6) End
Example 2
start

Flow chart:
Prompt for user temperature in Fahrenheit

Input temperature

Calculate temperature in Celsius by subtracting 32 from Fahrenheit and multiplying by


5 and dividing the result by 9

Display the temperature in Celsius

end

You might also like