chapter1 6

75
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

Upload: alish-al-shahab

Post on 13-Jan-2015

1.538 views

Category:

Documents


0 download

DESCRIPTION

BTI10202/BTI1022DTI2143

TRANSCRIPT

Page 1: Chapter1 6

UTHM Sem I 2010/11

Lecture Notes

Computer Programming

BTI 1022

Lecturer:Winardi Sani, Dipl.-Ing.

Tutors:

Imran bin RazaliMuhamad Zaini bin Yunos

Sharifah Z.R. Bt Syed AhmadFaizul Amin Anuar

Faculty of Mechanical EngineeringUniversiti Tun Hussein Onn Malaysia

Page 2: Chapter1 6
Page 3: Chapter1 6

Table of Content

1 Introduction 1-11.1 Lesson Plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11.2 Computer system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11.3 Computer programming . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21.4 Software development method . . . . . . . . . . . . . . . . . . . . . . 1-21.5 Algorithm and Pseudo code . . . . . . . . . . . . . . . . . . . . . . . . 1-31.6 Flow chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5

2 Structure of C Programs 2-12.1 Program Development . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12.2 Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12.3 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22.4 Structures of a C Program . . . . . . . . . . . . . . . . . . . . . . . . . . 2-32.5 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-32.6 Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4

2.6.1 Basic data types . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-42.6.1.1 Qualifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4

2.7 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-52.7.1 Variable definition . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5

2.8 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-62.8.1 Integer constants . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-62.8.2 Floating point constants . . . . . . . . . . . . . . . . . . . . . . . 2-62.8.3 Character constants . . . . . . . . . . . . . . . . . . . . . . . . . 2-72.8.4 String constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-72.8.5 Defined constants . . . . . . . . . . . . . . . . . . . . . . . . . . 2-82.8.6 Memory constants . . . . . . . . . . . . . . . . . . . . . . . . . . 2-82.8.7 A program example . . . . . . . . . . . . . . . . . . . . . . . . . 2-8

2.9 Formatted Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-92.9.1 printf() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-92.9.2 Output examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11

2.10 Formatted input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-112.10.1 Input examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12

2.11 Self exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-122.12 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-132.13 ASCII Code Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14

3 Operators and Expressions 3-13.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1

3.1.1 Integer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2

3

Page 4: Chapter1 6

Table of Content

3.1.2 Floating point arithmetic . . . . . . . . . . . . . . . . . . . . . . 3-33.1.3 Mixed mode arithmetic . . . . . . . . . . . . . . . . . . . . . . . 3-3

3.2 Relational and Logical Operators . . . . . . . . . . . . . . . . . . . . . 3-33.2.1 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . 3-33.2.2 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4

3.3 Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-63.3.1 Simple Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . 3-63.3.2 Compound Assignment . . . . . . . . . . . . . . . . . . . . . . . 3-6

3.4 Increment and Decrement Operators . . . . . . . . . . . . . . . . . . 3-73.4.1 Side Effects of the Increment and Decrement Operators . . . 3-7

3.5 Bit Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-83.5.1 Bit-Shift Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 3-83.5.2 Bit Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . 3-9

3.6 Cast Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-103.6.1 Casting Floating-Point Values to Integers . . . . . . . . . . . . . 3-11

3.7 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-113.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13

4 Selections 4-14.1 Statements and Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14.2 if statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14.3 if - else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-24.4 switch statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4

4.4.1 Evaluation of switch statement . . . . . . . . . . . . . . . . . . 4-44.5 else - if statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-64.6 Conditional Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-74.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8

5 Repetition 5-15.1 Concept of a loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15.2 Pretest and Post–Test Loop . . . . . . . . . . . . . . . . . . . . . . . . . 5-15.3 Loops in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-35.4 while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-35.5 do..while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-55.6 for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-65.7 continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-95.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10

6 Functions 6-16.1 Top-Down Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16.2 Functions in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1

6.2.1 Advantages of Functions . . . . . . . . . . . . . . . . . . . . . . 6-26.3 User-Defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2

4

Page 5: Chapter1 6

Table of Content

6.4 Recursive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-66.5 Parameter Passing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7

6.5.1 Pass by Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-76.5.2 Pass by Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8

6.6 Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-96.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10

5

Page 6: Chapter1 6
Page 7: Chapter1 6

CHAPTER 1

Introduction

1.1 Lesson Plan

Delivery Methods

• Lecture: 1 hour.

• Lab. Work (CAD/CAE Lab): 3 hours.

Assessment SchemeType of Assessments Weight Where to do

Test 1 and Test 2 30% On computer

Assignments and Group Project 30%

Final Examination 40% Examination HallRan 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 computerhas two main parts: hardware and software

Computer HardwareHardware 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 opera-tions)

• Primary storage or main memory: RAM

• Secondary storage: HD, FD, CD,DVD

• Output device:Monitor, Printer, Plotter, Speaker

Computer SoftwareTwo categories: System software and Application software

• System software: it manages the H/W resources and performs processingtasks. Three classes :

1-1

Page 8: Chapter1 6

1 Introduction

1. Operating system: it provides services such as a user interface, files anddatabase access and communication systems.

2. System support software: System utilities such as disk format.

3. System development softwares: Interpreters/compilers that convert pro-grams 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 pro-gramming language.

• Machine language: Each computer has its own machine language consist-ing 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 theprocess of designing, writing, testing, debugging / troubleshooting, and main-taining the source code of computer programs. This source code is written in aprogramming 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

AlgorithmA set of instructions for solving a problem, or, an ordered sequence of unambigu-ous and well-defined instructions that performs some task and halts in finite time(Al Kho-war-iz-mi a 9th century Persian mathematician).

AlgorithmThree Catagories of Algorithmic Operations

1-2

Page 9: Chapter1 6

1.5 Algorithm and Pseudo code

• sequential operations - instructions are executed in order

• conditional (”question asking”) operations - a control structure that asks atrue/false question and then selects the next instruction based on the an-swer

• iterative operations (loops) - a control structure that repeats the executionof a block of instructions

How to represent algorithms?

• Use natural languages: too verbose

• Use formal programming languages: too low level, complicated syntax ofprogramming language

• Pseudo-Code: natural language constructs modeled to look like statementsavailable in many programming languages

• Flow chart: a common type of diagram, that represents an algorithm orprocess, showing the steps as boxes of various kinds, and their order by con-necting these with arrows

1.5 Algorithm and Pseudo code

Pseudo codePseudo-Code is simply a numbered list of instructions to perform some task. Pseudo-code is best understood by looking at examples.

Example 1Computing Sales Tax : Pseudo-code the task of computing the final price of anitem after figuring in sales tax. Note the three types of instructions: input (get orread), 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

Page 10: Chapter1 6

1 Introduction

Example 2Computing Weekly Wages: Gross pay depends on the pay rate and the numberof hours worked per week. However, if you work more than 40 hours, you get paidtime-and-a-half for all hours worked over 40. Pseudo-code the task of computinggross 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 3Computing a Quiz Average: Pseudo-code a routine to calculate your quiz aver-age.

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

Page 11: Chapter1 6

1.6 Flow chart

Input/Outputget "variable", "variable", ...display "variable", "variable",

Conditionif "condition"statement

Iterativewhile "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 mustbe 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.

ExerciseA box has a dimension in height, width, and length. Write a pseudo code tocalculate the volume of the box.More exercise in the lab work.

1.6 Flow chart

Flow chartflow chart gives the logical flow of the solution in a diagrammatic form, and pro-vides a plan from which the computer program can be written. The logical flowof an algorithm can be seen by tracing through the flowchart. Some standardsymbols:

1-5

Page 12: Chapter1 6

1 Introduction

Flowchart constructs

The flowchart equivalents for the structured programming constructs are shownbelow:

SequenceSelection

single (if) double (if-else) multiple (switch-case)

Flowchart constructs,con’t

1-6

Page 13: Chapter1 6

1.6 Flow chart

Repetition

while do..while for

Examples of a Flow chartExample 1 and 2 are solved using a flow chart:

Exercises of algorithm constructionsSelf 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 divi-sor), testing to make sure that the divisor member is not zero, and displayingtheir quotient using a flowchart and a pseudo-code.

z =y

x, x 6= 0

3. See the formula below:

f(x) =

x if x ≥ 0

−x if x < 0

1-7

Page 14: Chapter1 6

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

Page 15: Chapter1 6

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 errorsexists, their must be fixed (compiling time).

• Together with other object codes, if any, the linker generates an executablecode.

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

• The cycle of modifying the source code, compiling, linking, and runningcontinues 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 canbe downloaded in internet for free (hopefully). Turbo C supports an IntegratedDevelopment Environment (IDE) and compiler for the C programming languagefrom Borland.

2-1

Page 16: Chapter1 6

2 Structure of C Programs

2.3 Background

Year Language Remarks

1960 ALGOL(AlgorithmicLanguage)

in teaching compiler construction

1967 BCPL (Basic Combined Compiler writing

Programming Lan-guage

1970 B System programming (type less)

1972 C 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 powerfuloperators. It is many time faster than BASIC

• a powerful and flexible language which helps system developers to delivervarious complex tasks with ease. C is used for diverse projects as operatingsystems, word processors, graphics, spreadsheets, and even compilers forother languages.

• C is popular among professional programmers for programming. Matlab isan example.

• C is highly portable language.

• Writing C program with user-defined functions makes program more simpleand easy to understand. Breaking a problem in terms of functions makesprogram debugging, maintenance and testing easier.

• its ability to extend itself. A C program is basically a collection of variousfunction supported by C library (also known as header files). We can alsoadd our own functions to the C library.

2-2

Page 17: Chapter1 6

2.4 Structures of a C Program

2.4 Structures of a C Program

• A C program (source code) musthave a file extention .c

• Every C program must contain min-imum a main function. A functionmay contain local variables andstatements. The purpose of mainfunction is for program execution.

• return 0 means the resource controlis passed back to the operating sys-tem.

• Preprocessor directives or precom-piler directives are necessary forpreparing the system during pro-gram compilation. Every direc-tive starts with a hash symbol (#).include<stdio.h> is the most im-portant one that inserts a headerfile for formating data in the stan-dard input output devices (key-board and screen). scanf() andprintf() are defined in this headerfile.

• Compiler reads a source code fromtop 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 ata unique address. The identifier is also a symbolic representation of datalocation.

2. To allow the compiler keep track of the data using the identifier to locatewhere the data is stored inside the computer memory. Rule of an identifier:

2-3

Page 18: Chapter1 6

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), orunderscore (_).

c) The first 31 characters are significant. C is case-sensitive.

d) It can not duplicate a reserved words (keywords).

Valid identifier Invalid identifier

Name Comment

a $sum $ is illegal

student_name 2name First char is digit

_force int Reserved word

2.6 Data types

A data type defines a set of values and a set of operations that can be appliedon these values. A function has also a data type that returns after its call. Classi-fication 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 tocomputer. The most common sizes of the data sizes on 16 – bit machine areshown in table 2.1.

2.6.1.1 Qualifiers

To manage the memory allocation for the basic data type, ANSI C provides qual-ifiers:

• short and long provide a different length for an integer data type. shortis often 16 bits long, and int only either 16 or 32 bits.

2-4

Page 19: Chapter1 6

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;

Character char 1 (8) -128 . . . 127 char c;

Floating Point float 4 (32) −2−31 . . . 231 − 1 float f;

Double precision floating Point double 8 (64) −2−63 . . . 263 − 1 double d;

Void void - Generic type void main()

• 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 Example

short int 2 Bytes -32,768 . . . 32,767 short int a

long int 4 Bytes −2−31 . . . 231 − 1 long int b

int 2 Bytes -32,768 . . . 32,767 int a;

unsigned int 2 Bytes 0 . . . 65,535 unsigned int a;

unsigned char 1 Byte 0 . . . 255 unsigned char a;

2.7 Variables

A variable is a symbolic name for a certain memory location in a computer ma-chine. It has a type and consequently a memory size and a set of operations tomanipulate the data.

2.7.1 Variable definition

• Each variable must be first declared and defined before use. Every variablehas a data type for the memory allocation and a set of operations appliedon 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

Page 20: Chapter1 6

2 Structure of C Programs

We can initialize a variable at the definition time by an initial value using anassignment (=) operator.

2.8 Constants

Constants are data values that cannot be changed during the program execu-tion. Every constant has a data type.

2.8.1 Integer constants

Eventhough integers are stored in the binary form, they are simply coded in dec-imal 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 astwo parts: the significand and the exponent. The default form for float constantis double. The Suffix F or f is used for a float type, and L or l for long double.

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-6

Page 21: Chapter1 6

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 themachine’s character set. For example, in the ASCII (American Standard Codesfor Information Interchange) character set the character constant ’0’ has thevalue 48, which is unrelated to the numeric value 0.

Special characters that begin with a backslash (\) are used for special pur-posed (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 for-mats.

1 #include <stdio.h>

2 void main (){

3 char c;

4 c=’d’;

5 printf (‘‘\nChar %c in ASCII code

6 is a %d \n’’,c,c);

7 }

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

2.8.4 String constants

A string constant, or string literal, is a sequence of zero or more characters sur-rounded by double quotes, as in:’’I am a string’’

The quotes are not part of the string, but serve only to delimit it. Technically, astring constant is an array of characters. The internal representation of a stringhas a null character ’\0’ at the end, so the physical storage required is one morethan the number of characters written between the quotes.

Be careful to distinguish between a character constant and a string that con-tains a single character: ’x’ is not the same as “x”. The former is an integer, usedto produce the numeric value of the letter x in the machine’s character set. Thelatter is an array of characters that contains one character (the letter x) and a’\0’.

2-7

Page 22: Chapter1 6

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. Definedconstants 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 can-not 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 /* This program calculates the area of a circle

2 with the radius as the input.

3 Author : Name of student

4 Matrix : Student’s Matrix Number

5 Seksyen : S?

6 Date : Date of submission

7 Instructor: Lab instructor/tutor

8 */

9 #include<stdio.h>

10 #define PI 3.14159

11 void main(){

12 const double pi = 3.14159;

13 double rad, area;

14 printf(‘‘\nWhat is the radius of the circle: ’’);

15 scanf(‘‘%f’’,&rad);

16 area = PI * rad * rad;

17 printf(‘‘\nThe area of the circle is: %f\n’’,area);

18 area = pi * rad * rad;

19 printf(‘‘\nThe area of the circle is: %f\n’’,area);

20 }

2-8

Page 23: Chapter1 6

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 con-sidered as an output file.

• scanf()

this function red the formatted input from keyboard. Keyboard is defined asan input file.

To use the functions, you must include a header file stdio.h at the beginningpart 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 stringit contains any text data to be printed and instructions for formatting. Theformat string is enclosed in a set of double quotation marks (“text and fieldspecification”). 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 floatingpoint.

• 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 shortinteger.

– l: this size is used with integer to indicate that the variable is longinteger.

– L: this size is used with floating point number to indicate that thevariable is long double

There is no size for the data types: int, char, and float. Examples:

2-9

Page 24: Chapter1 6

2 Structure of C Programs

Size Code Type Example

- c char %c

h d short int %hd

d int %d

l d long int %ld

- f float %f

- f double %f

L f long double %Lf

e float in exponential form. %e

le long double in exponential form. %le

E float in Exponential form. %E

• width: It is used to specify the minimum number of positions in theoutput. It is useful to align output in column. For a floating point num-ber, the number of decimal places can be specified using a precisionmodifier with the format:

.m

where m is number of decimal digits. If width and precision are used, thewidth must be larger enough to contain the integral value, the decimalpoint, and the number of digits. Examples:

%2hd /* short integer, 2 print positions */

%4d /* integer, 4 print positions */

%8ld /* long int, 8 positions */

%7.2f /* float, 7 print positions: nnnn.dd */

%10.3Lf /* long double, 10 positions: nnnnnn.ddd */

• flag: If the flag is zero and there is a width specification, then a num-ber will be printed with leading zeros. If the flag is a minus sign (-). thenthe data is formatted left justified.

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

%08d /* decimal, 8 print pos, leading zeros */

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

2-10

Page 25: Chapter1 6

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 z 4.1

107 A 53.6

5. printf(‘‘\’’%8c %d\’’’’,’h’,23)

Display:

‘‘ h 23’’

Quotes are printed using escape character (\).

2.10 Formatted input

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

can also be applied to scanf().

2-11

Page 26: Chapter1 6

2 Structure of C Programs

scanf(format string, address list)

To indicate an address you must prefix the variable name with an address op-erator, 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 specifi-cation.

4. Any character in the format string other than whitespace or a field spec-ification must be exactly matched by the user during the input, otherwisescanf 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

Page 27: Chapter1 6

2.12 Keywords

c) a floating point variable, product, initialized to 1.

