SlideShare une entreprise Scribd logo
1  sur  75
Télécharger pour lire hors ligne
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
  1.1 Lesson Plan . . . . . . . . . . . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   1-1
  1.2 Computer system . . . . . . . . .           .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   1-1
  1.3 Computer programming . . . .                .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   1-2
  1.4 Software development method                 .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   1-2
  1.5 Algorithm and Pseudo code . .               .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   1-3
  1.6 Flow chart . . . . . . . . . . . . .        .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   1-5

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

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



                                                                                                                                           3
Table of Content

          3.1.2 Floating point arithmetic . . . . . . . . . . . . . . . . . . .                                                    .   .   .   3-3
          3.1.3 Mixed mode arithmetic . . . . . . . . . . . . . . . . . . . .                                                      .   .   .   3-3
    3.2   Relational and Logical Operators . . . . . . . . . . . . . . . . . .                                                     .   .   .   3-3
          3.2.1 Relational Operators . . . . . . . . . . . . . . . . . . . . . .                                                   .   .   .   3-3
          3.2.2 Logical Operators . . . . . . . . . . . . . . . . . . . . . . .                                                    .   .   .   3-4
    3.3   Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . .                                                   .   .   .   3-6
          3.3.1 Simple Assignment . . . . . . . . . . . . . . . . . . . . . . .                                                    .   .   .   3-6
          3.3.2 Compound Assignment . . . . . . . . . . . . . . . . . . . .                                                        .   .   .   3-6
    3.4   Increment and Decrement Operators . . . . . . . . . . . . . . .                                                          .   .   .   3-7
          3.4.1 Side Effects of the Increment and Decrement Operators                                                              .   .   .   3-7
    3.5   Bit Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .                                              .   .   .   3-8
          3.5.1 Bit-Shift Operators . . . . . . . . . . . . . . . . . . . . . . .                                                  .   .   .   3-8
          3.5.2 Bit Logical Operators . . . . . . . . . . . . . . . . . . . . . .                                                  .   .   .   3-9
    3.6   Cast Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .                                                .   .   .   3-10
          3.6.1 Casting Floating-Point Values to Integers . . . . . . . . . .                                                      .   .   .   3-11
    3.7   Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . .                                                    .   .   .   3-11
    3.8   Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .                                              .   .   .   3-13

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

5 Repetition                                                                                                                                 5-1
  5.1 Concept of a loop . . . . .          .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 5-1
  5.2 Pretest and Post–Test Loop           .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 5-1
  5.3 Loops in C . . . . . . . . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 5-3
  5.4 while Loop . . . . . . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 5-3
  5.5 do..while Loop . . . . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 5-5
  5.6 for Loop . . . . . . . . . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 5-6
  5.7 continue Statement . . . .           .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 5-9
  5.8 Exercises . . . . . . . . . . .      .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 5-10

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



4
Table of Content

6.4 Recursive . . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 6-6
6.5 Parameter Passing . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 6-7
    6.5.1 Pass by Value .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 6-7
    6.5.2 Pass by Address       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 6-8
6.6 Math Library . . . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 6-9
6.7 Exercises . . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   . 6-10




                                                                                                                                                5
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 opera-
    tions)

  • 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 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 the
process of designing, writing, testing, debugging / troubleshooting, and main-
taining 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 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).
  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 an-
    swer

  • 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 con-
    necting these with arrows


1.5 Algorithm and Pseudo code

Pseudo code
Pseudo-Code is simply a numbered list of instructions to perform some task. Pseudo-
code 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 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
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 pro-
vides 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)   double (if-else)          multiple (switch-case)




  Flowchart constructs,con’t




1-6
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 divi-
     sor), 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=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          in teaching compiler construction
        Language)

 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 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 min-
     imum 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 sys-
     tem.

   • Preprocessor directives or precom-
     piler directives are necessary for
     preparing 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 header
     file for formating data in the stan-
     dard input output devices (key-
     board 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           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 applied
on 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 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 qual-
ifiers:

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

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


      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
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
machine’s 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 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>                      The    program      will   display:
2   void main (){
3     char c;
                                            Char d in ASCII code is a 100.
4     c=’d’;                                The same character constant will
5     printf (‘‘nChar %c in ASCII code     be displayed in different output
6             is a %d n’’,c,c);            formats (%c and %d). There are 255
7   }
                                            characters 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, 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 con-
tains 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 machine’s 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 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: %fn’’,area);
18         area = pi * rad * rad;
19         printf(‘‘nThe area of the circle is: %fn’’,area);
20   }




     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 con-
    sidered 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

                 -         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 the
         output. It is useful to align output in column. For a floating point num-
         ber, 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        /*   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 (-). then
         the data is formatted left justified.
         %-8d        /* decimal, 8 print pos, left-justified */
         %08d        /* 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(‘‘%dt%ct%5.1fn’’,number1, c, number2)
     printf(‘‘%dt%ct%5.1fn’’,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 : 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 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, 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    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
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 per-
form arithmetic or logical computations of data. An expression is a sequence of
operands 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 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 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 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         Result/Remark
                                            (x = 27, y = 5)

           +      Addition                  x+y               32

           -      Subtraction               x-y               22

           *      Multiplication            x*y               135

           /      Division                  x/y               5

                  Modulo    (Remain-
           %      der of an integers        x%y               2 (2 = 27 − 5 ∗ 5).
                  division)



       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 %dˇ, &num1, &num2); /*inputs the operands */
                     T
 9
10     sum = num1+num2; /*addition of numbers and storing in sum.*/
11     printf(‘‘n The sum is = %d’’,sum);/*display the output */
12
13     sub = num1-num2; /*subtraction of numbers and storing in sub.*/



     3-2
3.2 Relational and Logical Operators

14     printf(‘‘n The difference is = %d’’,sub);/*display the output */
15
16     mul = num1*num2; /*multiplication and storing in mul. */
17     printf(‘‘n The product is = %d’’,mul);/*display the output */
18
19     div = num1/num2; /*division of numbers and storing in div. */
20     printf(‘‘n The division is = %d’’,div);/*display the output */
21
22     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 results
   can 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 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                    Example           Result/ Re-
                                                    (x = 1, y = 2)    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   or      1 >= 2             FALSE
                         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 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 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 rela-
    tional 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   #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
3.2 Relational and Logical Operators


                            Table 3.3: Logical Operators Truth Table

       Operator         x           y        x AND y        Operator      x       y       x OR y

                   false       false          false                      false   false     false

                   false        true          false                      false   true      true
         AND                                                   OR
                    true       false          false                      true    false     true

                    true        true          true                       true    true      true

                                        Operator        x       NOT x

                                                       false     true
                                             NOT
                                                       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




 8
 9   clrscr();/* make screen clear */
10   z = x + y; /*arithmetic addition */
11   printf(¸n %d + %d = %dˇ, x,y,z); /*display x+y=z */
            S               T
12
13   /* relational operator */
14   z = (x < y);
15
16   printf(¸n %d < %d = %dˇ, x,y,z); /* display x<y = z */
            S               T
17
18   z = x == y;
19



                                                                                                   3-5
3 Operators and Expressions

20     printf(¸n %d < %d == %dˇ, x,y,z); /*display x == y = z*/
              S                T
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 expression
   has 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. There
   are 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
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-      ++a       Increment a first, be-
                     crement by 1                         fore use.

        a--          Use a first before          --a       Decrement a first, be-
                     decrement by 1                       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. 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 incre-
ments or decrements the variable. The temporary copy, which has the variable’s
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 in-
stances, it doesn’t 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 pos-
sible 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    =   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 increment
  and decrement operators:
1 #include <stdio.h>
2 int main(){
3   int j = 5, k = 5, l = 5, m = 5;
4   printf("j: %dt k: %dn", j++, k--);
5   printf("j: %dt k: %dn", j, k);
6   printf("l: %dt m: %dn", ++l, --m);
7   printf("l: %dt m: %dn", 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 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                  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. The
results 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 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 op-
erator (&) 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 value’s 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 value’s
    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 =       -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 rounded
value 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. If
operands 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 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

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


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

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




3-14
CHAPTER 4
                                   Selections


A selection statement alters a program’s execution flow by selecting one path
from a collection based on a specified controlling condition or expression. Using
a 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 followed
by 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 equivalent
to 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 corresponding
construct is as follows:




        if ( condition )
           statement;
        nextStatement;




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



                                                                                 4-1
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 fragment
can be used to obtain an absolute value of an integer number by evaluating a
value 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 are
more than one actions to be performed, they must be grouped into a compound
statement, 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 logic
flow 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
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 in
     the same evaluation. Regardless which statement has been executed, the flow
     will continue to the nextStatement. Which statement will be executed by the
     following 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 program
     example. The program arrangements two different integers always in an ascend-
     ing order.
 1   #include<stdio.h>
                                                                Input example:
 2   #include<conio.h>
                                                                a = 20, b = 5
 3   int main(){
                                                                min = 20
 4     int a, b, min;
                                                                if (5 < 20) → true.
 5     clrscr();
                                                                The input values must
 6     printf(‘‘nGive two different numbers:’’);
                                                                be swapped.
 7     scanf(‘‘%d, %d’’,&a, &b);
 8     printf(‘‘%dt%d’’, a, b);                                    min = 5
 9     min = a; /* set a minimum */
                                                                       b = 20
10     if (b < min){
11       min = b; /* swap the values */                                a = 5
12       b = a;
                                                                Display    on the
13       a = min;
                                                                screen:
14       printf(‘‘nb is greater than a.’’);
                                                                b is greater than
15       printf(‘‘ Change the order.’’);
                                                                a. Change the or-
16     }
                                                                der.
17     else
                                                                The ascending or-
18       printf(‘‘nThe order remain unchanged.’’);
                                                                der: 5 20.
19     printf(‘‘nThe ascending order: ’’);
20     printf(‘‘%dt%d’’, a, b);                                The statement of
21     getch();                                                 the else part is not
22     return 0;                                                executed.
23   }




                                                                                  4-3
4 Selections

  4.4 switch statement

  The switch statement is a conditional branching statement that selects among
  several statements or multiple statements based on constant values. The syntax
  and 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 executes
  any statements following the selected case label until a break, goto, or return
  statement 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 the
  nextStatement. Since this is usually what you want, you should almost always
  include 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, program
  flow continues with the statement that follows the matching case label. If none
  of the case labels match the switch condition, program flow continues at the
  default 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 control
  transfers outside of the switch statement.
     The following example will display the annual weather depending on the con-
  dition.




  4-4
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 charge
     based on the type of vehicle (’c’ for car, ’b’ for bus, and ’t’ for truck) and the
     hours 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
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 not
     integral, 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 multiple
     decision. The expressions are evaluated in order. If an expression is true, the
     statement associated with it is executed, and this terminates the whole chain.
     The flow continues then to the nextStatement. As always, the code for each
     statement is either a single statement, or a group of them in braces. The last
     else part handles the “none of the above” or default case where none of the
     other conditions is satisfied.
       Sometimes the trailing else statement n may be used for error checking to
     catch an “impossible” condition. To remember that an else is always associated
     with the nearest previous if. The else - if construct is used only when:

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

       • The same variable is being tested in the expression.

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



     4-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 an
        conditional expression. It has three operands and two operators. Each operand
        is 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
4 Selections

4.7 Exercises

  1. If originally x = 0, y = 0 and z = 1, what is the value of x, y and z after
     executing 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 after
     executing 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 three
     integer numbers. Verify your answer by writing the corresponding program
     source code and test it.

  4. If originally x = 1, y = 3 and z = 0, what is the value of x, y and z after
     executing 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’ for
     truck, 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
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 the
memory constant, const. What is the difference between them? If none
of the type of vehicle entered matches with any case label, displays wrong
input.




                                                                       4-9
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 series
of 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 ensure
that the action ends after the job is done, we must set a certain condition to
control the loop. This condition checks after each iteration to see either the job
is 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 is
executed, and if the test condition is false, the loop is terminated and the control
goes directly to the nextStatement.
  In the post–test loop, the statement is always executed at least once. At the
end of every iteration, the condition is tested. If the condition is true, the loop
repeats, but if the condition is false, the loop ends, and the control goes to the
nextStatement.
  Two steps are required in working with a loop.
  1. initialization
     The purpose of an initialization is to start the loop. In the pretest loop, the
     initial value of the test condition must be true. It is done before the first
     execution of the statement.



                                                                                    5-1
5 Repetition




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


  2. Updating
     The purpose of an updating is to repeat the execution of the statement and
     to 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 never
     stop.




 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 statement
execution. If the the statement in the loop is repeated x times, the updating is
also done x times.
  The limit test for a loop can be expressed into two categories:



5-2
5.3 Loops in C

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

  2. Counter-controlled loop
     When we know the number of times an action or an operation is to be
     executed, 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 two
are pretest loop, and the later is a post-test loop. All of them can be used for
event-controlled loop and counter-controlled loop. The while and do..while
are the most commonly used for event-controlled loop, and for loop is usually
used 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 a
    parenthesis {}.



                                                                             5-3
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 the
specified condition, expression, is true. The while statement tests expression and
if 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 be
performed 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(’nn’’’);
  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("Excellentn"); break;
 13          case ’B’:
 14          case ’b’: printf("Goodn"); break;
 15          default : printf("Invalid graden"); break;
 16        } /* end switch */
 17        printf("nAgain? ");
 18        scanf("%s", &answer);
 19    } /* end while loop */
 20 }



