Sei sulla pagina 1di 155

BEE1222 Computer Programming

By Hazizulden Abdul Aziz

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Course Synopsis

This course introduces computer programming techniques to electrical & electronic engineering students using a structured programming language called C

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Outcomes

Explain hardware/software interfacing Demonstrate structured programming techniques using high-level language Use computer programming techniques in solving electrical & electronics engineering problem Work in team and communicate effectively

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syllabus

Computer programming fundamentals Structured program development 5 elements of computer programming Aggregate data types Files Input and Output Hardware interfacing

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Assessment

Distribution Assignments (10%) Projects (20%) Quizzes (10%) Tests (60%)

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

References

B.W. Kernighan and D.M. Ritchie, C Programming Language, 2nd Ed, USA: Prentice Hall, 1988

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Additional References

S.G. Kochan, Programming in C, 3rd Ed., USA: Sams Publishing, 2005 G. Perry, Absolute Beginners Guide to Programming, 3rd Ed., IN: Que, 2003 H.M. Deitel and P.J. Deitel, C: How to Program, 3rd Ed., NJ:Prentice Hall, 2001 J.R. Hanly and E.B. Koffman, C Program Design for Engineers, 2nd Ed., MA: Addison Wesley, 2001

2010 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Internet Resources

www.cprogramming.com

2010 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Computer Programming

An overview of computer programming concept

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Programming & Engineering

Computer in engineering environment CNC machines PC based integrated system Embedded microprocessor & controller Scientific computing, complex tasking, data analysis, simulation & visualization

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Inside a Computer

Basic architecture of modern computer


Data Bus

I/O interfaces
Control bus

CPU

Memory (RAM/ROM)

Address Bus

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

The CPU

The brain of a computing devices Registers instruction & memory address ALU (Arithmetic & Logic Units) Clock processor speed Floating points coprocessor

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Computer Software (Program)

Operating software Master controller between hardware and other system application software Application software Written to solve specific problem and/or to simplified work processes

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Computer Languages

Means of communicating with computers Sequence of instructions for CPU Three types Machine Assembly High Level

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Machine Language

Built-in to the CPU Binary code Alternative codes: Octal Hexadecimal bits & bytes

Example:
00000000 00010101 00010110 00110101 01110111

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Assembly Language

Symbolic/mnemonics codes Unstructured Processor dependent Assembler translate to machine language

Example:
CLR MOV A,#2 ADD A,#2 MOV R0,A END

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

High Level Language


Use proper syntax Easy to understand Machine/Processor Independent Compiler language

High Level Language Fortran (1950s) Basic (1960s) Pascal (1960s) C (1970s)

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

C Programming Language

History 1972 by Dennis Ritchie Based on B/BCPL OS language ANSI/ISO C (1989) Evolution

C advantages Powerful language Lean & efficient Less rigid structure Support bitmanipulation

Borland C, visual C, C++, C#

Low high level language

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Compiler Translation Process


Libraries and other object code Source code (FILE.C) Editor Compiler Object code (FILE.OBJ) Linker

Executable program (FILE.EXE)

Errors and/or warnings

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Compiler & Linker

Compiler Translate code to machine language Linker Built executable program file

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Errors in Programming

Compilation error

Logic error

Syntax error Easy to identify and corrected

Programmer error Not easy to identify and correct May cause run-time error

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Development Environment

What you needs? A source code editor A compiler and linker An optional debugger Integrated Development Environment IDE All-in-One application (programming) software

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

DEVCpp Compiler

OSS License compiler IDE for ANSI C/C++ developer Source editor Compiler & Linker Debugger

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Borland C++ Compiler


Source Code editor Compiler & Linker Debugger

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Outcomes

Understand the needs to learn computer programming List the three levels of computer programming languages Explain how high level languages are translated to machine language Use DEVCpp and/or Borland C++ compilers IDE features

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Structured Programming

An introductory to structured programming paradigm

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

What is a Program?

A set of instruction for computer to execute A collection of instructions necessary to solve a specific problem SOFTWARE or FIRMWARE?

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Programming Paradigm

A point of view on how program execute Influence problem solving methodology

Examples: Unstructured Structured Sequential Procedural or Functional Object oriented

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Structured Programming

Disciplined approach to writing program that are clear, correct & easy to maintain Sequential, procedural or functional Top-Down approach to programming

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Program Execution

Computers execute instruction line-by-line basis Instructions and data are stored in allocated memory addresses Information stored in memory address is accessed by fetch-execute cycle Program Counter (PC) store current memory address information Registers store current instruction and data executed

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

The Memory Structure

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Program Construction

Start with problem statement Define requirements and test plan Develop Algorithm Create source file Compile and make correction Execute, test and debug

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Define the Problem


Understand what is the problem Define scope and generality Define inputs & outputs Define constants & formula Define computational needs

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Design Test Plan


Contains list of inputs & correct outputs Test normal & abnormal conditions Test extreme & out-of-bound data

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Design a Solution

Algorithm to consider Interaction user & program Fool proofing against illegal inputs

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Algorithm

Method for solving well structured problem Sequence of steps to accomplish specific task

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Representing Algorithm

Flow Chart Graphical symbols Flow of steps or processes Generic

Pseudo Code Algorithmic language Code without syntax May use borrowed syntax Easily translate

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Flow Chart Symbols


start/end
connector operation

input/output

Off-page connector

decision

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Pseudo-code statement

Simple English Gets first number Gets second number Add the two numbers Show result

Pseudo-code input(number1) input(number2) Result = number1 + number2 output(Result)

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Steps
Start A Problem Statement

Compile
Conceptual design Test Algorithm design Solution Source Code End

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Outcomes

Explain the structured programming approach Write appropriate problem definition and test plan Develop simple algorithm to solve basic arithmetic operation

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

C Programming Language

Explain C Language fundamentals

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

C Program Elements

Pre-processor* Declaration Keywords Statements Comments

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Pre-Processor

Analyze source file before compiling Process pre-processor directive Remove comments Divide program into tokens Result in more efficient & clearer code

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

How pre-processor works


Replace macros defined with #define directive

Source code file (FILE.C)

Pre-processor

Processed Source Code file

Compiler

Include files with #include directive

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Pre-Processor Directive

Begin with # character Call up essential definitions & libraries Pre-processor directives: #include includes header files #define define constant & macros

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Declaration

Define attribute (data type) of identifiers used Must precede executable statements Global vs. Local declaration

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Global vs. Local Variable


Global variable - declared outside any function Local variable - declared inside a function Local variable take precedence over global variable AVOID using global variables

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Keywords

Reserved words Predefined by compiler libraries Cannot be used as identifiers Must be written in lowercase Instruction set

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Statements

Sequence of instructions Branching or looping or Function calls Start with a command word and ends with ; Compounded by curly brackets { }

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Comments

Use to clarify program statements Make program code more readable Start with /* and end with */ Can be included anywhere in the program

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

C Program Structure
Pre-processor directives

Global declaration
main () {

Local declaration
Executable statements }

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Writing your program code

Programmer header block


/* * * * * Name: <type your full name> Student ID: <type your student ID #> Section: <type your section #> Title: <type the title of your program here> -------------------------------------------*/

/* <Your introduction goes here> */

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Outcomes

Explain each element of C Language structure Describe how pre-processor works in C Outline basic structure of C Language

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Programming Fundamentals

Explore in-depth the five fundamental elements of computer programming

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

The FIVE Elements


Declaration statements Action statements Selection statements Repetition statements Invocation statements

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Declaration Statement

Associates memory location to identifier Associates identifier to its attribute and data type Variable Constant Function

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

ANSI C Identifiers

Alphabets, digits and underscore Cannot begin with digit Case sensitive Unspecified length

Example:

student1_age Student1_Age iStudent1_Age

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Data types

Scalar/Simple Integer number Real number Character

Aggregate Arrays Strings Pointers

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Variables Declaration

Simple data types declaration


int float/double Char datatype identifier;

Syntax

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Initialization

Give initial value to variables data type Initialization statement In declaration statement Just before using the variable

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Assignment

= symbols (GETS) Assign a value to an identifier Syntax: identifier = value; identifier = expression;

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Constant Declaration

#define

const

Define constant of simple built type Syntax

#define VARNAME value

Define constant that depended on other constant Syntax

const datatype VARNAME = value;

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Action Statements

Input /Output statements Expression statements Arithmetic operations Algebraic expression Trigonometry functions

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Input/Output Statements

Interactive programming User interface with input/output devices

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

C Input/Output Statements

Pre-processor functions library #include <stdio.h> Input and output instruction in C... puts printf scanf

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: puts
puts(string);

Outputs a text string constant to the standard output device Example: puts(Computer Programming);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: printf
printf(format,argument);

Outputs a formatted text string to the output in a form defined by format using arguments argument Example:

printf(The value of var1 is %d,var1);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Formatting Operators
Operator %c %d %e %f %u Format Single character Signed decimal integer Scientific floating point Floating point Unsigned decimal integer Operator %s %o %% %x %g Format String of character Unsigned octal integer Print % character Unsigned hexadecimal integer Scientific notation

printf(%f %d %c,fVal1,iVal2,cCh); printf(%m.nf %md,fVal1,iVal2);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Esc Sequence Characters


Char \ \ \\ \n \t Function Double quote Single quote Backslash Line feed Horizontal tab spacing Char \b \a \f \r Function Backspace Audible bell Form-feed Carriage return

printf(Computer Programming\r\n); printf(I/O statement\b);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: scanf
scanf(format,&argument);

Reads formatted values from keyboard in a format defined by format and loads them into the argument argument
Example: scanf(%f %d %c,&fVal1,&iVal2, &cCh);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Arithmetic Expression

Performing arithmetic on numeric data Arithmetic expression is written as...

identifier = operand operator operand

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Arithmetic Operators
Operator + * / Operation Subtraction Addition Multiplication Division Operator -= += *= /= Operation minus equals Add equals Multiplied equals Divide equals

Modulus

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Increment & Decrement Operators


j++ Use the operands value in the expression, then add 1 to the variable
Use the operands value in the expression, then subtract 1 from the variable Add 1 to the variable then use the new value in the expression Subtract 1 from the variable then use the new value in the expression

j--

++j

--j

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Try this!

Write a short program in C and incorporate the following code:


i = 1; printf(i = %d\n, i); printf(i = %d\n, ++i); printf(i = %d\n, i);

Change the following line in the code:


(was) printf(i = %d\n, ++i); (is) printf(i = %d\n, i++);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Selection Statements

Decision & branching Choose between several possible sequences of action based on the value of expressions Two commonly used selection algorithm IF/ELSE SELECT/CASE

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Relational Operators
Operator Operation Operator Operation

<
<= ==

Less than
Less than or equal equal

>
>= !=

Greater than
Greater than or equals NOT equals

operand operator operand expression operator expression

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Logical Operators
Operator Operation

&& ||
!

AND OR
NOT

operand operator operand expression operator expression

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Flowchart for IF/THEN/ELSE

Used when one of the two statements must be chosen depending on a condition

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: if & if..else


Syntax: if
if (expression) { statement block; }

Syntax: if..else
if (expression) { statement block1; } else { statement block2; }

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: if..else if..else


Nested if..else statement Multiple nested

if (expression1) { statement block1; } else if (expression2) { statement block2; } else { statement block3; }

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Flowchart for SELECT..CASE

Used when one statement from many must be chosen as determined by a value

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: switch..case
switch (expression) { case const1: statement(s); break; case const2: statement(s); break; default: statement(s); break; }

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: break

Use to exit from a statement block Use with: switch..case for while () do..while()

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Repetition Statement

Looping and counting Control the repetitive re-execution or iteration of sequences of actions Two commonly used looping algorithm DO...WHILE WHILE...DO

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Flowchart for DOWHILE

Operation executed at least once

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: do..while
do { statement block; } while (condition);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Flowchart for WHILEDO

Operations performed if condition is met Also While loop FOR loop

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: while
while (condition) { statement block; }

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: for
for (start_value;test_condition;operation) { statement(s); }
where start_value test_condition operation: Starting value of the loop counter relational condition to continue looping. if test condition is TRUE, looping continue loop counting operation

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Syntax: continue

Use only in repetitive statement Transfer instruction execution sequence to test condition for repetitive statement

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Invocation

Call-up sub-programs/sub-routines Provide structure to a program by allowing the use of sub-programs

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Function

A sub-program or sub-routine A module of code that define specific job An identifiable pieces of code with defined interface Reusable can be used repeatedly

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Why use Function


Avoid redundancy in coding Provide logical clarity to program structure Customized library of routine instruction

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Standard Library Functions


Header File Comment

stdio.h
math.h ctype.h string.h stddef.h stdlib.h

Standard I/O routine


Math functions Character classification & conversion Strings manipulation functions Define common data types & macro Miscellaneous routine

time.h

Time functions

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Math Library Function

Contains trigonometry functions Pre-Processor header declaration

Examples:

#include <math.h>

abs(int val) fabs(double val) exp(double val) log(double val) sqrt(double val) pow(double val1, double val2) M_PI

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

User Defined Functions

Prototype Define function interface (declaration) Definition Block of statements associated to function Specify function operation Call Cause function to be executed

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Function Prototype

Syntax:

return_data_type function_name(argument_data_type argument_name);

Function declaration before function call

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Function Definition

Consist of two elements

Function block
Header()

