You are on page 1of 82

FACULTY OF ELECTRICAL ENGINEERING

UNIVERSITI TEKNOLOGI MARA

ECE 126
INTRODUCTION TO C
PROGRAMMING

COURSE NOTES
NAME :
GROUP:

LECTURER :

PROGRAMME
COURSE
CREDIT HOUR
SEMESTER
PRE-REQUISITE
STATUS
CONTACT HOUR

Diploma in Electrical Engineering


Introduction to C Programming
3
2
None
Core
4 (2 hrs. lecture, 2 hrs. lab)

SYNOPSIS
This course provides an introduction to C programming and its application in
solving simple engineering problems.
OBJECTIVES
Upon completion of this course, the students will be able to:
To develop algorithms and program the solutions to simple engineering
problems.
To understand the programming concepts required to implement the
solution in C programming language.
2

COURSE EVALUATION

Coursework
1. Lab/assignments
2. Test (2)
3. Mini Project (1)
Total Marks

Percentage
20%
50%
30%
100%

TEXT BOOK
DEITEL & DEITEL (Latest Edition). C How To Program by PEARSON/ Prentice Hall
REFERENCES
1. Jeri R. Hanley, Elliot B. Koffman, `C Program design for Engineers`, 2nd Edition,
Addison Wesley, 2000.
2. Pradip Dey & Manas Ghosh, `Computer Fundamentals and Programming in C`,
Oxford University Press, 2006.
3. H. M. Dietel & P.J. Dietel, `C How to Program`, Prentice Hall, 2004.
4. Behrouz A. Forouzan & Richard F. Gilberg, `A Structured Programming Approach
Using c`, Brooks/Cole, 2001.
3

COURSE TOPICS
WEEK
1
(2 hours)

CHAPTER
1
INTRODUCTION TO C
PROGRAMMING

2-3
(2 hours)

2
INPUT AND OUTPUT
OPERATION

4
(2 hours)

3
CONTROL FLOW

5
(4 hours)

3
CONTROL FLOW

6
(2 hours)

3
CONTROL FLOW
4
FUNCTIONS

CONTENT/SUB-CHAPTER
INITIAL CONCEPT
i. Introduction to C programming
ii. Producing an executable program (compiling
& linking)
iii. Constants, Variables and Data types types (int,
float,string,char)
iv. Operators and precedence
v. Data type conversion
i. Printf and Scanf
ii. Working with file
SELECTION STATEMENTS
i. If.else
ii. Switch case
REPETITIVE STATEMENTS
i. For
ii. While() and Dowhile()
SELECTION STATEMENTS
i. Break/continue
FUNCTIONS
i. Introduction to function
ii. Function prototype
iii. Function definition

REVISION FOR TEST 1 + MINI PROJECT TITLES GIVEN


TEST 1 (Chapter 1 3)
7
( 2 hours)

4
FUNCTIONS
5
SIMPLE ARRAY

8
(2 hours)

5
SIMPLE ARRAYS

9
(2 hours)

6
POINTER

INTRODUCTION TO POINTER
i. Pointer declaration and synatx
ii. call by value and call by reference

10
(2 hours)

6
POINTER

INTRODUCTION TO POINTER
i. Using pointer with functions and array

11
(2 hours)

7
STRUCTURES

12
12,13,14

FUNCTIONS
i. Function call
ii. Recursive function
SIMPLE ARRAY
i. Array declaration and syntax
i. One dimensional array
ii. Two dimensional array

STRUCTURE
i. Structure declaration and syntax
ii. Structure initialization
iii. Pointers to structure

TEST 2 (Chapter 4 7)
MINI PROJECT WORKS

Chapter 1

Introduction to C Programming
6

LESSON OUTCOME
At the end of the lesson, students should be able to
describe and explain:
Introduction to C Programming Language
Development Stages of C Program
Flowchart
Variables and Data types
Keywords and Constants
Operators and precedence
Data type conversion
7

What is a program?
A list of instructions.
Written in a programming language (c, c++, java).
Determines the behavior of a machine
(computer, robot).

Programming Language
A machine language that has its own set of
grammatical rules.
It is used to instruct a machine to perform
specific tasks.

History
C was developed in 1972 by Dennis Ritchie at
Bell Laboratories.
Based on a programming language called B
(which is derived from BCPL language).
C was designed and developed for the
development of UNIX operating system.
C has been widely used to develop many type
of application software from a basic to
operating system.
BCPL- Basic Combined Programming Language

