Lecture1 Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

programming

FUNDAMENTAL
BERC1313 Programming Fundamental
 Lecture (1BERE/1BERZ): Friday, 8am – 10am, DK 3 KDK

 Lab / Tutorial:
 1BERE (s1/1): Monday, 2pm – 5pm, MSK
 1 BERE (s1/2): Tuesday, 2pm – 5pm, MSK
 1 BERZ (s1/1): Thursday, 2pm – 5pm, MPK
 1 BERZ (s1/2): Tuesday, 8am – 11am, MPK

 Assessment:
 Lab Assessment – 30%
 Lab Test – 10%
 Mid Term Test – 20%
 Final Exam – 40%

2
Chapter 1:
Introduction to Computers &
the Programming Language

3
Objectives
You will learn about:
Overview of computers
Computer hardware & software
Computer language
Evolution of programming languages
Discover what a compiler does
Examine a basic C program
Explore how a C program is processed

4
What is a computer?
• A general purpose machine commonly consisting
of digital circuitry that accepts inputs; stores,
manipulates, and generates outputs (example:
numbers, graphics, voice, video, etc); in
accordance to instructions called a program.

5
How does it looks like?

6
7
Computer components
 Refers to the physical parts
Hardware of the computer that have
mass.
 Can be touched.

Computer

 Refers to program that


resides and executes
Software electronically inside the
hardware.
 Doesn’t exist physically!

8
Computer hardware

9
Hardware Inside the cpu

10
Computer software  Software that manages the system
resources and control the
operations of the hardware.
System  Normally supplied by the
manufacturer of the computer.
 System programs take control of the
computer, such as an Operating
Computer System.
Software  Example: Windows 7,8,10,11.

 Programs that provide services or


Application
solutions to the user.
 Example: Microsoft Word to do
word processing, Microsoft
PowerPoint to make presentations,
etc.

11
Hardware Inside the cpu
• CPU (Central Processing Unit) - performs most of the calculations
which enable a computer to function, and is sometimes referred to as
the "brain" of the computer. It is usually cooled by a heat sink and
fan.
• Chipset - mediates communication between the CPU and the other
components of the system, including main memory.
• RAM (Random-access Memory) - stores resident part of the current
running OS and all running processes. It is volatile, so main memory is
erased when program terminates or computer is turned off
• ROM (Read-only Memory) - stores the initial program that runs when
the computer is powered on or otherwise begins execution
(Bootstrapping also known as "booting" or "booting up").
• HDD (Hard Disk Drive) - for medium-term storage of data. It is non-
volatile, so data is retained even when program is not running or
computer is turned off.
• USB flash drive - a flash non-volatile memory data storage device
integrated with a USB interface, typically small, lightweight,
removable, and rewritable.

12
13
History Of Computer Languages:

Computer language evolution

The only language understood by a computer is machine language!

14
Machine language

• Early computers were programmed in machine language


• To calculate salary = rates x hours in machine
language:

100100 010001 //Load


100110 010010 //Multiply
100010 010011 //Store

15
Assembly language

• Using assembly language instructions, to calculate salary =


rates x hours
can be written as:

LOAD rate
MULT hour
STOR salary

16
High-level language

• Example: COBOL, FORTRAN, VB, C, C++, C#, Objective-C, etc…


• Portable to many different computers.
• Programmers use this language to write programs. Compiler then
translates the program written in a high-level language into machine
language.
• The equation salary = rate x hours can be written in C as:

wages = rate * hours;

17
Example 1
#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("Hello world!\n");

return 0;
}

Sample Run:
Hello world!

18
Example 2
#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("Computers are dumb.\nBut programmers make
them seem smart.\n\n");
printf("The sum of 2 plus 3 is %d\n", 2 + 3);

return 0;
}

Sample Run:
Computers are dumb.
But programmers make them seem smart.
The sum of 2 plus 3 is 5

19
Integrated Development Environments
(IDE)
• An integrated development environment, or IDE,
combine all the tools needed to write, compile,
and debug a program into a single software
application.
• Examples are Microsoft Visual C++, Borland C++
Builder, CodeBlocks, etc.

20
Integrated Development Environments
(IDE)

21
Why Program?
• Computer – programmable machine designed to
follow instructions.
• Program – instructions in computer memory to
make it do something.
• Programmer – person who writes instructions
(programs) to make computer perform a task.

• SO, without programmers, no programs; without


programs, a computer cannot do anything. (Pretty
useless!)

22
BERC 1313

