Chap 2 structure of c programming dti2143

60
Chapter 2 Basic Structure of Programming Faculty of Mechanical and Manufacturing Prepared by Alish Ahmad Al- shahab [email protected] m

Transcript of Chap 2 structure of c programming dti2143

Page 1: Chap 2  structure of c programming dti2143

Chapter 2Basic Structure of Programming

Faculty of Mechanical and Manufacturing

Prepared by Alish Ahmad [email protected]

Page 2: Chap 2  structure of c programming dti2143

Learning Objectives:

◊ Understand and implement the basic structure of computer programming.

◊ Write a computer program using C programming language.

◊ Convert algorithm into computer program.

Page 3: Chap 2  structure of c programming dti2143

CHAPTER 2

Program Development Environment

Basic Syntax of Programming

Variable Declarations

Data Types

Page 4: Chap 2  structure of c programming dti2143

Involves translating high-level language (programminglanguage such as C,C++, Visual Basic, C#)

Because computers do NOT understand high level language!

Translated to

000111010101010111011111

Page 5: Chap 2  structure of c programming dti2143

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

Edit/Write

Preprocess

Compile

Link

Load

Execute

Page 6: Chap 2  structure of c programming dti2143

1. Creating a Program

o Types or creates program in an editor

o Makes corrections if necessary

o Saves or stores program on disk such as C:\

or A:\ etc.

Editor or text editor is a type of program used for editing plain text files. E.g dev/turbo

Page 7: Chap 2  structure of c programming dti2143

Turbo C

editor(free)

Page 8: Chap 2  structure of c programming dti2143

DEV C++

(free)

Page 9: Chap 2  structure of c programming dti2143

2. Preprocessing

Write a command to compile the program.

Preprocessor program executes automaticallyand process the program code.

The preprocessor obeys commands from preprocessor directives.

Preprocessing occurs before a program is compiled.

Page 10: Chap 2  structure of c programming dti2143

3.Compiling a Program

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 proccess.

Select

Compile

Page 11: Chap 2  structure of c programming dti2143

3.Compiling a Program

The object code will be only created if the translation process into machine code is successful.

If unsuccessful, error messages will be displayedin the compiling dialogue box.

fix all the errors before proceed to the next phase.

The process of correcting errors is called debugging.

Page 12: Chap 2  structure of c programming dti2143

4.Linking

A linker links the object code with the libraries.

A linker will creates an executable file and stores it on diskif the program compiles and links correctly.

A linker might name the executable file with .exe file extension depending on type of programming languageused.

Page 13: Chap 2  structure of c programming dti2143

5. Loading

Before a program can be executed, the program must firstbe 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.

Page 14: Chap 2  structure of c programming dti2143

6. Executing

CPU takes each instructions and executes it.

Results or output will be displayed.

Page 15: Chap 2  structure of c programming dti2143

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.

Page 16: Chap 2  structure of c programming dti2143

Error(bugs)

Syntax ErrorsRun-time

ErrorsLogic Errors

Common Programming Errors

Page 17: Chap 2  structure of c programming dti2143

Syntax Error1Error occurred during compilationnormally due to syntax problem

Misplaced else. Declaration syntax error Undefined symbol ‘_main’ in module. Statement missing in function main()

Example:

Common Programming Errors

Page 18: Chap 2  structure of c programming dti2143

Logic Error2

Error occurred due to inappropriate

output.Programming mistake.Not detected during compilation.

Common Programming Errors

Page 19: Chap 2  structure of c programming dti2143

Which ONE?number pin or pin number?

Common Programming Errors

Page 20: Chap 2  structure of c programming dti2143

Run-time Error3

Error occurred due to wrong user input.

User’s mistake.

System would either display alert message or hang.

Common Programming Errors

Page 21: Chap 2  structure of c programming dti2143

C preprocessor directive

main function{ //Identifiers/Variables //C statements}

Program block components:

1. Preprocessor directive

2. Program body3. Main function4. Identifiers/

Variable5. C statements6. Comment

C Basic Structure

Page 22: Chap 2  structure of c programming dti2143

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 errorswill be occurred.

Two types of common preprocessor directive: #include and#define.

Preprocessor Directive

Page 23: Chap 2  structure of c programming dti2143

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

Format:

Example

#include <stdio.h>#include <conio.h>#include “jam.h”

Preprocessor Directive

Page 24: Chap 2  structure of c programming dti2143

Example:

#include <stdio.h>

A directive to the C preprocessor Lines beginning with # are processed by the

preprocessorbefore the program is compiled.

The above code line tells the preprocessor to include thecontents of stdio.h ( standard input/output header)

Called from standard library

Preprocessor Directive

Page 25: Chap 2  structure of c programming dti2143

Header file List of functionsstdio.h printf(), scanf(),fflush(),

dll

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

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

Standard Library

Consists of built-in functions

Functions contains standard instructions

Function will be called and linked to program via header file

Page 26: Chap 2  structure of c programming dti2143

User-definedLibrary

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

Page 27: Chap 2  structure of c programming dti2143

#define “file name” or #define constant_name constant_value

Format:

Example

#define MAX 100

Preprocessor Directive

Page 28: Chap 2  structure of c programming dti2143

The part in which the program code will be started toexecute.

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 :

Program body

Page 29: Chap 2  structure of c programming dti2143

int main( ){ return 0;} Main function

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

main( ){ return 0;}

Main Function

Page 30: Chap 2  structure of c programming dti2143

Write the most basic structures of C programming.

#include <stdio.h>void main(){}

Page 31: Chap 2  structure of c programming dti2143

Instructions to be executed by computersEvery statements must be ended with semicolon

Types

Declarationstatement

Input/Output statement

Compound statement

Control statement

Functionstatement

C Statement

Page 32: Chap 2  structure of c programming dti2143

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

Function

To documenta program

As a futurereferen

ces

To provide additional

information

To increaseprogram

readability

Comment

Page 33: Chap 2  structure of c programming dti2143

Using references from any C book, find and studythe following concepts (definition and examples):

A) Reserved WordB) VariableC) Constant

Page 34: Chap 2  structure of c programming dti2143

Standard/special word in standard library

Contain special meaning understood by compiler

RulesCase –sensitiveMust be written insmall case

Cannot be used as identifieror variables

Reserved Word

Page 35: Chap 2  structure of c programming dti2143

intThe acronym for integer

voidRefer to the function that will not

return any value

case default switch break

for continue float double

return while if do int

Example:

Reserved Word

Page 36: Chap 2  structure of c programming dti2143

Representing particular name in programmingStore values to be used in programmingRefers to the storage in computer

Standard identifier

User-definedidentifierType

Identifier

Page 37: Chap 2  structure of c programming dti2143

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

Standardidentifier

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

Identifier

Page 38: Chap 2  structure of c programming dti2143

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

User-definedidentifier

Constant VariableType

Identifier

Page 39: Chap 2  structure of c programming dti2143

User-defined identifier

Identifiers name can only consists of name, number and underscore

Identifiers name cannot be started with numbersSymbol cannot be used in identifier nameCannot contains spaces between two identifiers

nameIdentifiers name should be uniqueIdentifiers is not case sensitive

RULES

Identifier

Page 40: Chap 2  structure of c programming dti2143

UThM DIT1064 Seven_eleven integer

Valid identifiers

8Century BIT 1033 Two*four

‘Sixsense’ void

Invalid identifiers

Example:

WHY?

WHY?

WHY?WHY?

WHY?

Identifier

Page 41: Chap 2  structure of c programming dti2143

Name which used to store data valueRefer to name of one cell in computer storageContants value is fixed

Constant

How to give name to a constant value?

Follow identifiers rules

Identifier

Page 42: Chap 2  structure of c programming dti2143

const data_type const_name = const_value;

Declaration format:

const float pi = 3.142;Reserved word

Data type

1

Constant name

Constant Value

Page 43: Chap 2  structure of c programming dti2143

#define const_name const_value;

Declaration format:

#define pi 3.142;Reserved word

2

Constant n

ame

Constant value

Page 44: Chap 2  structure of c programming dti2143

#define minimum 0;#define MAX 100;

const int counter = 100;const char alphabet = ‘J’;const float value = 4.5;

Example of constant:

Page 45: Chap 2  structure of c programming dti2143

data_type variable_name;

Name which used to store data/input valueRefer to the name of one cell in computer storageVariable’s value can be modified/changed during execution

Variable

Declaration Format:

Identifier

Page 46: Chap 2  structure of c programming dti2143

Declaration Example

int number;

float weight;

char alphabet;

Declaration of a variable number of integer data type.

Declaration of a variable weight offloating point data type.

Declaration of a variable alphabet of character data type.

Page 47: Chap 2  structure of c programming dti2143

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

Page 48: Chap 2  structure of c programming dti2143

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; }

Page 49: Chap 2  structure of c programming dti2143

Method to give/assign value to variable

InitializationInteractive

Input/enter data through input devices

Use input statement (scanf/gets)

Assign value to variable during declaration.

Assign value to variable.

Use assign symbol, “=“

Page 50: Chap 2  structure of c programming dti2143

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

Example:

Initialize a variable

Page 51: Chap 2  structure of c programming dti2143

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

TypesInteger

Floatingpoint

Character

Data types

Page 52: Chap 2  structure of c programming dti2143

Represents any round number with +/- values.Divided into short and long integer.Reserved word for integer – intValid 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 thevariable is as follow: int age;

Data types

Page 53: Chap 2  structure of c programming dti2143

Floating number

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

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

float height;

Data types

Page 54: Chap 2  structure of c programming dti2143

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;

Data types

Page 55: Chap 2  structure of c programming dti2143

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

Exercise:

Page 56: Chap 2  structure of c programming dti2143

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

Exercise:

Page 57: Chap 2  structure of c programming dti2143

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:

Exercise:

Page 58: Chap 2  structure of c programming dti2143

Mrs Leeya needs to determine her students grade for programming subject based on the mark scored duringfinal examination. The ‘A’ grade will be given if the Mark scored is between 85 to 100. If a student has scored90 marks, what is the grade should Mrs Leeya give to the student?

Based on the following problem, determine the appropriate

variables can be declared:

Exercise:

Page 59: Chap 2  structure of c programming dti2143

Based on the following problem, determine the appropriate

variables can be declared:

Exercise:

A box has height, width and length. Calculate the volume of a box.

Page 60: Chap 2  structure of c programming dti2143

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 haveto pay for all the tin of paints he bought.

Based on the following problem, determine the appropriate

variables can be declared:

Exercise: