Your SlideShare is downloading. ×
  • Like
Chapter1 6
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Chapter1 6

  • 1,490 views
Published

BTI10202/BTI1022 …

BTI10202/BTI1022
DTI2143

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,490
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
116
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 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. Table of Content1 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-52 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-143 Operators and Expressions 3-1 3.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1 3.1.1 Integer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2 3
  • 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-134 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-85 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-106 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-24
  • 4. Table of Content6.4 Recursive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-66.5 Parameter Passing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7 6.5.1 Pass by Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7 6.5.2 Pass by Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-86.6 Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-96.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10 5
  • 5. CHAPTER 1 Introduction1.1 Lesson PlanDelivery 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 Pembelajaran1.2 Computer systemWhat is computer?A computer is an automatic device that performs calculations, makes decisions,and has capacity for storing and processing vast amounts of data. A computerhas two main parts: hardware and software Computer HardwareHardware is the electronic and mechanical parts of the computer including: • Input device: Keyboard, Mouse, Scanner, Touch screener, Pen or stylus • Central Processing Unit (CPU). It executes instructions (arithmetic opera- tions) • Primary storage or main memory: RAM • Secondary storage: HD, FD, CD,DVD • Output device:Monitor, Printer, Plotter, Speaker Computer SoftwareTwo categories: System software and Application software • System software: it manages the H/W resources and performs processing tasks. Three classes : 1-1
  • 6. 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 programmingTo write a program for a computer, we must use a computer language or a pro-gramming language. • Machine language: Each computer has its own machine language consist- ing of 0s and 1s program. Not readable for human being. • Symbolic language: – Low-level language/Assembly language: Assembler – High-level language/Compiler: Fortran, Pascal, C, C++ • Natural language: in development phase Computer programming (often shortened to programming or coding) is theprocess of designing, writing, testing, debugging / troubleshooting, and main-taining the source code of computer programs. This source code is written in aprogramming language.1.4 Software development method • Specify problem • Analyze problem • Design algorithm • Implement algorithm (write a C program) • Test and verify program • Maintain and update program AlgorithmA set of instructions for solving a problem, or, an ordered sequence of unambigu-ous and well-defined instructions that performs some task and halts in finite time(Al Kho-war-iz-mi a 9th century Persian mathematician). AlgorithmThree Catagories of Algorithmic Operations1-2
  • 7. 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 instructionsHow 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 arrows1.5 Algorithm and Pseudo codePseudo codePseudo-Code is simply a numbered list of instructions to perform some task. Pseudo-code is best understood by looking at examples. Example 1Computing Sales Tax : Pseudo-code the task of computing the final price of anitem after figuring in sales tax. Note the three types of instructions: input (get orread), process/calculate (=) and output (display) 1. start 2. get price of item 3. get sales tax rate 4. sales tax = price of item * sales tax rate 5. final price = price of item + sales tax 6. display final price 7. halt/end 1-3
  • 8. 1 Introduction Example 2Computing Weekly Wages: Gross pay depends on the pay rate and the numberof hours worked per week. However, if you work more than 40 hours, you get paidtime-and-a-half for all hours worked over 40. Pseudo-code the task of computinggross pay given pay rate and hours worked. 1. start 2. get hours worked 3. if hours worked ≤ 40 then a) gross pay = pay rate * hours worked 4. else a) gross pay = pay rate * 40 + 1.5 * pay rate *(hours worked - 40) 5. display gross pay 6. halt/endExample 3Computing a Quiz Average: Pseudo-code a routine to calculate your quiz aver-age. 1. start 2. get number of quizzes 3. sum = 0 4. count = 0 5. while count < number of quizzes a) get quiz grade b) sum = sum + quiz grade c) count = count + 1 6. average = sum / number of quizzes 7. display average 8. halt/end Pseudo code construction Computation/Assignments"variable" = "expression"1-4
  • 9. 1.6 Flow chart Input/Outputget "variable", "variable", ...display "variable", "variable", Conditionif "condition"statement Iterativewhile "condition"statement Rules for a pseudo code construction 1. Consist of a statement of instructions in sequence 2. Every step consists of keyword 3. Every step should be written in different step, if continued, thr next row 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.ExerciseA box has a dimension in height, width, and length. Write a pseudo code tocalculate the volume of the box.More exercise in the lab work.1.6 Flow chartFlow chartflow chart gives the logical flow of the solution in a diagrammatic form, and pro-vides a plan from which the computer program can be written. The logical flowof an algorithm can be seen by tracing through the flowchart. Some standardsymbols: 1-5
  • 10. 1 IntroductionFlowchart constructs The flowchart equivalents for the structured programming constructs are shownbelow: Selection Sequence single (if) double (if-else) multiple (switch-case) Flowchart constructs,con’t1-6
  • 11. 1.6 Flow chart Repetition while do..while for Examples of a Flow chartExample 1 and 2 are solved using a flow chart:Exercises of algorithm constructionsSelf exercises 1. Construct a flowchart for the pseudo-code given in example 3. 2. Express an algorithm to get two numbers from the user ( dividend and divi- sor), testing to make sure that the divisor member is not zero, and 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
  • 12. 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
  • 13. CHAPTER 2 Structure of C Programs2.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 CompilerIn this course, Turbo C is used as the compiler and it works under MS-DOS. It canbe downloaded in internet for free (hopefully). Turbo C supports an IntegratedDevelopment Environment (IDE) and compiler for the C programming languagefrom Borland. 2-1
  • 14. 2 Structure of C Programs2.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
  • 15. 2.4 Structures of a C Program2.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 IdentifiersPurposes 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
  • 16. 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 word2.6 Data typesA data type defines a set of values and a set of operations that can be appliedon these values. A function has also a data type that returns after its call. Classi-fication of the data types in C language: • Basic data type • Derived data type • User-defined data typeIn this course, the emphasis is on the basic data type.2.6.1 Basic data typesThe size of a data type is machine dependent. It can vary from computer tocomputer. The most common sizes of the data sizes on 16 – bit machine areshown in table 2.1.2.6.1.1 QualifiersTo 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
  • 17. 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 VariablesA variable is a symbolic name for a certain memory location in a computer ma-chine. It has a type and consequently a memory size and a set of operations tomanipulate the data.2.7.1 Variable definition • Each variable must be first declared and defined before use. Every 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
  • 18. 2 Structure of C Programs We can initialize a variable at the definition time by an initial value using an assignment (=) operator.2.8 ConstantsConstants are data values that cannot be changed during the program execu-tion. Every constant has a data type.2.8.1 Integer constantsEventhough 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 + 1234LUOmitting 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 constantsFloating point constants are number with decimal parts and stored in memory astwo parts: the significand and the exponent. The default form for float constantis double. The Suffix F or f is used for a float type, and L or l for long double. Literal Value Type Example 0. 0.0 double double sum = 0. .0 0.0 double int sum = .0 -2.0f -2.0 float float sum = sum + -2.0f 3.1415926L 3.1415926 long double sum = sum + 3.1415926L2-6
  • 19. 2.8 Constants2.8.3 Character constantsA character constant is enclosed in two single quotes (apostrophes) such as ’y’.The value of a character constant is the numeric value of the character in themachine’s character set. For example, in the ASCII (American Standard Codesfor Information Interchange) character set the character constant ’0’ has thevalue 48, which is unrelated to the numeric value 0. Special characters that begin with a backslash () are used for special pur-posed (escape sequences). Symbolic name ASCII char. Symbolic name ASCII char. ’0’ null ’a’ alert (bell) ’b’ backspace ’t’ horizontal tab ’n’ newline ’v’ vertical tab ’r’ carriage return ’’ backslashThe 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 will5 printf (‘‘nChar %c in ASCII code be displayed in different output6 is a %d n’’,c,c); formats (%c and %d). There are 2557 } characters defined in ASCII code.2.8.4 String constantsA string constant, or string literal, is a sequence of zero or more characters sur-rounded by double quotes, as in:’’I am a string’’The quotes are not part of the string, but serve only to delimit it. Technically, astring constant is an array of characters. The internal representation of a stringhas a null character ’0’ at the end, so the physical storage required is one morethan the number of characters written between the quotes. Be careful to distinguish between a character constant and a string that con-tains a single character: ’x’ is not the same as “x”. The former is an integer, usedto produce the numeric value of the letter x in the machine’s character set. Thelatter is an array of characters that contains one character (the letter x) and a’0’. 2-7
  • 20. 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.1415911 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
  • 21. 2.9 Formatted Input/Output2.9 Formatted Input/OutputC 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 beginningpart of your program, see the program example above.2.9.1 printf() printf(format string, data list)The formatted output printf() requires two parameters: 1. format 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
  • 22. 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
  • 23. 2.10 Formatted input2.9.2 Output examplesThe 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 inputThe standard formatted input in C is scanf(). It requires two parameters : formatstring and address list. The format string describes the data and the address listidentifies where the data to be placed in memory. The format string in printf()can also be applied to scanf(). 2-11
  • 24. 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 examplesThe 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
  • 25. 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 KeywordsThe C language contains several keywords or reserved words that cannot beused for functions, variables, and named constants. They are shown in table 2.2. Table 2.2: Keywords of C language auto extern sizeof break case float static struct char for const goto switch continue if typedef default int union do long unsigned double register void else return volatile enum short while signed define main 2-13
  • 26. 2 Structure of C Programs2.13 ASCII Code Table Figure 2.1: 7-bit ASCII codes table2-14
  • 27. CHAPTER 3 Operators and ExpressionsOperators are symbols which take one or more operands or expressions and per-form arithmetic or logical computations of data. An expression is a sequence ofoperands and operators that reduces to a single value: Example of an expres-sion: 2 + 7 Plus sign (+) is the operator for addition and 2 and 7 are the operands thatreceive an action of the operator for an addition. This expression reduces to asingle value (9). C language has a set of operators including: 1 Arithmetic Operators 2 Relational and Logical Operators 3 Assignment Operators 4 Increments and Decrement Operators 5 Conditional Operators 6 Bit Operators There is no limit to the number of operator and operand sets that may be com-bined to form an expression. The only rule is that, when they have been evalu-ated the result is a single value that represents the expression.3.1 Arithmetic OperatorsAll the basic arithmetic operations can be carried out in C. All the operatorshave almost the same meaning as in other languages. Both unary and binaryoperations are available in C language. Unary operations operate on a singeoperand, therefore the number 5 when operated by unary – will have the value-5. 3-1
  • 28. 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 910 sum = num1+num2; /*addition of numbers and storing in sum.*/11 printf(‘‘n The sum is = %d’’,sum);/*display the output */1213 sub = num1-num2; /*subtraction of numbers and storing in sub.*/ 3-2
  • 29. 3.2 Relational and Logical Operators14 printf(‘‘n The difference is = %d’’,sub);/*display the output */1516 mul = num1*num2; /*multiplication and storing in mul. */17 printf(‘‘n The product is = %d’’,mul);/*display the output */1819 div = num1/num2; /*division of numbers and storing in div. */20 printf(‘‘n The division is = %d’’,div);/*display the output */2122 mod = num1%num2; /*modulus of numbers and storing in mod. */23 printf(‘‘n The modulus is = %d’’,mod);/*display the output */24 getch();25 } 3.1.2 Floating point arithmetic When an arithmetic operation is preformed on two real numbers or fraction num- bers such an operation is called floating point arithmetic. The floating point 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
  • 30. 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 variables6 int x,y,z;7 x = 2; y = 20; 3-4
  • 31. 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 T1213 /* relational operator */14 z = (x < y);1516 printf(¸n %d < %d = %dˇ, x,y,z); /* display x<y = z */ S T1718 z = x == y;19 3-5
  • 32. 3 Operators and Expressions20 printf(¸n %d < %d == %dˇ, x,y,z); /*display x == y = z*/ S T21 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
  • 33. 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 OperatorsAn increment or decrement expression is an unary expression. It has one oper-ator and one operand. The increment operator (++) adds 1 to its operand. Thedecrement operator (--) subtracts 1 from its operand. The operand must be ascalar value and it is illegal to increment or decrement a constant, structure, orunion. The postfix increment and decrement operators fetch the current value of thevariable and store a copy of it in a temporary location. The compiler then incre-ments or decrements the variable. The temporary copy, which has the variable’svalue before it was modified, is used in the expression. In many cases, you areinterested only in the side effect, not in the result of the expression. In these in-stances, it doesn’t matter whether you use postfix or prefix. You need to be careful, however, when you use the increment and decrementoperators within an expression.3.4.1 Side Effects of the Increment and Decrement OperatorsThe increment and decrement operators and the assignment operators causeside effects. That is, they not only result in a value, but they change the value ofa variable as well. A problem with side effect operators is that it is not always pos-sible to predict the order in which the side effects occur. Consider the followingstatement: 3-7
  • 34. 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
  • 35. 3.5 Bit Operators Table 3.7: Truth Table for Bitwise Logical AND Operator Bit of Operand1 Bit of Operand2 AND Relation Result 0 0 0 AND 0 0 0 1 0 AND 1 0 1 0 1 AND 0 0 1 1 1 AND 1 1 short int left_shifted_result, right_shifted_result; left_shifted_result = to_the_left << 2; right_shifted_result = to_the_right >> 2; sets left_shifted_result to 212 and right_shifted_result to 13. Theresults are clearer in binary: 0000000000110101 53 0000000011010100 212 /* 53 shifted left 2 bits */ 0000000000001101 13 /* 53 shifted right 2 bits */ Shifting to the left is equivalent to multiplying by powers of two:x << y is equivalent to x ∗ 2y .Shifting non-negative integers to the right is equivalent to dividing by powers of2: xx >> y is equivalent to y . 2 Make sure that the right operand is not larger than the size of the object beingshifted.3.5.2 Bit Logical OperatorsThe logical bitwise operators are similar to the Boolean operators, except thatthey operate on every bit in the operand(s). For instance, the bitwise AND op-erator (&) compares each bit of the left operand to the corresponding bit in therighthand operand. If both bits are 1, a 1 is placed at that bit position in the result.Otherwise, a 0 is placed at that bit position. • Bitwise AND Operator (&) The bitwise AND operator performs logical operations on a bit-by-bit level using the following truth table: The following example shows the use of the bitwise logical AND operator. 3-9
  • 36. 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 103.6 Cast OperatorTo cast a value means to explicitly convert it to another data type. The syntax ofa cast operator has the form:3-10
  • 37. 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 IntegersCasting a floating-value to an integer is made by by truncating the fractionalpart of the number. For example, the floating-point value 3.712 is converted tothe integer 3, and the floating-point value -504.2 is converted to -504. Anotherexamples: float f = 3.700, f2 = -502.2, f3 = 7.35e9; (int)f => 3 (unsigned int)f => 3 (char)f => 3 (int)f2 => -502 in decimal fffffe0a in hex (unsigned int)f2 => 4294966794 in decimal (char)f2 => 10 in decimal 0a in hex (int)f3 => run-time error (unsigned int)f3 => run-time error (char)f3 => run-time error Converting a large float to a char produces unpredictable results if the roundedvalue cannot fit in one byte. If the value cannot fit in four bytes, the run-time sys-tem issues an overflow error.3.7 Operator PrecedencePrecedence is the order in which the compiler groups operands with operators.The C compiler evaluates certain operators and their operands before others. Ifoperands are not grouped using parentheses, the compiler groups them accord-ing to its own rules. The table 3.8 lists the common used C operator precedencein highest to lowest precedence: 3-11
  • 38. 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 L3-12
  • 39. 3.8 Exercises3.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
  • 40. 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
  • 41. CHAPTER 4 SelectionsA selection statement alters a program’s execution flow by selecting one pathfrom a collection based on a specified controlling condition or expression. Usinga selection statement, the order of the computation flow is specified.4.1 Statements and BlockAn expression such as i = 0; or a += i becomes a statement if it is followedby a semicolon. A compound statement or a block consists of a group of state-ments that starts and ends with an curly bracket. Syntatically a block is equivalentto a single statement. Example of a block: { i = 0; a += i; printf(‘‘%2d : %3d’’,i, a); } There is no semicolon after the right curly bracket that indicates the block end.4.2 if statementif statement is used for a single selection with the syntax and the correspondingconstruct is as follows: if ( condition ) statement; nextStatement; if statement evaluates the value of condition to select either the statementis executed or not. C executes statement only if condition is true, if false, C fallsthrough to nextStatement without executing the statement. In C, a nonzero value 4-1
  • 42. 4 Selectionsrepresents true, and a zero value is used to represent a false condition. So, con-dition tests a numeric value, either 0 or nonzero. The following program fragmentcan be used to obtain an absolute value of an integer number by evaluating avalue of x. x = -2; if (x < 0) /* (-2 < 0) = (TRUE) = 1 */ x = -x; /* x = -(-2) = 2 */ printf(‘‘x = %3d’’,x); /* display x = 2 */To remember that the condition must be enclosed in parentheses (). If there aremore than one actions to be performed, they must be grouped into a compoundstatement, that is a pair of curly brackets ({}). Example: x = -2; if (x < 0){ /* Compound statement */ x = -x; printf(‘‘nx is initially a negative number: %3d’’,x); } printf(‘‘nabsolute value of x = %3d’’,x);4.3 if - else statementC implements the double selection with the if - else statement and is consi-dered as the basic decision statement in the computer programming language.The if statement is the simplified form of this statement. The syntax and the logicflow is shown in the figure below: if ( condition ) statement1; else statement2; nextStatement;if - else statement makes a decision between two alternatives. The com-puter selects which statement being executed depends on the value of the4-2
  • 43. 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 = 2010 if (b < min){11 min = b; /* swap the values */ a = 512 b = a; Display on the13 a = min; screen:14 printf(‘‘nb is greater than a.’’); b is greater than15 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 of21 getch(); the else part is not22 return 0; executed.23 } 4-3
  • 44. 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
  • 45. 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
  • 46. 4 Selections18 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
  • 47. 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 else14 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
  • 48. 4 Selections4.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
  • 49. 4.7 Exercises Vehicle Charge rate/hr. motor cycle RM 1.00 car RM 2.50 bus RM 3.50 truck RM 4.50Use the preprocesssor command define for the charge rates instead of thememory constant, const. What is the difference between them? If noneof the type of vehicle entered matches with any case label, displays wronginput. 4-9
  • 50. CHAPTER 5 RepetitionRepetition or looping is one of the basic structured programming concepts. Rep-etition shows the power of computers in ability to repeat an operation or a seriesof operations.5.1 Concept of a loopThe concept of a loop is shown in Figure 5.1. Figure 5.1: Loop concept The loop illustrates the statement is always repeated. It never stops. To ensurethat the action ends after the job is done, we must set a certain condition tocontrol the loop. This condition checks after each iteration to see either the jobis done or not. If not, it repeats one more time, and if it is done, it exists the loop.5.2 Pretest and Post–Test LoopIn pretest loop, the condition is checked before the loop starts and at the be-ginning of each iteration after the first. If the condition is true, the statement isexecuted, and if the test condition is false, the loop is terminated and the controlgoes directly to the nextStatement. In the post–test loop, the statement is always executed at least once. At theend of every iteration, the condition is tested. If the condition is true, the looprepeats, but if the condition is false, the loop ends, and the control goes to thenextStatement. Two steps are required in working with a loop. 1. 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
  • 51. 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 statementexecution. If the the statement in the loop is repeated x times, the updating isalso done x times. The limit test for a loop can be expressed into two categories:5-2
  • 52. 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 Loop5.3 Loops in CC language has three loop statements: for, while, and do..while. The first twoare pretest loop, and the later is a post-test loop. All of them can be used forevent-controlled loop and counter-controlled loop. The while and do..whileare the most commonly used for event-controlled loop, and for loop is usuallyused for counter-controlled loop.5.4 while LoopThe 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
  • 53. 5 Repetition while (expression) statement nextStatement Figure 5.5: while Loop and the flow chart The while statement executes the statements within a loop as long as thespecified condition, expression, is true. The while statement tests expression andif it is true (nonzero), statement is executed. Once expression becomes false (0),execution of the loop stops and the program control goes to the nextStatement.Since expression could be false the first time it is tested, statement may not beperformed even once.A program Example for while loop: 1 #include <stdio.h> 2 int main(void) { 3 char answer, grade; 4 answer = ’y’; 5 printf(’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
  • 54. 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? n5.5 do..while LoopThe syntax of the do..while with its corresponding flow chart are shown in Figure5.6. do statement; while (expression); nextStatement Figure 5.6: do..while Loop and the flow chart The do statement executes statement within a loop until a specified conditionis satisfied. Unlike the for and while loops, do ˇ while performs statement first Eand then tests expression. If expression evaluates to nonzero (true), statementexecutes again, but when expression evaluates to zero (false), execution of theloop stops and the program control goes to the nextStatement. This type ofloop is always executed at least once.Program Example for do..while LoopThe program example calculates the summation of an integer that a user suppliesand the summation of the squares of that integer. Mathematically, the summa-tion can be expressed as follows: n sum = i = 1 + 2 + 3 + ... + n i=1 n ∗ (n + 1) = 2 5-5
  • 55. 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? n5.6 for LoopThe 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
  • 56. 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 correspondingflow chart are shown in Figure 5.7.for (Initial; Condition; Update) statement;nextStatement; Figure 5.7: do..for loop and the flow chart The for statement can be formulated in while loop and vice versa. The equiv-alent construct in the while loop is given as follows: Initial; while (Condition) { statement; Update; } nextStatement; Example how to express the for loop with a while is shown in the followingprogram fragment: for (j = 0; j < 10; j++){ printf(‘‘j = %dt’’, j); if (j % 4 == 0) /* new line */ printf(‘‘n’’); } getch(); 5-7
  • 57. 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 LoopThe following program calculates the permutation of two integer numbers withthe 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 atime) separated by a space: 4 3P(4,3) = 245-8
  • 58. 5.7 continue Statement5.7 continue Statementcontinue belongs to the jump statements. The continue statement halts execu-tion of its enclosing for, while, or do/while loop and skips to the next iterationof the loop. In the while and do/while, this means the condition expressionis tested immediately, and in the forloop, the update expression (if present) isevaluated. The effect of the continue statement is illustrated in the Figure 5.8. Figure 5.8: The continue statement in the loop The following program fragment calculates the sum of only odd numbers: const int MAX = 10; int i, sum = 0; for (i = 0; i < MAX; i++){ if (i % 2) /* even number? yes, then */ continue; /* jump to i++ */ sum += i; } printf(‘‘sum = %3d’’,sum); 5-9
  • 59. 5 Repetition5.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 15-10
  • 60. 5.8 Exercises4. 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
  • 61. CHAPTER 6 Functions6.1 Top-Down DesignA program is divided into a main module and its related modules. The divisionof modules proceeds until the module consists only of elemantary processes andcannot be further sibdivided. This process is known as factoring. The top-downdesign is illustrated using a structure chart as shown in Figure 6.1. Terminology: • Main Module: Calling module. It has submodules, Module 1, 2, and 3. • Called Module: Module 1, 2, and 3. Communication between the main module and its submodules is 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
  • 62. 6 Functions main. The program always starts and ends with main function. It can call other functions to do specific task. See Figure 6.2. • A function in C is an independent module. A called function receives con- trol from a calling function. When the called function completes its task, it returns to the calling function. It mays or may not return a value to the caller function. The main function is called by the operating system for program execution. Figure 6.2: Structure chart for a C program • The purpose of a function is to receive zero or more data, operate on it, and returns at most one data.6.2.1 Advantages of Functions • Problems can be factored into understandable and manageable steps. • Functions provide a reuse code. Once a function is defined, it can be called anytime required. • C language provides a rich library for reuse. Example, a math library (math.h) contains lots of standard mathematic functions that make work easier for mathematic calculation including sqrt(), log(), cos(). • Functions protect data. Logical data defined in a function are available only to the function and while the function is executing. When the function is not running, the data is not accessible outside. Data in one function cannot be seen or changed by a function outside its scope.6.3 User-Defined FunctionsSteps working with functions:6-2
  • 63. 6.3 User-Defined Functions1. Function Declaration or prototype declaration. It consists only of a function header. A prototype header has three part: the return type, the function name, and formal parameters list. It terminates with a semicolon. Figure 6.3: Prototype declaration2. Function Definition. It contains the source code for the function and is made up of two parts. • Function header It consists three parts: – A return type: int, char, short, float, double, or void. – A function name: A name that complies with the syntax rule for an identifier. – The formal parameter list. It is a list of data for the communication purpose with the calling function. If there is no data to be passed, keyword void is declared. The formal parameter list defined hereby must be matched with that as declared in the prototype. • Function body It contains the local declarations and statements for the function. The function body terminates with a return statement. If void is used for the return type, it is allowed without return or return with no expres- sion or value. Figure 6.4: Function definition 6-3
  • 64. 6 Functions 3. Function Call A function call is a postfix expression and in the calling function, it is at a very high level in the precedence table. If a function call is used as a part of a larger expression, it will be first evaluated. The operand in a function call is the function name. The actual parameters identify the values to be sent to the called function. They must match in type and order of the formal parameters of the called function. Comma sign is used to separate the value of the parameters. A program example for the use of functions is shown by modifying the followingcodes into three functions. 1 #include <stdio.h> 2 int main(void){ 3 4 int a, b, c, d, total; 5 6 /* Input */ 7 printf("n "); 8 printf("nGive two integer numbers, separate by a comma: "); 9 scanf("%d %d", &a, &b); 10 printf("nGive two integer numbers, separate by a comma: "); 11 scanf("%d %d", &c, &d); 12 13 /* adding the values */ 14 tot = a + b + c * d; 15 16 /* display message */ 17 printf("n Display result: "); 18 printf("n "); 19 20 printf(" a + b + c *d = %3d", tot); 21 22 getch(); 23 return 0; 24 } The program is factored into five functions: • inputMessage() • addData() • multiply() • displayMessage(), and • main()The associated structure chart is illustrated in Figure 6.5.6-4
  • 65. 6.3 User-Defined Functions Figure 6.5: Structure chart of the function example program 1 #include <stdio.h> 2 void inputMessage(void); /* Prototype of functions */ 3 int addData(int a, int b); 4 int multiplyData(int a, int b); 5 void displayMessage(void); 6 7 void inputMessage(void){ /* Definition of function */ 8 printf("n "); 9 printf("nGive two integer numbers, separate by a comma: ");10 return ;11 }12 int multiplyData(int x, int y){ /* Definition of function */13 int mul;14 mul = x * y;15 return mul;16 }17 int addData(int x, int y){ /* Definition of function */18 int sum;19 sum = x + y;20 return sum;21 }22 void displayMessage(void){ /* Definition of function */23 printf("n Display result: ");24 printf("n ");25 return;26 }27 int main(void){ /* Definition of function */28 int a, b, c, d, tot;29 /* Input */30 inputMessage(); /* Function call */31 scanf("%d %d", &a, &b); /* Function call */32 inputMessage(); /* Function call */33 scanf("%d %d", &c, &d); /* Function call */34 /* adding the values */35 tot = addData(a, b) + multiplyData(c,d); /* Function call */36 /* display the values */37 displayMessage(); /* Function call */38 getch(); /* Function call */ 6-5
  • 66. 6 Functions39 printf(" a + b + c *d = %3d", tot);40 printf()41 return 0;42 } The summation of n integer numbers can be expressed: n sum = i = 1 + 2 + 3 + ... + n i=1 The implementation in C program is as follows: 1 int summation(int n){ 2 int i, sum; 3 sum = 0; 4 for (i = 1; i <= n; i++) 5 sum += i; 6 return sum; 7 } The program above can only be compiled but it cannot be run. To execute the program we need main function as shown below: 1 #include<stdio.h> 2 int summation(int n); /* prototype */ 3 4 int summation(int n){ 5 int i, sum; 6 sum = 0; 7 for (i = 1; i <= n; i++) 8 sum += i; 9 return sum; 10 } 11 12 int main(void){ 13 int n; 14 printf(‘‘n = ’’,&n); 15 scanf(‘‘%d’’, &n); 16 printf(‘‘The sum of n integers: %d’’, summation(n)); 17 getch(); 18 return 0; 19 } 6.4 Recursive Functions can be used recursively. In other words, a function can be called direct or indirectly. An example for the use of recursive is given through the factorial of 6-6
  • 67. 6.5 Parameter Passingn integer numbers: n! = 1 ∗ 2 ∗ 3 ∗ . . . ∗ n = n ∗ (n − 1)!, with 0! = 1! = 1The factorial problem can be solved either using one of the tree loops or a recur-sive function as shown as follows: 1 #include<stdio.h> 2 #include<conio.h> 3 int factorial(int ); /* prototype */ 4 5 int factorial(int n){ 6 int i; 7 8 if (n > 1) 9 return n * factorial(n-1); /* recursive */ 10 else 11 return 1; /* terminates the recursion */ 12 } 13 14 int main(void){ 15 int n; 16 clrscr(); 17 printf(’’n = ’’, &n); 18 scanf(‘‘%d’’, &n); 19 if (n < 0) 20 printf(’’nNegative number is not allowed!’’); 21 else 22 printf(’’The factorial of n integers: %d’’, factorial(n)); 23 getch(); 24 return 0; 25 }6.5 Parameter PassingParameters of the calling function can be passed to the called function by twotechniques that are described below.6.5.1 Pass by ValueSo far, all the parameters in the calling user-defined functions have been passedby value. The original values in in the calling function are never changed in thecalled functions because only a copy of the value is passed to the called func-tion. With this mechanism the original data is protected against any modificationoutside the function. 6-7
  • 68. 6 Functions6.5.2 Pass by AddressThe second mechanism for passing the actual parameters to the called functionis known as pass by address. The address of the original data in the calling func-tion is passed to the called function. The consequence is the called function hasthe chance to change the value because it refer to the same address. How thetwo mechanisms work is described by solving a sorting problem. Figure 6.6: Swap problem 1 #include<stdio.h> 2 #include<conio.h> 3 void swapByValue(int a, int b ); /* prototype */ 4 void swapByAddress(int *a, int *b ); 5 6 void swapByValue(int a, int b ){ 7 int temp; 8 temp = a; 9 a = b; 10 b = a; 11 } 12 13 void swapByAddress(int *a, int *b ){ 14 int temp; 15 temp = *a; 16 *a = *b; 17 *b = *a; 18 } 19 int main(void){ 20 int a, b; 21 a = 8, b = 5; 22 clrscr(); 23 printf(’’n%3d %3d ’’, a, b); 24 swapByValue(a, b); 25 printf(’’n%3d %3d ’’, a, b); 26 swapByAddress(&a, &b); 27 printf(’’n%3d %3d ’’, a, b); 28 getch(); 29 return 0; 30 }6-8
  • 69. 6.6 Math Library6.6 Math LibraryThe following mathematic functions are found in math.h library. Function Return type Prototype ceil double ceil(double number) exp double exp(double number) fabs double fabs(double number) floor double floor(double number) fmod double fmod(double number1, double number2) log double log(double number) log10 double log10(double number) pow double pow(double number1, double number2) sqrt double sqrt(double number) sin double sin(double number) sinh double sinh(double number) asin double asin(double number) cos double cos(double number) cosh double cosh(double number) acos double acos(double number) tan double tan(double number) tanh double tanh(double number) atan double atan(double number) atan2 double atan2(double number1, dounle number2) 6-9
  • 70. 6 Functions6.7 Exercises 1. Draw a structure chart for the following program. What output does it pro- duce? 1 #include<stdio.h> 2 #include<conio.h> 3 int funA(int x); 4 int funB(int x); 5 6 int main(){ 7 int a, b, c; 8 a = 10; 9 clrscr(); 10 funB(a); 11 b = 5; 12 funA(b); 13 c = funA(b); 14 funB(c); 15 printf(’’n%3d %3d %3d’’, a, b, c); 16 return 0; 17 } 18 19 int funA(int x){ 20 return c * x; 21 } 22 23 void funB(int x){ 24 int y; 25 y = x % 2; 26 x /= 2; 27 printf(’’n%3d %3dn’’, x, y); 28 return ; 29 } 2. Write a function to compute the perimeter c of a right angle, see Figure, when a and b given. c= a2 + b26-10
  • 71. 6.7 Exercises3. Write a function to sort four integer numbers entered by the keyboard in descending order. Example: Input : 2 5 6 1 Output: 1 2 5 64. Write a C function to calculate the permutation of two integer numbers with the formula:    n  n! P (n, m) =   = (n − m)! m 1 ∗ 2 ∗ ... ∗ n = 1 ∗ 2 ∗ . . . ∗ (n − m)5. To evaluate an integral numerically, a Simpson’s rule one-third can be ap- plied. The formula and the associated figure are shown below: x2 h f (x)dx = [f (x0 ) + 4f (x1 ) + f (x2 )] x0 3 x2 − x0 where h = , x1 = x0 + h 2 Write a C function for the Simpson’s rule one-third technique. Test your func- tion with f (x) = x2 + 1, and the lower and upper limits 0 and 1, respectively. For more accurate, divide the f (x) into N intervals, and apply the Simpson’s rule for each interval. Compare your result with the analytical value. 6-11