Sunteți pe pagina 1din 42

UTHM

Sem I 2010/11

Lecture Notes

Computer Programming
BTI 1022
Lecturer:
Winardi Sani, Dipl.-Ing.

Tutors:
Imran bin Razali
Muhamad Zaini bin Yunos
Sharifah Z.R. Bt Syed Ahmad
Faizul Amin Anuar

Faculty of Mechanical Engineering


Universiti Tun Hussein Onn Malaysia

Table of Content

1 Introduction
1.1 Lesson Plan . . . . . . . . . . . . .
1.2 Computer system . . . . . . . . .
1.3 Computer programming . . . .
1.4 Software development method
1.5 Algorithm and Pseudo code . .
1.6 Flow chart . . . . . . . . . . . . .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

1-1
1-1
1-1
1-2
1-2
1-3
1-5

2 Structure of C Programs
2.1 Program Development . . . .
2.2 Compiler . . . . . . . . . . . . .
2.3 Background . . . . . . . . . . .
2.4 Structures of a C Program . . .
2.5 Identifiers . . . . . . . . . . . . .
2.6 Data types . . . . . . . . . . . .
2.6.1 Basic data types . . . .
2.6.1.1 Qualifiers . . . .
2.7 Variables . . . . . . . . . . . . .
2.7.1 Variable definition . . .
2.8 Constants . . . . . . . . . . . .
2.8.1 Integer constants . . . .
2.8.2 Floating point constants
2.8.3 Character constants . .
2.8.4 String constants . . . . .
2.8.5 Defined constants . . .
2.8.6 Memory constants . . .
2.8.7 A program example . .
2.9 Formatted Input/Output . . . .
2.9.1 printf() . . . . . . . . . .
2.9.2 Output examples . . . .
2.10 Formatted input . . . . . . . . .
2.10.1 Input examples . . . . .
2.11 Self exercises . . . . . . . . . . .
2.12 Keywords . . . . . . . . . . . . .
2.13 ASCII Code Table . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

2-1
2-1
2-1
2-2
2-3
2-3
2-4
2-4
2-4
2-5
2-5
2-6
2-6
2-6
2-7
2-7
2-8
2-8
2-8
2-9
2-9
2-11
2-11
2-12
2-12
2-13
2-14

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

3 Operators and Expressions


3-1
3.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1
3.1.1 Integer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2

Table of Content

3.2

3.3

3.4
3.5

3.6
3.7
3.8

3.1.2 Floating point arithmetic . . . . . . . . . . . . . . . . . . .


3.1.3 Mixed mode arithmetic . . . . . . . . . . . . . . . . . . . .
Relational and Logical Operators . . . . . . . . . . . . . . . . . .
3.2.1 Relational Operators . . . . . . . . . . . . . . . . . . . . . .
3.2.2 Logical Operators . . . . . . . . . . . . . . . . . . . . . . .
Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . .
3.3.1 Simple Assignment . . . . . . . . . . . . . . . . . . . . . . .
3.3.2 Compound Assignment . . . . . . . . . . . . . . . . . . . .
Increment and Decrement Operators . . . . . . . . . . . . . . .
3.4.1 Side Effects of the Increment and Decrement Operators
Bit Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.5.1 Bit-Shift Operators . . . . . . . . . . . . . . . . . . . . . . .
3.5.2 Bit Logical Operators . . . . . . . . . . . . . . . . . . . . . .
Cast Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.6.1 Casting Floating-Point Values to Integers . . . . . . . . . .
Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . .
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

3-3
3-3
3-3
3-3
3-4
3-6
3-6
3-6
3-7
3-7
3-8
3-8
3-9
3-10
3-11
3-11
3-13
4-1
4-1
4-1
4-2
4-4
4-4
4-6
4-7
4-8

4 Selections
4.1 Statements and Block . . . . . . . . . .
4.2 if statement . . . . . . . . . . . . . . .
4.3 if - else statement . . . . . . . . . .
4.4 switch statement . . . . . . . . . . . .
4.4.1 Evaluation of switch statement
4.5 else - if statement . . . . . . . . . .
4.6 Conditional Expressions . . . . . . . . .
4.7 Exercises . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

5 Repetition
5.1 Concept of a loop . . . . .
5.2 Pretest and PostTest Loop
5.3 Loops in C . . . . . . . . . .
5.4 while Loop . . . . . . . . .
5.5 do..while Loop . . . . . . .
5.6 for Loop . . . . . . . . . . .
5.7 continue Statement . . . .
5.8 Exercises . . . . . . . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

5-1
. 5-1
. 5-1
. 5-3
. 5-3
. 5-5
. 5-6
. 5-9
. 5-10

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

6 Functions
6.1 Top-Down Design . . . . . . . . .
6.2 Functions in C . . . . . . . . . . .
6.2.1 Advantages of Functions
6.3 User-Defined Functions . . . . . .

.
.
.
.
.
.
.
.

.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

6-1
6-1
6-1
6-2
6-2

Table of Content
6.4 Recursive . . . . . . . .
6.5 Parameter Passing . .
6.5.1 Pass by Value .
6.5.2 Pass by Address
6.6 Math Library . . . . . .
6.7 Exercises . . . . . . . .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

. 6-6
. 6-7
. 6-7
. 6-8
. 6-9
. 6-10

CHAPTER 1
Introduction

1.1 Lesson Plan


Delivery Methods
Lecture: 1 hour.
Lab. Work (CAD/CAE Lab): 3 hours.
Assessment Scheme
Type of Assessments

Weight

Where to do

Test 1 and Test 2

30%

On computer

Assignments and Group Project

30%

Final Examination
40%
Examination Hall
Ran cangan Pengajaran dan Pembelajaran

1.2 Computer system


What is computer?
A computer is an automatic device that performs calculations, makes decisions,
and has capacity for storing and processing vast amounts of data. A computer
has two main parts: hardware and software
Computer Hardware
Hardware is the electronic and mechanical parts of the computer including:
Input device: Keyboard, Mouse, Scanner, Touch screener, Pen or stylus
Central Processing Unit (CPU). It executes instructions (arithmetic operations)
Primary storage or main memory: RAM
Secondary storage: HD, FD, CD,DVD
Output device:Monitor, Printer, Plotter, Speaker
Computer Software
Two categories: System software and Application software
System software: it manages the H/W resources and performs processing
tasks. Three classes :

1-1

1 Introduction
1. Operating system: it provides services such as a user interface, files and
database access and communication systems.
2. System support software: System utilities such as disk format.
3. System development softwares: Interpreters/compilers that convert programs into machine language. Assembler, C, C++, Basic, Java, etc.
Application software: word processors, DB management systems, CAD/CAE.

1.3 Computer programming


To write a program for a computer, we must use a computer language or a programming language.
Machine language: Each computer has its own machine language consisting of 0s and 1s program. Not readable for human being.
Symbolic language:
Low-level language/Assembly language: Assembler
High-level language/Compiler: Fortran, Pascal, C, C++
Natural language: in development phase
Computer programming (often shortened to programming or coding) is the
process of designing, writing, testing, debugging / troubleshooting, and maintaining the source code of computer programs. This source code is written in a
programming language.

1.4 Software development method


Specify problem
Analyze problem
Design algorithm
Implement algorithm (write a C program)
Test and verify program
Maintain and update program
Algorithm
A set of instructions for solving a problem, or, an ordered sequence of unambiguous and well-defined instructions that performs some task and halts in finite time
(Al Kho-war-iz-mi a 9th century Persian mathematician).
Algorithm
Three Catagories of Algorithmic Operations

1-2

1.5 Algorithm and Pseudo code


sequential operations - instructions are executed in order
conditional (question asking) operations - a control structure that asks a
true/false question and then selects the next instruction based on the answer
iterative operations (loops) - a control structure that repeats the execution
of a block of instructions
How to represent algorithms?
Use natural languages: too verbose
Use formal programming languages: too low level, complicated syntax of
programming language
Pseudo-Code: natural language constructs modeled to look like statements
available in many programming languages
Flow chart: a common type of diagram, that represents an algorithm or
process, showing the steps as boxes of various kinds, and their order by connecting these with arrows

1.5 Algorithm and Pseudo code


Pseudo code
Pseudo-Code is simply a numbered list of instructions to perform some task. Pseudocode is best understood by looking at examples.
Example 1
Computing Sales Tax : Pseudo-code the task of computing the final price of an
item after figuring in sales tax. Note the three types of instructions: input (get or
read), process/calculate (=) and output (display)
1. start
2. get price of item
3. get sales tax rate
4. sales tax = price of item * sales tax rate
5. final price = price of item + sales tax
6. display final price
7. halt/end

1-3

1 Introduction
Example 2
Computing Weekly Wages: Gross pay depends on the pay rate and the number
of hours worked per week. However, if you work more than 40 hours, you get paid
time-and-a-half for all hours worked over 40. Pseudo-code the task of computing
gross pay given pay rate and hours worked.
1. start
2. get hours worked
3. if hours worked 40 then
a) gross pay = pay rate * hours worked
4. else
a) gross pay = pay rate * 40 + 1.5 * pay rate *(hours worked - 40)
5. display gross pay
6. halt/end
Example 3
Computing a Quiz Average: Pseudo-code a routine to calculate your quiz average.
1. start
2. get number of quizzes
3. sum = 0
4. count = 0
5. while count < number of quizzes
a) get quiz grade
b) sum = sum + quiz grade
c) count = count + 1
6. average = sum / number of quizzes
7. display average
8. halt/end
Pseudo code construction
Computation/Assignments
"variable" = "expression"

1-4

1.6 Flow chart


Input/Output
get "variable", "variable", ...
display "variable", "variable",
Condition
if "condition"
statement
Iterative
while "condition"
statement
Rules for a pseudo code construction

1. Consist of a statement of instructions in sequence


2. Every step consists of keyword
3. Every step should be written in different step, if continued, thr next row must
be indented
4. if/else for condition, while/do for repetition
5. Every step must contain clear statement and easy to understand
6. Use start for beginning of operation, and end/halt for finishing it.
Exercise
A box has a dimension in height, width, and length. Write a pseudo code to
calculate the volume of the box.
More exercise in the lab work.

1.6 Flow chart


Flow chart
flow chart gives the logical flow of the solution in a diagrammatic form, and provides a plan from which the computer program can be written. The logical flow
of an algorithm can be seen by tracing through the flowchart. Some standard
symbols:

1-5

1 Introduction

Flowchart constructs
The flowchart equivalents for the structured programming constructs are shown
below:

Selection

Sequence
single (if)

Flowchart constructs,cont

1-6

double (if-else)

multiple (switch-case)

1.6 Flow chart

Repetition
while

do..while

for

Examples of a Flow chart


Example 1 and 2 are solved using a flow chart:

Exercises of algorithm constructions


Self exercises
1. Construct a flowchart for the pseudo-code given in example 3.
2. Express an algorithm to get two numbers from the user ( dividend and divisor), testing to make sure that the divisor member is not zero, and displaying
their quotient using a flowchart and a pseudo-code.
y
z = , x 6= 0
x
3. See the formula below:

x if x 0
f (x) =
x if x < 0

1-7

1 Introduction
Write a pseudo-code and the relevant algorithm to solve the function.
4. Follow the instruction given by the tutor for more exercises and assignments.

1-8

CHAPTER 2
Structure of C Programs

2.1 Program Development

A programmer writes a source code in an editor.

The compiler translates it into a machine code (.obj). If any syntax errors
exists, their must be fixed (compiling time).

Together with other object codes, if any, the linker generates an executable
code.

During program execution, error may exist (run time), and correction must
be done at this stage (debugging).

The cycle of modifying the source code, compiling, linking, and running
continues until the program is complete and free of errors.

Errors occurring at compiling time are normal, especially for learners.

2.2 Compiler
In this course, Turbo C is used as the compiler and it works under MS-DOS. It can
be downloaded in internet for free (hopefully). Turbo C supports an Integrated
Development Environment (IDE) and compiler for the C programming language
from Borland.

2-1

2 Structure of C Programs

2.3 Background
Year

Language

Remarks

1960

ALGOL(Algorithmic
Language)

in teaching compiler construction

1967

BCPL (Basic Combined

Compiler writing

Programming
guage

Lan-

1970

System programming (type less)

1972

Combination of BCPL and B

1978

Standard traditional C

Kerninghan and Ritchie

1989

ANSI/ISO C

American National Standards Institute

1990

ISO C

Standard for C

Features of C:
very efficient and fast. This is due to its variety of data types and powerful
operators. It is many time faster than BASIC
a powerful and flexible language which helps system developers to deliver
various complex tasks with ease. C is used for diverse projects as operating
systems, word processors, graphics, spreadsheets, and even compilers for
other languages.
C is popular among professional programmers for programming. Matlab is
an example.
C is highly portable language.
Writing C program with user-defined functions makes program more simple
and easy to understand. Breaking a problem in terms of functions makes
program debugging, maintenance and testing easier.
its ability to extend itself. A C program is basically a collection of various
function supported by C library (also known as header files). We can also
add our own functions to the C library.

2-2

2.4 Structures of a C Program

2.4 Structures of a C Program

A C program (source code) must


have a file extention .c
Every C program must contain minimum a main function. A function
may contain local variables and
statements. The purpose of main
function is for program execution.
return 0 means the resource control
is passed back to the operating system.
Preprocessor directives or precompiler directives are necessary for
preparing the system during program compilation.
Every directive starts with a hash symbol (#).
include<stdio.h> is the most important one that inserts a header
file for formating data in the standard input output devices (keyboard and screen). scanf() and
printf() are defined in this header
file.
Compiler reads a source code from
top downward and left to right.

2.5 Identifiers
Purposes of an identifier in any programming language:
1. To name data and other objects. Every data in a computer is stored at
a unique address. The identifier is also a symbolic representation of data
location.
2. To allow the compiler keep track of the data using the identifier to locate
where the data is stored inside the computer memory. Rule of an identifier:

2-3

2 Structure of C Programs
a) First character must be alphabetic or underscore.
b) It must consist of alphabetic characters (A . . . Z, a . . . z, digits (0 . . . 9), or
underscore (_).
c) The first 31 characters are significant. C is case-sensitive.
d) It can not duplicate a reserved words (keywords).

Valid identifier

a
student_name
_force

Invalid identifier
Name

Comment

$sum

$ is illegal

2name

First char is digit

int

Reserved word

2.6 Data types


A data type defines a set of values and a set of operations that can be applied
on these values. A function has also a data type that returns after its call. Classification of the data types in C language:
Basic data type
Derived data type
User-defined data type
In this course, the emphasis is on the basic data type.
2.6.1 Basic data types
The size of a data type is machine dependent. It can vary from computer to
computer. The most common sizes of the data sizes on 16 bit machine are
shown in table 2.1.
2.6.1.1 Qualifiers
To manage the memory allocation for the basic data type, ANSI C provides qualifiers:
short and long provide a different length for an integer data type. short
is often 16 bits long, and int only either 16 or 32 bits.

2-4

2.7 Variables

Table 2.1: Basic data types


Name

Type

Size in Bytes (bits)

Range of values

Declaration

Integer

int

2 (16)

-32,768 . . . 32,767

int a;

char

1 (8)

-128 . . . 127

char c;

float

4 (32)

231 . . . 231 1

float f;

double

8 (64)

263 . . . 263 1

double d;

void

Generic type

void main()

Character
Floating Point
Double precision floating Point
Void

signed and unsigned may be applied on a character and any integer.


unsigned numbers are always positive or zero.
Qualifier

Memory allocation/Size

Data range

short int

2 Bytes

-32,768 . . . 32,767

long int

4 Bytes

