Upload
others
View
6
Download
0
Embed Size (px)
Citation preview
Introduction to Computer Programming - CPU1141 Faculty of Natural Sciences Department of Mathematics & Computer Science Bachelor of Science Degree Computer Science: Level 3
Course Details • Printed Materials: ▫ Introduction to Computer Programming Course
Material ▫ Introduction to Computer Programming Practical
Guide • Day Schools • Practical Sessions • Practical Test • Continuous Assessment Tests [NBT I & NBT II] • Final Exam
Course content • Computer Programming • Introduction to Pascal ▫ Data Types & Variables ▫ Operations & Expressions ▫ Control Structures ▫ Functions & Procedures ▫ Arrays & Pointers
• Introduction to C ▫ Data Types & Variables ▫ Operations & Expressions ▫ Control Structures ▫ Input output functions ▫ Arrays, Strings, Pointers and Functions ▫ File Handling
Today’s Sequence
• Computer Programming • Introduction to Pascal • Data Type & Variables • Operations & Expressions • Control Structures
Learning Outcome
• Aim: ▫ To provide a brief introduction to the computer
programming
• You will be able to: ▫ Get an idea about programming and the level of
languages
Introduction
• This chapter discuss the reasons for learning programming and level of languages
What is a program?
A program is a set of step by step instructions that directs the computer to do the tasks you want it to do and produce the result you want
Introduction
Why programming? • Programming helps you understand computers • Writing few simple programs increases your
confident level • Learning programming lets you find out how
you solve problems analytically.
Introduction
Terms: • Programming Language: A set of rules that provides a way of telling a
computer what operations to perform
Levels of Languages • Programming Language mainly divided into two
namely “Lower” and “Higher” • Lower:
How close it is to the language of the computer eg: 1’s and 0’s
• Higher: How close it is to the language of people use eg: similar to English language
Levels of Languages
• There are five levels of language: ▫ Machine Language ▫ Assembly Language ▫ High-Level Language ▫ Very High-Level Language ▫ Natural Language
Levels of Languages Machine Language: • The lowest level of programming language • Only understood by the computer and
IMPOSSIBLE for humans • Each type of computer has its own machine
language • Represent the data and program instructions as
1s and 0s • These 1s and 0s are corresponded to the ON and
OFF electrical states in the computer respectively.
Levels of Languages Assembly Language: • Used abbreviation which are easily remembered
by human to replace 1s and 0s ▫ Eg: ADD, MUL
• Each type of computer has its own assembly language
• Requires a translator called “Assembler” to convert the assembly language program into machine language
Assembly Language
Machine Language
Translator ( Assembler)
Levels of Languages High-Level Language: • Began using of High-Level language in early 1960 • Programs were written in similar to English
Language • Eg: COBOL, Fortran, Pascal, C, C++, C# • Runs on any machine • Benefits: ▫ Convenient ▫ More production with less effort ▫ Tend to focus on solving much complex problems
Levels of Languages High-Level Language: • A translator called “Compiler” is needed to translate
the symbolic statements into machine language
• Programmers write programs in a form called “Source Code”
• Compiler is used to translate source code to machine language
• The compiler produces an intermediary form called “object code”
• Object code is much similar to a computer’s machine language
Translator ( Compiler)
Source Code Object Code
Levels of Languages
Very High-Level Language: • These are known by their generation number;
fourth generation languages (4GLs) • 4GL languages are programming languages
closer to human languages than typical high level languages
• Mostly used to access databases
Levels of Languages
Natural Language: • These are used for artificial intelligence and
neural networks • Eg: Prolog • Prolog is used to develop Expert Systems
PART A: PASCAL LANGUAGE
Learning Outcomes
Aims: • To provide a brief introduction to the Pascal
Language You will be able to: • Identify the major segments of a Pascal program • Write a simple Pascal program
Introduction
Major segments of a Pascal Program: • A Pascal program has three major segments: ▫ The program identification and description
segment ▫ The declaration segment ▫ The main body of the program
Introduction Segment 1: Program Identification & Description: • The structure of the first line in the program
• Explanation:
PROGRAM example01 (INPUT, OUTPUT);
Code Description
PROGRAM First word of any Pascal program
example01 Program Name
(INPUT, OUTPUT) To indicate whether program has any input or output
; Last character of any Pascal line
Introduction Segment 1: Program Identification & Description: • Every Pascal line should end with a semicolon
“;” • So, it is possible to spread one Pascal line over a
no. of horizontal lines • Pascal is not case sensitive language • Upper case characters were used to represent
keywords in examples
Introduction Segment 1: Program Identification & Description: Rules in Pascal for giving program name to a program: • Name has to start with a letter of the alphabet “a-z”
or an underscore “_” • Do not start a program name with a digit or special
characters “#, ?” • The other items in a name could contain any
keyboard character • There should be no blank space within a name
▫ Eg: if a name contain 2 components, it can be separated using an underscore
• Do not include keywords used in Pascal for naming a program
Introduction Segment 1: Program Identification & Description: Keywords in Pascal:
And Downto If Or Then Array Else In Packed
To Begin End Label Procedure
Type Case File Mod
Program
Until Const For Nil Record Var Div Function
Not Repeat While Do Goto Of Set with
Introduction Segment 2: Declaration: • Define variables, constants etc. in the program • All of the entities going to be used in the
program must be defined • For that, data types and variables will be deeply
discussed in chapter 2
Introduction Segment 3: Main body of the program: • Main body of the program is written within
BEGIN-END pair • This is equivalent to a set of brackets • It is possible to have any no. of BEGIN-END
pairs in a single program • However, no. of BEGIN statements should
match no. of END statements
Introduction
Segment 3: Main body of the program: • Example:
PROGRAM firstprogram (OUTPUT); BEGIN WRITELN (‘Hello my friend’); END
Introduction Displaying output : WRITELN, WRITE command • To display several lines of text you need a
WRITELN statement for each line • Example PROGRAM lineOftext (OUTPUT);
BEGIN WRITELN (‘Hi there’); WRITELN (‘How are you today?’); WRITELN (‘Are you ready for Pascal’) END
Introduction Displaying output : WRITELN, WRITE command • Explanation: ▫ Each statement must be separated from the next
one with semicolon • This is the only way the compiler can recognize
the end of the statement • But, you may skip the semicolon in the last
statement of the program block
Introduction Displaying output : WRITELN, WRITE command • Output:
• The WRITELN statement displays a line of text followed by a new line
• Use WRITE statement, if you want to display two string on the same line
Hi there How are you today? Are you ready for Pascal
Introduction Displaying output : WRITELN, WRITE command • Code:
• Output:
Hi there How are you today? Are you ready for Pascal
PROGRAM Twolines (OUTPUT); BEGIN WRITE (‘Hi there’); WRITELN (‘How are you today?’); WRITELN (‘Are you ready for Pascal’) END
Introduction Displaying output : WRITELN, WRITE command • To display the content of the variable you need a
WRITELN or WRITE statement without using quotes
• Also WRITELN or WRITE can be used to display text and content of variables in the same statement by separating them with a coma
WRITELN (‘The Result is =’, r);
Introduction
Comments: • Comments are enclosed with braces or bracket
and a star in cases
• Can be included in anywhere in the program • Compiler ignores the comment • Comments are useful to explain the program to a
human reader
(*This is a comment*)
Introduction
Indentations: • It is customary to a line each BEGIN-END pair
along the same vertical line • Eg: five horizontal spaces should be kept from
the previous block when starting a new
PART A: PASCAL LANGUAGE
Learning Outcomes
Aims: • To provide an overview of some significant
features of the Pascal Language You will be able to: • Identify the data types in Pascal Language • Get an idea about declaring the variable and
constant • Learn how to format you numeric outputs
Data Types
• When writing program, it is necessary to store information in component form to manipulate them later
• For that, variables are used • Every variable should have a name and a type • Type mean the values that the variable can take • It helps to determine the amount of memory
space to store a variable
Data Types
• Variable should be declared in the declaration section
• There are no. of standard data types ▫ Integer ▫ Real ▫ Boolean ▫ Char
Data Types Integer: • This type allows to represent, store and process integer
numbers • Contains all the integer values in the range of;
-maxint,…., -1, 0,+1,….,+maxint
• The value of maxint is 32767 on minicomputer • 2147483647 in large computers • So, outcome of any arithmetic on integer values will be
correct only of they are in ± maxint • Or else, the answers will be unpredictable (overflow)
Data Types
Real: • Real numbers are numbers with decimal values ▫ eg: 14.65 meters, 9.2 seconds
• The limit of the real numbers which can be stored in a computer is very large compared to integers
Data Types
BOOLEAN: • Can only have two values ▫ True ▫ False
• Normal arithmetic operations cannot be performed on a boolean variable
Data Types Char: • Can hold any single given character at a time ▫ Eg: if x is char variable, it can hold only one
character at a time • Blank space also considered as a character • When assigning char variable, enclosed the
character with single quotes ▫ Eg: ‘A’
• Each char requires a one byte of memory
Variables
• Variable is a location in memory referenced by a variable name (identifier) where a data can be stored
• Can hold only one value at a time during the program execution
• Values can be changed during several executions
Variables
Variable Names: • A variable must be declared before using the
program • Variables are the identifiers • When declaring a variable, it consists with ▫ Sequence of letters and digits ▫ First character should be either a letter or
underscore ▫ Keywords cannot be used
Variables Variable Declaration: • The type and the name of a variable should be
initiate before using a program • It should be declared in the declaration part in
the program • Declaration part starts with the keyword VAR • Eg:
VAR gross_salary : REAL; n, i : INTEGER name : CHAR;
Variables Variable Declaration: • Eg1:
Following equation gives the total resistance R of three resisters r1, r2 and r3 connected in parallel
• The programmer should consider before writing the program for the above problem, ▫ Read the values for r1, r2 and r3 ▫ Calculate R ▫ Print the result
Variables Variable Declaration: • Eg1:
PROGRAM calc_of_resistance (INPUT, OUTPUT); VAR r1,r2,r3,R : REAL; BEGIN WRITE (‘Enter three resisters:’); READLN (‘r1,r2,r3’); R :=1/r1+1/r2+1/r3; R := 1/R; WRITELN (‘Total Resistance is’, R); END.
Line 1
Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10
Variables Variable Declaration : • Explanation:
Line 1: Program naming Line 2: variable naming and declaration Line 4 - 10 : solving the given problem Line 6: Reading the user inputs for r1, r2, and r3 Line 7: calculating the R with given r1, r2 and r3 Line 8: replacing the R with value of 1/R Line 9: printing the calculated value for R
Variables Variable Declaration : how practically run a program for Eg1 • Enter the given program • Save and compile it • Compiler show if any syntax errors available • Fix them until the program is free from syntax errors • When the compilation is successful you are ready to run
the program • The computer waits until you put three values for r1, r2
and r3 when the program runs • Once entered values, the total resistance will be
displayed Enter three resisters: 2 3 4
Total Resistance is : 9.2307692308E-01
Variables
Reading from the keyboard: READLN, READ: • READLN and READ commands in Pascal program
are used to read values given by user to produce results
• READ: is used to read a value of one variable at a time ▫ Eg: READ (variable) / READ (r1);
• READLN: is used to read the value of one or more variables ▫ Eg: READLN (variable_list) / READLN (r1,r2,r3);
Variables
Formatting Output: • You can format your output in a fixed notation • Eg1:
• The format 8:2 determines a field width of 8
positions including 2 decimal places
WRITELN (‘Total Resistance is’, R:8:2);
Total Resistance is : *******0.92
Variables Constants : • A constant remains unchanged throughout the
execution of the program • It is often useful to give a symbolic name
(identifier) to a constant • This can then be used throughout the program
whenever the value of the constant is required ▫ Eg: if the program replace 3.14159 with pi, it
would be much easier to read
Variables
Constants : • Keyword CONST is used to declare constants in
the declaration segment of the program ▫ Syntax:
▫ Example:
CONST identifier = constant;
CONST pi = 22/7;
PART A: PASCAL LANGUAGE
Learning Outcomes
Aims: • To provide an overview of some important
features of the Pascal Language You will be able to: • Learn various operators and their precedence in
Pascal
Types of Operators
• The operators define how the variables and constants in and expression will be manipulated
• Three operators allowed in Pascal; ▫ Arithmetic Operators ▫ Relational Operators ▫ Logical Operators
Types of Operators
Expression: • An Expression is a combination of variables,
constants and operators written according to the syntax of the language
• Eg: ▫ a + b ▫ a + 200*w ▫ total + x/3
Types of Operators Arithmetic Operators: • Basic arithmetic operations
• + : addition • - : subtraction • * : multiplication • / : division
• These operators act as usual operators • The entities on which the operators are applied are
called as Operands • Eg: o 5+3 o Here, 5 and 3 are operands and + is the operator
Types of Operators
Arithmetic Operators: • Additionally, ▫ DIV and MOD are used as operators
• Eg: ▫ For integer division, DIV is used [a DIV b] Divide a by b and give the divisor 10 DIV 5 = 2
▫ MOD is used to get the remainder of integer division [a MOD b] Divide a by b and give the remainder 10 MOD 5 = 0
Types of Operators Relational Operators: • A relational operator is used to make
comparisons between two expressions • Allowed relational operators in Pascal;
Operator Usage
= Equal to
< Less than
> Grater than
Not equal to
= Grater than or equal to
Types of Operators Relational Operators: • Each one of the operator compares its left hand
side operand with its right hand side operand • Operands can be variables or expressions • The whole expression involving the relational
operator then evaluates to an integer
Types of Operators
Logical Operators: • Logical operators let you combine two or more
relational expressions into a single expression which evaluates to either true or false
• Eg for Pascal logical operators; ▫ NOT ▫ AND ▫ OR
Types of Operators
Logical Operators: AND Operator
Expression 1 Expression 2 Result
True True True
True False False
False True False
False False False
Types of Operators Logical Operators: OR Operator
Logical Operators: NOT Operator
Expression 1 Expression 2 Result
True True True
True False True
False True True
False False False
Expression Result
True False
False True
Operator Precedence
• Operators are used in a program according to their priority order (precedence) as follows;
Operation Symbol Precedence
Multiplication *, /, DIV, MOD 1
Addition +, - 2
Relation =, , , =
3
Logical NOT 4
AND 5
OR 6
Operator Precedence
• Brackets always have higher precedence than all the above operators
• If bracket used; ▫ The content inside the innermost pair of brackets
will be evaluated first • When several operations having same
precedence; ▫ Evaluation will be done in left to right
Character operations
• In addition to the comparison statements, following are used as operators ▫ ORD ▫ SUCC ▫ PRED ▫ CHR
Character operations
ORD: • ORD function has one argument which should
be a character or a character variable • It will return an integer number corresponding
to the internal representation • If ASCII is used, then the ORD function will
return the corresponding ASCII value
Character operations
CHR: • CHR function takes an integer as an input
argument and returns the corresponding character
• Opposite of the ORD function SUCC: • SUCC function takes a single character or a
character variable as an argument • Returns the next character
Character operations
PRED: • PRED function takes a single character or a
character variable as the input argument • Returns the previous character
PART A: PASCAL LANGUAGE
Learning Outcomes
Aims: • To provide an overview of control structures in
Pascal Language You will be able to: • Use the major control structures such as
repetition loops conditional statements in Pascal Language
Control Structures
• For practical use of computers, selective and repetitive expressions are necessary
Conditional statements: • There are two main types of statements in Pascal
for selective operations ▫ IF-THEN ▫ CASE
Conditional Statements IF-THEN: • Use when we have to select a set of actions from
two sets depending on a condition
• However, the ELSE is optional • IF-THEN and IF-THEN-ELSE statements are
treated as one compound statement • So, a semicolon is used only at the end
IF condition THEN statement ELSE statement;
Conditional Statements IF-THEN: • The condition with IF must produce a boolean result • The boolean expression is evaluated ▫ If it is true, The statements following THEN will be executed
▫ Otherwise, The statements following ELSE will be executed
• If there are more than one statement with IF-THEN or ELSE statements, they are grouped with BEGIN-END
Conditional Statements IF-THEN: • Example:
• ELSE-IF statements are used to make multi-way decision based on several conditions
• This is done by cascading several comparisons • As soon as one of a else-if gives a true result,
corresponding statements will be executed and no further comparisons will be performed
IF A > B THEN max := A ELSE max := B;
Conditional Statements ELSE-IF: • Example:
IF (result >= 75) THEN WRITELN (‘Passed: Grade A’) ELSE IF (result >= 60) THEN WRITELN (‘Passed: Grade B’) ELSE IF (result >= 45) THEN WRITELN (‘Passed: Grade C’) ELSE WRITELN (‘Failed’);
Conditional Statements
Nested IF Statements: • IF statement inside the other IF statements are
known as Nested IF Statement • If there is a problem that involved with more
than two alternatives courses of action can be coded using nested if statement
• In the nested if, the else statement is always associated with the nearest if statement
Conditional Statements Nested IF Statements: • Example:
IF i > 10 THEN BEGIN WRITELN (‘i is more than 10’); IF j > 3 THEN WRITELN (‘j is more than 3’); ELSE WRITELN (‘j is less than or equal to 3’); END
ELSE WRITELN (‘i is less than equal to 10’);
Conditional Statements
IF Statements: Example: • Write a program in Pascal to read a set of
numbers and to find the maximum value. The program should be terminated when a-1 is read
• Refer page 22
Conditional Statements
CASE Statements: • CASE statement allows the choice of one out of
several sets of action • The selection is done by matching the value of
the selector with a case label attached to each statement
Conditional Statements
CASE Statements:
CASE selector OF case label1: statement case label2: statement . . case labeln: statement ELSE statement END;
Conditional Statements CASE Statements: • Depending on the selection value, the case
statement will pick the appropriate action • If the SELECTOR has a value for which no
action has been described, then the ELSE statement is executed
CASE month OF 1,3,5,7,8,10,12: no. of days := 31; 2 : no. of days := 28; 4,6,9,11 : no. of days := 30; END;
Conditional Statements
CASE Statements: • If there is value range then the CASE statement
are written as follow;
CASE mark OF 0..39 : grade := ‘F’; 40..59 : grade := ‘C’; 60..79 : grade := ‘B’; 80..100: grade := ‘A’; END;
Conditional Statements
CASE Statements: Example: • Write a program to read a number between 1-7.
if the number is 1 then print “Monday”. If it is 2 then print “Tuesday” and so on.
CASE Statements: Example: PROGRAM eg_case(INPUT, OUTPUT); VAR number : INTEGER; BEGIN WRITELN(‘Enter a number within 1-7:’); READLN(number); CASE number OF 1 : WRITELN(‘Monday’); 2 : WRITELN(‘Tuesday’); 3 : WRITELN(‘Wednesday’); 4 : WRITELN(‘Thursday’); 5 : WRITELN(‘Friday’); 6 : WRITELN(‘Saturday’); 7 : WRITELN(‘Sunday’); ELSE WRITELN(‘Invalid day of the week!!!’); END; END.
Repetition
• There are three main types of statements for repeating certain instructions ▫ REPEAT UNTIL Loop ▫ WHILE Loop ▫ FOR Loop
Repetition REPEAT-UNTIL Loop: • This will repeat everything that is inside this
loop, as the condition given with the until statement is false
• When the statement becomes true, the loop is completed
• Any statements after UNTIL are then executed • The expression supplied with the UNTIL
statement must give a boolean value
Repetition REPEAT-UNTIL Loop: • Example:
REPEAT statement(s) UNTIL boolean_expression;
x:=1; REPEAT WRITELN(x); x:= x +1; UNTIL x > 10;
Repetition
REPEAT-UNTIL Loop: Example: • Write a program to read a set of integer numbers
and to calculate the total and the average. The end of the list of numbers is denoted by -1.
REPEAT-UNTIL Loop: Example PROGRAM eg_repeatuntil(INPUT, OUTPUT); CONST endmark = -1; VAR value, total, count, avg : INTEGER; BEGIN total := 0; count := 0; avg := 0; REPEAT WRITELN(‘Enter a number:’); READLN(value); count := count + 1; total := total + value; avg := total DIV count; WRITELN(‘The total is: ’, total, ‘and the average is: ’, avg); UNTIL value = endmark; END.
Repetition REPEAT-UNTIL Loop: Example: • This program will add the endmark (-1) to the
output.
• So this should be corrected as follows
REPEAT-UNTIL Loop: Example PROGRAM eg_repeatuntil(INPUT, OUTPUT); CONST endmark = -1; VAR value, total, count, avg : INTEGER; BEGIN total := 0; count := 0; avg := 0; WRITELN(‘Enter a number:’); READLN(value); REPEAT count := count + 1; total := total + value; avg := total DIV count; WRITELN(‘The total is: ’, total, ‘and the average is: ’, avg); WRITELN(‘Enter a number:’); READLN(value); UNTIL value = endmark; END.
Repetition REPEAT-UNTIL Loop: Example: • This program will do the answers correctly as
follows;
Repetition
WHILE Loop: • WHILE loop checks the condition at the
beginning • So the constants within the loop may or may not
be executed • WHILE loop will be executed as long as the
condition is true • If there are more than one statement with the
WHILE statement, they can be grouped with BEGIN-END
Repetition WHILE Loop: • Example:
WHILE boolean_expression DO statement;
x:=1; WHILE x
REPEAT-UNTIL Loop: Example using WHILE PROGRAM eg_while(INPUT, OUTPUT); CONST endmark = -1; VAR value, total, count, avg : INTEGER; BEGIN total := 0; count := 0; avg := 0; WRITELN(‘Enter a number:’); READLN(value); WHILE value endmark DO BEGIN count := count + 1; total := total + value; avg := total DIV count; WRITELN(‘The total is: ’, total, ‘and the average is: ’, avg); WRITELN(‘Enter a number:’); READLN(value); END; END.
Repetition FOR Loop: • Used in repeating a loop for several times
• a, b and c could be any data type for which it is possible to go from b to c in a finite no. of increments ▫ a,b and c are real variables ▫ Most cases they will be integers
FOR a := b TO c DO
Repetition FOR Loop:
• In this loop, the values are decreased from b to c • If there are more than one statement with the
FOR statement, they are grouped with BEGIN-END
FOR a:=b DOWNTO c DO
Repetition FOR Loop:
• Example:
FOR control_variable:= initial TO/ DOWNTO DO statement;
FOR x:= 1 TO 10 DO WRITELN (x);
FOR x:= 10 DOWNTO 1 DO WRITELN (x);
REPEAT-UNTIL Loop: Example using FOR LOOP to find the total and average of
5 numbers PROGRAM eg_for(INPUT, OUTPUT); VAR value, total, count, avg : INTEGER; i : INTEGER; BEGIN total := 0; count := 0; avg := 0; FOR i := 1 TO 5 DO BEGIN WRITELN(‘Enter a number:’); READLN(value); count := count + 1; total := total + value; avg := total DIV count; WRITELN(‘The total is: ’, total, ‘and the average is: ’, avg); END; END.