10

Christopher
Strachey
Uni. Cambridge
& Uni. London
Complex thus
not popular

Martin Richards
Powerful and
Portable
One data type

B
Ken Thompson
& Dennis Ritchie

Bell Labs
One data type

1972

BCPL

1969

CPL (Combined
Programming
Language)

1966

1963

History
C
Dennis Ritchie
at Bell
Laboratories
Based on a
programming
language called
B
Designed and
developed for
the
development of
UNIX operating
system

11

Development stages of C program

12

13

Editing
Process of writing the C source code.
Using editor program (i.e. vi and emacs for
Linux, Notepad for Windows)
Software package provides programming
environment
Integrated editor
Managing and maintaining source code
i.e. C++ Builder, Code::Blocks, Dev-C++, Microsoft
Visual Studio

14

Pre-processing and Compiling


Pre-processing performs directives such as
inclusion of header files and substitution.
Compiling process of translating the source
code (programming language) to machine
code (machine language).

15

Linking
Process of combining generated object files.
Add required codes from C standard library.
Produce an executable file.

16

Executing
Run the program to check whether it produce
the desired output.
Testing stage where you check the output of
your program.
The program does not produces the suppose
output, then you have made logic (semantic)
error.

17

C Program Layout
C program consists of two sections:
Pre-processor directives
Main function

pre-processor directives
main()
Pre-processor section
{
Main function section
statements
}
18

Pre-processor Directives
Specify what compiler should do before
compilation.
Include header files.
Header file keep information about the library
functions (printf, scanf).
Pre-processor directives begins with the #
symbol.

19

Main Function
The program starts its execution.
Define the program definition.

20

An Example of C Program

Sample output:
C program example

21

Additional - Comments
A comment, not actually part of the program.
Provide information on what the program
does.
Begin with /* and end with */ or written as
//.
Good habit to include comments.
Keep inform what are the code actually doing.
22

Important line in C
Symbol # indicates that this is a pre-processor
directive
Include stdio.h header file in our program
stdio.h contains information on
input/output routines.
We are using the printf() function from
stdio.h
23

Defines the start of the function main().


Keyword int signifies main function returns
an integer value.
The () is where we specify information to be
transferred to function main().

24

The portion that begins with { and ends with


} is called block or body.
Within the block is where we write the
statements.

25

Function printf() instructs the computer


to display characters or a string enclosed by
the double quotes on the monitor screen.
A string is a combination of numerous
characters.

26

Function main() is defined to return a value


of integer type.
Return 0 is needed to indicate that the
program has terminated successfully.

27

Flowchart
Basic shapes of flowchart
point / terminal
data / process

input / output operation


no

decision / option
yes

flow of the flowchart


28

Flowchart
Sequence flow

start

Boil water
Coffee = 1 spoon
Sugar = 2 spoon
Pour coffee and
sugar into a cup

Add water
Display coffee is
ready
end
29

start

Flowchart
Boil water

Looping flow
Pour coffee into a
cup

Add sugar

Add water

Taste the coffee

yes

Over sweet?
no

end

30

Flowchart
Combination
flow

start
A

Boil water

end

no

Over sweet?
yes

Pour coffee into a


cup

Add water

Add sugar and


water

Taste the coffee

end

no

Tasteless?
yes

Add sugar
31

EXAMPLE 1
Read 1 integer number entered by the user via a keyboard. Check and display
the output, which one is the positive and negative values.

32

EXAMPLE 2
Read 2 integer numbers entered by the user via a keyboard. Compare and
display the output, which one is greater between two inputs.

33

Exercise
Draw a flowchart to solve below problem:
Prepare cupcakes. Ingredients are flour, yeast,
and sugar. Make sure you taste the dough
before baking process.
Find solution to calculate the average marks for
3 of student. Then, display the average value.
34

ANSWER
#include<stdio.h>
main(){
int mark1,mark2,mark3;
float average=0;
printf("Enter marks for student 1:");
scanf("%d",&mark1);
printf("Enter mark for student 2:");
scanf("%d",&mark2);
printf("Enter marks for student 3:");
scanf("%d",&mark3);
average = (mark1 + mark2 + mark3) / 3.0;
printf("The average marks for all students entered is %.2f\n", average);
return 0;
}
35

EXAMPLE
Draw a flowchart to solve below problem:
Read 10 integer numbers, entered by a user
through a keyboard. Search a highest and lowest
number. Display the output which are the
highest and lowest number.

ANSWER
start

