0% found this document useful (0 votes)
20 views18 pages

Lectures PF 1

Uploaded by

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

Lectures PF 1

Uploaded by

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

Lecture 1 & 2 Programming Fundamentals

Note: Documents provided are only to be used as helping materials we will focus more on Conceptual Based Learning

What is Computer?
• A computer is a machine that
– inputs (takes in) facts and information (known as data*)
– then processes (does something to or with) it
– can also store data
– afterwards it outputs, or displays, the results for you to see
* Data is all kinds of information, including, pictures, letters, numbers, and sounds

Defining feature of modern computers:


The defining feature of modern computers which distinguishes them from all other machines is that
they can be programmed
– a list of instructions (the program) can be given to the computer e.g.,
– add one number to another
– move some data from one location to another
– send a message to some external device, etc.
– it will store them (in memory)
– and carry them out (execute) some time in future
– Usually in the same order in which the instructions were given
Four kinds of Computers:
 Microcomputers
o These are the most widely used and the fastest-growing type of computers. There
are two major categories:
o Desktop Computers are small enough to fit on top or along the side of a desk and yet
are too big to carry around.
 Personal Computers
 Workstations
o Portable Computers are small enough and light enough to move easily from one
place to another.
 Laptops: 10-16 pounds in weight
 Notebooks: 5-10 pounds in weight
 Subnotebooks: 2-6 pounds in weight
 Personal Digital Assistants: Also known as palmtop computers and handheld
PCs. They combine pen input, writing recognition and communication
capabilities

 Minicomputers
o They are desk size machines.
o They fall between microcomputers and mainframe computers in their processing
speeds and data-storing capabilities.
o They might be used for research or monitoring a particular manufacturing process.
Smaller companies have been using minicomputers for their data processing needs such as
accounting/billing systems
 Mainframe Computers
o These are large computers.
o They are capable of great processing speeds and data-storing.
o They are used by large organizations – business, banks, government agencies etc –
to handle millions of transactions.
o For example, airline companies use mainframe computers to process information
about millions of travelers.

 Supercomputers
o The most powerful type of computer is the supercomputer.
o These machines are special, high-capacity computers used by very large
organizations.
o For example, NASA uses supercomputers to track and control space explorations.
o Supercomputers are also used for oil exploration, simulations and worldwide
weather forecasting.

Computer: Internal Components


Mostly on Motherboard:

 PCI Slot [sound, network, modem]


 AGP Slot [Graphics]
 DRAM Memory Slot
 Slot for Microprocessor
 IDE / ATA Connector [hard disk, CD-ROM]
 Connectors & Ports

Computer: An External Look


• Casing [with components inside]
• Monitor
– Let’s the user see how the computer is responding to their command
• Keyboard
– For entering text commands
• Mouse
– Point-and-Click interface for interacting with graphical environment

Computer: Peripherals
• A peripheral device is an equipment that might be added to a computer system to enhance
its functionality
– Printer
– Digital camera
– Scanner
– Projector
– Joystick
– Graphics tablet
Introduction to Problem Solving

Definition “Problem”
 A problem is generally considered to be a task, a situation or a certain scenario which is
difficult to deal with or control due to certain complexity.
 Example: Arranging a set of 10 000 random numbers in ascending order.

Definition “Problem Solving”


 Problem-solving skills are the ability to identify problems, brainstorm and analyze answers,
and implement the best solutions.

Steps to “Problem Solving”


Step 1 – Identify the problem that must be solved. The first step is to identify the problem
that needs to be solved.
Step 2 – Understand what the problem presents.
Step 3 – Determine how to solve the problem.
Step 4 – Selecting the solution.
Step 5 – Develop a method to achieve the solution.

Problem Solving in “Programming Fundamentals”


 It is about writing a list of instructions to tell the computer what to do step by step. After the
execution of these instructions, the results are stored.

Example “Problem Statements”


 Write a program that Displays the following Output (Program 1):

 Write a Program that displays a structure of N (odd) asterisk, similar to the image shown
below (Program 2):
A brief review of Von-Neumann architecture

The Von Neumann architecture is a standard design of computer system with different entities
connected over a bus:

1) Input/output or I/O Unit


2) A central processing unit (CPU)
3) Dedicated registers
4) Buses

I/O Devices
Inputs are the signals or data received into the computer system from the outside world via input
devices. The data is stored in internal registers. Outputs are the signals or data returned from the
computer system to the outside world via output devices. Together these peripheral devices form
the I/O unit.

The Processing unit


The CPU is responsible for carrying out the fetch-decode-execute cycle. The CPU fetches instructions
and data from the RAM or cache, decodes then executes. It is separated into the ALU (Arithmetic
logic unit) and a Control Unit