2. Write a C program that calculates the perimeter, the surface area, andthe volume of a cylinder. The input data: the radius and the height of thecylinder. Use proper data types for each variable, and write on the screenthe value of radius, height, surface area, perimeter, and the volume. Thedata 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 oftwo different integer numbers.

5. To write a constant, C provides two alternatives. You can use a keywordconst or define the constant in the precompiler part using #define. Explainthe difference between them.

2.12 Keywords

The C language contains several keywords or reserved words that cannot beused for functions, variables, and named constants. They are shown in table 2.2.

Table 2.2: Keywords of C language

auto extern sizeof break case float

static struct char for const goto

switch continue if typedef default int

union do long unsigned double register

void else return volatile enum short

while signed define main

2-13

Page 28: Chapter1 6

2 Structure of C Programs

2.13 ASCII Code Table

Figure 2.1: 7-bit ASCII codes table

2-14

Page 29: Chapter1 6

CHAPTER 3

Operators and Expressions

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

2 + 7

Plus sign (+) is the operator for addition and 2 and 7 are the operands thatreceive an action of the operator for an addition. This expression reduces to asingle 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 com-bined to form an expression. The only rule is that, when they have been evalu-ated 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 operatorshave almost the same meaning as in other languages. Both unary and binaryoperations are available in C language. Unary operations operate on a singeoperand, therefore the number 5 when operated by unary – will have the value-5.

3-1

Page 30: Chapter1 6

3 Operators and Expressions

3.1.1 Integer Arithmetic

When an arithmetic operation is performed on two whole numbers or integersthan such an operation is called as integer arithmetic. It always gives an integeras 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 leadsto the results shown in Table 3.1. The modulus operator (%) is valid only for integertype.

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 5

%Modulo (Remain-der of an integersdivision)

x%y 2 (2 = 27− 5 ∗ 5).

Program example:

1 #include<stdio.h>

2 #include<conio.h>

3 /* tell the compiler the start of the program */

4 void main(){

5 /* declaration of variables */

6 int numb1, num2, sum, sub, mul, div, mod;

7 clrsc();/* make screen clear */

8 scanf (‘‘%d %dT, &num1, &num2); /*inputs the operands */

910 sum = num1+num2; /*addition of numbers and storing in sum.*/

11 printf(‘‘\n The sum is = %d’’,sum);/*display the output */

1213 sub = num1-num2; /*subtraction of numbers and storing in sub.*/

3-2

Page 31: Chapter1 6

3.2 Relational and Logical Operators

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

1516 mul = num1*num2; /*multiplication and storing in mul. */

17 printf(‘‘\n The product is = %d’’,mul);/*display the output */

1819 div = num1/num2; /*division of numbers and storing in div. */

20 printf(‘‘\n The division is = %d’’,div);/*display the output */

2122 mod = num1%num2; /*modulus of numbers and storing in mod. */

23 printf(‘‘\n The modulus is = %d’’,mod);/*display the output */

24 getch();

25 }

3.1.2 Floating point arithmetic