PROGRAMMING FUNDAMENTAL
System Development
 The critical process determines the overall quality
and success of the program.
 If any program is designed carefully using good
structured development techniques, the program will
be efficient, error-free and easy to maintain.
 Most programming projects are built using system
development life cycle.
 One of the popular development life cycle is known
as the waterfall model.
Waterfall model
Program Development
• A multi-step process that requires you understand the
problem, design a solution, write the program, and test the
program.

• Program design - To determine how to take inputs and


convert them into the output that have been specified in the
program requirements statement

• 4 steps involve in solving a problem:


– Analyse: Understand the problem
– Design: Design the algorithm to solve problem
– Code: Develop (or write) the program
– Test: Test the program
Problem 1:
Your summer surveying job requires you to
study some maps that give distances in miles,
but you and your co-workers prefer to deal in
metric measurements (kilometers).

Write a program that performs the necessary


conversion. The program will display the
resulting distance in km.

Formula: (1 mile = 1.609 kilometers)


Step 1: analyse
• Understand the problem! Highlight important clues!
Your summer surveying job requires you to study
some maps that give distances in miles, but you
and your co-workers prefer to deal in metric
measurements (kilometers).

Write a program that performs the necessary


conversion. The program will display the
resulting distance in km.

Formula: (1 mile = 1.609 kilometers)


Step 2: design
• Determine the input, process & output!
• Input
– the distance in miles
(M)

• Process (or formula)


– 1 mile = 1.609 kilometers
– K = M x 1.609

• Output
– the distance in kilometers
(K)
Step 3: write the program
// written by: John, 1 BETC
/* Problem Solving Exercise:
Introduction to C */

#include <stdio.h>
#include <stdlib.h>

int main()
{
float distanceMiles;
float distanceKm;

// get user input


printf("Please enter distance in miles: ");
scanf("%f", &distanceMiles);
// calculate
distanceKm = distanceMiles * 1.609;
// display output
printf("Distance in km is %f\n", distanceKm);

return 0;
}
Step 4: test
• Output of the program:

* Check for any syntax / run-time / logic errors


Structure of a C Program
Structure of a C Program
 Preprocessor directive start with a pound sign (# is a syntax in
C)
 #include <stdio.h>
 include tells the preprocessor that you want the
library in the < >
 Tells the compiler to include input/output stream header
file in the program
 The program need this header file because it will print a
message to the console (monitor)
 All preprocessor directive starts with pound sign (#)
 Format or syntax of this directive must be exact
 No space between # and include
Structure of a C Program
• C program is made up of a global declaration section and one
or more functions.
• Global declaration section comes at the beginning of the
program.
• Function contains two types of codes :
– Local Declarations
• Data that you’ll be using in the function
• Also called local declaration because only visible to the
function that contain them
– Statements
• Instructions to the computer to do something
Structure of a C Program
• int main( )
• The word int says that the function will return an integer value to the
operating system (main function)
• Statements in main function are to print message and to terminate the
program
• The output string contains what you want to displayed enclosed in
double quote marks ( “ )
• “\n” at the end of the message tells the computer to advance to the
next line in the output.
• return 0 terminates the program
• The body of the function starts with an open brace and terminates with
a closed brace. { }
Basic Command of Output

Escape Name Description


Sequence

\t Horizontal Tab Takes the cursor to the next tab stop

\n or endl New line Takes the cursor to the beginning of the next line

\v Vertical Tab Takes the cursor to the next tab stop vertically.

\" Double Quote Displays a quotation mark (")


\' Apostrophe Displays an apostrophe (')
\? Question mark Displays a question mark
\\ Backslash Displays a backslash (\)
\a Audible alert sound
Character Set And Token
 Character set consist of :
1. Number : 0 to 9
2. Alphabetical : a to z and A to Z
3. Spacing
4. Special Character :
, . : ; ? ! ( ) {} “ ‘ + - * / = > < # % & ^ ~ | / _

 Token : combination of characters, consist of


1. Reserved words/keywords
2. Identifiers (variable, constant, function name)
3. Punctuators
4. Operators
5. Literal String
Identifiers
 Allows programmers to name data and other objects in the
program-variable, constant, function etc.

 Can use any capital letter A through Z, lowercase letters a through z,


digits 0 through 9 and also underscore ( _ )

 Rules for identifier


 The first character must be alphabetic character or
underscore
 It must consists only of alphabetic characters, digits and
underscores, cannot contain spaces
 It cannot duplicate any reserved word
 C is case-sensitive; this means that CASE, Case, case, and CaSe are
