Chap 2 structure of c programming dti2143
-
Upload
alish-al-shahab -
Category
Technology
-
view
1.953 -
download
5
Transcript of Chap 2 structure of c programming dti2143
Chapter 2Basic Structure of Programming
Faculty of Mechanical and Manufacturing
Prepared by Alish Ahmad [email protected]
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 (programminglanguage such as C,C++, Visual Basic, C#)
Because computers do NOT understand high level language!
Translated to
000111010101010111011111
Typical program development environment consist of six phases to be executed.
Edit/Write
Preprocess
Compile
Link
Load
Execute
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
Turbo C
editor(free)
DEV C++
(free)
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.
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
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.
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.
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.
6. Executing
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.
Error(bugs)
Syntax ErrorsRun-time
ErrorsLogic Errors
Common Programming Errors
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
Logic Error2
Error occurred due to inappropriate
output.Programming mistake.Not detected during compilation.
Common Programming Errors
Which ONE?number pin or pin number?
Common Programming Errors
Run-time Error3
Error occurred due to wrong user input.
User’s mistake.
System would either display alert message or hang.
Common Programming Errors
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
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
#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
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
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
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
#define “file name” or #define constant_name constant_value
Format:
Example
#define MAX 100
Preprocessor Directive
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
int main( ){ return 0;} Main function
void main( ){ …………..}
main( ){ return 0;}
Main Function
Write the most basic structures of C programming.
#include <stdio.h>void main(){}
Instructions to be executed by computersEvery statements must be ended with semicolon
Types
Declarationstatement
Input/Output statement
Compound statement
Control statement
Functionstatement
C Statement
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
Using references from any C book, find and studythe following concepts (definition and examples):
A) Reserved WordB) VariableC) Constant
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
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
Representing particular name in programmingStore values to be used in programmingRefers to the storage in computer
Standard identifier
User-definedidentifierType
Identifier
Special built-in wordsReferred as function name which will called from C library
Standardidentifier
printf() scanf()puts() gets()
Identifier
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
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
UThM DIT1064 Seven_eleven integer
Valid identifiers
8Century BIT 1033 Two*four
‘Sixsense’ void
Invalid identifiers
Example:
WHY?
WHY?
WHY?WHY?
WHY?
Identifier
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
const data_type const_name = const_value;
Declaration format:
const float pi = 3.142;Reserved word
Data type
1
Constant name
Constant Value
#define const_name const_value;
Declaration format:
#define pi 3.142;Reserved word
2
Constant n
ame
Constant value
#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 valueRefer to the name of one cell in computer storageVariable’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 offloating 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
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, “=“
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
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
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
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
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
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:
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:
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:
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:
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.
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: