2 - Structure of Programming

Preview:

DESCRIPTION

computer programming

Citation preview

Chapter 2

Basic Structure of Programming

Learning Objectives:

◊ Understand and implement the basic structure of computer programming.

◊ Write a computer program using C programming language.

◊ Convert algorithm into computer program.

CHAPTER 2

Program

Development

Environment

Basic Syntax

of Programming

Variable

Declarations

Data Types

Involves translating high-level language (programming language such as C,C++, Java, PHP,Visual Basic, C#,etc.)

WHY? Because computers do NOT

understand high level language!

Translated to

00011101 01010101 11011111

Typical program development environment consist of six phases to be executed.

Edit

Preprocess

Compile

Link

Load

Execute

Creating a Program Phase 1:

Programmer types or creates program in an editor. Makes corrections if necessary. Saves or stores program on disk such as C:\ or A:\ etc.

Editor? Editor or text editor is a type of program used for editing plain text files.

Turbo C editor (free)

Preprocessing Phase 2:

Programmer gives command to compile the program. Preprocessor program executes automatically and process the program code. The prepocessor obeys commands from preprocessor directives. Preprocessing occurs before a program is compiled.

Compiling a Program Phase 3:

When compiled, compiler translates program into machine language code and creates object code. The object code will be stored in disk.

Dialog box in Turbo C editor

shows compiling process.

Programmer click

Compile

Compiling a Program Phase 3:

The object code will be only created if the translation process into machine code is successful. Otherwise, if unsuccessful, error messages will be displayed in the compiling dialogue box. Programmer must fix all the errors before proceed to the next phase. The process of correcting errors is called debugging.

Linking Phase 4:

A linker links the object code with the libraries. A linker will creates an executable file and stores it on disk if the program compiles and links correctly. A linker might name the executable file with .exe file extension depending on type of programming language used.

Loading Phase 5:

Before a program can be executed, the program must first be placed in memory. Loader takes the stored program from disk and puts in memory. Additional components from shared libraries that support the program are also loaded.

Executing Phase 6:

CPU takes each instructions and executes it. Results or output will be displayed.

Terms Description

Machine language Binary number codes understood by a specific CPU.

High-level language

Machine-independent programming language that combines algebraic expressions and English symbols.

Source file File containing a program written in a high-level language; the input for compiler

Compiler Software that translates a high-level language program into machine language.

Linker Software that combines object files and create an executable machine language program.

Common Programming Errors

Error (bugs)

Syntax Errors

Run-time

Errors

Logic Errors

Common Programming Errors

Syntax Error 1

Error occurred during compilation normally due to syntax problem

Misplaced else.

Declaration sytanx error

Undefined symbol ‘_main’ in module. Statement missing in function main()

Common Programming Errors

Logic Error 2

Error occurred due to inappropriate output. Programming mistake. Not detected during compilation.

Common Programming Errors

Run-time Error 3

Error occurred due to wrong user input. User’s mistake. System would either display alert message or hang.

Computer Program

HOW

WHAT

UNDERSTAND THE SYNTAX AND FORMAT

STRUCTURE OF PROGRAMMING

C Basic Structure

C preprocessor directive

main function

{

//Identifiers/Variables

//C statements

}

Program block

components:

1. Preprocessor directive

2. Program body

3. Main function

4. Identifiers/Variable 5. C statements

6. Comment

PROGRAM BLOCK

PREPROCESSOR

DIRECTIVE

MAIN FUNCTION

IDENTIFIERS/

VARIABLE

C

STATEMENT

COMMENT

PROGRAM

BODY

PICK AND MATCH

Preprocessor Directive

Utility program which link files from compiler library to the program code. Must be included in the first line of a computer program. Must be started with the symbol #, otherwise syntax errors will be occurred. Two types of common preprocessor directive: #include and #define.

Preprocessor Directive

#include <header file> or #include “user defined files”

Format:

Example

#include <stdio.h>

#include <conio.h>

#include “jam.h”

Preprocessor Directive

Example:

#include <stdio.h>

A directive to the C preprocessor Lines beginning with # are processed by the preprocessor before the program is compiled. The above code line tells the preprocessor to include the contents of stdio.h ( standard input/output header)

Called from standard library

Standard Library

Consists of built-in functions

Functions contains standard instructions

Function will be called and linked to program via header file

List of header file and its function

Header file List of functions

stdio.h printf(), scanf(),fflush(), dll

conio.h clrscr(),putch().getc().dll

math.h sqrt(),pow(), log(),dll

User-defined Library

List of header file and its function

Contain functions defined by programmer.

Developed by expert programmers.

Header file List of user-defined

functions

utama.h cetak(),baca(),papar(),dll

kira.h plus(),minus(), divide(),dll

Preprocessor Directive

#define “file name” or #define constant_name constant_value

Format:

Example

#define MAX 100

#define “jam.h”

Program Body The part in which the program code will be started to execute. Consists of main function, C statements and identifiers. Use { to start the program code and } to end the program code.

main function { //identifiers //C statements }

Format:

Main function

int main( ) { return 0; }

Main function

void main( ) { …………..}

main( ) { return 0; }

Write the most basic structures of

C programming.

#include <stdio.h>

void main()

{

}

C Statement

Instructions to be executed by computers Every statements must be ended with semicolon

Types

Declaration

statement

Input/Output

statement

Compound

statement

Control

statement

Function

statement

Comment

Statement in program code that will be ignored by compiler Differs in terms of colour : grey

Function

To document

a program

As a future

references To provide additional

information

To increase

program readability

Standard/special word in standard library Contain special meaning understood by compiler

Rules Case –sensitive

Must be written in

small case

Cannot be used as identifier

or variables

Reserved Word

Reserved Word

int The acronym for integer

void Refer to the function that will not

return any value

case default switch break

for continue float double

return while if do int

Example:

Identifier

Representing particular name in programming Store values to be used in programming Refers to the storage in computer

Standard identifier

User-defined identifier Type

Special built-in words Referred as function name which will called from C library

Standard identifier

printf() scanf() puts() gets()

Identifier

Name given to the declaration of data to be used in program Refer to the storage name Store data values/result/output

User-defined identifier

Constant Variable Type

Identifier

User-defined identifier

Identifiers name can only consists of name, number and underscore Identifiers name cannot be started with numbers Symbol cannot be used in identifier name Cannot contains spaces between two identifiers name Identifiers name should be unique Identifiers is not case sensitive

RULES

Identifier

UThM DIT1064 Seven_eleven integer

Valid identifiers

8Century BIT 1033 Two*four

‘Sixsense’ void

Invalid identifiers

Identifier

WHY?

WHY?

WHY? WHY?

WHY?

Name which used to store data value

Refer to name of one cell in compu

storage

Contants value is fixed

Constant

Identifier

How to give name to a

constant value? Follow identifiers rules

const data_type const_name = const_value;

Declaration format:

const float pi = 3.142; Reserved word

1

Constant

Value

#define const_name const_value;

Declaration format:

#define pi 3.142; Reserved word

2

#define minimum 0;

#define MAX 100;

const int counter = 100;

const char alphabet = ‘J’; const float value = 4.5;

Example of constant:

data_type variable_name;

Name which used to store data/input value

Refer to the name of one cell in computer storage

Variable’s value can be modified/changed during execution

Variable

Declaration Format:

Identifier

Declaration Example

int number; float weight; char alphabet;

Declaration of a variable number of integer data type.

Declaration of a variable weight of floating point data type.

Declaration of a variable alphabet of character data type.

Variable/constant declaration example

//Variable and constant declration

#include <stdio.h>

int number;

float weight;

void main()

{

const float pi =3.142;

int bilangan;

float berat;

char abjad;

}

Constant declaration

Variable declaration

Variable declaration

Variable and constant declaration example:

//Variable and constant declaration

#include <stdio.h>

const float pi=3.142;

void main()

{

int bilangan, bil, bilang;

float berat, kg;

char A;

}

Method to give/assign value to variable

Initialization

Interactive

Input/enter data through

input devices Use input statement (scanf/gets)

Assign value to variable during

declaration. Assign value to variable. Use assign symbol, “=“

Assigning value to variables

#include <stdio.h>

void main()

{

int number = 10;

float weight;

weight = 60.00;

printf(“Enter the value of number :”); scanf(“%d”,&number);

number = 50.00;

}

Initialize a variable

Interactive

Initialize a variable

Represents types of data can be stored in computer. Types of data to be stored and used in programming should be informed to the compiler/system

Types

Integer

Floating point

Character

Data Types

Data Types Represents any round number with +/- values. Divided into short and long integer. Reserved word for integer – int Valid until 5 places of integer number.

Integer

Example: age is used to represent the age of students between 18 and 25 years old. The declaration for the variable is as follow:

int age;

Data Types

Represents any floating point numbers +/- Reserved word– double /float

Floating number

Example: height is used to represent the student’s height between 150 cm and 180 cm. The declaration for the variable is as follow:

float height;

Data Types

Represents character data. Reserved word – char

Character

Example: gender is used to represent the gender of a student. The declaration for the variable is as follow:

char gender;

Determine whether the following identifiers is valid or invalid. Give reason for invalid cases.

1) Parit Raja

2) 20thCentury

3) int

4) INTEGER

5) _BMW2003

6) Reservedword

7) BIT1033

8) markah_pelajar

9) jam*kredit

10) printf

Write a suitable variable declaration for each of the following statement:

i. Salary of an employee

ii. Student’s mark for programming subject

iii. ATM pin number

iv. Phone number

v. Price of one item

vi. Bus seat number

vii. Student name

Given the value of x is 10 and a is 12,

find the result of the following equation:

y = 2x + a - 6

Based on the following problem, determine the appropriate

variables can be declared:

Mrs Sue needs to determine her students grade for

programming subject based on the mark scored during

final examination. The ‘A’ grade will be given if the mark

scored is between 85 to 100. If a student has scored 90

marks, what is the grade should Mrs Sue gives to the student?

Based on the following problem, determine the appropriate

variables can be declared:

Based on the following problem, determine the appropriate

variables can be declared:

A box has height, width and length.

Calculate the volume of a box.

Uncle Degawan wants to buy 5 tins of paint from

Cinda’s shop. The price of each tin of the paint is RM 15.60. Calculate the price which Uncle Degawan have

to pay for all the tin of paints he bought.

Based on the following problem, determine the appropriate

variables can be declared:

Recommended