231 . . . 231 1

int

2 Bytes

-32,768 . . . 32,767

unsigned int

2 Bytes

0 . . . 65,535

unsigned char

1 Byte

0 . . . 255

Example
short int a
long

int b
int a;

unsigned int a;
unsigned char a;

2.7 Variables
A variable is a symbolic name for a certain memory location in a computer machine. It has a type and consequently a memory size and a set of operations to
manipulate the data.
2.7.1 Variable definition
Each variable must be first declared and defined before use. Every variable
has a data type for the memory allocation and a set of operations applied
on it.
Defining a variable means creating an object. Examples:

int counter; /* variable definition. */


int sum = 0; /* variable definition with initialization*/
char c = c;

2-5

2 Structure of C Programs
We can initialize a variable at the definition time by an initial value using an
assignment (=) operator.

2.8 Constants
Constants are data values that cannot be changed during the program execution. Every constant has a data type.
2.8.1 Integer constants
Eventhough integers are stored in the binary form, they are simply coded in decimal form. Types of an integer constant are
signed integer, signed long
unsigned integer, unsigned long

Literal

Value

Type

Example

+123

123

int

int sum = +123

-123

-123

int

int sum = -123

-12345L

123,45

long int

long int sum = -12345L

1234LU

1,234

unsigned long int

sum = sum + 1234LU

Omitting the suffix on a literal, it defaults to int. The Suffix L or l is for a long type,
and u or U for the unsigned type.
2.8.2 Floating point constants
Floating point constants are number with decimal parts and stored in memory as
two parts: the significand and the exponent. The default form for float constant
is double. The Suffix F or f is used for a float type, and L or l for long double.

2-6

Literal

Value

Type

Example

0.

0.0

double

double sum = 0.

.0

0.0

double

int sum = .0

-2.0f

-2.0

float

float sum = sum + -2.0f

3.1415926L

3.1415926

long double

sum = sum + 3.1415926L

2.8 Constants
2.8.3 Character constants
A character constant is enclosed in two single quotes (apostrophes) such as y.
The value of a character constant is the numeric value of the character in the
machines character set. For example, in the ASCII (American Standard Codes
for Information Interchange) character set the character constant 0 has the
value 48, which is unrelated to the numeric value 0.
Special characters that begin with a backslash (\) are used for special purposed (escape sequences).

Symbolic name

ASCII char.

Symbolic name

ASCII char.

\0

null

\a

alert (bell)

\b

backspace

\t

horizontal tab

\n

newline

\v

vertical tab

\r

carriage return

\\

backslash

The program below will show the output of a character constant in different formats.
1
2
3
4
5
6
7

#include <stdio.h>
void main (){
char c;
c=d;
printf (\nChar %c in ASCII code
is a %d \n,c,c);
}

The
program
will
display:
Char d in ASCII code is a 100.
The same character constant will
be displayed in different output
formats (%c and %d). There are 255
characters defined in ASCII code.

2.8.4 String constants


A string constant, or string literal, is a sequence of zero or more characters surrounded by double quotes, as in:
I am a string
The quotes are not part of the string, but serve only to delimit it. Technically, a
string constant is an array of characters. The internal representation of a string
has a null character \0 at the end, so the physical storage required is one more
than the number of characters written between the quotes.
Be careful to distinguish between a character constant and a string that contains a single character: x is not the same as x. The former is an integer, used
to produce the numeric value of the letter x in the machines character set. The
latter is an array of characters that contains one character (the letter x) and a
\0.

2-7

2 Structure of C Programs
2.8.5 Defined constants
Another way to designate a constant is to use the preprocessor command define.
Example:

#define SALES_TAX_RATE 0.15

At the compiling time, SALES_TAX_RATE will be replaced by the value 0.15.


There is no semi colon (;) at the end of the preprocessor command. Defined
constants are usually written in capital letters to distinguish with variable names.
2.8.6 Memory constants
A memory constant uses a type qualifier (const) to indicate that tha data cannot be changed. Example:

const float SALES_TAX_RATE = 0.15;


const double PI = 3.1459;

2.8.7 A program example


The program below calculates the area of the circle with a radius as the input.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

/* This program calculates the area of a circle


with the radius as the input.
Author
: Name of student
Matrix
: Students Matrix Number
Seksyen
: S?
Date
: Date of submission
Instructor: Lab instructor/tutor
*/
#include<stdio.h>
#define PI 3.14159
void main(){
const double pi = 3.14159;
double rad, area;
printf(\nWhat is the radius of the circle: );
scanf(%f,&rad);
area = PI * rad * rad;
printf(\nThe area of the circle is: %f\n,area);
area = pi * rad * rad;
printf(\nThe area of the circle is: %f\n,area);
}

2-8

2.9 Formatted Input/Output

2.9 Formatted Input/Output


C uses two different functions to format input and output.
printf()
this function writes the formatted output on monitor/screen. Monitor is considered as an output file.
scanf()
this function red the formatted input from keyboard. Keyboard is defined as
an input file.
To use the functions, you must include a header file stdio.h at the beginning
part of your program, see the program example above.

2.9.1 printf()
printf(format string, data list)
The formatted output printf() requires two parameters:
1. format string
it contains any text data to be printed and instructions for formatting. The
format string is enclosed in a set of double quotation marks (text and field
specification). The field specification for formatting purpose has the syntax:
%<flag><minimum width><precision><size>conversion-code

