Anda di halaman 1dari 45

What will you learn in this module (Semester 1)

You will learn

The C programming language Structured programming programming techniques and proper

What is a Computer?
Device capable of performing computations and making logical decisions Computers process data under the control of sets of instructions called computer programs

Various devices comprising a computer Keyboard, screen, mouse, disks, memory, CD-ROM, and processing units

Programs that run on a computer

Introduction to Programming
A program is a set of step by step instructions which a computer follows to process data into useful information. Eg. To calculate the total marks of a student: Obtain Exam marks Obtain Coursework marks Total marks = Exam Marks + coursework marks Display Total Marks

Define the problem

Given a computational problem, we must decide whether to
Develop or buy software? If we decide to develop our own software, we follow a software development lifecycle (SDLC)
Development process Analysis Design Implementation Testing Deployment

SDLC (1)
Decide what the project is supposed to do Do not think about how the program will accomplish tasks At the end of this process, we get a requirements document that
Describes what program will do once completed

Plan how to implement the system Discover structures that underlie problem to be solved

SDLC (2)
Write and compile the code Code implements classes and methods discovered in the design phase At the end of the process we will obtain the completed program

Run tests to verify the program works correctly

Users install program Users use program for its intended purpose

To solve a computational problem

You need:
Clear, specific statement of goal

Expected output
Expected input

You must use Algorithms pseudocode flowcharts


What are algorithms used for?

To solve computational problems
What is a computational problem?
Mathematical object representing a question that computers might want to solve Specifies an input-output relationship in general terms
What does the input look like? What should the output be for each input?

Input: An integer value N Output: Is the number prime? Input: A list of names of people Output: The same list sorted alphabetically

We seek algorithms which are correct and efficient.

Algorithm Correctness
For any algorithm, we must prove that it always returns the desired output for all legal instances of the problem.
For sorting, this means even if
1. the input is already sorted, or 2. it contains repeated elements.

Properties of algorithms

Correctness Composed of a series of concrete steps No ambiguity as to next step Composed of a finite number of steps Will terminate

Examples of algorithms
shampoo instructions
Lather. Rinse. Repeat. Does not terminate

No: most recipes

Stir-fry until crisp-tender. Next step ambiguous

If not an algorithm, then what?
Procedure Heuristic

Examples of algorithms(Continued) long division Yes:

14.5 4 58 4 18 16 20 20 0

Designing the program (1)

Pseudo code method
Logical Steps written in English Obtain Exam marks Obtain Coursework marks Total marks = Exam Marks + coursework marks Display Total Marks


Designing the program (2)


Flow Chart-Logical steps represented by standard symbols

Input Exam Marks Input Course work marks

Compute Total Marks =Exam Marks + Course work marks

Display Total marks



Designing the program(3)

Does it solve our problem? no yes - select another design - return to the analysis of the problem - move on

Choose a language Write the code


Flowcharts and Pseudocodes

Flowcharts were the first design tool to be widely used, but unfortunately they do not reflect some of the concepts of structured programming very well. Pseudocode, on the other hand, is a newer tool and has features that make it more reflective of the structured concepts. The drawback is that the narrative presentation is not as easy to understand and/or follow.

Rules for Pseudocode

Write only one statement per line Capitalize initial keyword Indent to show hierarchy End multiline structures Keep statements language independent

One Statement Per Line

Each statement in pseudocode should express just one action for the computer. If the task list is properly drawn, then in most cases each task will correspond to one line of pseudocode.
Task List
Read name, hours worked, rate of pay Perform calculations gross = hours worked * rate of pay Write name, hours worked, gross

READ name, hoursWorked, payRate gross = hoursWorked * payRate WRITE name, hoursWorked, gross

Capitalize Initial Keyword

In the example below note the words: READ and WRITE. These are just a few of the keywords to use, others include:

READ name, hoursWorked, payRate gross = hoursWorked * payRate WRITE name, hoursWorked, gross

Indent to Show Hierarchy

Each design structure uses a particular indentation pattern, called the control structure
Keep statements in sequence all starting in the same column

Indent statements that fall inside selection structure, but not the keywords that form the selection

Indent statements that fall inside the loop but not keywords that form the loop
READ name, grossPay, taxes IF taxes > 0 net = grossPay taxes ELSE net = grossPay ENDIF WRITE name, net

End Multiline Structures

READ name, grossPay, taxes IF taxes > 0 net = grossPay taxes ELSE net = grossPay ENDIF WRITE name, net

See the IF/ELSE/ENDIF as constructed above, the ENDIF is in line with the IF. The same applies for WHILE/ENDWHILE etc

Language Independence
Resist the urge to write in whatever language you are most comfortable with, in the long run you will save time. Remember you are describing a logic plan to develop a program, you are not programming!

The Selection Structure

yes amount < 100 no

interestRate = .06

interestRate = .10

IF amount < 100 interestRate = .06


ELSE Interest Rate = .10 ENDIF

The Looping Structure

In flowcharting one of the more confusing things is to separate selection from looping. This is because each structure use the diamond as their control symbol. In pseudocode we avoid this by using specific keywords to designate looping WHILE/ENDWHILE REPEAT/UNTIL