ALU
This calculates the arithmetic logic of instructions from programs (carries out calculations on the
data) needed by programs. It can carry out simple calculations like
adding/subtracting/multiplying/dividing and make logic operations like `greater than’ or `less than’
or `equal to’. It also acts as a conduit for input and output to and from the processor.

Control Unit
This controls the flow of data through the processor. It manages the execution of machine code by
sending control signals to the rest of the computer. Control signals are sent over the control bus to
connected devices like hard drives and graphics cards. The control unit synchronises instructions to
the internal clock speed. Some instructions can take less than one clock cycle to complete but the
CPU will only start on the next instruction once the clock cycle is over. The control unit command for
instructions and data to be fetched by assigning control signals to the memory registers. Once the
instruction is decoded it sends more signals to the hardware to execute it (i.e. it tells the computers’
memory, ALU and I/O devices how to respond to an instruction).

Memory unit
The memory unit is responsible for fetching data and instructions from the main memory and pulling
them into registers needed for the data to be processed. An instruction can only run on data within a
register so the memory unit is responsible for fetching from and saving to memory. Therefore, the
memory unit makes use of what is known as the fetch-decode-execute cycle.

Processor speed
This is measured by the number of clocks cycles a processor can perform per second and is
measured in hertz (Hz). Clock cycle = One increment of the CPU clock (fetch-decode-execute a single
instruction)

Bus types
The bus is a set of parallel wires connecting two or more components of a computer. It typically
consists of 8, 16, 32 or 64 lines. They connect all the components (I/O devices) to the CPU and RAM
and allow the transfer of data between the components.

 Address bus: is used to identify locations in other components by transferring memory


addresses to the either the memory or the I/O controller. Unidirectional flow. The address
may be for a location of an instruction or piece of data to be fetched or stored.
 Control bus – is used to send signals that coordinate the flow of data and manage the
activities of the peripheral devices. It transmits command, timing and specific status
information between components.
 Data bus – transfers data and instructions between peripherals, memory and the CPU.

These 3 buses are commonly collectively called the system bus. Each bus is a shared transmission
medium, so only one device can transmit along the bus at any given time. (The von Neumann
architecture has only one data bus so data transfers and instruction fetches are scheduled: They
cannot run at the simultaneously).

The main idea the Von Neumann architecture introduced was that not only the data but also the
program processing the data should also be stored in the memory. This made it easy to re-program
the computer.

The control bus is bidirectional so signals can be transferred in both directions. The data and address
buses are shared by all components in the system. Control lines must, therefore, be provided to
ensure access and use of the data and address busses by different components does not conflict.

Data Representation
Definition
 Modern computers are digital devices
– A digital device works with discrete data, such as the digits 1 and 0
– An analog device works with continuous data
Just as a standard light switch is a simpler technology than a dimmer, so is digital when compared to
analog
Why Data Representation is Important

Number System
• We use decimal number system [base 10] when representing numeric values in our daily life
– E.g., consider the number 123
• 123 = 100 + 20 + 3 = 1*102 + 2 * 101 + 3*100
• Most modern computer systems do not use the decimal system to represent numeric
values.
– Instead, they use a binary numbering system [base 2]
• Consisting of only two digits: 1 and 0
• Uses powers of 2 rather than 10
Representing Non-Numeric Data
• Some decimal values & their binary equivalents
• In addition to numeric data, computers also
manipulate character data
• numbers, symbols, numerals that are not used
in arithmetic operations
– To represent them, codes have been developed
that specify binary equivalent for each character
• ASCII – 7 bits
• Unicode – 16 bits
• Sounds and pictures must be transformed
into a format the computer can understand
– A computer must digitize colors, notes, and
instrument sounds into 1s and 0s

Quantifying Bits and Bytes


• A bit is one binary digit (b):
– can have value either 0 or 1
• A nibble is 4 bits
– 0100
• A byte is 8 bits (B)
– 0010 0100
• Kilo- means a 1000; Mega- means million; Giga -means billion
– Kilobit (Kb) is 1,024 bits
– Kilobyte (KB) is 1,024 bytes
– Megabyte (MB) is 1,048,576 bytes
– Gigabyte (GB) is 1,073,741,824 bytes
• Bits take the form of electrical pulses that can travel over circuits
– Almost the same way as electricity flows over a wire when you turn on a light switch.
Lecture 3 & 4 Programming Fundamentals

Introduction to programming
What is Programming
 Programming refers to a technological process for telling a computer which tasks to perform
in order to solve problems.
 A plan or schedule of activities, procedures, etc., to be followed.
 Programs are created to implement algorithms. These algos can be represented in the form
of flowcharts, mind maps or pseudocode, and programming is the translation of these ideas
into a computer program.
Examples of Programming Languages:

 C/C++
 Java
 Python
 JavaScript
 Ruby and many more
Steps in Learning Programming Language

C++ language character set


C++ language constants

C++ Key Words


C++ Syntax Recap
Hello World Program Recap

#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

Line 1: #include <iostream> is a header file library that lets us work with input and output objects,
such as cout (used in line 5). Header files add functionality to C++ programs.

Line 2: using namespace std means that we can use names for objects and variables from the
standard library.

Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable.

Line 4: Another thing that always appear in a C++ program, is int main(). This is called a function. Any
code inside its curly brackets {} will be executed.

Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to
output/print text. In our example it will output "Hello World!".

Note: Every C++ statement ends with a semicolon ;.

Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }

Remember: The compiler ignores white spaces. However, multiple lines makes the code more
readable.
Line 6: return 0 ends the main function.

Line 7: Do not forget to add the closing curly bracket } to actually end the main function.

C++ Output Recap

#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}

 The “cout” object, together with the “<<” operator, is used to output values/print text.
 You can add as many cout objects as you want. However, note that it does not insert a new
line at the end of the output
C++ Adding of New or Blank lines

#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++"<<endl;
return 0;
}

 Both \n and endl are used to break lines. However, \n is most used.
 But what is \n exactly?
 The newline character (\n) is called an Escape Sequence, and it forces the cursor to change
its position to the beginning of the next line on the screen. This results in a new line.
C++ Single Line Comments

// This is a comment
cout << "Hello World!";
-------------------------------------------------------------------
cout << "Hello World!"; // This is a comment
-------------------------------------------------------------------
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
Comments can be used to explain C++ code, and to make it more readable. It can also be used to
prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.

Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for example:
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 double - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
 string - stores text, such as "Hello World". String values are surrounded by double quotes
 bool - stores values with two states: true or false
General syntax

type variableName = value;

Creating a Variable

int myNum = 15;


cout << myNum;

Assigning Values to Existing Variable

int myNum = 15;


myNum = 10;
cout << myNum;

Other Types Variable Declaration

int myNum = 5; // Integer (whole number without


decimals)
double myFloatNum = 5.99; // Floating point number (with
decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
Displaying Variables

int myAge = 35;


cout << "I am " << myAge << " years old.";

Addition of Two Variables

int x = 5;
int y = 6;
int sum = x + y;
cout << sum;

Declaring Multiple Variables

int x, y, z;
x = y = z = 50;
cout << x + y + z;

C++ Identifiers

// Good
int minutesPerHour = 60;

// OK, but not so easy to understand


what m actually is
int m = 60;

The general rules for naming variables are:


 Names can contain letters, digits and underscores.
 Names must begin with a letter or an underscore (_).
 Names are case sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (like C++ keywords, such as int) cannot be used as names.
C++ Constants
When you do not want others (or yourself) to change existing variable values, use the const keyword
(this will declare the variable as "constant", which means unchangeable and read-only). E.g,
Minutes per hour or values of pi.

const int myNum = 15;


myNum = 10; // Do you see any error in this line?

User inputs

int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;

C++ Data types


Basic Data Types

Data Type Size Description

Boolean 1 byte Stores true or false values

char 1 byte Stores a single character/letter/number, or ASCII values

int 2 or 4 bytes Stores whole numbers, without decimals

float 4 bytes Stores fractional numbers, containing one or more decimals.


Sufficient for storing 6-7 decimal digits

double 8 bytes Stores fractional numbers, containing one or more decimals.


Sufficient for storing 15 decimal digits
C++ Numeric Data Types
Int

int myNum = 1000;


cout << myNum;

Float

float myNum = 5.75;


cout << myNum;

Double

double myNum = 19.99;


cout << myNum;

E to the power (Scientific Numbers)

float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;

C++ Boolean Data Types


A Boolean data type is declared with the bool keyword and can only take the values true or false.
When the value is returned, true = 1 and false = 0.

#include <iostream>
using namespace std;
int main() {
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun << "\n";
cout << isFishTasty;
return 0;
}
C++ Character Data Types
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':

char myGrade = 'B';


cout << myGrade;

C++ String Data Types


The string type is used to store a sequence of characters (text). This is not a built-in type, but it
behaves like one in its most basic usage. String values must be surrounded by double quotes:

string greeting = "Hello";


cout << greeting;

C++ Operators
Operators are used to perform operations on variables and values.There are four main types of
operators:

Arithmetic
Addition
 Adds together two values.
 Operator (+)
 Example Syntax (x + y)

Subtraction
Subtracts one value from another

 Example Syntax (x + y)
 Operator (-)
 Example Syntax (x - y)

Multiplication
 Multiplies two values
 Operator (*)
 Example Syntax (x * y)
Division
 Divides one value by another
 Operator (/)
 Example Syntax (x / y)
Modulus
 Returns the division remainder
 Operator (%)
 Example Syntax (x % y)

Increment
 Increases the value of a variable by 1
 Operator (++)
 Example Syntax (++x)

Decrement
 Decreases the value of a variable by 1
 Operator (--)
 Example Syntax (--x)

Assignment
Assignment operators are used to assign values to variables.

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Comparison
Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.

The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are
known as Boolean values
Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Logical
As with comparison operators, you can also test for true (1) or false (0) values with logical
operators. Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements x < 5 && x < 10
are true

|| Logical or Returns true if one of the x < 5 || x < 4


statements is true

! Logical not Reverse the result, returns false if !(x < 5 && x < 10)
the result is true

-------------------Assignment 1-------------------
 Create a Simple Calculator that takes an input of two number and perform ‘Addition’,
’Subtraction’, ’Multiplication’ and ‘Division’; displaying all 4 results as output.
 Create a Simple Calculator that takes an input of two numbers and asks user which one of
the following operations needs to be done Addition’, ’Subtraction’, ’Multiplication’ and
‘Division’; displaying one desired output only.

You might also like