When an arithmetic operation is preformed on two real numbers or fraction num-bers such an operation is called floating point arithmetic. The floating point resultscan be truncated according to the properties requirement. The remainder oper-ator (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 arithmeticoperation is carried out on these 2 operands then it is called as mixed modearithmetic. If any one operand is of real type then the result will always be realthus 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 thefollowing form:

expr_1 RelationalOperator expr_2

3-3

Page 32: Chapter1 6

3 Operators and Expressions

Table 3.2: Relational Operators

Operator Meaning Example(x = 1, y = 2)

Result/ Re-mark

< is less than 1 < 2 TRUE

<= is less than or equal to 1 <= 2 TRUE

> is greater than 1 > 2 FALSE

>= is greater than orequal to

1 >= 2 FALSE

== is equal to 1 == 2 FALSE

!= is not equal to 1 != 2 TRUE

Relational expressions are used in decision making statements of C languagesuch as if, while and for statements to decide the course of action of a run-ning process. Table 3.2 shows the relational operators defined in C with the cor-responding meaning along with the relational examples.

C has no logical data type with values of TRUE or FALSE. Instead, the value ofzero (0) is used to represent the logical value FALSE, and one (1) is for TRUE. Theexpression 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 rela-tional expressions. The common way to show the logical relationships in in a truthtable as shown in Table 3.3.

Examples of the logical operators in the C expressions are given in table 3.4. Theprogram example for the use of the relational operators is shown in the followingsource code.

1 #include<stdio.h>

2 #include<conio.h>

3 /* tell the compiler the start of the program */

4 int main(){

5 //declaration of variables

6 int x,y,z;

7 x = 2; y = 20;

3-4

Page 33: Chapter1 6

3.2 Relational and Logical Operators

Table 3.3: Logical Operators Truth Table

Operator x y x AND y

false false false

false true false

true false falseAND

true true true

Operator x y x OR y

false false false

false true true

true false trueOR

true true true

Operator x NOT x

false trueNOT

true false

Table 3.4: Examples of Logical Operators in C

a b Expr1 x y Expr2 Expr1 Operator Expr2 Value

1 2 a < b 10 20 x == y a < b && x == y

1 0 1 && 0 0

1 0 a < b || x == y

1 || 0 1

89 clrscr();/* make screen clear */

10 z = x + y; /*arithmetic addition */

11 printf(S\n %d + %d = %dT, x,y,z); /*display x+y=z */

1213 /* relational operator */

14 z = (x < y);

1516 printf(S\n %d < %d = %dT, x,y,z); /* display x<y = z */

1718 z = x == y;

19

3-5

Page 34: Chapter1 6

3 Operators and Expressions

20 printf(S\n %d < %d == %dT, x,y,z); /*display x == y = z*/

21 getch();/* hold on screen before enter */

22 return 0;

23 } /* 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 oper-ator (=) and places its value in the variable on the left. The assignment expressionhas a value and a result.

3.3.1 Simple Assignment

This is a assignment form found in algebraic expression. Examples of the assign-ment statements:

a = b; z = x * y; i = i + 1;

The left-hand side operand in an assignment expression must be a single vari-able. 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 re-quires that the left operand be repeated as part of the right expression. Thereare five compound assignment operators defined in C.

Table 3.5: Compound Assignments

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-6

Page 35: Chapter1 6

3.4 Increment and Decrement Operators

Table 3.6: Increment and Decrement Operators

Postfix Form Meaning Prefix Form Meaning

a++ Use a first before in-crement by 1

++a Increment a first, be-fore use.

a-- Use a first beforedecrement by 1

--a Decrement a first, be-fore use.

If a compound assignment is used with a binary expression, the binary expres-sion 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 oper-ator and one operand. The increment operator (++) adds 1 to its operand. Thedecrement operator (--) subtracts 1 from its operand. The operand must be ascalar value and it is illegal to increment or decrement a constant, structure, orunion.

The postfix increment and decrement operators fetch the current value of thevariable and store a copy of it in a temporary location. The compiler then incre-ments or decrements the variable. The temporary copy, which has the variable’svalue before it was modified, is used in the expression. In many cases, you areinterested only in the side effect, not in the result of the expression. In these in-stances, it doesn’t matter whether you use postfix or prefix.

You need to be careful, however, when you use the increment and decrementoperators within an expression.

3.4.1 Side Effects of the Increment and Decrement Operators

The increment and decrement operators and the assignment operators causeside effects. That is, they not only result in a value, but they change the value ofa variable as well. A problem with side effect operators is that it is not always pos-sible to predict the order in which the side effects occur. Consider the followingstatement:

3-7

Page 36: Chapter1 6

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 anexpression. Examples:

i = k--; /* Stores the value of k in i then decrements k. */

j = l++; /* Stores the value of l in j then increments l. */

i = --k; /* Decrements k then stores the new value of k in i. */

j = ++l; /* Increments l then stores the new value of l in j. */

The following program demonstrates the uses both prefix and postfix incrementand 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: 5 k: 5

j: 6 k: 4

l: 6 m: 4

l: 6 m: 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 sixbit 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 operandsmust have integer type, and all automatic promotions are performed for eachoperand. For example, the program fragment:

short int to_the_left = 53, to_the_right = 53;

3-8

Page 37: Chapter1 6

3.5 Bit Operators

Table 3.7: Truth Table for Bitwise Logical AND Operator

Bit of Operand1 Bit of Operand2 AND Relation Result

0 0 0 AND 0 0

0 1 0 AND 1 0

1 0 1 AND 0 0

1 1 1 AND 1 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. Theresults are clearer in binary:

0000000000110101 53

0000000011010100 212 /* 53 shifted left 2 bits */

0000000000001101 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 of2:x >> y is equivalent to

x

2y.

Make sure that the right operand is not larger than the size of the object beingshifted.

3.5.2 Bit Logical Operators

The logical bitwise operators are similar to the Boolean operators, except thatthey operate on every bit in the operand(s). For instance, the bitwise AND op-erator (&) compares each bit of the left operand to the corresponding bit in therighthand 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 levelusing the following truth table: The following example shows the use of thebitwise logical AND operator.

3-9

Page 38: Chapter1 6

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 (|) ORThe bitwise inclusive OR operator (|) places a 1 in the resulting value’s bitposition 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 value’sbit 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. Anexample:

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 ofa cast operator has the form:

3-10

Page 39: Chapter1 6

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 fractionalpart of the number. For example, the floating-point value 3.712 is converted tothe integer 3, and the floating-point value -504.2 is converted to -504. Anotherexamples:

float f = 3.700, f2 = -502.2, f3 = 7.35e9;

(int)f => 3

(unsigned int)f => 3

(char)f => 3

(int)f2 => -502 in decimal fffffe0a in hex

(unsigned int)f2 => 4294966794 in decimal

(char)f2 => 10 in decimal 0a in hex

(int)f3 => run-time error

(unsigned int)f3 => run-time error

(char)f3 => run-time error

Converting a large float to a char produces unpredictable results if the roundedvalue cannot fit in one byte. If the value cannot fit in four bytes, the run-time sys-tem 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. Ifoperands are not grouped using parentheses, the compiler groups them accord-ing to its own rules. The table 3.8 lists the common used C operator precedencein highest to lowest precedence:

3-11

Page 40: Chapter1 6

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 << >> L to R

relational < <= > >= left to right

equality == = ! L to R

bitwise AND & L to R

logical AND && L to R

logical OR || L to R

conditional ?: R to L

assignment

= += -= *=

/= %= >>=

<<= &= ^= |=R to L

comma , R to L

3-12

Page 41: Chapter1 6

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 Result

j > m j > m 0

m / n < x (m / n) < x 1

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 evaluateit to to get the right result.

2 Write a program that coverts and prints a user-supplied measurement ininches 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. Usefloating-point data types for all values.

1 read x

2 read y

3 compute p = x * y

4 compute s = x + y

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

6 display x and y

7 display total

3-13

Page 42: Chapter1 6

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 Equivalent Expressions Result

j && m (j) && (m) 0

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

m + n || !j (m + n) || (!j) 1

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 evaluateit to to get the right result.

6 Write a C program code for the question 5 to verify your answer.

3-14

Page 43: Chapter1 6

CHAPTER 4

Selections

A selection statement alters a program’s execution flow by selecting one pathfrom a collection based on a specified controlling condition or expression. Usinga selection statement, the order of the computation flow is specified.

4.1 Statements and Block

An expression such as i = 0; or a += i becomes a statement if it is followedby a semicolon. A compound statement or a block consists of a group of state-ments that starts and ends with an curly bracket. Syntatically a block is equivalentto a single statement. Example of a block:

{

i = 0;

a += i;

printf(‘‘%2d : %3d’’,i, a);

}

There is no semicolon after the right curly bracket that indicates the block end.

4.2 if statement

if statement is used for a single selection with the syntax and the correspondingconstruct is as follows:

if ( condition )

statement;

nextStatement;

if statement evaluates the value of condition to select either the statementis executed or not. C executes statement only if condition is true, if false, C fallsthrough to nextStatement without executing the statement. In C, a nonzero value

4-1

Page 44: Chapter1 6

4 Selections

represents true, and a zero value is used to represent a false condition. So, con-dition tests a numeric value, either 0 or nonzero. The following program fragmentcan be used to obtain an absolute value of an integer number by evaluating avalue of x.

x = -2;

if (x < 0) /* (-2 < 0) = (TRUE) = 1 */

x = -x; /* x = -(-2) = 2 */

printf(‘‘x = %3d’’,x); /* display x = 2 */

To remember that the condition must be enclosed in parentheses (). If there aremore than one actions to be performed, they must be grouped into a compoundstatement, that is a pair of curly brackets ({}). Example:

x = -2;

if (x < 0){ /* Compound statement */

x = -x;

printf(‘‘\nx is initially a negative number: %3d’’,x);

}

printf(‘‘\nabsolute value of x = %3d’’,x);

4.3 if - else statement

C implements the double selection with the if - else statement and is consi-dered as the basic decision statement in the computer programming language.The if statement is the simplified form of this statement. The syntax and the logicflow is shown in the figure below:

if ( condition )

statement1;

else

statement2;

nextStatement;

if - else statement makes a decision between two alternatives. The com-puter selects which statement being executed depends on the value of the

4-2

Page 45: Chapter1 6

4.3 if - else statement

condition. If the condition is true (a nonzero value), statement1 is executed,otherwise statement2 is executed. It is impossible to execute both statements inthe same evaluation. Regardless which statement has been executed, the flowwill continue to the nextStatement. Which statement will be executed by thefollowing program fragment?:

char gender;

/* set first gender as a girl */

gender = ’w’

if ( gender == ’m’)

printf(‘‘\n You are a boy.’’);

else

printf(‘‘\n You are a girl.’’);

printf(‘‘\n Thank You.’’);

The use of a compound statement is demonstrated by the following programexample. The program arrangements two different integers always in an ascend-ing order.

1 #include<stdio.h>

2 #include<conio.h>

3 int main(){

4 int a, b, min;

5 clrscr();

6 printf(‘‘\nGive two different numbers:’’);

7 scanf(‘‘%d, %d’’,&a, &b);

8 printf(‘‘%d\t%d’’, a, b);

9 min = a; /* set a minimum */

10 if (b < min){

11 min = b; /* swap the values */

12 b = a;

13 a = min;

14 printf(‘‘\nb is greater than a.’’);

15 printf(‘‘ Change the order.’’);

16 }

17 else

18 printf(‘‘\nThe order remain unchanged.’’);

19 printf(‘‘\nThe ascending order: ’’);

20 printf(‘‘%d\t%d’’, a, b);

21 getch();

22 return 0;

23 }

Input example:a = 20, b = 5

min = 20

if (5 < 20)→ true.The input values mustbe swapped.

min = 5

b = 20

a = 5

Display on thescreen:b is greater thana. Change the or-der.The ascending or-der: 5 20.

The statement ofthe else part is notexecuted.

4-3

Page 46: Chapter1 6

4 Selections

4.4 switch statement

The switch statement is a conditional branching statement that selects amongseveral statements or multiple statements based on constant values. The syntaxand the logic flow of the switch statement is shown as follows:

switch ( expression ){

case constant1:

statement 1; break;

case constant2:

statement 2; break;

default:

statement n;

}

nextStatement;

The expression immediately after the switch keyword must be enclosed in paren-theses and must be an integral expression. The constant following the case key-words must be integral constant expressions; that is, they may not contain vari-ables.

An important feature of the switch statement is that the compiler executesany statements following the selected case label until a break, goto, or returnstatement appears. The break statement explicitly exits the switch construct,passing control to the statement following the switch statement. With a break

statement the program jump out of the switch statement and continues to thenextStatement. Since this is usually what you want, you should almost alwaysinclude a break statement at the end of the statement list following each case

label.

4.4.1 Evaluation of switch statement

The switch expression is evaluated; if it matches one of the case labels, programflow continues with the statement that follows the matching case label. If noneof the case labels match the switch condition, program flow continues at thedefault label, if it exists. No two case labels may have the same value.default in the switch statement is not required an it is an optional label. If

the value of the condition expression does not match with any label, the controltransfers outside of the switch statement.

The following example will display the annual weather depending on the con-dition.

4-4

Page 47: Chapter1 6

4.4 switch statement

char weather;

printf(‘‘\n Enter s,w,a,p for summer, winter,

autumn, or spring:’’);

scanf(‘‘%c’’, &weather);

switch(weather){

case ’s’: printf(‘‘\nIt is summer time’’); break;

case ’w’: printf(‘‘\nIt is winter time’’); break;

case ’a’: printf(‘‘\nIt is autumn time’’); break;

case ’p’: printf(‘‘\nIt is spring time’’); break;

default : printf(‘‘\nYou entered a wrong character!’’);

}

printf(‘‘\nThank you’’);

The following program part demonstrate how to calculate the parking chargebased on the type of vehicle (’c’ for car, ’b’ for bus, and ’t’ for truck) and thehours a vehicle spent in the parking lot. The parking rates are below:

Type of vehicle Rate per hour

car RM 2.00

bus RM 3.00

truck RM 4.00

1 char vehicle;

2 short int hours;

3 float charge;

4 const float CAR_RATE = 2.00;

5 const float BUS_RATE = 3.00;

6 const float TRUCK_RATE = 4.00;

7 printf(‘‘\nEnter c,b,or t for car, bus, and truck,respectively:’’);

8 scanf(‘‘%c’’, &vehicle);

9 printf(‘‘Hours spent: ’’); scanf(‘‘%hd’’, &hours);

10 switch( vehicle ){

11 case ’c’:

12 charge = hours * CAR_RATE; break;

13 case ’b’:

14 charge = hours * BUS_RATE; break;

15 case ’t’:

16 charge = hours * TRUCK_RATE;

17 }

4-5

Page 48: Chapter1 6

4 Selections

18 printf(‘‘\nParking charges: RM %5.2f’’, charge);

4.5 else - if statement

The switch statement works only when the values of the case labels are integer.To handle a multiple selection with a decision on the basis of a value that is notintegral, else - if constructs may be utilized as shown in the figure below:

if (expression 1)

statement 1;

else if (expression 2)

statement 2;

else if (expression 3)

statement 3;

else if (expression n-1)

statement n-1;

else

statement n;

nextStatement;

The sequence of if statements is the most general way of writing a multipledecision. The expressions are evaluated in order. If an expression is true, thestatement associated with it is executed, and this terminates the whole chain.The flow continues then to the nextStatement. As always, the code for eachstatement is either a single statement, or a group of them in braces. The lastelse part handles the “none of the above” or default case where none of theother conditions is satisfied.

Sometimes the trailing else statement n may be used for error checking tocatch an “impossible” condition. To remember that an else is always associatedwith the nearest previous if. The else - if construct is used only when:

• The selection variable is not an integral. The expression has also a booleanvalue, true or false.

• The same variable is being tested in the expression.

The following program fragment demonstrates the use of else - if statementto solve a score – grade relationship problem. You are advised to refer to theassociated flow chart to trace the steps in the source code.

4-6

Page 49: Chapter1 6

4.6 Conditional Expressions

1 /* Score -- Grade Relationship */

2 char grade;

3 short score;

4 scanf(‘‘%hd’’,&score);

5 if (score >= 90)

6 grade = ’A’;

7 else if (score >= 80)

8 grade = ’B’;

9 else if (score >= 70)

10 grade= ’C’;

11 else if (score >= 60)

12 grade = ’D’;

13 else

14 grade = ’F’;

15 printf(’’Grade: %c’’, grade);

16 /* Add the missing parts*/

4.6 Conditional Expressions

C provides an alternative to traditional if else for two way selection using anconditional expression. It has three operands and two operators. Each operandis an expression. The syntax is as follows:

expression ? expr1 : expr2;

The above statement is equivalent to the construct:

if (expression)

expr1;

else

expr2;

Example:

a = 5, b = 10;

result = a < b : a + b; a -b;

What is the value of result?

4-7

Page 50: Chapter1 6

4 Selections

4.7 Exercises

1. If originally x = 0, y = 0 and z = 1, what is the value of x, y and z afterexecuting the following code?

if (z = x < y){

x += 3;

y -= 1;

}

else

x = y++;

2. If originally x = 0, y = 0 and z = 1, what is the value of x, y and z afterexecuting the following code?

switch (x) {

case 0: x = 2;

y = 3;

case 1: x = 4;

default: y = 3;

x = 1;

}

3. Construct a flowchart to find out the minimum and maximum value of threeinteger numbers. Verify your answer by writing the corresponding programsource code and test it.

4. If originally x = 1, y = 3 and z = 0, what is the value of x, y and z afterexecuting the following code?

switch (x) {

case 0: x = 2;

y = 3;

break;

case 1: x = 4; break;

default: y = 3;

x = 1;

}

5. Write a program that sorts three integer numbers in an ascending order.

6. Write a program that, given the type of vehicle (’c’ for car, ’b’ for bus, ’t’ fortruck, and ’m’ for motor cycle) and hours a vehicle spent in the parking lot,displays the parking charge based on the rates shown below:

4-8

Page 51: Chapter1 6

4.7 Exercises

Vehicle Charge rate/hr.

motor cycle RM 1.00

car RM 2.50

bus RM 3.50

truck RM 4.50

Use the preprocesssor command define for the charge rates instead of thememory constant, const. What is the difference between them? If noneof the type of vehicle entered matches with any case label, displays wronginput.

4-9

Page 52: Chapter1 6
Page 53: Chapter1 6

CHAPTER 5

Repetition

Repetition or looping is one of the basic structured programming concepts. Rep-etition shows the power of computers in ability to repeat an operation or a seriesof operations.

5.1 Concept of a loop

The concept of a loop is shown in Figure 5.1.

Figure 5.1: Loop concept

The loop illustrates the statement is always repeated. It never stops. To ensurethat the action ends after the job is done, we must set a certain condition tocontrol the loop. This condition checks after each iteration to see either the jobis done or not. If not, it repeats one more time, and if it is done, it exists the loop.

5.2 Pretest and Post–Test Loop

In pretest loop, the condition is checked before the loop starts and at the be-ginning of each iteration after the first. If the condition is true, the statement isexecuted, and if the test condition is false, the loop is terminated and the controlgoes directly to the nextStatement.

In the post–test loop, the statement is always executed at least once. At theend of every iteration, the condition is tested. If the condition is true, the looprepeats, but if the condition is false, the loop ends, and the control goes to thenextStatement.

Two steps are required in working with a loop.

1. initializationThe purpose of an initialization is to start the loop. In the pretest loop, theinitial value of the test condition must be true. It is done before the firstexecution of the statement.

5-1

Page 54: Chapter1 6

5 Repetition

Figure 5.2: Pretest (left) and Post-Test (right) Loop

2. UpdatingThe purpose of an updating is to repeat the execution of the statement andto change the condition from true to false. If the condition is always true,the loop will be infinite, in other word, the program execution does neverstop.

Figure 5.3: Initialization and Updating for Pretest (left) and Post-Test (right) Loop

Updating is done in each iteration, usually as the last action after the statementexecution. If the the statement in the loop is repeated x times, the updating isalso done x times.

The limit test for a loop can be expressed into two categories:

5-2

Page 55: Chapter1 6

5.3 Loops in C

1. Event-controlled loopIn this loop, the event changes the control condition or expression of theloop from true to false. For example, when reading data, reaching the endof data will change the loop control condition from true to false.

2. Counter-controlled loopWhen we know the number of times an action or an operation is to beexecuted, we use a counter-controlled loop. We must initialize, update,and test the counter. The update can be an increment or decrement.

Figure 5.4: Event- and Counter- controlled Loop

5.3 Loops in C

C language has three loop statements: for, while, and do..while. The first twoare pretest loop, and the later is a post-test loop. All of them can be used forevent-controlled loop and counter-controlled loop. The while and do..while

are the most commonly used for event-controlled loop, and for loop is usuallyused for counter-controlled loop.

5.4 while Loop

The while statement is a pretest loop. The syntax of the while with its corre-sponding flow chart are shown in Figure 5.5.

• expression: Any expression.

• statement: This statement is executed when the expression is true. State-ment can be a single statement or a series of statements that encloses in aparenthesis {}.

5-3

Page 56: Chapter1 6

5 Repetition

while (expression)

statement

nextStatement

Figure 5.5: while Loop and the flow chart

The while statement executes the statements within a loop as long as thespecified condition, expression, is true. The while statement tests expression andif it is true (nonzero), statement is executed. Once expression becomes false (0),execution of the loop stops and the program control goes to the nextStatement.Since expression could be false the first time it is tested, statement may not beperformed even once.A program Example for while loop:

1 #include <stdio.h>

2 int main(void) {

3 char answer, grade;

4 answer = ’y’;

5 printf(’\n\n’’’);

6 while (answer == ’y’ || answer == ’Y’) {

7 printf("Enter student’s grade: ");

8 scanf("%c", &grade);

9 printf("\nComments: ");

10 switch (grade) {

11 case ’A’:

12 case ’a’: printf("Excellent\n"); break;

13 case ’B’:

14 case ’b’: printf("Good\n"); break;

15 default : printf("Invalid grade\n"); break;

16 } /* end switch */

17 printf("\nAgain? ");

18 scanf("%s", &answer);

19 } /* end while loop */

20 }

5-4

Page 57: Chapter1 6

5.5 do..while Loop

If the program is executed, the output will be as follows:

Enter student’s grade: B

Comments: Good

Again? y

Enter student’s grade: A

Comments: Excellent

Again? n

5.5 do..while Loop

The syntax of the do..while with its corresponding flow chart are shown in Figure5.6.

do

statement;

while (expression);

nextStatement

Figure 5.6: do..while Loop and the flow chart

The do statement executes statement within a loop until a specified conditionis satisfied. Unlike the for and while loops, do E while performs statement firstand then tests expression. If expression evaluates to nonzero (true), statementexecutes again, but when expression evaluates to zero (false), execution of theloop stops and the program control goes to the nextStatement. This type ofloop is always executed at least once.

Program Example for do..while Loop

The program example calculates the summation of an integer that a user suppliesand the summation of the squares of that integer. Mathematically, the summa-tion can be expressed as follows:

sum =

n∑i=1

i = 1 + 2 + 3 + . . .+ n

=n ∗ (n+ 1)

2

5-5

Page 58: Chapter1 6

5 Repetition

1 #include <stdio.h>

2 int main(void){

3 int num, sum;

4 char answer;

5 printf("\n ");

6 do {

7 printf("Enter an integer: ");

8 scanf("%d", &num);

9 sum = (num*(num+1))/2;

10 printf("The summation of %d is: %d\n ", num, sum);

11 printf("\nAgain? ");

12 scanf("%c", &answer);

13 }while ((answer != ’n’) && (answer != ’N’));

14 }

If you execute this program, you get the following output:

Enter an integer: 10

The summation of 10 is: 55

Again? y

Enter an integer: 25

The summation of 25 is: 325

Again? n

5.6 for Loop

The for statement is a pretest loop that uses three expressions:

• InitializationThe initialization expression that typically specifies the initial values of vari-ables. It is evaluated only once before the first iteration of the loop.

• Condition controlThe controlling expression determines whether or not to terminate the loop.It is evaluated before each iteration of the loop. If the condition value is anonzero, the statement is executed. If it evaluates to 0, execution of thestatement is terminated and control passes to the nextStatement. Thismeans that if the initial value of condition becomes zero, the statementisnever executed.

• Update expressionThis expression is the increment or decrement expression that typically incre-ments or decrement the variables initialized in initialization part. It is evalu-

5-6

Page 59: Chapter1 6

5.6 for Loop

ated after each iteration of the statement and before the next evaluationof the condition control expression.

Semicolons separate the expressions in the for loop. Each expression is optional,but the semicolons must be included. The syntax of the for with its correspondingflow chart are shown in Figure 5.7.

for (Initial; Condition; Update)

statement;

nextStatement;

Figure 5.7: do..for loop and the flow chart

The for statement can be formulated in while loop and vice versa. The equiv-alent construct in the while loop is given as follows:

Initial;

while (Condition) {

statement;

Update;

}

nextStatement;

Example how to express the for loop with a while is shown in the followingprogram fragment:

for (j = 0; j < 10; j++){

printf(‘‘j = %d\t’’, j);

if (j % 4 == 0) /* new line */

printf(‘‘\n’’);

}

getch();

5-7

Page 60: Chapter1 6

5 Repetition

is the same as the following while loop:

j = 0;

while (j<10){

printf(‘‘j = %d\t’’, j);

if (j % 4 == 0) /* new line */

printf(‘‘\n’’);

j++;

}

getch();

Program Example using for Loop

The following program calculates the permutation of two integer numbers withthe formula:

P (n,m) =

n

m

=n!

(n−m)!

=1 ∗ 2 ∗ . . . ∗ n

1 ∗ 2 ∗ . . . ∗ (n−m)

1 #include <stdio.h>

2 #define SIZE 10

3 int main(void){

4 int n, m, n_total, m_total, perm, i, j;

5 printf("Enter the numbers for the permutation (n things ");

6 printf("taken m at a time)\nseparated by a space: ");

7 scanf("%d %d", &n, &m);

8 n_total = m_total = 1;

9 for (i = n; i > 0; i--) /* compute n! */

10 n_total *= i;

11 for (i = n - m; i > 0; i--) /* compute (n-m)! */

12 m_total *= i;

13 perm = n_total/m_total;

14 printf("P(%d,%d) = %d\n\n", n, m, perm);

15 }

If you execute this program, you get the following output:

Enter the numbers for the permutation (n things taken m at a

time) separated by a space: 4 3

P(4,3) = 24

5-8

Page 61: Chapter1 6

5.7 continue Statement

5.7 continue Statement

continue belongs to the jump statements. The continue statement halts execu-tion of its enclosing for, while, or do/while loop and skips to the next iterationof the loop. In the while and do/while, this means the condition expressionis tested immediately, and in the forloop, the update expression (if present) isevaluated. The effect of the continue statement is illustrated in the Figure 5.8.

Figure 5.8: The continue statement in the loop

The following program fragment calculates the sum of only odd numbers:

const int MAX = 10;

int i, sum = 0;

for (i = 0; i < MAX; i++){

if (i % 2) /* even number? yes, then */

continue; /* jump to i++ */

sum += i;

}

printf(‘‘sum = %3d’’,sum);

5-9

Page 62: Chapter1 6

5 Repetition

5.8 Exercises

1. What would be printed from each of the following program segment?

a) while loop:

x = 12;

while(x > 7){

printf(‘‘%d\n’’, x);

x--;

}

b) for loop:

for (x = 12; x > 7; x--){

printf(‘‘%d\n’’, x);

}

c) do..while loop:

x = 12;

do{

printf(‘‘%d\n’’, x);

x--;

}while(x > 7)

2. What will be printed from the following program segment?

for (x = 10; x >= 1; x--){

for (y = x; y >= 2; y--){

printf(‘‘%3d ’’, x);

printf(’’\n’’);

}

3. Write a program that creates the following pattern:

1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8

1 2 3 4 5 6 7

1 2 3 4 5 6

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

5-10

Page 63: Chapter1 6

5.8 Exercises

4. Write a for loop that will produce each of the following sequences:

a) 6, 8, 10, 12,..., 66

b) 7, 9, 11, 13,..., 67

c) The sum of the numbers between 1 and 15 inclusive

d) The sum of even numbers between 10 and 40 inclusive.

5. Write a program that prompts the user to enter an integer, n, and then nreal numbers. As the numbers are read, the program will calculate the sumand the average of the positive numbers.The program repeats again from the beginning. The program terminatesonly if the user enter an ’n’ or ’N’ as the answer.

6. Euler’s number, e, is used as the base of natural logarithms. It can be ap-proximated using the following formula:

e = 1 +1

1!+

1

2!+

1

3!+

1

4!+ . . .++

1

(n− 1)!+

1

n!

5-11

Page 64: Chapter1 6
Page 65: Chapter1 6

CHAPTER 6

Functions

6.1 Top-Down Design

A program is divided into a main module and its related modules. The divisionof modules proceeds until the module consists only of elemantary processes andcannot be further sibdivided. This process is known as factoring. The top-downdesign is illustrated using a structure chart as shown in Figure 6.1.

Terminology:

• Main Module: Calling module. It has submodules, Module 1, 2, and 3.

• Called Module: Module 1, 2, and 3.Communication between the main module and its submodules is allowedonly through a calling module. If Module 1 needs to send data to Module 2,the data must be passed through the calling module. No communicationtakes place directly between the submodules that do not have a calling–called relationship.

Figure 6.1: Top-down Design

Two techniques are used for the passing data to a module:

1. Pass By ValueIn this technique, a copy of the data is made and the copy is sent to thecalled module. The original data in the calling module cannot be changed.

2. Pass By ReferenceThe calling module sends the address of the data to the called module. Inthis case, the called module can change the original data in the callingmodule.

6.2 Functions in C

• Top-down design is implemented using functions. A C program consists ofone or more functions. One and only one of the functions must be named