conversion-code: c for character, d for integer, and f for floating


point.
Size:
it is used to modify the type specified in the conversion code.
There are different sizes:
h: this size is used with integer to indicate that the variable is short
integer.
l: this size is used with integer to indicate that the variable is long
integer.
L: this size is used with floating point number to indicate that the
variable is long double
There is no size for the data types: int, char, and float. Examples:

2-9

2 Structure of C Programs

Size

Code

Type

Example

char

%c

short int

%hd

int

%d

long int

%ld

float

%f

double

%f

long double

%Lf

float in exponential form.

%e

le

long double in exponential form.

%le

float in Exponential form.

%E

width:
It is used to specify the minimum number of positions in the
output. It is useful to align output in column. For a floating point number, the number of decimal places can be specified using a precision
modifier with the format:
.m

where m is number of decimal digits. If width and precision are used, the
width must be larger enough to contain the integral value, the decimal
point, and the number of digits. Examples:
%2hd
%4d
%8ld
%7.2f
%10.3Lf

/*
/*
/*
/*
/*

short integer, 2 print positions */


integer, 4 print positions
*/
long int, 8 positions
*/
float, 7 print positions: nnnn.dd */
long double, 10 positions: nnnnnn.ddd */

flag: If the flag is zero and there is a width specification, then a number will be printed with leading zeros. If the flag is a minus sign (-). then
the data is formatted left justified.
%-8d
%08d

/* decimal, 8 print pos, left-justified */


/* decimal, 8 print pos, leading zeros */

2. data list
The second parameter is the data list to be printed on the monitor with the
format set by the first parameter in the field specification. The data list may
be a constant, variable name, or a combination of them.

2-10

2.10 Formatted input


2.9.2 Output examples
The following examples show the use of printf.
1. printf(%d%c%f,23, z, 4.1)
Display:
23z4.100000
There is no space in the field specification.
2. printf(%d %c %f,23, z, 4.1)
Display:
23 z 4.100000
3. int number1 = 23;
char c = z;
float number2 = 4.1;
printf(%d %c %f,number1, c, number2)
Display:
23 z 4.100000
4. printf(%d\t%c\t%5.1f\n,number1, c, number2)
printf(%d\t%c\t%5.1f\n,107, A, 53.6)
Display:
23
107

z
A

4.1
53.6

5. printf(\%8c

%d\,h,23)

Display:

23

Quotes are printed using escape character (\).

2.10 Formatted input


The standard formatted input in C is scanf(). It requires two parameters : format
string and address list. The format string describes the data and the address list
identifies where the data to be placed in memory. The format string in printf()
can also be applied to scanf().

2-11

2 Structure of C Programs
scanf(format string, address list)
To indicate an address you must prefix the variable name with an address operator, the ampersand (&).
The following rules are applied for using scanf():
1. The conversion operation continues until:
End of file is reached.
The maximum number of characters have been processed.
A whitespace character is found after a digit in a numeric application.
An error is detected.
2. There must be a field specification for each variable to be read.
3. There must be a variable address of the proper type for each field specification.
4. Any character in the format string other than whitespace or a field specification must be exactly matched by the user during the input, otherwise
scanf stops.
2.10.1 Input examples
The following examples show the use of scanf.
1. Input: 214 156 14 z
scanf(%d %d %d %c, &a, &b, &c, &d);
2. Input: 214 156 2.14
scanf(%d %d %d %f, &a, &b, &c);
3. Input: 14/26 15/77
scanf(%2d/2%d %2d/%2d, &a, &b, &c,&d);
4. Input: 20-7-2010
scanf(%d-%d-%d, &a, &b, &c);

2.11 Self exercises


1. Code the variable definitions for each of the following:
a) a character variable named option.
b) an integer variable, sum, initialized to 0.

2-12

2.12 Keywords
c) a floating point variable, product, initialized to 1.
2. Write a C program that calculates the perimeter, the surface area, and
the volume of a cylinder. The input data: the radius and the height of the
cylinder. Use proper data types for each variable, and write on the screen
the value of radius, height, surface area, perimeter, and the volume. The
data output shall be in convenient format.
3. What is the difference between the data type of short, int, and long int,
with respect to:
a) Memory allocation
b) Type format, and
c) The lower and upper data limit?
4. Write a program to verify your answer in question 3 through an addition of
two different integer numbers.
5. To write a constant, C provides two alternatives. You can use a keyword
const or define the constant in the precompiler part using #define. Explain
the difference between them.

2.12 Keywords
The C language contains several keywords or reserved words that cannot be
used for functions, variables, and named constants. They are shown in table 2.2.
Table 2.2: Keywords of C language
auto

extern

sizeof

static

struct

char

switch

continue

if

union

do

long

void

else

while

signed

break

case

float

const

goto

default

int

unsigned

double

register

return

volatile

enum

short

define

main

for
typedef

2-13

2 Structure of C Programs

2.13 ASCII Code Table

Figure 2.1: 7-bit ASCII codes table

2-14

CHAPTER 3
Operators and Expressions

Operators are symbols which take one or more operands or expressions and perform arithmetic or logical computations of data. An expression is a sequence of
operands and operators that reduces to a single value: Example of an expression:

2 + 7