Read input number

Keep into low variables

Highest?
no
yes
Keep into high variables

10 input integers?
no
yes
Display the highest and lowest integer

End

Variables
Every variable has name, type and value.
Variable name / Identifier :
Must start with character or underscore ( _ ), cannot
start with number or symbol and not a keyword .
Must not include any space and it is letter case sensitive.
Eg:
stud1, Stud1, stud_name, _student (valid)
@stud, stud name, 1stud (invalid)
Variable type :
Based on the data type integer, floating point numbers
and characters.
The value can be change any time.
Whenever a new value is placed into a variable, it
replaces the previous value.

Variables
Variable must be declare / initialize before it can be used
in the next line of statements.
Variable declaration :
To declare a variable with a name and suitable data
type.
Eg:
int student; int staff;
double x, y;
Variable initialization :
To declare a variable and assign a certain value to the
varible.
Eg:
int student=5; int staff=1;
double x=1.12;
double y=9.999;

Data Types
Integer:
Whole number (decimal).
Positive, negative or zero : 25, 0, -9.
Variable declaration:
int x;
Floating point numbers:
double / float
Variable declaration: double y;
float z;
Characters:
A character is a single letter, digit, symbol or space. Eg:
m,B,#,3,=,@, .
A string is series of characters .
Eg:
student ,F#,$35,
class_93,ALI BABA.