four completely different words.
Reserved word/ Keyword
 A word that has special meaning in C.
 Used only for their intended purpose.
 Keywords cannot be used to name identifiers.
 All reserves word appear in lowercase.
C and C++ Reserved Words
auto do goto signed union
break double if sizeof unsigned
case else int static void
char enum long struct volatile
const extern register switch while
continue float return typedef
default for short

C++ Reserved Words


asm delete mutable register true
bool dynamic_ namespac reinterpret_cast try
catch cast e static_cast typeid
class explicit new string typename
cin false operator template using
const_cas friend private this virtual
t inline protected throw wchar_t
cout interrupt public
Valid/Invalid Identifiers

Valid names Invalid names


A $sum // $ is illegal
student_name 2names // can’t start with 2
_aSystemName stdnt Nmbr // can’t have space
pi int // reserved word
al
stdntNm
_anthrSysNm
PI
Constants
• Data values that cannot be changed during the execution of a
program

• Types of constant
– Integer constant
– Float constant
• Numbers with decimal part
– Character constant
• Enclosed between two single quotes (‘)
– String constant
• A sequence of zero or more characters enclosed in double
quotes (“)
– Symbolic constant
• Defined constant and memory constant
Constants
• Three different ways
– Literal constants
• An unnamed constant used to specify data
• If the data cannot be changed, we can simply code the data
value itself in a statement
• E.g

‘A’ // a char literal


5 // a numeric literal 5
a+5 // numeric literal
3.1435 // a float literal
“Hello” // a string literal
Constants
– Defined constant
• Using the preprocessor command define
• Like other preprocessor commands, it is also prefaced with the
pound sign (#)
• Placed at the beginning of a program to make it easy to find
and change

• E.g #define SALES_TAXES_RATE .0825

• The way define work is that the expressions that follows the
name (.0825) replaces the name wherever it is found in the
program (like search and replace command)
Constants
– Memory constant
• C provides the capability to define a named constant where we
can add the type qualifier, const before the definition
• Type qualifier indicates that data cannot be changed and to fix
the contents of the memory location
• E.g
const float pi = 3.1416;
Variables
• Named memory locations that have a type, such as integer
or character and a size which is inherited from their type

• Each variables in programs must be declared and defined

• When we create variables, the declaration gives them a


symbolic name and definition reserves memory for them

• Once defined, variables are used to hold the data that are
required by the program from its operation
Variables
Variables

Variable declaration syntax :


<variable type> <variable name>
Examples :
short int maxItems; // word separator : capital
long int national_debt; // word separator : _
float payRate; // word separator : capital
double tax;
char code;
bool valid;
int a, b;
Variable initialization
• Initializer establishes the first value that the variable will
contain

• To initialize a variable when it is defined, the identifier is


followed by the assignment operator (=) and then the
initializer which is the value the variable is to have when the
functions starts

• Eg:
– int count = 0;
– int count , sum = 0; // Only sum is initialize.
– int count=0 , sum = 0; OR int count =0; int sum = 0;
Punctuator
 Use for completing program structure
 Including [ ] ( ) { } , ; : * # symbols
Operator
 C uses a set of built in operators ( Eg : +, -, *,
/).
 There are several classes of operators :
Arithmetic, relational, logical and assignment.
Common Programming Errors

Categories

syntax errors logic errors run-time errors

missing semicolon,
illegal operation,
undeclared program follows a
such as dividing by
variables, missing faulty algorithm
zero.
braces
Common Programming Errors
• Errors in programs can be categorized into 1)
syntax errors, 2) logic errors, 3) run-time errors
• Syntax errors:
– When your code violate some or more grammar rules
of C.
– Detected by compiler as it attempts to translate your
program.
– Compiler cant translate your program and will not be
executed.
– Example : missing semicolon, undeclared variables,
missing braces etc.
Common Programming Errors
• Logic errors:
– Occur when a program follows a faulty algorithm.
– Logic errors usually do not cause run time errors
and do not display error messages.
– They are very difficult to detect.
– The only sign of a logic error may be incorrect
program output.
– You can detect logic errors by testing the program
thoroughly, comparing its output to calculated
results.
Common Programming Errors
• Run-time errors:
– Detected and displayed by the computer during
the execution of a program.
– Occurs when the program directs the computer to
perform an illegal operation, such as dividing by
zero.
– The computer will stop executing your program
and will display a diagnostic message that
indicates the line where the error was detected.

You might also like