count = 0 WHILE count < 10 ADD 1 to count WRITE count ENDWHILE WRITE The End

count = 0

count <10 Write The End

Mainline count = 0 WHILE count < 10 DO Process ENDWHILE WRITE The End Process ADD 1 to count WRITE count


add 1 to count

write count


Advantages & Disadvantages

Flowchart Advantages:
Standardized Visual

Pseudocode Advantages
Easily modified Implements structured concepts Done easily on Word Processor

Flowchart Disadvantages: Pseudocode Disadvantages:

Hard to modify Structured design elements not implemented Special software required Not visual No accepted standard, varies from company to company

Example -Calculating Income Tax(1)

Problem: Calculate Tax Payable by a person

1. Identify the output

The amount to be paid as Income TAX

2. Identify the list of Inputs

Salary Personal Deduction No. of children Child deduction Loan Interests Insurance Premium

Example-Calculating Income Tax(2)

Algorithm: Input salary Input personal deductions Input no. of children Input child deductions Input loans interests Input Insurance premium Calculate Emolument relief = 0.15 x salary Calculate Total Deductions = personal deductions + Emolument relief + (No.of children x child deductions) + Loan Interest + Insurance premium 28

Example-Calculating Income Tax(3)

Calculate Taxable Income = Salary - Total Deductions IF Taxable Income < 0 Tax payable =0 ELSE IF Taxable income < 20000 Tax payable = 0.15 x Taxable income ELSE Tax Payable = (0.15 x 20000) + 0.25 (x Taxable Income 20000) ENDIF Display Tax Payable

Programming Languages (1)

Over 200 languages Language depends upon task C C++ JAVA Python Scheme Prolog .many more


Programming Languages (2)

Three types of programming languages
1. Machine languages
Strings of numbers giving machine specific instructions Example:
+1300042774 +1400593419 +1200274027

2. Assembly languages
English-like abbreviations representing elementary computer operations (translated via assemblers) Example:

Programming Languages (3)

3. High-level languages
Codes similar to everyday English Use mathematical notations (translated via compilers) Example:
grossPay = basePay + overTimePay


Coding programs
A program is usually written in a high (or mid) level programming language. Well use C as our programming Language. A program written in C has to be entered in the computer using an editor. A C program has to be translated into machine language so that the computer can understand it. The process of translating a program from high-level language to machine-language is known as compiling. For the Compiler, well use the gnu C Compiler.


Writing C Programs(1)
A programmer uses a text editor to create or modify files containing C code. Code is also known as source code. A file containing source code is called a source file. After a C source file has been created, the programmer must invoke the C compiler before the program can be executed (run).

Writing C Programs(2) You need an editor to write your program

We will use textpad or notepad

You need a compiler to compile your program

We will use gcc (gnu C compiler), an opensource program, which normally runs in linux/unix environment But we will use the Minimalist gnu for Windows (MinGW)

A Simple C Program
/* Filename: hello.c Author: Brian Kernighan & Dennis Ritchie Date written: ?/?/1978 Description: This program prints the greeting Hello, World! */ #include <stdio.h> int main ( void ) { printf ( Hello, World!\n ) ; return 0 ; }

Anatomy of a C Program
program header comment preprocessor directives (if any) int main ( void ) { statement(s) return 0 ; }

Program Header Comment

A comment is descriptive text used to help a reader of the program understand its content. All comments must begin with the characters /* and end with the characters */ These are called comment delimiters The program header comment always comes first. Look at the class web page for the required contents of our header comment.

Preprocessor Directives
Lines that begin with a # in column 1 are called preprocessor directives (commands). Example: the #include <stdio.h> directive causes the preprocessor to include a copy of the standard input/output header file stdio.h at this point in the code. This header file was included because it contains information about the printf ( ) function that is used in this program.

When we write our programs, there are libraries of functions to help us so that we do not have to write the same code over and over. Some of the functions are very complex and long. Not having to write them ourselves make it easier and faster to write programs. Using the functions will also make it easier to learn to program!

int main ( void )

Every program must have a function called main. This is where program execution begins. main() is placed in the source code file as the first function for readability. There must be a function with this name or gcc can not successful compile and link your program. The reserved word int indicates that main() returns an integer value. The parentheses following the reserved word main indicate that it is a function. The reserved word void means nothing is there.

The Function Body

A left brace (curly bracket) -- { -- begins the body of every function. A corresponding right brace -- } -- ends the function body. The style is to place these braces on separate lines in column 1 and to indent the entire function body 3 to 5 spaces.

printf (Hello, World!\n) ;

This line is a C statement. It is a call to the function printf ( ) with a single argument (parameter), namely the string Hello, World!\n. Even though a string may contain many characters, the string itself should be thought of as a single quantity. Notice that this line ends with a semicolon. All statements in C end with a semicolon.

return 0 ;
Because function main() returns an integer value, there must be a statement that indicates what this value is. The statement

return 0 ;
indicates that main() returns a value of zero to the operating system. A value of 0 indicates that the program successfully terminated execution. Do not worry about this concept now. Just remember to use the statement.

Running the programs using MinGW gcc

First write your program using textpad and save as <progname.c> e.g hello.c Choose MinGW shell cd / cd d:/ [the actual path] gcc o hello.c hello.out hello.out