6-1

Page 66: Chapter1 6

6 Functions

main. The program always starts and ends with main function. It can callother functions to do specific task. See Figure 6.2.

• A function in C is an independent module. A called function receives con-trol from a calling function. When the called function completes its task, itreturns to the calling function. It mays or may not return a value to the callerfunction. The main function is called by the operating system for programexecution.

Figure 6.2: Structure chart for a C program

• The purpose of a function is to receive zero or more data, operate on it, andreturns at most one data.

6.2.1 Advantages of Functions

• Problems can be factored into understandable and manageable steps.

• Functions provide a reuse code. Once a function is defined, it can be calledanytime required.

• C language provides a rich library for reuse. Example, a math library (math.h)contains lots of standard mathematic functions that make work easier formathematic calculation including sqrt(), log(), cos().

• Functions protect data. Logical data defined in a function are availableonly to the function and while the function is executing. When the function isnot running, the data is not accessible outside. Data in one function cannotbe seen or changed by a function outside its scope.

6.3 User-Defined Functions

Steps working with functions:

6-2

Page 67: Chapter1 6

6.3 User-Defined Functions

1. Function Declaration or prototype declaration.It consists only of a function header. A prototype header has three part:the return type, the function name, and formal parameters list. It terminateswith a semicolon.

Figure 6.3: Prototype declaration

2. Function Definition.It contains the source code for the function and is made up of two parts.

• Function headerIt consists three parts:

– A return type: int, char, short, float, double, or void.

– A function name: A name that complies with the syntax rule for anidentifier.

– The formal parameter list.It is a list of data for the communication purpose with the callingfunction. If there is no data to be passed, keyword void is declared.The formal parameter list defined hereby must be matched withthat as declared in the prototype.

• Function bodyIt contains the local declarations and statements for the function. Thefunction body terminates with a return statement. If void is used forthe return type, it is allowed without return or return with no expres-sion or value.

Figure 6.4: Function definition

6-3

Page 68: Chapter1 6

6 Functions

3. Function CallA function call is a postfix expression and in the calling function, it is at a veryhigh level in the precedence table. If a function call is used as a part of alarger expression, it will be first evaluated. The operand in a function call isthe function name.The actual parameters identify the values to be sent to the called function.They must match in type and order of the formal parameters of the calledfunction. Comma sign is used to separate the value of the parameters.

A program example for the use of functions is shown by modifying the followingcodes into three functions.

1 #include <stdio.h>

2 int main(void){

34 int a, b, c, d, total;

56 /* Input */

7 printf("\n ");

8 printf("\nGive two integer numbers, separate by a comma: ");

9 scanf("%d %d", &a, &b);

10 printf("\nGive two integer numbers, separate by a comma: ");

11 scanf("%d %d", &c, &d);

1213 /* adding the values */

14 tot = a + b + c * d;

1516 /* display message */

17 printf("\n Display result: ");

18 printf("\n ");

1920 printf(" a + b + c *d = %3d", tot);

2122 getch();

23 return 0;

24 }

The program is factored into five functions:

• inputMessage()

• addData()

• multiply()

• displayMessage(), and

• main()