Plus sign (+) is the operator for addition and 2 and 7 are the operands that
receive an action of the operator for an addition. This expression reduces to a
single value (9). C language has a set of operators including:
1 Arithmetic Operators
2 Relational and Logical Operators
3 Assignment Operators
4 Increments and Decrement Operators
5 Conditional Operators
6 Bit Operators
There is no limit to the number of operator and operand sets that may be combined to form an expression. The only rule is that, when they have been evaluated the result is a single value that represents the expression.

3.1 Arithmetic Operators


All the basic arithmetic operations can be carried out in C. All the operators
have almost the same meaning as in other languages. Both unary and binary
operations are available in C language. Unary operations operate on a singe
operand, therefore the number 5 when operated by unary will have the value
-5.

3-1

3 Operators and Expressions


3.1.1 Integer Arithmetic
When an arithmetic operation is performed on two whole numbers or integers
than such an operation is called as integer arithmetic. It always gives an integer
as the result. In integer division the fractional part is truncated.
Let x = 27 and y = 5 be 2 two integer numbers. Then the integer operation leads
to the results shown in Table 3.1. The modulus operator (%) is valid only for integer
type.
Table 3.1: Integer Arithmetic Operators

Operator

Use for

Example
(x = 27, y = 5)

Result/Remark

Addition

x+y

32

Subtraction

x-y

22

Multiplication

x*y

135

Division

x/y

Modulo
(Remainder of an integers
division)

x%y

2 (2 = 27 5 5).

Program example:
1
2
3
4
5
6
7
8
9
10
11
12
13

#include<stdio.h>
#include<conio.h>
/* tell the compiler the start of the program */
void main(){
/* declaration of variables */
int numb1, num2, sum, sub, mul, div, mod;
clrsc();/* make screen clear */
scanf (%d %d
T, &num1, &num2); /*inputs the operands */
sum = num1+num2; /*addition of numbers and storing in sum.*/
printf(\n The sum is = %d,sum);/*display the output */
sub = num1-num2; /*subtraction of numbers and storing in sub.*/

3-2

3.2 Relational and Logical Operators


14
15
16
17
18
19
20
21
22
23
24
25 }

printf(\n The difference is = %d,sub);/*display the output */


mul = num1*num2; /*multiplication and storing in mul. */
printf(\n The product is = %d,mul);/*display the output */
div = num1/num2; /*division of numbers and storing in div. */
printf(\n The division is = %d,div);/*display the output */
mod = num1%num2; /*modulus of numbers and storing in mod. */
printf(\n The modulus is = %d,mod);/*display the output */
getch();

3.1.2 Floating point arithmetic


When an arithmetic operation is preformed on two real numbers or fraction numbers such an operation is called floating point arithmetic. The floating point results
can be truncated according to the properties requirement. The remainder operator (modulo) is not applicable for floating point arithmetic operands. Example,
Let x = 14.0 and y = 4.0 then:
x + y = 18.0
x y = 10.0
x y = 56.0
x/y = 3.50
3.1.3 Mixed mode arithmetic
When one of the operand is real and other is an integer and if the arithmetic
operation is carried out on these 2 operands then it is called as mixed mode
arithmetic. If any one operand is of real type then the result will always be real
thus 15/10.0 = 1.5.

3.2 Relational and Logical Operators


3.2.1 Relational Operators
A simple relational expression contains only one relational operator and takes the
following form:
expr_1 RelationalOperator expr_2

3-3

3 Operators and Expressions

Table 3.2: Relational Operators


Operator

<
<=
>

Meaning

is less than
is less than or equal to
is greater than
than

or

Example
(x = 1, y = 2)

Result/ Remark

1 < 2

TRUE

1 <= 2

TRUE

1 > 2

FALSE

1 >= 2

FALSE

>=

is greater
equal to

==

is equal to

1 == 2

FALSE

!=

is not equal to

1 != 2

TRUE

Relational expressions are used in decision making statements of C language


such as if, while and for statements to decide the course of action of a running process. Table 3.2 shows the relational operators defined in C with the corresponding meaning along with the relational examples.
C has no logical data type with values of TRUE or FALSE. Instead, the value of
zero (0) is used to represent the logical value FALSE, and one (1) is for TRUE. The
expression such as 1 < 2 has a value of 1.
3.2.2 Logical Operators
C has three logical operators for comparing or evaluating the logical and relational expressions. The common way to show the logical relationships in in a truth
table as shown in Table 3.3.
Examples of the logical operators in the C expressions are given in table 3.4. The
program example for the use of the relational operators is shown in the following
source code.
1
2
3
4
5
6
7

#include<stdio.h>
#include<conio.h>
/* tell the compiler the start of the program
int main(){
//declaration of variables
int x,y,z;
x = 2; y = 20;

3-4

*/

3.2 Relational and Logical Operators

Table 3.3: Logical Operators Truth Table


Operator

AND

x AND y

false

false

false

false

true

false

true

false

true

true

Operator

x OR y

false

false

false

false

true

true

false

true

false

true

true

true

true

true

OR

Operator
NOT

NOT x

false

true

true

false

Table 3.4: Examples of Logical Operators in C


a

Expr1

Expr2

Expr1 Operator Expr2

a < b

10

20

x == y

a < b && x == y

1 && 0

a < b || x == y

Value

1 || 0

8
9
10
11
12
13
14
15
16
17
18
19