Eg
Sample: Integer & float
#include<stdio.h>
int main()
{
int a, b;
float c;
printf("Enter two numbers to add\n");
scanf("%d%d",&a,&b);
printf(Value of entered number a : %d\n",a);
c = (float)a / b;
printf(Average of entered numbers = %2f\n",c);
return 0;
}

Sample : Character
#include <stdio.h>

int main()
{
char string[] = "Hello World";
printf("%s\n", string);
return 0;
}

Keywords
Special words reserved for C.
Cannot be used as variable names.
Eg: data types (int,void,const,static)
instruction statements
(if,for,case,break,return,include)

Constants
Constant name is declared just like variable name.
Constant value cannot be changed after its declaration.
2 ways for constant declaration :
const double pi = 3.147; or
#define pi 3.147

Assignment Operator

To assign a value to a variable.


Is a binary operator (at least has two operands).
Variable that receiving the value is on the left.
Eg: int num;
num
(in memory)
num = 3;

num is assigned to value of 3.


Arithmetic operation c = a + b
Multiple assignment x = y = z = 7
Compound assignment +=,=,*=,/=,%=
sum += 5
sum = sum+5

Arithmetic Operators
Operators

Symbol

Addition

Substraction

Multiplication

Division

Modulus

x % y produces remainder when x / y.


Eg: 5/3=1,5%3=2.

Ex : Arithmetic Operators
#include <stdio.h>
int main()
{
int first, second, add, subtract, multiply;
int divide, modulus;
printf("Enter two integers\n");
scanf("%d%d", &first, &second);
add = first + second;
subtract = first - second;
multiply = first * second;
divide = first / second;
modulus= first % second;
printf("Sum = %d\n",add);
printf("Difference = %d\n",subtract);
printf("Multiplication = %d\n",multiply);
printf("Division = %d\n",divide);
printf("Modules = %d\n",modulus);
return 0;
}

Output of program:

Relational Operators
Operator

Symbol

Less than

<

Less than or equal to <=


Greater than

>

Greater than or
equal to

>=

Equal to

==

Not equal to

!=

Also
known as
Equality
Operators

Used to compare numerical values .

Logical Operators
Operators

Symbol

NOT

AND

&&

OR

||
Expression

Value

!1

!0

Expression

Value

0 && 0

0 && 1

1 && 0

1 && 1

Expression

Value

0 || 0

0 || 1

1 || 0

1 || 1

Increment and
Decrement Operators
Increment operator ++
add 1

Decrement operator --;


subtract 1
These operators can be used as
prefix (++a/--a) or postfix (a++/a--).
Prefix increase/decrease the operand
before it is used.

Postfix increase/decrease the operand


after it is used.
49

Increment and
Decrement Operators
Example
y

int y,c,x;
y=5,c=1,x=3;

c++;

x+=2;

--y;

y=c++;

y=++x;

(in memory)

50

Operator Precedence
Highest Precedence / Priority

parenthesis,
logical op.

( ) !

Function call,

arithmetic op.

* / %

Multiplication, division, modulus

arithmetic op.

+ -

relational op.

< <= > >=

Addition, subtraction
Comparisons: less-than, ...

equality op.

== !=

logical op.

&&

Logical AND

logical op.

||

Logical OR

Equal, not equal

Highest Precedence / Priority


The order of operations used throughout mathematics, science, technology and many
computer programming languages is expressed as:
exponents and roots
multiplication and division
addition and subtraction

Example
The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20, then calculate:
Operator Description

Example

Answer

Adds two operands.

A+B

30

Subtracts second operand from


the first.

AB

10

Multiplies both operands.

AB

200

Divides numerator by denumerator.

BA

Modulus Operator and remainder


of after an integer division.

B%A

++

Increment operator increases the


integer value by one.

A++

11

--

Decrement operator decreases the A-integer value by one.

9
52

Operator Precedence
Eg:
3 + 4 5 = 4 5 + 3 = 23
2 + (3 4) = (3 4)+2 = 14
Ex 1
7 % 3 + 4 * 2 (1 + 12) / 4
Ans:6
Ex 2
Let x=4 ,y =5,z=9.
x > 5 || y < 7 && z != 2
Ans:Yes

Example Operator Precedence


#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}

Program output:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

Exercise
What data types would you use to hold the
following data?
Customer name
Your house number
A price
Car registrations
The time
A six digit number
Write C statements to declare them all.
55

Exercise (Jan 2012)


What value is assigned to each variable during
the execution of each line of statement?
Fill in the blank memories.
num1

num2

num3

int num1, num2, num3;


num1 = 2, num2 = 4, num3 = 6;
num3 /= 4;
num2 = num3 + --num1;
num1 = num2++;
num3 = num1 * ++num2;

56

Exercise : Answer
num1

num2

num3

int num1, num2, num3;


num1 = 2, num2 = 4, num3 = 6;
num3 /= 4;
num2 = num3 + --num1;
num1 = num2++;
num3 = num1 * ++num2;
#include<stdio.h>
main(){
int num1, num2, num3;
num1 = 2, num2 = 4, num3 = 6;
num3 /= 4;
num2 = num3 + --num1;
num1 = num2++;
num3 = num1 * ++num2;
printf("total is %d\n", num1);
printf("total is %d\n", num2);
printf ("total is %d", num3);
}

Output of program:

57

Exercise (July 2013)


What value is assigned to each variable after the execution of each statement?
Fill in the blank memories
x

int main() {
int x = 10, y, z;
x++;
y = ++x;
z= x + y-}

58

Exercise (July 2012)


What value is assigned to each variable during the execution of each
statement? Fill in the blank memories.

int a = 0, b = 10, c = 5, d = 8;
b = ++a * b;
a *= c++;
c--;

d /= --c;
b = a % c++;

59

Chapter 2

Input Output Operation


60

LESSON OUTCOME
At the end of the lesson, students should be able to
describe and explain:
Input and Output Devices
printf statement
scanf statement
Field Widths and Precisions
Printing Literals and Escape Sequences

61

Input Output Devices


Input devices are used to perform the input
operation.
Eg: keyboard, mouse, microphone, scanner.
Output devices are used to perform the
output operation.
Eg: monitor, printer, speaker.

62

Input Output Operation


Input operation in basic C programming is to
get input data from the keyboard using
scanf statement.
While output operation is to display the data
at the monitor screen using printf
statement.

63

Input Output Operation

printf

display the
data at the
monitor

get input data


from the
keyboard

scanf
64

Formatting Output with printf


printf
Precise output formatting
Conversion specifications: flags, field widths, precisions, etc.
Can perform rounding, aligning columns, right/left justification,
inserting literal characters, exponential format, hexadecimal format,
and fixed width and precision
Format
printf( format-control-string, other-arguments );
Format control string: describes output format
Other-arguments: correspond to each conversion specification in
format-control-string
Each specification begins with a percent sign(%), ends with
conversion specifier
65

Printing Integers
Integer
Whole number (no decimal point): 25, -9, 0
Positive, negative, or zero
Only minus sign prints by default

66

Printing Integers
Conversion Specifier Description
d
o
u
x or X

Display a signed decimal integer.


Display an unsigned octal integer.
Display an unsigned decimal integer.
Display an unsigned hexadecimal integer. X causes the digits 0-9
and the letters A-F to be displayed and x causes the digits 0-9 and
a-f to be displayed.

67

Printing Floating-Point Numbers


Floating Point Numbers
Have a decimal point (33.5)
f print floating point with at least one digit to left of
decimal

68

Printing Character and Strings


c Prints char argument
Cannot be used to print the first character of a string
s
Requires a pointer to char as an argument
Prints characters until NULL ('\0') encountered
Cannot print a char argument
Remember
Single quotes for character constants ('z')
Double quotes for strings "z" (which actually contains
two characters, 'z' and '\0')
69

The following declaration and initialization create a string consisting of the word "Hello". To hold
the null character at the end of the array, the size of the character array containing the string is
one more than the number of characters in the word "Hello.

If you follow the rule of array initialization then you can write the above statement as follows

Following is the memory presentation of the above defined string in C

#include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}

70

Formatting Input with scanf


scanf
Input formatting
Capabilities
Input all types of data
Input specific characters
Skip specific characters
Format
scanf(format-control-string, other-arguments);
Format-control-string
Describes formats of inputs
Other-arguments
Pointers to variables where input will be stored
Can include field widths to read a specific number of characters from
the stream
71

Formatting Input with scanf


Conversion specifier
Integers
d
o
x or X
Floating-point numbers
f

Description
Read an optionally signed decimal integer. The corresponding
argument is a pointer to integer.
Read an octal integer. The corresponding argument is a pointer to
unsigned integer.
Read a hexadecimal integer. The corresponding argument is a
pointer to unsigned integer.
Read a floating-point value. The corresponding argument is a
pointer to a floating-point variable.

Characters and strings


c

Read a character. The corresponding argument is a pointer to


char, no null ('\0') is added.

Read a string. The corresponding argument is a pointer to an array


of type char that is large enough to hold the string and a
terminating null ('\0') characterwhich is automatically added.

72

Field Widths and Precisions


Field width
Size of field in which data is printed
If width larger than data, default right justified
If field width too small, increases to fit data
Minus sign uses left justified

Integer width inserted between % and conversion


specifier
%4d (field width of 4)

73

Field Widths and Precisions


Precision
Format
Use a dot (.) then precision number after %
%.3f (precision of 3)
Meaning varies depending on data type
Integers
Minimum number of digits to print
If data too small, prefixed with zeros
Floating point
Number of digits to appear after decimal point
Strings
Maximum number of characters to be written from string
74

Field Widths and Precisions


Field width and precision
Can both be specified
%field_width.precision
%5.3f

Negative field width left justified


Positive field width right justified
Precision must be positive
Can use integer expressions to determine field
width and precision values
75

Field Widths and Precisions


Example1 :

int x = 123;
printf(%2d, x) output:123
printf(%5d, x) output: 123
printf(%-5d, x) output:123
printf(%.5d, x) output:00123
printf(%7.5d, x) output:00123

76

Field Widths and Precisions


Example 2:

float y = 4.56;
printf(%2f, x) output:4.56
printf(%9f, x) output: 4.560000
printf(%-9f, x) output:4.560000
printf(%.4f, x) output:4.5600
printf(%.1f, x) output:4.6
printf(%6.3f, x) output: 4.560

77

Field Widths and Precisions


Example 3:

char a = Z;
char b[] = ZOO;
printf(%2c, a) output: Z
printf(%-2c, a) output:Z
printf(%2s, b) output:ZOO
printf(%5s, b) output: ZOO
printf(%-5s, x) output:ZOO

78

Printing Literals and Escape


Sequences
Printing Literals
Most characters can be printed
Certain "problem" characters, such as the
quotation mark "
Must be represented by escape sequences
Represented by a backslash \ and followed by an
escape character

79

Printing Literals and Escape


Sequences
Table of all escape sequences
Esc a p e seq uenc e Desc rip tion
\'

Output the single quote (') character.

\"

Output the double quote (") character.

\?

Output the question mark (?) character.

\\

Output the backslash (\) character.


Cause an audible (bell) or visual alert.
Move the cursor back one position on the current line.
Move the cursor to the start of the next logical page.
Move the cursor to the beginning of the next line.
Move the cursor to the beginning of the current line.
Move the cursor to the next horizontal tab position.
Move the cursor to the next vertical tab position.

\a
\b
\f
\n
\r
\t
\v

80

Exercise
Write a statement to accomplish each of the following:
i. Define the variables x, y, z and result to be of type
int.
ii. Prompt the user to enter three integers.
iii. Read three integers from the keyboard and store
them in the variables x, y and z.
iv. Compute the product of the three integers
contained in variables x, y and z, and assign the
result to the variable result.
v. Print the result.
81

Answer

82