5-4
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 Figure
5.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 condition
is satisfied. Unlike the for and while loops, do ˇ while performs statement first
                                                E
and then tests expression. If expression evaluates to nonzero (true), statement
executes again, but when expression evaluates to zero (false), execution of the
loop stops and the program control goes to the nextStatement. This type of
loop is always executed at least once.

Program Example for do..while Loop

The program example calculates the summation of an integer that a user supplies
and the summation of the squares of that integer. Mathematically, the summa-
tion can be expressed as follows:
                                   n
                        sum =           i = 1 + 2 + 3 + ... + n
                                  i=1
                                  n ∗ (n + 1)
                              =
                                       2


                                                                                 5-5
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: %dn ", 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:

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

  • Condition control
    The controlling expression determines whether or not to terminate the loop.
    It is evaluated before each iteration of the loop. If the condition value is a
    nonzero, the statement is executed. If it evaluates to 0, execution of the
    statement is terminated and control passes to the nextStatement. This
    means that if the initial value of condition becomes zero, the statementis
    never executed.

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



5-6
5.6 for Loop

     ated after each iteration of the statement and before the next evaluation
     of 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 corresponding
flow 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 following
program fragment:
     for (j = 0; j < 10; j++){
      printf(‘‘j = %dt’’, j);
      if (j % 4 == 0) /* new line */
        printf(‘‘n’’);
     }
      getch();



                                                                             5-7