The associated structure chart is illustrated in Figure 6.5.

6-4

Page 69: Chapter1 6

6.3 User-Defined Functions

Figure 6.5: Structure chart of the function example program

1 #include <stdio.h>

2 void inputMessage(void); /* Prototype of functions */

3 int addData(int a, int b);

4 int multiplyData(int a, int b);

5 void displayMessage(void);

67 void inputMessage(void){ /* Definition of function */

8 printf("\n ");

9 printf("\nGive two integer numbers, separate by a comma: ");

10 return ;

11 }

12 int multiplyData(int x, int y){ /* Definition of function */

13 int mul;

14 mul = x * y;

15 return mul;

16 }

17 int addData(int x, int y){ /* Definition of function */

18 int sum;

19 sum = x + y;

20 return sum;

21 }

22 void displayMessage(void){ /* Definition of function */

23 printf("\n Display result: ");

24 printf("\n ");

25 return;

26 }

27 int main(void){ /* Definition of function */

28 int a, b, c, d, tot;

29 /* Input */

30 inputMessage(); /* Function call */

31 scanf("%d %d", &a, &b); /* Function call */

32 inputMessage(); /* Function call */

33 scanf("%d %d", &c, &d); /* Function call */

34 /* adding the values */

35 tot = addData(a, b) + multiplyData(c,d); /* Function call */

36 /* display the values */

37 displayMessage(); /* Function call */

38 getch(); /* Function call */

6-5

Page 70: Chapter1 6

6 Functions

39 printf(" a + b + c *d = %3d", tot);

40 printf()

41 return 0;

42 }

The summation of n integer numbers can be expressed:

sum =

n∑i=1

i = 1 + 2 + 3 + . . .+ n

The implementation in C program is as follows:

1 int summation(int n){

2 int i, sum;

3 sum = 0;

4 for (i = 1; i <= n; i++)

5 sum += i;

6 return sum;

7 }

The program above can only be compiled but it cannot be run. To executethe program we need main function as shown below:

1 #include<stdio.h>

2 int summation(int n); /* prototype */

34 int summation(int n){

5 int i, sum;

6 sum = 0;

7 for (i = 1; i <= n; i++)

8 sum += i;

9 return sum;

10 }

1112 int main(void){

13 int n;

14 printf(‘‘n = ’’,&n);

15 scanf(‘‘%d’’, &n);

16 printf(‘‘The sum of n integers: %d’’, summation(n));

17 getch();

18 return 0;

19 }

6.4 Recursive

Functions can be used recursively. In other words, a function can be called director indirectly. An example for the use of recursive is given through the factorial of

6-6

Page 71: Chapter1 6

6.5 Parameter Passing

n integer numbers:

n! = 1 ∗ 2 ∗ 3 ∗ . . . ∗ n= n ∗ (n− 1)!, with 0! = 1! = 1

The factorial problem can be solved either using one of the tree loops or a recur-sive function as shown as follows:

1 #include<stdio.h>

2 #include<conio.h>

3 int factorial(int ); /* prototype */

45 int factorial(int n){

6 int i;

78 if (n > 1)

9 return n * factorial(n-1); /* recursive */

10 else

11 return 1; /* terminates the recursion */

12 }

1314 int main(void){

15 int n;

16 clrscr();

17 printf(’’n = ’’, &n);

18 scanf(‘‘%d’’, &n);

19 if (n < 0)

20 printf(’’\nNegative number is not allowed!’’);

21 else

22 printf(’’The factorial of n integers: %d’’, factorial(n));

23 getch();

24 return 0;

25 }

6.5 Parameter Passing

Parameters of the calling function can be passed to the called function by twotechniques that are described below.

6.5.1 Pass by Value

So far, all the parameters in the calling user-defined functions have been passedby value. The original values in in the calling function are never changed in thecalled functions because only a copy of the value is passed to the called func-tion. With this mechanism the original data is protected against any modificationoutside the function.

6-7

Page 72: Chapter1 6

6 Functions

6.5.2 Pass by Address

The second mechanism for passing the actual parameters to the called functionis known as pass by address. The address of the original data in the calling func-tion is passed to the called function. The consequence is the called function hasthe chance to change the value because it refer to the same address. How thetwo mechanisms work is described by solving a sorting problem.

Figure 6.6: Swap problem

1 #include<stdio.h>

2 #include<conio.h>

3 void swapByValue(int a, int b ); /* prototype */

4 void swapByAddress(int *a, int *b );

56 void swapByValue(int a, int b ){

7 int temp;

8 temp = a;

9 a = b;

10 b = a;

11 }

1213 void swapByAddress(int *a, int *b ){

14 int temp;

15 temp = *a;

16 *a = *b;

17 *b = *a;

18 }

19 int main(void){

20 int a, b;

21 a = 8, b = 5;

22 clrscr();

23 printf(’’\n%3d %3d ’’, a, b);

24 swapByValue(a, b);

25 printf(’’\n%3d %3d ’’, a, b);

26 swapByAddress(&a, &b);

27 printf(’’\n%3d %3d ’’, a, b);

28 getch();

29 return 0;

30 }

6-8

Page 73: Chapter1 6

6.6 Math Library

6.6 Math Library

The following mathematic functions are found in math.h library.

Function Return type Prototype

ceil double ceil(double number)

exp double exp(double number)

fabs double fabs(double number)

floor double floor(double number)

fmod double fmod(double number1, double number2)

log double log(double number)

log10 double log10(double number)

pow double pow(double number1, double number2)

sqrt double sqrt(double number)

sin double sin(double number)

sinh double sinh(double number)

asin double asin(double number)

cos double cos(double number)

cosh double cosh(double number)

acos double acos(double number)

tan double tan(double number)

tanh double tanh(double number)

atan double atan(double number)

atan2 double atan2(double number1, dounle number2)

6-9

Page 74: Chapter1 6

6 Functions

6.7 Exercises

1. Draw a structure chart for the following program. What output does it pro-duce?

1 #include<stdio.h>

2 #include<conio.h>

3 int funA(int x);

4 int funB(int x);

56 int main(){

7 int a, b, c;

8 a = 10;

9 clrscr();

10 funB(a);

11 b = 5;

12 funA(b);

13 c = funA(b);

14 funB(c);

15 printf(’’\n%3d %3d %3d’’, a, b, c);

16 return 0;

17 }

1819 int funA(int x){

20 return c * x;

21 }

2223 void funB(int x){

24 int y;

25 y = x % 2;

26 x /= 2;

27 printf(’’\n%3d %3d\n’’, x, y);

28 return ;

29 }

2. Write a function to compute the perimeter c of a right angle, see Figure,when a and b given.

c =√

a2 + b2

6-10

Page 75: Chapter1 6

6.7 Exercises

3. Write a function to sort four integer numbers entered by the keyboard indescending order. Example:Input : 2 5 6 1Output: 1 2 5 6

4. Write a C function to calculate the permutation of two integer numbers withthe formula:

P (n,m) =

n

m

=n!

(n−m)!

=1 ∗ 2 ∗ . . . ∗ n

1 ∗ 2 ∗ . . . ∗ (n−m)

5. To evaluate an integral numerically, a Simpson’s rule one-third can be ap-plied. The formula and the associated figure are shown below:∫ x2

x0

f(x)dx =h

3[f(x0) + 4f(x1) + f(x2)]

where h =x2 − x0

2, x1 = x0 + h

Write a C function for the Simpson’s rule one-third technique. Test your func-tion with f(x) = x2 + 1, and the lower and upper limits 0 and 1, respectively.For more accurate, divide the f(x) into N intervals, and apply the Simpson’srule for each interval. Compare your result with the analytical value.

6-11