clrscr();/* make screen clear */


z = x + y; /*arithmetic addition */
printf(
S\n %d + %d = %d
T, x,y,z); /*display x+y=z */
/* relational operator */
z = (x < y);
printf(
S\n %d < %d = %d
T, x,y,z); /* display x<y = z */
z = x == y;

3-5

3 Operators and Expressions


20
21
22
23 }

printf(
S\n %d < %d == %d
T, x,y,z); /*display x == y = z*/
getch();/* hold on screen before enter */
return 0;
/* end of program */
The output of the program example is:
2 + 20 = 22
2 < 20 = 1
2 == 20 = 0

3.3 Assignment Operators


Assignment expression evaluates the operand on the right hand side of the operator (=) and places its value in the variable on the left. The assignment expression
has a value and a result.
3.3.1 Simple Assignment
This is a assignment form found in algebraic expression. Examples of the assignment statements:
a = b;

z = x * y;

i = i + 1;

The left-hand side operand in an assignment expression must be a single variable. So, it is not allowed to write x * y = z, why?.
3.3.2 Compound Assignment
Compound assignment is a shorthand notation for a simple assignment. It requires that the left operand be repeated as part of the right expression. There
are five compound assignment operators defined in C.
Table 3.5: Compound Assignments

3-6

Compound Assignment

Equivalent simple assignment

x *= y

x = x * y

x /= y

x = x / y

x += y

x = x + y

x -= y

x = x - y

x %= y

x = x % y

3.4 Increment and Decrement Operators

Table 3.6: Increment and Decrement Operators


Postfix Form

Meaning

Prefix Form

Meaning

a++

Use a first before increment by 1

++a

Increment a first, before use.

a--

Use a first before


decrement by 1

--a

Decrement a first, before use.

If a compound assignment is used with a binary expression, the binary expression is evaluated first. Example:
x *= y - 2
is evaluated as:
x *= x * (y - 2)

3.4 Increment and Decrement Operators


An increment or decrement expression is an unary expression. It has one operator and one operand. The increment operator (++) adds 1 to its operand. The
decrement operator (--) subtracts 1 from its operand. The operand must be a
scalar value and it is illegal to increment or decrement a constant, structure, or
union.
The postfix increment and decrement operators fetch the current value of the
variable and store a copy of it in a temporary location. The compiler then increments or decrements the variable. The temporary copy, which has the variables
value before it was modified, is used in the expression. In many cases, you are
interested only in the side effect, not in the result of the expression. In these instances, it doesnt matter whether you use postfix or prefix.
You need to be careful, however, when you use the increment and decrement
operators within an expression.
3.4.1 Side Effects of the Increment and Decrement Operators
The increment and decrement operators and the assignment operators cause
side effects. That is, they not only result in a value, but they change the value of
a variable as well. A problem with side effect operators is that it is not always possible to predict the order in which the side effects occur. Consider the following
statement:

3-7

3 Operators and Expressions

x *= j * j++;
If j equals 3, what will be the value of x?. It is advisable not to use such an
expression. Examples:
i
j
i
j

=
=
=
=

k--;
l++;
--k;
++l;

/*
/*
/*
/*

Stores the
Stores the
Decrements
Increments

value of k in
value of l in
k then stores
l then stores

i then decrements k. */
j then increments l. */
the new value of k in i. */
the new value of l in j. */

The following program demonstrates the uses both prefix and postfix increment
and decrement operators:
1 #include <stdio.h>
2 int main(){
3
int j = 5, k = 5, l = 5, m = 5;
4
printf("j: %d\t k: %d\n", j++, k--);
5
printf("j: %d\t k: %d\n", j, k);
6
printf("l: %d\t m: %d\n", ++l, --m);
7
printf("l: %d\t m: %d\n", l, m);
8
return 0;
9 }
The output of the program is as follows:
j:
j:
l:
l:

5
6
6
6

k:
k:
m:
m:

5
4
4
4

The output shows that the initial values of j and k are used in the first printf().
They also show that l and m are incremented and decremented, respectively,
before the third printf() call.

3.5 Bit Operators


The bit operators access specific bits in an object. ANSI C supports the usual six
bit operators, which can be grouped into shift operators and logical operators.
3.5.1 Bit-Shift Operators
The << and >> operators shift an integer left or right respectively. The operands
must have integer type, and all automatic promotions are performed for each
operand. For example, the program fragment:
short int to_the_left = 53, to_the_right = 53;

3-8

3.5 Bit Operators

Table 3.7: Truth Table for Bitwise Logical AND Operator


Bit of Operand1

Bit of Operand2

AND Relation

Result

0 AND 0

0 AND 1

1 AND 0

1 AND 1

short int left_shifted_result, right_shifted_result;


left_shifted_result = to_the_left << 2;
right_shifted_result = to_the_right >> 2;
sets left_shifted_result to 212 and right_shifted_result to 13. The
results are clearer in binary:
0000000000110101
0000000011010100
0000000000001101

53
212 /* 53 shifted left 2 bits */
13 /* 53 shifted right 2 bits */

Shifting to the left is equivalent to multiplying by powers of two:


x << y is equivalent to x 2y .
Shifting non-negative integers to the right is equivalent to dividing by powers of
2:
x
x >> y is equivalent to y .
2
Make sure that the right operand is not larger than the size of the object being
shifted.
3.5.2 Bit Logical Operators
The logical bitwise operators are similar to the Boolean operators, except that
they operate on every bit in the operand(s). For instance, the bitwise AND operator (&) compares each bit of the left operand to the corresponding bit in the
righthand operand. If both bits are 1, a 1 is placed at that bit position in the result.
Otherwise, a 0 is placed at that bit position.
Bitwise AND Operator (&)
The bitwise AND operator performs logical operations on a bit-by-bit level
using the following truth table: The following example shows the use of the
bitwise logical AND operator.

3-9

3 Operators and Expressions

Operand

Bit Representation

53

00 11 01 01

50

00 11 00 10

53 & 50

00 11 00 00

Bitwise Inclusive (|) OR


The bitwise inclusive OR operator (|) places a 1 in the resulting values bit
position if either operand has a bit set at the position. Example:
Operand

Bit Representation

53

00 11 01 01

50

00 11 00 10

53 | 50

00 11 01 11

Bitwise exclusive OR (^)


The bitwise exclusive OR (XOR) operator (^) sets a bit in the resulting values
bit position if either operand (but not both) has a bit set at the position.
Example:
Operand

Bit Representation

53

00 11 01 01

50

00 11 00 10

53 ^ 50

00 00 01 11

Bitwise Complement (~)


The bitwise complement operator (~) reverses each bit in the operand. An
example:
Operand

Bit Representation

53

00 11 01 01

~53

11 00 10 10

3.6 Cast Operator


To cast a value means to explicitly convert it to another data type. The syntax of
a cast operator has the form:

3-10

3.7 Operator Precedence


( Data Type ) expression
For example, given the two definitions:
int y = 5;
float x;
The following cast operation casts the value of y to float:
x = (float) y; /* x now equals 5.0 */

3.6.1 Casting Floating-Point Values to Integers


Casting a floating-value to an integer is made by by truncating the fractional
part of the number. For example, the floating-point value 3.712 is converted to
the integer 3, and the floating-point value -504.2 is converted to -504. Another
examples:
float f = 3.700, f2 =
(int)f
=>
(unsigned int)f =>
(char)f
=>
(int)f2
=>
(unsigned int)f2 =>
(char)f2
=>
(int)f3
=>
(unsigned int)f3 =>
(char)f3
=>

-502.2, f3 = 7.35e9;
3
3
3
-502 in decimal fffffe0a in hex
4294966794 in decimal
10 in decimal 0a in hex
run-time error
run-time error
run-time error

Converting a large float to a char produces unpredictable results if the rounded


value cannot fit in one byte. If the value cannot fit in four bytes, the run-time system issues an overflow error.

3.7 Operator Precedence


Precedence is the order in which the compiler groups operands with operators.
The C compiler evaluates certain operators and their operands before others. If
operands are not grouped using parentheses, the compiler groups them according to its own rules. The table 3.8 lists the common used C operator precedence
in highest to lowest precedence:

3-11

3 Operators and Expressions

Table 3.8: Operator Precedence with a highest to lowest order


Class of Operator

Operators

Grouping

primary

() [] ->

L to R

unary

(type casting)
sizeof
& (address of)
* (dereference)
- (reverse sign)
~
!
++
--

R to L

multiplicative

* / %

L to R

additive

L to R

shift

<<

relational

< <= > >=

equality

==

L to R

>>

left to right
L to R

=!

bitwise AND

&

L to R

logical AND

&&

L to R

logical OR

||

L to R

conditional

?:

R to L

assignment

=
/=
<<=

comma

3-12

+=
%=
&=

-=
>>=
^=

*=
R to L
|=
R to L

3.8 Exercises

3.8 Exercises
1 Relational operators
Given the following declaration:
int j = 0, m = 1, n = 1;
float x = 2.5, y = 0.0;
Expression

Equivalent Expressions

j > m
m / n < x

Result

j > m

(m / n) < x

j <= m >= n

j <= x == m

-x + j == y > n > m

x += (y >= n)

++j == m != y * 2

Replace the ? sign in each row with the equivalent expression and evaluate
it to to get the right result.
2 Write a program that coverts and prints a user-supplied measurement in
inches into:
(a) foot (12 inches)
(b) yard (36 inches)
(c) centimeter (25.4/inch)
(d) meter (39.37 inches)
3 Given the pseudocode below, write a C program that executes it. Use
floating-point data types for all values.
1
2
3
4
5
6
7

read x
read y
compute
compute
compute
display
display

p = x
s = x
total
x and
total

* y
+ y
= s^2 + p * (s - x) * (p + y)
y

3-13

3 Operators and Expressions


4 Write a C program code for the question 1 to verify your answer.
5 Logical operators
Given the following declaration:
int j = 0, m = 1, n = 1;
float x = 2.5, y = 0.0;
Expression
j && m
j < m && n < m
m + n || !j

Equivalent Expressions

Result

(j) && (m)

(j < m) && (n < m)

(m + n) || (!j)

x * 5 && 5 || m / n

j <= 10 && x >= 1 && m

!x || !n || m+n

x * y < j + m || n

(x > y) + !j || n++

(j || m) + (x || ++n)

Replace the ? sign in each row with the equivalent expression and evaluate
it to to get the right result.
6 Write a C program code for the question 5 to verify your answer.

3-14

S-ar putea să vă placă și