5 Repetition

  is the same as the following while loop:

      j = 0;
      while (j<10){
        printf(‘‘j = %dt’’, 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 with
the formula:
                                 
                               n              n!
                   P (n, m) =     =
                                             (n − m)!
                                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) = %dnn", 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
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 iteration
of the loop. In the while and do/while, this means the condition expression
is tested immediately, and in the forloop, the update expression (if present) is
evaluated. 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
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(‘‘%dn’’, x);
               x--;
             }

        b) for loop:
           for (x = 12; x > 7; x--){
               printf(‘‘%dn’’, x);
             }

        c) do..while loop:
           x = 12;
           do{
               printf(‘‘%dn’’, 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
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 n
   real numbers. As the numbers are read, the program will calculate the sum
   and the average of the positive numbers.
   The program repeats again from the beginning. The program terminates
   only 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:
                              1  1  1  1           1      1
                    e=1+        + + + + ... + +         +
                              1! 2! 3! 4!       (n − 1)! n!




                                                                         5-11
CHAPTER 6
                                Functions



6.1 Top-Down Design

A program is divided into a main module and its related modules. The division
of modules proceeds until the module consists only of elemantary processes and
cannot be further sibdivided. This process is known as factoring. The top-down
design 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 allowed
    only through a calling module. If Module 1 needs to send data to Module 2,
    the data must be passed through the calling module. No communication
    takes 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 Value
     In this technique, a copy of the data is made and the copy is sent to the
     called module. The original data in the calling module cannot be changed.

  2. Pass By Reference
     The calling module sends the address of the data to the called module. In
     this case, the called module can change the original data in the calling
     module.

6.2 Functions in C

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



                                                                           6-1
Chapter1 6
Chapter1 6
Chapter1 6
Chapter1 6
Chapter1 6
Chapter1 6
Chapter1 6
Chapter1 6
Chapter1 6
Chapter1 6

Contenu connexe

En vedette

Bca 2nd sem-u-1.4 digital logic circuits, digital component
Bca 2nd sem-u-1.4 digital logic circuits, digital componentBca 2nd sem-u-1.4 digital logic circuits, digital component
Bca 2nd sem-u-1.4 digital logic circuits, digital componentRai University
 
4 coding from algorithms
4 coding from algorithms4 coding from algorithms
4 coding from algorithmshccit
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming hccit
 
goskateboardingshop shop.vinaskate.com vietnam skateboard
goskateboardingshop shop.vinaskate.com vietnam skateboardgoskateboardingshop shop.vinaskate.com vietnam skateboard
goskateboardingshop shop.vinaskate.com vietnam skateboardLinh Vo
 
Bti1022 lab sheet 7
Bti1022 lab sheet 7Bti1022 lab sheet 7
Bti1022 lab sheet 7alish sha
 
Harvard_University_-_Linear_Al
Harvard_University_-_Linear_AlHarvard_University_-_Linear_Al
Harvard_University_-_Linear_Alramiljayureta
 
14 o codigo_xenetico
14 o codigo_xenetico14 o codigo_xenetico
14 o codigo_xeneticojuanapardo
 
How to Upload a List From Excel to InfusionSoft
How to Upload a List From Excel to InfusionSoftHow to Upload a List From Excel to InfusionSoft
How to Upload a List From Excel to InfusionSoftMarvin Libron
 
24 celula citoplasma
24 celula citoplasma24 celula citoplasma
24 celula citoplasmajuanapardo
 
Sustainable Reading - Concept Workshop
Sustainable Reading - Concept WorkshopSustainable Reading - Concept Workshop
Sustainable Reading - Concept Workshopstoryofxu
 
Rèdais & IED_Pericoli
Rèdais & IED_PericoliRèdais & IED_Pericoli
Rèdais & IED_PericoliRèdais
 
A history of lemonade
A history of lemonadeA history of lemonade
A history of lemonadeLemonadeDay
 
Materiales.1274367220
Materiales.1274367220Materiales.1274367220
Materiales.1274367220juanapardo
 

En vedette (20)

Bca 2nd sem-u-1.4 digital logic circuits, digital component
Bca 2nd sem-u-1.4 digital logic circuits, digital componentBca 2nd sem-u-1.4 digital logic circuits, digital component
Bca 2nd sem-u-1.4 digital logic circuits, digital component
 
Pengaturcaraan asas
Pengaturcaraan asasPengaturcaraan asas
Pengaturcaraan asas
 
4 coding from algorithms
4 coding from algorithms4 coding from algorithms
4 coding from algorithms
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming
 
El agua.
El agua.El agua.
El agua.
 
goskateboardingshop shop.vinaskate.com vietnam skateboard
goskateboardingshop shop.vinaskate.com vietnam skateboardgoskateboardingshop shop.vinaskate.com vietnam skateboard
goskateboardingshop shop.vinaskate.com vietnam skateboard
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
ΠΑΡΟΥΣΙΑΣΗ ECOMOBILITY 2014
ΠΑΡΟΥΣΙΑΣΗ  ECOMOBILITY  2014ΠΑΡΟΥΣΙΑΣΗ  ECOMOBILITY  2014
ΠΑΡΟΥΣΙΑΣΗ ECOMOBILITY 2014
 
Bti1022 lab sheet 7
Bti1022 lab sheet 7Bti1022 lab sheet 7
Bti1022 lab sheet 7
 
Harvard_University_-_Linear_Al
Harvard_University_-_Linear_AlHarvard_University_-_Linear_Al
Harvard_University_-_Linear_Al
 
14 o codigo_xenetico
14 o codigo_xenetico14 o codigo_xenetico
14 o codigo_xenetico
 
How to Upload a List From Excel to InfusionSoft
How to Upload a List From Excel to InfusionSoftHow to Upload a List From Excel to InfusionSoft
How to Upload a List From Excel to InfusionSoft
 
24 celula citoplasma
24 celula citoplasma24 celula citoplasma
24 celula citoplasma
 
Pop
PopPop
Pop
 
Sustainable Reading - Concept Workshop
Sustainable Reading - Concept WorkshopSustainable Reading - Concept Workshop
Sustainable Reading - Concept Workshop
 
Rèdais & IED_Pericoli
Rèdais & IED_PericoliRèdais & IED_Pericoli
Rèdais & IED_Pericoli
 
υδραγωγεια
υδραγωγειαυδραγωγεια
υδραγωγεια
 
MUNDO DAS IDÉIAS
MUNDO DAS IDÉIASMUNDO DAS IDÉIAS
MUNDO DAS IDÉIAS
 
A history of lemonade
A history of lemonadeA history of lemonade
A history of lemonade
 
Materiales.1274367220
Materiales.1274367220Materiales.1274367220
Materiales.1274367220
 

Similaire à Chapter1 6

Learn C# Includes The C# 3.0 Features
Learn C# Includes The C# 3.0 FeaturesLearn C# Includes The C# 3.0 Features
Learn C# Includes The C# 3.0 FeaturesZEZUA Z.
 
Getstart graphic
Getstart graphicGetstart graphic
Getstart graphicalldesign
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Perl &lt;b>5 Tutorial&lt;/b>, First Edition
Perl &lt;b>5 Tutorial&lt;/b>, First EditionPerl &lt;b>5 Tutorial&lt;/b>, First Edition
Perl &lt;b>5 Tutorial&lt;/b>, First Editiontutorialsruby
 
Motorola air defense mobile 6.1 user guide
Motorola air defense mobile 6.1 user guideMotorola air defense mobile 6.1 user guide
Motorola air defense mobile 6.1 user guideAdvantec Distribution
 
Motorola air defense mobile 6.1 user guide
Motorola air defense mobile 6.1 user guideMotorola air defense mobile 6.1 user guide
Motorola air defense mobile 6.1 user guideAdvantec Distribution
 
Ibm info sphere datastage data flow and job design
Ibm info sphere datastage data flow and job designIbm info sphere datastage data flow and job design
Ibm info sphere datastage data flow and job designdivjeev
 
Ibm Datamodeling
Ibm DatamodelingIbm Datamodeling
Ibm Datamodelingguest24adb7
 
Information extraction systems aspects and characteristics
Information extraction systems  aspects and characteristicsInformation extraction systems  aspects and characteristics
Information extraction systems aspects and characteristicsGeorge Ang
 

Similaire à Chapter1 6 (20)

Learn C# Includes The C# 3.0 Features
Learn C# Includes The C# 3.0 FeaturesLearn C# Includes The C# 3.0 Features
Learn C# Includes The C# 3.0 Features
 
Notes econometricswithr
Notes econometricswithrNotes econometricswithr
Notes econometricswithr
 
R Data
R DataR Data
R Data
 
Expert_Programming_manual.pdf
Expert_Programming_manual.pdfExpert_Programming_manual.pdf
Expert_Programming_manual.pdf
 
Getstart graphic
Getstart graphicGetstart graphic
Getstart graphic
 
Perl 5 guide
Perl 5 guidePerl 5 guide
Perl 5 guide
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Perl &lt;b>5 Tutorial&lt;/b>, First Edition
Perl &lt;b>5 Tutorial&lt;/b>, First EditionPerl &lt;b>5 Tutorial&lt;/b>, First Edition
Perl &lt;b>5 Tutorial&lt;/b>, First Edition
 
perltut
perltutperltut
perltut
 
perltut
perltutperltut
perltut
 
Perl tut
Perl tutPerl tut
Perl tut
 
Motorola air defense mobile 6.1 user guide
Motorola air defense mobile 6.1 user guideMotorola air defense mobile 6.1 user guide
Motorola air defense mobile 6.1 user guide
 
Motorola air defense mobile 6.1 user guide
Motorola air defense mobile 6.1 user guideMotorola air defense mobile 6.1 user guide
Motorola air defense mobile 6.1 user guide
 
Ibm info sphere datastage data flow and job design
Ibm info sphere datastage data flow and job designIbm info sphere datastage data flow and job design
Ibm info sphere datastage data flow and job design
 
Ibm Datamodeling
Ibm DatamodelingIbm Datamodeling
Ibm Datamodeling
 
Information extraction systems aspects and characteristics
Information extraction systems  aspects and characteristicsInformation extraction systems  aspects and characteristics
Information extraction systems aspects and characteristics
 
R data
R dataR data
R data
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
test6
test6test6
test6
 
test5
test5test5
test5
 

Plus de alish sha

T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9alish sha
 
July 2014 theory exam (theory)
July 2014 theory exam (theory)July 2014 theory exam (theory)
July 2014 theory exam (theory)alish sha
 
Accounting basic equation
Accounting basic equation Accounting basic equation
Accounting basic equation alish sha
 
It 302 computerized accounting (week 2) - sharifah
It 302   computerized accounting (week 2) - sharifahIt 302   computerized accounting (week 2) - sharifah
It 302 computerized accounting (week 2) - sharifahalish sha
 
It 302 computerized accounting (week 1) - sharifah
It 302   computerized accounting (week 1) - sharifahIt 302   computerized accounting (week 1) - sharifah
It 302 computerized accounting (week 1) - sharifahalish sha
 
What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)alish sha
 
Lab 9 sem ii_12_13
Lab 9 sem ii_12_13Lab 9 sem ii_12_13
Lab 9 sem ii_12_13alish sha
 
Lab 10 sem ii_12_13
Lab 10 sem ii_12_13Lab 10 sem ii_12_13
Lab 10 sem ii_12_13alish sha
 
Lab 5 2012/2012
Lab 5 2012/2012Lab 5 2012/2012
Lab 5 2012/2012alish sha
 
Purpose elaborate
Purpose elaboratePurpose elaborate
Purpose elaboratealish sha
 
Test 1 alish schema 1
Test 1 alish schema 1Test 1 alish schema 1
Test 1 alish schema 1alish sha
 
Lab 6 sem ii_11_12
Lab 6 sem ii_11_12Lab 6 sem ii_11_12
Lab 6 sem ii_11_12alish sha
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&aalish sha
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&aalish sha
 
Final project
Final projectFinal project
Final projectalish sha
 
Final project
Final projectFinal project
Final projectalish sha
 
Attn list test
Attn list testAttn list test
Attn list testalish sha
 
Carry markdam31303
Carry markdam31303Carry markdam31303
Carry markdam31303alish sha
 

Plus de alish sha (20)

T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9
 
July 2014 theory exam (theory)
July 2014 theory exam (theory)July 2014 theory exam (theory)
July 2014 theory exam (theory)
 
Accounting basic equation
Accounting basic equation Accounting basic equation
Accounting basic equation
 
It 302 computerized accounting (week 2) - sharifah
It 302   computerized accounting (week 2) - sharifahIt 302   computerized accounting (week 2) - sharifah
It 302 computerized accounting (week 2) - sharifah
 
It 302 computerized accounting (week 1) - sharifah
It 302   computerized accounting (week 1) - sharifahIt 302   computerized accounting (week 1) - sharifah
It 302 computerized accounting (week 1) - sharifah
 
What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)
 