Header correspond to prototype definition Body collection of statements contained within {} bracket

{
declaration statements;

other executable statements;


return();

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Function Call

Syntax:

Function_name(argument); Identifier = function_name(argument);

Function call can be made from Main() function block or from another function block

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

void:void Function

Accept no argument and return no value Function prototype declaration

Function definition

void fname(void) {

void fname(void); fname();

Function call

declaration statements; executable statements; }

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

void:one Function

Return no value but accept all argument(s) Prototype declaration

Function definition

void fname(argument type argument_name); fname(argument);

Function call

void fname(argument type argument_name) { declaration statements; executable statements; }

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

one:void Function

Return a value and does not accept any argument Prototype declaration

Function definition

return_type fname(void); identifier = fname();

Function call

return_type fname(void) { declaration statements; executable statements; return(argument); }

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

one:one Function

Return a value and accept all argument(s) Prototype declaration

Function definition

return_type fname(argument_type argument_name);

Function call

identifier = fname(arguments);

return_type fname(argument_type argument_name) { declaration statements; executable statements; return(argument); }

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Outcomes

Explain five elements of structured programming Write an executable code in C demonstrating all five elements of structured programming approach Develop a basic algorithm and write a basic program to solve engineering related numerical analysis

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Numeric Arrays

Introduce the numeric array data type

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Arrays

A series of variables with same data type that share one variable name Related terms Array slots/cells Array elements Array size/length (always an integer number)

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Using Arrays

Array data type can be used in all elements of programming Declaration Action statements Repetitive statement Selective statement Function statement

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

One-Dimension Numeric Arrays

Array data type Declaration

data_type array_name[array_length];

Initialization

array_name[array_length] = {val1,};

Addressing an array element


array_name[index] Note: indexing of array slot start with 0

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Functions with Array Arguments


Functions use same memory area for arrays Function can not return an array value Declare array as function argument if function modify array element value

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Function Prototype & 1D-Array

Function prototype with array arguments

void fname(ary_type ary_name[], int n, arg_type arg_name); return_type fname(ary_type ary_name[], int n, arg_type arg_name)

Using an array element with a function?

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Two-Dimension Numeric Arrays

Declaration

data_type ary_name[row][col];

Declaration with Initialization

data_type ary_name[row][col] = {{r0c0,r0c1,},{r1c0,r1c1},{r2c0,}};

Addressing an array element


array_name[row_index][col_index] Note: indexing of array slot start with 0

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

2D Numeric Arrays & Function

Function prototype with array arguments

void fname(ary_type ary_name[][col], int n, arg_type arg_name); return_type fname(ary_type ary_name[][col], int n, arg_type arg_name)

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Outcomes

Explain the structure of numeric array data type (one- and two-dimensional array) Write a code in C demonstrating the use of numeric array data type

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Strings

Introduce string data type as array of character

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Character Data Type

Declaration & initialization of character variable


char identifier_name; char identifier_name = char_literal; Identifier_name = char_literal;

Accept single character of alphanumeric or symbols (including blank).

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Character Input and Output


Character input scanf( %c, &ch)

Character output printf(%c, &ch)

Note:

A space included before %c type specifier

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Operations on Character Type


Operation Copy ch1 = ch2

Character manipulation #include <ctype.h>

Logical operators

Example

==/!= <, <=, >=, >

Increment/decrement

isalpha() islower() isupper() isdigit() isspace() tolower() toupper()

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

String

Character array (array of char data type) Declaration & initialization of string variable char str[str_len]; char str[] = strings_value;
Note: string will add null character \0 to mark end of string causing number of character stored always one less than str_len

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

String Input and Output


String Input scanf(%ms, str); gets(str);

String Output printf(%-s,str); puts(str);

Note:

Note:

Ampersand (&) not included as prefix to string variable identifier Input Text longer than string length will cause overflow of string variable

Adding minus (-) sign to type specifier (s) cause left justification of string String variable without null character (\0) may cause run-time error

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Operation with String

String library function #include <string.h>


String initialization or assignment statement strcpy(str_var, str_text); Checking length of string variable to avoid overflow strlen(str_var);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Using Strings with Functions

Sting is array of character, therefore using string data type with function is similar to using numeric array with function discussed in earlier topic.

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Array of String

Two-dimensional array of character type Declaration char str_ary[row][col]; char str_ary[row][col] = {str1, str2, , str_row};

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Pointers

Introduce pointers data type

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

What is Pointers?

Address of a memory location of a data Points to a memory location where a data is stored Pointer variable contains address of a memory location

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Usage

Pointer variable is used To return more than one value from a function To create and/or process string variable To manipulate contents of arrays To construct dynamics array

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Pointer Declaration & Initialization

Declaring a pointer variable base_type *pointer_variable_name;


Declaring and initializing a pointer variable as NULL pointer base_type *pointer_name = NULL;

Note: A pointer can refer only to object/data of its base type

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Pointer Operators
& operator

* operator

Reference or address operator Example:

Dereference or Indirection operator Inverse of & operator

Instruction m = &k return address of variable k

&*p == p and *&m == m

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Using Pointer as Call-by-Address


Return multiple values from a function Pointer variable is declared as a parameter in function prototype Address of a variable is pass to a function in function call Address of a variable is stored in pointer variable (parameter) of the function

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Pointers as Function Parameters

Function prototype with pointer arguments

void fname(pointer_datatype *pointer_name); return_type fname(pointer_datatype *pointer_name);

Function call

fname(&var_name);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

File INPUT/OUTPUT

Explain how to read and write text data files

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Working with Data Files

Use files to store data in permanent form Useful when collecting large quantity of data

Use text file (.txt or .dat file format) Data stored in ASCII characters format

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Using Data Files

Declaration FILE data type FILE *file_ptr;


Opening a file

file_ptr = fopen(filename, attrib);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Files Attributes
Attribute
r w a

Description
Open for reading only Create for writing Append/create for writing

r+ w+
a+

Read & write (update) Create (update)


Append (update)

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Write Data to File (fprintf())

Syntax

fprintf(file_ptr,format,argument);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Read Data from File (fscanf())

Syntax

fscanf(file_ptr,format,arguments);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Finding End-of-File (feof())


feof() return a TRUE if End-of-File if found


Syntax

feof(file_ptr);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Close a Data File (fclose())

Syntax fclose(file_ptr);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Outcomes

Explain how program read from and store data to a file Write a code in C to write data to a data file Write a code in C to read data from a data file

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Hardware Interface

Discuss how to interface with external input/output devices

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Software/Hardware Interface

Software (program) to control peripheral device Communicate via I/O ports

Common I/O ports Parallel port Serial port FIREWIRE port USB port

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Accessing an I/O ports


Access to I/O ports is restricted by OS Need I/O port device driver to allow access Communicate via IOCTL calls

User program

IOCTL Call

I/O Port device drive

I/O Port

Peripheral device

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Parallel Port (IEEE1284 Port)


Commonly used port for (Engineering) projects Allow data transfer in parallel 1 byte at a time Identifiable by D-Type 25 pins connector PC uses Male type connector Almost OBSOLETE replaced by USB port

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Hardware Properties

IEEE 1284 Type A: D-Type 25pin connector Data line: Pins (2-9) Port Addresses LPT1: 378h 37Fh LPT2: 278h 27Fh

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

PORTTALK

Parallel Port device driver for Windows XP Originally written for Borland turbo C++ compiler Pre-Installed on the programming device Invoke through preprocessor directive #include pt_ioctl.c

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

PortTalk Calls

Open PortTalk OpenPortTalk(); Close PortTalk ClosePortTalk();

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Parallel PORT Read/Write

Receive data from peripheral device var_name = inportb(PortID,dataHx); Sent data to peripheral device outportb(PortID,dataHx);

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Outcomes

Explain how program communicates with peripheral devices Write a code in C to write data to parallel port Write a code in C to read data from parallel port

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

In pursuit of life-long learning

CLOSING NOTES

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Course Outcomes (revisit)

Demonstrate structured programming techniques using high-level language Use computer programming techniques in solving electrical & electronics engineering problem

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Further Readings

Not explore in this course: Structured data type Stream inputs/outputs


Unstructured branching Dynamic Arrays Bit data type and Bitwise operation Other standard library functions Object Oriented Programming

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Migration to RAD

RAD Rapid Application Development programming language (e.g. C++ Builder, Visual C++) Object Oriented Programming paradigm

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Application Languages

Scripting programming language (e.g. VBA Macros) Webpage programming language (e.g. HTML, Java) Database programming language (e.g. SQL)

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Ultimately, its not about the language you use or its syntax, but about how you think about your problems. And more about the tools and structure in your mind than in your language. If you have the former, you can usually work around the deficiencies in the latter

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

The END

Hazizulden Abdul Aziz Faculty of Electrical & Electronics Engineering Universiti Malaysia PAHANG

2009 Hazizulden Abdul Aziz, Faculty of Electrical & Electronics Engineering, UMP

Potrebbero piacerti anche