Lab 9 sem ii_12_13
Lab 9 sem ii_12_13Lab 9 sem ii_12_13
Lab 9 sem ii_12_13
 
Lab 10 sem ii_12_13
Lab 10 sem ii_12_13Lab 10 sem ii_12_13
Lab 10 sem ii_12_13
 
Lab 6
Lab 6Lab 6
Lab 6
 
Lab 5 2012/2012
Lab 5 2012/2012Lab 5 2012/2012
Lab 5 2012/2012
 
Purpose elaborate
Purpose elaboratePurpose elaborate
Purpose elaborate
 
Lab sheet 1
Lab sheet 1Lab sheet 1
Lab sheet 1
 
Test 1 alish schema 1
Test 1 alish schema 1Test 1 alish schema 1
Test 1 alish schema 1
 
Lab 6 sem ii_11_12
Lab 6 sem ii_11_12Lab 6 sem ii_11_12
Lab 6 sem ii_11_12
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&a
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&a
 
Final project
Final projectFinal project
Final project
 
Final project
Final projectFinal project
Final project
 
Attn list test
Attn list testAttn list test
Attn list test
 
Carry markdam31303
Carry markdam31303Carry markdam31303
Carry markdam31303
 

Chapter1 6

  • 1. 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
  • 2.
  • 3. Table of Content 1 Introduction 1-1 1.1 Lesson Plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1 1.2 Computer system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1 1.3 Computer programming . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 1.4 Software development method . . . . . . . . . . . . . . . . . . . . . . 1-2 1.5 Algorithm and Pseudo code . . . . . . . . . . . . . . . . . . . . . . . . 1-3 1.6 Flow chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 2 Structure of C Programs 2-1 2.1 Program Development . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1 2.2 Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1 2.3 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 2.4 Structures of a C Program . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3 2.5 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3 2.6 Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4 2.6.1 Basic data types . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4 2.6.1.1 Qualifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4 2.7 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5 2.7.1 Variable definition . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5 2.8 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6 2.8.1 Integer constants . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6 2.8.2 Floating point constants . . . . . . . . . . . . . . . . . . . . . . . 2-6 2.8.3 Character constants . . . . . . . . . . . . . . . . . . . . . . . . . 2-7 2.8.4 String constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7 2.8.5 Defined constants . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8 2.8.6 Memory constants . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8 2.8.7 A program example . . . . . . . . . . . . . . . . . . . . . . . . . 2-8 2.9 Formatted Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9 2.9.1 printf() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9 2.9.2 Output examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11 2.10 Formatted input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11 2.10.1 Input examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12 2.11 Self exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12 2.12 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13 2.13 ASCII Code Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14 3 Operators and Expressions 3-1 3.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1 3.1.1 Integer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2 3
  • 4. Table of Content 3.1.2 Floating point arithmetic . . . . . . . . . . . . . . . . . . . . . . 3-3 3.1.3 Mixed mode arithmetic . . . . . . . . . . . . . . . . . . . . . . . 3-3 3.2 Relational and Logical Operators . . . . . . . . . . . . . . . . . . . . . 3-3 3.2.1 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . 3-3 3.2.2 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4 3.3 Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6 3.3.1 Simple Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6 3.3.2 Compound Assignment . . . . . . . . . . . . . . . . . . . . . . . 3-6 3.4 Increment and Decrement Operators . . . . . . . . . . . . . . . . . . 3-7 3.4.1 Side Effects of the Increment and Decrement Operators . . . 3-7 3.5 Bit Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8 3.5.1 Bit-Shift Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8 3.5.2 Bit Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . 3-9 3.6 Cast Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10 3.6.1 Casting Floating-Point Values to Integers . . . . . . . . . . . . . 3-11 3.7 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11 3.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13 4 Selections 4-1 4.1 Statements and Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1 4.2 if statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1 4.3 if - else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 4.4 switch statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4 4.4.1 Evaluation of switch statement . . . . . . . . . . . . . . . . . . 4-4 4.5 else - if statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6 4.6 Conditional Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7 4.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8 5 Repetition 5-1 5.1 Concept of a loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1 5.2 Pretest and Post–Test Loop . . . . . . . . . . . . . . . . . . . . . . . . . 5-1 5.3 Loops in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 5.4 while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 5.5 do..while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5 5.6 for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6 5.7 continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9 5.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10 6 Functions 6-1 6.1 Top-Down Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1 6.2 Functions in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1 6.2.1 Advantages of Functions . . . . . . . . . . . . . . . . . . . . . . 6-2 6.3 User-Defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2 4
  • 5. Table of Content 6.4 Recursive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6 6.5 Parameter Passing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7 6.5.1 Pass by Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7 6.5.2 Pass by Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8 6.6 Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9 6.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10 5
  • 6.
  • 7. 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 opera- tions) • 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
  • 8. 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 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 the process of designing, writing, testing, debugging / troubleshooting, and main- taining 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 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). Algorithm Three Catagories of Algorithmic Operations 1-2
  • 9. 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 an- swer • 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 con- necting these with arrows 1.5 Algorithm and Pseudo code Pseudo code Pseudo-Code is simply a numbered list of instructions to perform some task. Pseudo- code 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
  • 10. 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 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
  • 11. 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 pro- vides 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
  • 12. 1 Introduction Flowchart constructs The flowchart equivalents for the structured programming constructs are shown below: Selection Sequence single (if) double (if-else) multiple (switch-case) Flowchart constructs,con’t 1-6
  • 13. 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 divi- sor), 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=0 x 3. See the formula below:   x if x ≥ 0 f (x) =  −x if x < 0 1-7
  • 14. 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
  • 15. 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
  • 16. 2 Structure of C Programs 2.3 Background Year Language Remarks 1960 ALGOL(Algorithmic in teaching compiler construction Language) 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 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
  • 17. 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 min- imum 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 sys- tem. • Preprocessor directives or precom- piler directives are necessary for preparing 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 header file for formating data in the stan- dard input output devices (key- board 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
  • 18. 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 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 applied on 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 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 qual- ifiers: • 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
  • 19. 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 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
  • 20. 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 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 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. 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
  • 21. 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 machine’s 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 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> The program will display: 2 void main (){ 3 char c; Char d in ASCII code is a 100. 4 c=’d’; The same character constant will 5 printf (‘‘nChar %c in ASCII code be displayed in different output 6 is a %d n’’,c,c); formats (%c and %d). There are 255 7 } characters 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, 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 con- tains 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 machine’s character set. The latter is an array of characters that contains one character (the letter x) and a ’0’. 2-7
  • 22. 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 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: %fn’’,area); 18 area = pi * rad * rad; 19 printf(‘‘nThe area of the circle is: %fn’’,area); 20 } 2-8
  • 23. 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 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
  • 24. 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 the output. It is useful to align output in column. For a floating point num- ber, 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 /* 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 (-). then the data is formatted left justified. %-8d /* decimal, 8 print pos, left-justified */ %08d /* 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
  • 25. 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(‘‘%dt%ct%5.1fn’’,number1, c, number2) printf(‘‘%dt%ct%5.1fn’’,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 : 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
  • 26. 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, 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
  • 27. 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 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
  • 28. 2 Structure of C Programs 2.13 ASCII Code Table Figure 2.1: 7-bit ASCII codes table 2-14
  • 29. 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 of operands 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 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 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 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
  • 30. 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 Result/Remark (x = 27, y = 5) + Addition x+y 32 - Subtraction x-y 22 * Multiplication x*y 135 / Division x/y 5 Modulo (Remain- % der of an integers x%y 2 (2 = 27 − 5 ∗ 5). division) 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 %dˇ, &num1, &num2); /*inputs the operands */ T 9 10 sum = num1+num2; /*addition of numbers and storing in sum.*/ 11 printf(‘‘n The sum is = %d’’,sum);/*display the output */ 12 13 sub = num1-num2; /*subtraction of numbers and storing in sub.*/ 3-2
  • 31. 3.2 Relational and Logical Operators 14 printf(‘‘n The difference is = %d’’,sub);/*display the output */ 15 16 mul = num1*num2; /*multiplication and storing in mul. */ 17 printf(‘‘n The product is = %d’’,mul);/*display the output */ 18 19 div = num1/num2; /*division of numbers and storing in div. */ 20 printf(‘‘n The division is = %d’’,div);/*display the output */ 21 22 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 results can 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 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
  • 32. 3 Operators and Expressions Table 3.2: Relational Operators Operator Meaning Example Result/ Re- (x = 1, y = 2) 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 or 1 >= 2 FALSE 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 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 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 rela- tional 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 #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
  • 33. 3.2 Relational and Logical Operators Table 3.3: Logical Operators Truth Table Operator x y x AND y Operator x y x OR y false false false false false false false true false false true true AND OR true false false true false true true true true true true true Operator x NOT x false true NOT 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 8 9 clrscr();/* make screen clear */ 10 z = x + y; /*arithmetic addition */ 11 printf(¸n %d + %d = %dˇ, x,y,z); /*display x+y=z */ S T 12 13 /* relational operator */ 14 z = (x < y); 15 16 printf(¸n %d < %d = %dˇ, x,y,z); /* display x<y = z */ S T 17 18 z = x == y; 19 3-5
  • 34. 3 Operators and Expressions 20 printf(¸n %d < %d == %dˇ, x,y,z); /*display x == y = z*/ S T 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 expression has 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. There are 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
  • 35. 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- ++a Increment a first, be- crement by 1 fore use. a-- Use a first before --a Decrement a first, be- decrement by 1 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. 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 incre- ments or decrements the variable. The temporary copy, which has the variable’s 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 in- stances, it doesn’t 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 pos- sible to predict the order in which the side effects occur. Consider the following statement: 3-7
  • 36. 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 = 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 increment and decrement operators: 1 #include <stdio.h> 2 int main(){ 3 int j = 5, k = 5, l = 5, m = 5; 4 printf("j: %dt k: %dn", j++, k--); 5 printf("j: %dt k: %dn", j, k); 6 printf("l: %dt m: %dn", ++l, --m); 7 printf("l: %dt m: %dn", 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 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
  • 37. 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. The results 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 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 op- erator (&) 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
  • 38. 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 value’s 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 value’s 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
  • 39. 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 = -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 rounded value 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. If operands 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 precedence in highest to lowest precedence: 3-11
  • 40. 3 Operators and Expressions Table 3.8: Operator Precedence with a highest to lowest order Class of Operator Operators Grouping primary () [] -> L to R (type casting) sizeof & (address of) unary * (dereference) R to L - (reverse sign) ~ ! ++ -- 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
  • 41. 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 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 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
  • 42. 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 evaluate it to to get the right result. 6 Write a C program code for the question 5 to verify your answer. 3-14
  • 43. CHAPTER 4 Selections A selection statement alters a program’s execution flow by selecting one path from a collection based on a specified controlling condition or expression. Using a 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 followed by 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 equivalent to 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 corresponding construct is as follows: if ( condition ) statement; nextStatement; if statement evaluates the value of condition to select either the statement is executed or not. C executes statement only if condition is true, if false, C falls through to nextStatement without executing the statement. In C, a nonzero value 4-1
  • 44. 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 fragment can be used to obtain an absolute value of an integer number by evaluating a value 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 are more than one actions to be performed, they must be grouped into a compound statement, 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 logic flow 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
  • 45. 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 in the same evaluation. Regardless which statement has been executed, the flow will continue to the nextStatement. Which statement will be executed by the following 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 program example. The program arrangements two different integers always in an ascend- ing order. 1 #include<stdio.h> Input example: 2 #include<conio.h> a = 20, b = 5 3 int main(){ min = 20 4 int a, b, min; if (5 < 20) → true. 5 clrscr(); The input values must 6 printf(‘‘nGive two different numbers:’’); be swapped. 7 scanf(‘‘%d, %d’’,&a, &b); 8 printf(‘‘%dt%d’’, a, b); min = 5 9 min = a; /* set a minimum */ b = 20 10 if (b < min){ 11 min = b; /* swap the values */ a = 5 12 b = a; Display on the 13 a = min; screen: 14 printf(‘‘nb is greater than a.’’); b is greater than 15 printf(‘‘ Change the order.’’); a. Change the or- 16 } der. 17 else The ascending or- 18 printf(‘‘nThe order remain unchanged.’’); der: 5 20. 19 printf(‘‘nThe ascending order: ’’); 20 printf(‘‘%dt%d’’, a, b); The statement of 21 getch(); the else part is not 22 return 0; executed. 23 } 4-3
  • 46. 4 Selections 4.4 switch statement The switch statement is a conditional branching statement that selects among several statements or multiple statements based on constant values. The syntax and 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 executes any statements following the selected case label until a break, goto, or return statement 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 the nextStatement. Since this is usually what you want, you should almost always include 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, program flow continues with the statement that follows the matching case label. If none of the case labels match the switch condition, program flow continues at the default 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 control transfers outside of the switch statement. The following example will display the annual weather depending on the con- dition. 4-4
  • 47. 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 charge based on the type of vehicle (’c’ for car, ’b’ for bus, and ’t’ for truck) and the hours 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
  • 48. 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 not integral, 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 multiple decision. The expressions are evaluated in order. If an expression is true, the statement associated with it is executed, and this terminates the whole chain. The flow continues then to the nextStatement. As always, the code for each statement is either a single statement, or a group of them in braces. The last else part handles the “none of the above” or default case where none of the other conditions is satisfied. Sometimes the trailing else statement n may be used for error checking to catch an “impossible” condition. To remember that an else is always associated with the nearest previous if. The else - if construct is used only when: • The selection variable is not an integral. The expression has also a boolean value, true or false. • The same variable is being tested in the expression. The following program fragment demonstrates the use of else - if statement to solve a score – grade relationship problem. You are advised to refer to the associated flow chart to trace the steps in the source code. 4-6
  • 49. 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 an conditional expression. It has three operands and two operators. Each operand is 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
  • 50. 4 Selections 4.7 Exercises 1. If originally x = 0, y = 0 and z = 1, what is the value of x, y and z after executing 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 after executing 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 three integer numbers. Verify your answer by writing the corresponding program source code and test it. 4. If originally x = 1, y = 3 and z = 0, what is the value of x, y and z after executing 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’ for truck, 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
  • 51. 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 the memory constant, const. What is the difference between them? If none of the type of vehicle entered matches with any case label, displays wrong input. 4-9
  • 52.
  • 53. 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 series of 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 ensure that the action ends after the job is done, we must set a certain condition to control the loop. This condition checks after each iteration to see either the job is 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 is executed, and if the test condition is false, the loop is terminated and the control goes directly to the nextStatement. In the post–test loop, the statement is always executed at least once. At the end of every iteration, the condition is tested. If the condition is true, the loop repeats, but if the condition is false, the loop ends, and the control goes to the nextStatement. Two steps are required in working with a loop. 1. initialization The purpose of an initialization is to start the loop. In the pretest loop, the initial value of the test condition must be true. It is done before the first execution of the statement. 5-1
  • 54. 5 Repetition Figure 5.2: Pretest (left) and Post-Test (right) Loop 2. Updating The purpose of an updating is to repeat the execution of the statement and to 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 never stop. 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 statement execution. If the the statement in the loop is repeated x times, the updating is also done x times. The limit test for a loop can be expressed into two categories: 5-2
  • 55. 5.3 Loops in C 1. Event-controlled loop In this loop, the event changes the control condition or expression of the loop from true to false. For example, when reading data, reaching the end of data will change the loop control condition from true to false. 2. Counter-controlled loop When we know the number of times an action or an operation is to be executed, 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 two are pretest loop, and the later is a post-test loop. All of them can be used for event-controlled loop and counter-controlled loop. The while and do..while are the most commonly used for event-controlled loop, and for loop is usually used 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 a parenthesis {}. 5-3
  • 56. 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 the specified condition, expression, is true. The while statement tests expression and if 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 be performed 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(’nn’’’); 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("Excellentn"); break; 13 case ’B’: 14 case ’b’: printf("Goodn"); break; 15 default : printf("Invalid graden"); break; 16 } /* end switch */ 17 printf("nAgain? "); 18 scanf("%s", &answer); 19 } /* end while loop */ 20 } 5-4
  • 57. 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 Figure 5.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 condition is satisfied. Unlike the for and while loops, do ˇ while performs statement first E and then tests expression. If expression evaluates to nonzero (true), statement executes again, but when expression evaluates to zero (false), execution of the loop stops and the program control goes to the nextStatement. This type of loop is always executed at least once. Program Example for do..while Loop The program example calculates the summation of an integer that a user supplies and the summation of the squares of that integer. Mathematically, the summa- tion can be expressed as follows: n sum = i = 1 + 2 + 3 + ... + n i=1 n ∗ (n + 1) = 2 5-5
  • 58. 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: %dn ", 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: • Initialization The initialization expression that typically specifies the initial values of vari- ables. It is evaluated only once before the first iteration of the loop. • Condition control The controlling expression determines whether or not to terminate the loop. It is evaluated before each iteration of the loop. If the condition value is a nonzero, the statement is executed. If it evaluates to 0, execution of the statement is terminated and control passes to the nextStatement. This means that if the initial value of condition becomes zero, the statementis never executed. • Update expression This expression is the increment or decrement expression that typically incre- ments or decrement the variables initialized in initialization part. It is evalu- 5-6
  • 59. 5.6 for Loop ated after each iteration of the statement and before the next evaluation of 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 corresponding flow 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 following program fragment: for (j = 0; j < 10; j++){ printf(‘‘j = %dt’’, j); if (j % 4 == 0) /* new line */ printf(‘‘n’’); } getch(); 5-7
  • 60. 5 Repetition is the same as the following while loop: j = 0; while (j<10){ printf(‘‘j = %dt’’, 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 with the formula:    n  n! P (n, m) =   = (n − m)! 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) = %dnn", 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
  • 61. 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 iteration of the loop. In the while and do/while, this means the condition expression is tested immediately, and in the forloop, the update expression (if present) is evaluated. 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
  • 62. 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(‘‘%dn’’, x); x--; } b) for loop: for (x = 12; x > 7; x--){ printf(‘‘%dn’’, x); } c) do..while loop: x = 12; do{ printf(‘‘%dn’’, 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
  • 63. 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 n real numbers. As the numbers are read, the program will calculate the sum and the average of the positive numbers. The program repeats again from the beginning. The program terminates only 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: 1 1 1 1 1 1 e=1+ + + + + ... + + + 1! 2! 3! 4! (n − 1)! n! 5-11
  • 64.
  • 65. CHAPTER 6 Functions 6.1 Top-Down Design A program is divided into a main module and its related modules. The division of modules proceeds until the module consists only of elemantary processes and cannot be further sibdivided. This process is known as factoring. The top-down design 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 allowed only through a calling module. If Module 1 needs to send data to Module 2, the data must be passed through the calling module. No communication takes 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 Value In this technique, a copy of the data is made and the copy is sent to the called module. The original data in the calling module cannot be changed. 2. Pass By Reference The calling module sends the address of the data to the called module. In this case, the called module can change the original data in the calling module. 6.2 Functions in C • Top-down design is implemented using functions. A C program consists of one or more functions. One and only one of the functions must be named 6-1