Chapter 1 – Introduction to Computers and C++ Programming Outline 1.1 Introduction 1.2 What Is a Computer? 1.3 Computer Or...
Chapter 1 – Introduction to Computers and C++ Programming Outline 1.15 Hardware Trends 1.16 History of the Internet 1.17 H...
1.1 Introduction <ul><li>We will learn </li></ul><ul><ul><li>The C programming language </li></ul></ul><ul><ul><li>Structu...
1.2  What is a Computer? <ul><li>Computer  </li></ul><ul><ul><li>Device capable of performing computations and making logi...
1.3 Computer Organization <ul><li>Six logical units in every computer: </li></ul><ul><ul><li>Input unit </li></ul></ul><ul...
1.4 Evolution of Operating Systems <ul><li>Batch processing </li></ul><ul><ul><li>Do only one job or task at a time </li><...
1.5 Personal Computing, Distributed Computing, and Client/Server Computing <ul><li>Personal computers  </li></ul><ul><ul><...
1.6 Machine Languages, Assembly Languages, and High-level Languages <ul><li>Three types of programming languages </li></ul...
1.6 Machine Languages, Assembly Languages, and High-level Languages <ul><ul><li>High-level languages </li></ul></ul><ul><u...
1.7 History of C <ul><li>C  </li></ul><ul><ul><li>Evolved by Ritchie from two previous programming languages, BCPL and B <...
1.8 The C Standard Library <ul><li>C programs consist of pieces/modules called functions </li></ul><ul><ul><li>A programme...
1.9 The Key Software Trend: Object Technology <ul><li>Objects  </li></ul><ul><ul><li>Reusable software components that mod...
1.10 C++ and C++ How to Program <ul><li>C++ </li></ul><ul><ul><li>Superset of C developed by Bjarne Stroustrup at Bell Lab...
1.11 Java and Java How to Program <ul><li>Java is used to  </li></ul><ul><ul><li>Create Web pages with dynamic and interac...
1.12 Other High-level Languages <ul><li>Other high-level languages </li></ul><ul><ul><li>FORTRAN  </li></ul></ul><ul><ul><...
1.13 Structured Programming <ul><li>Structured programming  </li></ul><ul><ul><li>Disciplined approach to writing programs...
1.14 Basics of a Typical C Program Development Environment <ul><li>Phases of C++ Programs: </li></ul><ul><ul><li>Edit </li...
1.15 Hardware Trends <ul><li>Every year or two the following approximately double: </li></ul><ul><ul><li>Amount of memory ...
1.16 History of the Internet <ul><li>The Internet enables </li></ul><ul><ul><li>Quick and easy communication via e-mail </...
1.17 History of the World Wide Web <ul><li>World Wide Web  </li></ul><ul><ul><li>Locate and view multimedia-based document...
1.18 General Notes About C and This Book <ul><li>Program clarity </li></ul><ul><ul><li>Programs that are convoluted are di...
Chapter 2 - Introduction to C Programming Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Ano...
2.1 Introduction <ul><li>C programming language </li></ul><ul><ul><li>Structured and disciplined approach to program desig...
2.2 A Simple C Program: Printing a Line of Text <ul><li>Comments </li></ul><ul><ul><li>Text surrounded by  /*  and  */  is...
2.2 A Simple C Program: Printing a Line of Text <ul><li>int main() </li></ul><ul><ul><li>C++ programs contain one or more ...
2.2 A Simple C Program: Printing a Line of Text <ul><li>printf(   &quot;Welcome to C!n&quot;   ); </li></ul><ul><ul><li>In...
2.2 A Simple C Program: Printing a Line of Text <ul><li>return   0; </li></ul><ul><ul><li>A way to exit a function </li></...
1. Initialize variables 2. Input 2.1 Sum 3. Print Program Output Enter first integer 45 Enter second integer 72 Sum is 117...
2.3 Another Simple C Program: Adding Two Integers <ul><li>As before </li></ul><ul><ul><li>Comments,  #include <stdio.h>  a...
2.3 Another Simple C Program: Adding Two Integers <ul><li>scanf( &quot;%d&quot;, &integer1 ); </li></ul><ul><ul><li>Obtain...
2.3 Another Simple C Program: Adding Two Integers <ul><li>=  (assignment operator) </li></ul><ul><ul><li>Assigns a value t...
2.4 Memory Concepts <ul><li>Variables  </li></ul><ul><ul><li>Variable names correspond to locations in the computer's memo...
2.5  Arithmetic <ul><li>Arithmetic calculations </li></ul><ul><ul><li>Use  *  for multiplication and  /  for division </li...
2.5  Arithmetic <ul><li>Arithmetic operators: </li></ul><ul><li>Rules of operator precedence: </li></ul>
2.6 Decision Making: Equality and Relational Operators <ul><li>Executable statements </li></ul><ul><ul><li>Perform actions...
2.6 Decision Making: Equality and Relational Operators
2.6 Decision Making: Equality and Relational Operators
1. Declare variables 2. Input 2.1  if  statements 3. Print 1 /* Fig. 2.13: fig02_13.c 2   Using if statements, relational ...
3.1 Exit  main Program Output Enter two integers, and I will tell you  the relationships they satisfy: 3 7 3 is not equal ...
Chapter 3 - Structured Program Development Outline 3.1 Introduction 3.2 Algorithms 3.3 Pseudocode 3.4 Control Structures 3...
3 .1 Introduction <ul><li>Before writing a program: </li></ul><ul><ul><li>Have a thorough understanding of the problem  </...
3 .2 Algorithms <ul><li>Computing problems  </li></ul><ul><ul><li>All can be solved by executing a series of actions in a ...
3 .3 Pseudocode <ul><li>Pseudocode </li></ul><ul><ul><li>Artificial, informal language that helps us develop algorithms </...
3 .4 Control Structures <ul><li>Sequential execution  </li></ul><ul><ul><li>Statements executed one after the other in the...
3 .4 Control Structures <ul><li>Flowchart  </li></ul><ul><ul><li>Graphical representation of an algorithm </li></ul></ul><...
3 .5 The  if  Selection Structure <ul><li>Selection structure:  </li></ul><ul><ul><li>Used to choose among alternative cou...
3 .5 The  if  Selection Structure <ul><li>Pseudocode statement in C: </li></ul><ul><ul><ul><li>if ( grade >= 60 )    print...
3 .5 The  if  Selection Structure <ul><li>if  structure is a single-entry/single-exit structure </li></ul>  A decision can...
3 .6 The  if / else  Selection Structure <ul><li>if </li></ul><ul><ul><li>Only performs an action if the condition is  tru...
3 .6 The  if / else  Selection Structure <ul><li>C code: </li></ul><ul><ul><ul><li>if ( grade >= 60 ) </li></ul></ul></ul>...
3 .6 The  if / else  Selection Structure <ul><li>Flow chart of the  if / else  selection structure </li></ul><ul><li>Neste...
3 .6 The  if / else  Selection Structure <ul><ul><li>Pseudocode for a nested  if / else  structure </li></ul></ul><ul><ul>...
3 .6 The  if / else  Selection Structure <ul><li>Compound statement:  </li></ul><ul><ul><li>Set of statements within a pai...
3 .6 The  if / else  Selection Structure <ul><li>Block: </li></ul><ul><ul><li>Compound statements with declarations </li><...
3 .7 The  while  Repetition Structure <ul><li>Repetition structure </li></ul><ul><ul><li>Programmer specifies an action to...
3 .7 The  while  Repetition Structure <ul><li>Example:  </li></ul><ul><ul><ul><li>int product = 2; </li></ul></ul></ul><ul...
3 .8 Formulating Algorithms (Counter-Controlled Repetition) <ul><li>Counter-controlled repetition </li></ul><ul><ul><li>Lo...
1.  Initialize Variables 2.  Execute Loop 3.  Output results 1 /* Fig. 3.6: fig03_06.c 2   Class average program with  3  ...
Program Output Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade...
3 .9 Formulating Algorithms with Top-Down, Stepwise Refinement <ul><li>Problem becomes:  </li></ul><ul><ul><li>Develop a c...
3 .9 Formulating Algorithms with Top-Down, Stepwise Refinement <ul><li>Top-down, stepwise refinement  </li></ul><ul><ul><l...
3 .9 Formulating Algorithms with Top-Down, Stepwise Refinement <ul><li>Refine the initialization phase from  Initialize va...
3 .9 Formulating Algorithms with Top-Down, Stepwise Refinement <ul><li>Refine  Calculate and print the class average  to <...
1.  Initialize Variables 2.  Get user input 2.1  Perform Loop 1 /* Fig. 3.8: fig03_08.c 2   Class average program with   3...
3.  Calculate Average 3.1  Print Results Program Output Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade,...
3.10  Nested control structures <ul><li>Problem  </li></ul><ul><ul><li>A college has a list of test results ( 1  = pass,  ...
3.10  Nested control structures <ul><li>Top level outline </li></ul><ul><ul><ul><li>Analyze exam results and decide if tui...
3.10  Nested control structures <ul><li>Refine  Input the ten quiz grades and count passes and failures  to  </li></ul><ul...
1.  Initialize variables 2.  Input data and count passes/failures 3.  Print results   1 /* Fig. 3.10: fig03_10.c 2   Analy...
Program Output Enter Result (1=pass,2=fail): 1 Enter Result (1=pass,2=fail): 2 Enter Result (1=pass,2=fail): 2 Enter Resul...
3 .11 Assignment Operators <ul><li>Assignment operators abbreviate assignment expressions </li></ul><ul><ul><ul><li>c = c ...
3 .12 Increment and Decrement Operators <ul><li>Increment operator ( ++ ) </li></ul><ul><ul><li>Can be used instead of  c+...
3 .12 Increment and Decrement Operators <ul><li>If  c  equals  5 , then  </li></ul><ul><ul><ul><li>printf(   &quot;%d&quot...
Chapter 5 - Functions Outline 5.1 Introduction 5.2 Program Modules in C 5.3 Math Library Functions 5.4 Functions 5.5 Funct...
5.1 Introduction <ul><li>Divide and conquer  </li></ul><ul><ul><li>Construct a program from smaller pieces or components <...
5.2 Program Modules in C <ul><li>Functions </li></ul><ul><ul><li>Modules in C </li></ul></ul><ul><ul><li>Programs combine ...
5.3 Math Library Functions <ul><li>Math library functions  </li></ul><ul><ul><li>perform common mathematical calculations ...
5.4 Functions <ul><li>Functions </li></ul><ul><ul><li>Modularize a program </li></ul></ul><ul><ul><li>All variables declar...
5.5 Function Definitions <ul><li>Function definition format </li></ul><ul><ul><ul><li>return-value-type  function-name( pa...
5.5 Function Definitions <ul><li>Function definition format (continued) </li></ul><ul><ul><ul><li>return-value-type  funct...
<ul><li>1.  Function prototype (3 parameters) </li></ul><ul><li>2.  Input values </li></ul><ul><li>2.1  Call function </li...
5.6 Function Prototypes <ul><li>Function prototype  </li></ul><ul><ul><li>Function name </li></ul></ul><ul><ul><li>Paramet...
5.7 Header Files <ul><li>Header files </li></ul><ul><ul><li>Contain function prototypes for library functions </li></ul></...
5.8 Calling Functions: Call by Value and Call by Reference <ul><li>Used when invoking functions </li></ul><ul><li>Call by ...
5.9 Random Number Generation <ul><li>rand  function </li></ul><ul><ul><li>Load  <stdlib.h> </li></ul></ul><ul><ul><li>Retu...
5.9 Random Number Generation <ul><li>srand  function </li></ul><ul><ul><li><stdlib.h> </li></ul></ul><ul><ul><li>Takes an ...
1.  Initialize seed 2.  Input value for seed 2.1  Use  srand  to change random sequence 2.2  Define Loop  3.  Generate and...
Program Output Enter seed: 867 2  4  6  1  6 1  1  3  6  2    Enter seed: 67 6  1  4  6  2 1  6  1  6  4   Enter seed: 67 ...
5.10 Example: A Game of Chance <ul><li>Craps simulator </li></ul><ul><li>Rules </li></ul><ul><ul><li>Roll two dice </li></...
1.  rollDice  prototype 1.1  Initialize variables 1.2  Seed  srand   2.  Define  switch  statement for win/loss/continue 2...
2.2  Print win/loss Program Output Player rolled 6 + 5 = 11 Player wins 33   if  ( sum == myPoint )  /* win by making poin...
Program Output Player rolled 6 + 6 = 12 Player loses   Player rolled 4 + 6 = 10 Point is 10 Player rolled 2 + 4 = 6 Player...
5.11 Storage Classes <ul><li>Storage class specifiers </li></ul><ul><ul><li>Storage duration  –  how long an object exists...
5.11 Storage Classes <ul><li>Static storage  </li></ul><ul><ul><li>Variables exist for entire program execution </li></ul>...
5.12 Scope Rules <ul><li>File scope  </li></ul><ul><ul><li>Identifier defined outside function, known in all functions </l...
5.12 Scope Rules <ul><li>Block scope  </li></ul><ul><ul><li>Identifier declared inside a block  </li></ul></ul><ul><ul><ul...
1.  Function prototypes 1.1  Initialize global variable 1.2  Initialize local variable 1.3  Initialize local variable in b...
3.1 Function definitions 31 32   printf( &quot;local x in main is %dn&quot;, x ); 33   return  0; 34 } 35 36 void  a(  voi...
Program Output local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5...
5.13 Recursion <ul><li>Recursive functions  </li></ul><ul><ul><li>Functions that call themselves </li></ul></ul><ul><ul><l...
5.13 Recursion <ul><li>Example: factorials </li></ul><ul><ul><li>5! = 5 * 4 * 3 * 2 * 1 </li></ul></ul><ul><ul><li>Notice ...
5.14 Example Using Recursion: The Fibonacci Series <ul><li>Fibonacci series: 0, 1, 1, 2, 3, 5, 8... </li></ul><ul><ul><li>...
5.14 Example Using Recursion: The Fibonacci Series <ul><li>Set of recursive calls to function  fibonacci </li></ul>  f( 3 ...
1.  Function prototype 1.1  Initialize variables 2.  Input an integer 2.1  Call function  fibonacci 2.2  Output results. 3...
Program Output Enter an integer: 2 Fibonacci(2) = 1 Enter an integer: 3 Fibonacci(3) = 2 Enter an integer: 4 Fibonacci(4) ...
5.15 Recursion vs. Iteration <ul><li>Repetition </li></ul><ul><ul><li>Iteration:  explicit loop </li></ul></ul><ul><ul><li...
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays 6.3 Declaring Arrays 6.4 Examples Using Arrays 6.5 Passing Arrays t...
6.1 Introduction <ul><li>Arrays  </li></ul><ul><ul><li>Structures of related data items </li></ul></ul><ul><ul><li>Static ...
6.2 Arrays <ul><li>Array </li></ul><ul><ul><li>Group of consecutive memory locations  </li></ul></ul><ul><ul><li>Same name...
6.2 Arrays <ul><li>Array elements are like normal variables </li></ul><ul><ul><ul><li>c[ 0 ] =  3; </li></ul></ul></ul><ul...
6.3 Declaring Arrays <ul><li>When declaring arrays, specify </li></ul><ul><ul><li>Name </li></ul></ul><ul><ul><li>Type of ...
6.4 Examples Using Arrays <ul><li>Initializers </li></ul><ul><ul><ul><li>int n[ 5 ] = { 1, 2, 3, 4, 5 };  </li></ul></ul><...
1. Initialize array 2.  Loop 3. Print 1 /* Fig. 6.8: fig06_08.c 2   Histogram printing program */ 3 #include  <stdio.h> 4 ...
Program Output Element  Value  Histogram 0  19  ******************* 1  3  *** 2  15  *************** 3  7  ******* 4  11  ...
6.4 Examples Using Arrays <ul><li>Character arrays </li></ul><ul><ul><li>String  “first”  is really a static array of char...
1.  Initialize strings 2.  Print strings 2.1  Define loop 2.2  Print characters  individually 2.3  Input string 3.  Print ...
6.5 Passing Arrays to Functions <ul><li>Passing arrays </li></ul><ul><ul><li>To pass an array argument to a function, spec...
6.5 Passing Arrays to Functions <ul><li>Function prototype </li></ul><ul><ul><ul><li>void modifyArray( int b[], int arrayS...
1. Function definitions 2. Pass array to a function 2.1 Pass array element to a function 3. Print 1 /* Fig. 6.13: fig06_13...
3.1 Function definitions Program Output Effects of passing entire array call by reference: The values of the original arra...
6.6 Sorting Arrays <ul><li>Sorting data </li></ul><ul><ul><li>Important computing application </li></ul></ul><ul><ul><li>V...
6.7 Case Study: Computing Mean, Median and Mode Using Arrays <ul><li>Mean  –  average </li></ul><ul><li>Median  –  number ...
1.  Function prototypes 1.1  Initialize array 2.  Call functions  mean ,  median , and  mode 1 /* Fig. 6.16: fig06_16.c 2 ...
3.  Define function  mean 3.1  Define function  median 3.1.1 Sort Array 3.1.2 Print middle element 33 34 void  mean(  cons...
3.2  Define function  mode 3.2.1 Increase  frequency[]  depending on  response[] 65 } 66 67 void  mode(  int  freq[],  con...
3.3 Define  bubbleSort 3.3 Define  printArray 95   printf( &quot;n&quot; ); 96   } 97 98   printf( &quot;The mode is the m...
Program Output ******** Mean ******** The mean is the average value of the data items. The mean is equal to the total of a...
Program Output ******** Mode ******** Response  Frequency  Histogram   1  1  2  2 5  0  5  0  5   1  1  * 2  3  *** 3  4  ...
6.8 Searching Arrays: Linear Search and Binary Search <ul><li>Search an array for a  key value </li></ul><ul><li>Linear se...
6.8 Searching Arrays: Linear Search and Binary Search <ul><li>Binary search  </li></ul><ul><ul><li>For sorted arrays </li>...
6.9 Multiple-Subscripted Arrays <ul><li>Multiple subscripted arrays  </li></ul><ul><ul><li>Tables with rows and columns ( ...
6.9 Multiple-Subscripted Arrays <ul><li>Initialization </li></ul><ul><ul><li>int b[   2   ][   2   ]   =   {   {   1,   2 ...
1.  Initialize variables 1.1  Define functions to take double scripted arrays 1.2  Initialize  studentgrades[][] 2.  Call ...
3.  Define functions 33 34 /* Find the minimum grade */ 35 int  minimum(  const   int  grades[][ EXAMS ],  36   int  pupil...
3.  Define functions 65   int  i, total = 0; 66 67   for  ( i = 0; i <= tests - 1; i++ ) 68   total += setOfGrades[ i ]; 6...
Program Output The array is: [0]  [1]  [2]  [3] studentGrades[0] 77  68  86  73  studentGrades[1] 96  87  89  78  studentG...
Chapter 7 - Pointers Outline 7.1 Introduction 7.2 Pointer Variable Declarations and Initialization 7.3 Pointer Operators 7...
7.1 Introduction <ul><li>Pointers  </li></ul><ul><ul><li>Powerful, but difficult to master </li></ul></ul><ul><ul><li>Simu...
7.2 Pointer Variable Declarations and Initialization <ul><li>Pointer variables </li></ul><ul><ul><li>Contain memory addres...
7.2 Pointer Variable Declarations and Initialization <ul><li>Pointer declarations </li></ul><ul><ul><li>*  used with point...
7.3 Pointer Operators <ul><li>&  (address operator) </li></ul><ul><ul><li>Returns address of operand </li></ul></ul><ul><u...
7.3 Pointer Operators <ul><li>*  (indirection/dereferencing operator) </li></ul><ul><ul><li>Returns a synonym/alias of wha...
1.  Declare variables 2  Initialize variables 3.  Print Program Output The address of a is 0012FF88 The value of aPtr is 0...
7.4 Calling Functions by Reference <ul><li>Call by reference with pointer arguments </li></ul><ul><ul><li>Pass address of ...
<ul><li>Function prototype </li></ul><ul><li>1.1  Initialize variables </li></ul><ul><li>2.  Call function </li></ul><ul><...
7.5 Using the  const  Qualifier with Pointers <ul><li>const  qualifier </li></ul><ul><ul><li>Variable cannot be changed </...
1.  Declare variables 1.1  Declare  const  pointer to an  int 2.  Change  *ptr  (which is  x ) 2.1  Attempt to change  ptr...
7.6 Bubble Sort Using Call-by-reference <ul><li>Implement bubblesort using pointers </li></ul><ul><ul><li>Swap two element...
7.6 Bubble Sort Using Call-by-reference <ul><li>sizeof </li></ul><ul><ul><li>Returns size of operand in bytes </li></ul></...
1.  Initialize array 1.1  Declare variables 2.  Print array 2.1  Call  bubbleSort 2.2  Print array 1 /* Fig. 7.15: fig07_1...
3. Function definitions Program Output Data items in original order 2  6  4  8  10  12  89  68  45  37 Data items in ascen...
7.7 Pointer Expressions and Pointer Arithmetic <ul><li>Arithmetic operations can be performed on pointers </li></ul><ul><u...
7.7 Pointer Expressions and Pointer Arithmetic <ul><li>5 element  int  array on machine with 4 byte  int s </li></ul><ul><...
7.7 Pointer Expressions and Pointer Arithmetic <ul><li>Subtracting pointers </li></ul><ul><ul><li>Returns number of elemen...
7.7 Pointer Expressions and Pointer Arithmetic <ul><li>Pointers of the same type can be assigned to each other </li></ul><...
7.8 The Relationship Between Pointers and Arrays <ul><li>Arrays and pointers closely related </li></ul><ul><ul><li>Array n...
7.8 The Relationship Between Pointers and Arrays <ul><ul><li>Element  b[   3   ]  </li></ul></ul><ul><ul><ul><li>Can be ac...
7.9 Arrays of Pointers <ul><li>Arrays can contain pointers </li></ul><ul><li>For example: an array of strings </li></ul><u...
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Book ppt
Upcoming SlideShare
Loading in...5
×

Book ppt

2,153

Published on

Published in: Education, Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,153
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
157
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Book ppt

  1. 1. Chapter 1 – Introduction to Computers and C++ Programming Outline 1.1 Introduction 1.2 What Is a Computer? 1.3 Computer Organization 1.4 Evolution of Operating Systems 1.5 Personal Computing, Distributed Computing and Client/Server Computing 1.6 Machine Languages, Assembly Languages and High-level Languages 1.7 The History of C 1.8 The C Standard Library 1.9 The Key Software Trend: Object Technology 1.10 C++ and C++ How to Program 1.11 Java and Java How to Program 1.12 Other High-level Languages 1.13 Structured Programming 1.14 The Basics of a typical C Program Development Environment
  2. 2. Chapter 1 – Introduction to Computers and C++ Programming Outline 1.15 Hardware Trends 1.16 History of the Internet 1.17 History of the World Wide Web 1.18 General Notes About C and this Book
  3. 3. 1.1 Introduction <ul><li>We will learn </li></ul><ul><ul><li>The C programming language </li></ul></ul><ul><ul><li>Structured programming and proper programming techniques </li></ul></ul><ul><li>This book also covers </li></ul><ul><ul><li>C++ </li></ul></ul><ul><ul><ul><li>Chapter 15 – 23 introduce the C++ programming language </li></ul></ul></ul><ul><ul><li>Java </li></ul></ul><ul><ul><ul><li>Chapters 24 – 30 introduce the Java programming language </li></ul></ul></ul><ul><li>This course is appropriate for </li></ul><ul><ul><li>Technically oriented people with little or no programming experience </li></ul></ul><ul><ul><li>Experienced programmers who want a deep and rigorous treatment of the language </li></ul></ul>
  4. 4. 1.2 What is a Computer? <ul><li>Computer </li></ul><ul><ul><li>Device capable of performing computations and making logical decisions </li></ul></ul><ul><ul><li>Computers process data under the control of sets of instructions called computer programs </li></ul></ul><ul><li>Hardware </li></ul><ul><ul><li>Various devices comprising a computer </li></ul></ul><ul><ul><li>Keyboard, screen, mouse, disks, memory, CD-ROM, and processing units </li></ul></ul><ul><li>Software </li></ul><ul><ul><li>Programs that run on a computer </li></ul></ul>
  5. 5. 1.3 Computer Organization <ul><li>Six logical units in every computer: </li></ul><ul><ul><li>Input unit </li></ul></ul><ul><ul><ul><li>Obtains information from input devices (keyboard, mouse) </li></ul></ul></ul><ul><ul><li>Output unit </li></ul></ul><ul><ul><ul><li>Outputs information (to screen, to printer, to control other devices) </li></ul></ul></ul><ul><ul><li>Memory unit </li></ul></ul><ul><ul><ul><li>Rapid access, low capacity, stores input information </li></ul></ul></ul><ul><ul><li>Arithmetic and logic unit (ALU) </li></ul></ul><ul><ul><ul><li>Performs arithmetic calculations and logic decisions </li></ul></ul></ul><ul><ul><li>Central processing unit (CPU) </li></ul></ul><ul><ul><ul><li>Supervises and coordinates the other sections of the computer </li></ul></ul></ul><ul><ul><li>Secondary storage unit </li></ul></ul><ul><ul><ul><li>Cheap, long-term, high-capacity storage </li></ul></ul></ul><ul><ul><ul><li>Stores inactive programs </li></ul></ul></ul>
  6. 6. 1.4 Evolution of Operating Systems <ul><li>Batch processing </li></ul><ul><ul><li>Do only one job or task at a time </li></ul></ul><ul><li>Operating systems </li></ul><ul><ul><li>Manage transitions between jobs </li></ul></ul><ul><ul><li>Increased throughput </li></ul></ul><ul><ul><ul><li>Amount of work computers process </li></ul></ul></ul><ul><li>Multiprogramming </li></ul><ul><ul><li>Computer resources are shared by many jobs or tasks </li></ul></ul><ul><li>Timesharing </li></ul><ul><ul><li>Computer runs a small portion of one user’s job then moves on to service the next user </li></ul></ul>
  7. 7. 1.5 Personal Computing, Distributed Computing, and Client/Server Computing <ul><li>Personal computers </li></ul><ul><ul><li>Economical enough for individual </li></ul></ul><ul><li>Distributed computing </li></ul><ul><ul><li>Computing distributed over networks </li></ul></ul><ul><li>Client/server computing </li></ul><ul><ul><li>Sharing of information across computer networks between file servers and clients (personal computers) </li></ul></ul>
  8. 8. 1.6 Machine Languages, Assembly Languages, and High-level Languages <ul><li>Three types of programming languages </li></ul><ul><ul><li>Machine languages </li></ul></ul><ul><ul><ul><li>Strings of numbers giving machine specific instructions </li></ul></ul></ul><ul><ul><ul><li>Example: </li></ul></ul></ul><ul><ul><ul><ul><ul><li>+1300042774 </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>+1400593419 </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>+1200274027 </li></ul></ul></ul></ul></ul><ul><ul><li>Assembly languages </li></ul></ul><ul><ul><ul><li>English-like abbreviations representing elementary computer operations (translated via assemblers) </li></ul></ul></ul><ul><ul><ul><li>Example: </li></ul></ul></ul><ul><ul><ul><ul><ul><li>LOAD BASEPAY </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>ADD OVERPAY </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>STORE GROSSPAY </li></ul></ul></ul></ul></ul>
  9. 9. 1.6 Machine Languages, Assembly Languages, and High-level Languages <ul><ul><li>High-level languages </li></ul></ul><ul><ul><ul><li>Codes similar to everyday English </li></ul></ul></ul><ul><ul><ul><li>Use mathematical notations (translated via compilers) </li></ul></ul></ul><ul><ul><ul><li>Example: </li></ul></ul></ul><ul><ul><ul><ul><li>grossPay = basePay + overTimePay </li></ul></ul></ul></ul>
  10. 10. 1.7 History of C <ul><li>C </li></ul><ul><ul><li>Evolved by Ritchie from two previous programming languages, BCPL and B </li></ul></ul><ul><ul><li>Used to develop UNIX </li></ul></ul><ul><ul><li>Used to write modern operating systems </li></ul></ul><ul><ul><li>Hardware independent (portable) </li></ul></ul><ul><ul><li>By late 1970's C had evolved to &quot;Traditional C&quot; </li></ul></ul><ul><li>Standardization </li></ul><ul><ul><li>Many slight variations of C existed, and were incompatible </li></ul></ul><ul><ul><li>Committee formed to create a &quot;unambiguous, machine-independent&quot; definition </li></ul></ul><ul><ul><li>Standard created in 1989, updated in 1999 </li></ul></ul>
  11. 11. 1.8 The C Standard Library <ul><li>C programs consist of pieces/modules called functions </li></ul><ul><ul><li>A programmer can create his own functions </li></ul></ul><ul><ul><ul><li>Advantage: the programmer knows exactly how it works </li></ul></ul></ul><ul><ul><ul><li>Disadvantage: time consuming </li></ul></ul></ul><ul><ul><li>Programmers will often use the C library functions </li></ul></ul><ul><ul><ul><li>Use these as building blocks </li></ul></ul></ul><ul><ul><li>Avoid re-inventing the wheel </li></ul></ul><ul><ul><ul><li>If a premade function exists, generally best to use it rather than write your own </li></ul></ul></ul><ul><ul><ul><li>Library functions carefully written, efficient, and portable </li></ul></ul></ul>
  12. 12. 1.9 The Key Software Trend: Object Technology <ul><li>Objects </li></ul><ul><ul><li>Reusable software components that model items in the real world </li></ul></ul><ul><ul><li>Meaningful software units </li></ul></ul><ul><ul><ul><li>Date objects, time objects, paycheck objects, invoice objects, audio objects, video objects, file objects, record objects, etc. </li></ul></ul></ul><ul><ul><ul><li>Any noun can be represented as an object </li></ul></ul></ul><ul><ul><li>Very reusable </li></ul></ul><ul><ul><li>More understandable, better organized, and easier to maintain than procedural programming </li></ul></ul><ul><ul><li>Favor modularity </li></ul></ul>
  13. 13. 1.10 C++ and C++ How to Program <ul><li>C++ </li></ul><ul><ul><li>Superset of C developed by Bjarne Stroustrup at Bell Labs </li></ul></ul><ul><ul><li>&quot;Spruces up&quot; C, and provides object-oriented capabilities </li></ul></ul><ul><ul><li>Object-oriented design very powerful </li></ul></ul><ul><ul><ul><li>10 to 100 fold increase in productivity </li></ul></ul></ul><ul><ul><li>Dominant language in industry and academia </li></ul></ul><ul><li>Learning C++ </li></ul><ul><ul><li>Because C++ includes C, some feel it is best to master C, then learn C++ </li></ul></ul><ul><ul><li>Starting in Chapter 15, we begin our introduction to C++ </li></ul></ul>
  14. 14. 1.11 Java and Java How to Program <ul><li>Java is used to </li></ul><ul><ul><li>Create Web pages with dynamic and interactive content </li></ul></ul><ul><ul><li>Develop large-scale enterprise applications </li></ul></ul><ul><ul><li>Enhance the functionality of Web servers </li></ul></ul><ul><ul><li>Provide applications for consumer devices (such as cell phones, pagers and personal digital assistants) </li></ul></ul><ul><li>Java How to Program </li></ul><ul><ul><li>Closely followed the development of Java by Sun </li></ul></ul><ul><ul><li>Teaches first-year programming students the essentials of graphics, images, animation, audio, video, database, networking, multithreading and collaborative computing </li></ul></ul>
  15. 15. 1.12 Other High-level Languages <ul><li>Other high-level languages </li></ul><ul><ul><li>FORTRAN </li></ul></ul><ul><ul><ul><li>Used for scientific and engineering applications </li></ul></ul></ul><ul><ul><li>COBOL </li></ul></ul><ul><ul><ul><li>Used to manipulate large amounts of data </li></ul></ul></ul><ul><ul><li>Pascal </li></ul></ul><ul><ul><ul><li>Intended for academic use </li></ul></ul></ul>
  16. 16. 1.13 Structured Programming <ul><li>Structured programming </li></ul><ul><ul><li>Disciplined approach to writing programs </li></ul></ul><ul><ul><li>Clear, easy to test and debug and easy to modify </li></ul></ul><ul><li>Multitasking </li></ul><ul><ul><li>Specifying that many activities run in parallel </li></ul></ul>
  17. 17. 1.14 Basics of a Typical C Program Development Environment <ul><li>Phases of C++ Programs: </li></ul><ul><ul><li>Edit </li></ul></ul><ul><ul><li>Preprocess </li></ul></ul><ul><ul><li>Compile </li></ul></ul><ul><ul><li>Link </li></ul></ul><ul><ul><li>Load </li></ul></ul><ul><ul><li>Execute </li></ul></ul>Program is created in the editor and stored on disk.   Preprocessor program processes the code. Loader puts program in memory. CPUtakes each instruction and executes it, possibly storing new data values as the program executes. Compiler creates object code and stores it on disk. Linker links the object code with the libraries Loader Primary Memory Compiler Editor Preprocessor Linker   Primary Memory . . . . . . . . . . . . Disk Disk Disk CPU Disk Disk
  18. 18. 1.15 Hardware Trends <ul><li>Every year or two the following approximately double: </li></ul><ul><ul><li>Amount of memory in which to execute programs </li></ul></ul><ul><ul><li>Amount of secondary storage (such as disk storage) </li></ul></ul><ul><ul><ul><li>Used to hold programs and data over the longer term </li></ul></ul></ul><ul><ul><li>Processor speeds </li></ul></ul><ul><ul><ul><li>The speeds at which computers execute their programs </li></ul></ul></ul>
  19. 19. 1.16 History of the Internet <ul><li>The Internet enables </li></ul><ul><ul><li>Quick and easy communication via e-mail </li></ul></ul><ul><ul><li>International networking of computers </li></ul></ul><ul><li>Packet switching </li></ul><ul><ul><li>The transfer of digital data via small packets </li></ul></ul><ul><ul><li>Allows multiple users to send and receive data simultaneously </li></ul></ul><ul><li>No centralized control </li></ul><ul><ul><li>If one part of the Internet fails, other parts can still operate </li></ul></ul><ul><li>Bandwidth </li></ul><ul><ul><li>Information carrying capacity of communications lines </li></ul></ul>
  20. 20. 1.17 History of the World Wide Web <ul><li>World Wide Web </li></ul><ul><ul><li>Locate and view multimedia-based documents on almost any subject </li></ul></ul><ul><ul><li>Makes information instantly and conveniently accessible worldwide </li></ul></ul><ul><ul><li>Possible for individuals and small businesses to get worldwide exposure </li></ul></ul><ul><ul><li>Changing the way business is done </li></ul></ul>
  21. 21. 1.18 General Notes About C and This Book <ul><li>Program clarity </li></ul><ul><ul><li>Programs that are convoluted are difficult to read, understand, and modify </li></ul></ul><ul><li>C is a portable language </li></ul><ul><ul><li>Programs can run on many different computers </li></ul></ul><ul><ul><li>However, portability is an elusive goal </li></ul></ul><ul><li>We will do a careful walkthrough of C </li></ul><ul><ul><li>Some details and subtleties are not covered </li></ul></ul><ul><ul><li>If you need additional technical details </li></ul></ul><ul><ul><ul><li>Read the C standard document </li></ul></ul></ul><ul><ul><ul><li>Read the book by Kernigan and Ritchie </li></ul></ul></ul>
  22. 22. Chapter 2 - Introduction to C Programming Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic in C 2.6 Decision Making: Equality and Relational Operators
  23. 23. 2.1 Introduction <ul><li>C programming language </li></ul><ul><ul><li>Structured and disciplined approach to program design </li></ul></ul><ul><li>Structured programming </li></ul><ul><ul><li>Introduced in chapters 3 and 4 </li></ul></ul><ul><ul><li>Used throughout the remainder of the book </li></ul></ul>
  24. 24. 2.2 A Simple C Program: Printing a Line of Text <ul><li>Comments </li></ul><ul><ul><li>Text surrounded by /* and */ is ignored by computer </li></ul></ul><ul><ul><li>Used to describe program </li></ul></ul><ul><li>#include <stdio.h> </li></ul><ul><ul><li>Preprocessor directive </li></ul></ul><ul><ul><ul><li>Tells computer to load contents of a certain file </li></ul></ul></ul><ul><ul><li><stdio.h> allows standard input/output operations </li></ul></ul>Welcome to C! 1 /* Fig. 2.1: fig02_01.c 2 A first program in C */ 3 #include <stdio.h> 4 5 int main() 6 { 7 printf( &quot;Welcome to C!n&quot; ); 8 9 return 0; 10 }
  25. 25. 2.2 A Simple C Program: Printing a Line of Text <ul><li>int main() </li></ul><ul><ul><li>C++ programs contain one or more functions, exactly one of which must be main </li></ul></ul><ul><ul><li>Parenthesis used to indicate a function </li></ul></ul><ul><ul><li>int means that main &quot;returns&quot; an integer value </li></ul></ul><ul><ul><li>Braces ( { and } ) indicate a block </li></ul></ul><ul><ul><ul><li>The bodies of all functions must be contained in braces </li></ul></ul></ul>
  26. 26. 2.2 A Simple C Program: Printing a Line of Text <ul><li>printf( &quot;Welcome to C!n&quot; ); </li></ul><ul><ul><li>Instructs computer to perform an action </li></ul></ul><ul><ul><ul><li>Specifically, prints the string of characters within quotes ( “ ” ) </li></ul></ul></ul><ul><ul><li>Entire line called a statement </li></ul></ul><ul><ul><ul><li>All statements must end with a semicolon ( ; ) </li></ul></ul></ul><ul><ul><li>Escape character ( ) </li></ul></ul><ul><ul><ul><li>Indicates that printf should do something out of the ordinary </li></ul></ul></ul><ul><ul><ul><li>n is the newline character </li></ul></ul></ul>
  27. 27. 2.2 A Simple C Program: Printing a Line of Text <ul><li>return 0; </li></ul><ul><ul><li>A way to exit a function </li></ul></ul><ul><ul><li>return 0 , in this case, means that the program terminated normally </li></ul></ul><ul><li>Right brace } </li></ul><ul><ul><li>Indicates end of main has been reached </li></ul></ul><ul><li>Linker </li></ul><ul><ul><li>When a function is called, linker locates it in the library </li></ul></ul><ul><ul><li>Inserts it into object program </li></ul></ul><ul><ul><li>If function name is misspelled, the linker will produce an error because it will not be able to find function in the library </li></ul></ul>
  28. 28. 1. Initialize variables 2. Input 2.1 Sum 3. Print Program Output Enter first integer 45 Enter second integer 72 Sum is 117 1 /* Fig. 2.5: fig02_05.c 2 Addition program */ 3 #include <stdio.h> 4 5 int main() 6 { 7 int integer1, integer2, sum; /* declaration */ 8 9 printf( &quot;Enter first integern&quot; ); /* prompt */ 10 scanf( &quot;%d&quot;, &integer1 ); /* read an integer */ 11 printf( &quot;Enter second integern&quot; ); /* prompt */ 12 scanf( &quot;%d&quot;, &integer2 ); /* read an integer */ 13 sum = integer1 + integer2; /* assignment of sum */ 14 printf( &quot;Sum is %dn&quot;, sum ); /* print sum */ 15 16 return 0; /* indicate that program ended successfully */ 17 }
  29. 29. 2.3 Another Simple C Program: Adding Two Integers <ul><li>As before </li></ul><ul><ul><li>Comments, #include <stdio.h> and main </li></ul></ul><ul><li>int integer1, integer2, sum; </li></ul><ul><ul><li>Declaration of variables </li></ul></ul><ul><ul><ul><li>Variables: locations in memory where a value can be stored </li></ul></ul></ul><ul><ul><li>int means the variables can hold integers ( -1 , 3 , 0 , 47 ) </li></ul></ul><ul><ul><li>Variable names (identifiers) </li></ul></ul><ul><ul><ul><li>integer1 , integer2 , sum </li></ul></ul></ul><ul><ul><ul><li>Identifiers: consist of letters, digits (cannot begin with a digit) and underscores( _ ) </li></ul></ul></ul><ul><ul><ul><ul><li>Case sensitive </li></ul></ul></ul></ul><ul><ul><li>Declarations appear before executable statements </li></ul></ul><ul><ul><ul><li>If an executable statement references and undeclared variable it will produce a syntax (compiler) error </li></ul></ul></ul>
  30. 30. 2.3 Another Simple C Program: Adding Two Integers <ul><li>scanf( &quot;%d&quot;, &integer1 ); </li></ul><ul><ul><li>Obtains a value from the user </li></ul></ul><ul><ul><ul><li>scanf uses standard input (usually keyboard) </li></ul></ul></ul><ul><ul><li>This scanf statement has two arguments </li></ul></ul><ul><ul><ul><li>%d - indicates data should be a decimal integer </li></ul></ul></ul><ul><ul><ul><li>&integer1 - location in memory to store variable </li></ul></ul></ul><ul><ul><ul><li>& is confusing in beginning – for now, just remember to include it with the variable name in scanf statements </li></ul></ul></ul><ul><ul><li>When executing the program the user responds to the scanf statement by typing in a number, then pressing the enter (return) key </li></ul></ul>
  31. 31. 2.3 Another Simple C Program: Adding Two Integers <ul><li>= (assignment operator) </li></ul><ul><ul><li>Assigns a value to a variable </li></ul></ul><ul><ul><li>Is a binary operator (has two operands) </li></ul></ul><ul><ul><ul><li>sum = variable1 + variable2; </li></ul></ul></ul><ul><ul><ul><li>sum gets variable1 + variable2; </li></ul></ul></ul><ul><ul><li>Variable receiving value on left </li></ul></ul><ul><li>printf( &quot;Sum is %dn&quot;, sum ); </li></ul><ul><ul><li>Similar to scanf </li></ul></ul><ul><ul><ul><li>%d means decimal integer will be printed </li></ul></ul></ul><ul><ul><ul><li>sum specifies what integer will be printed </li></ul></ul></ul><ul><ul><li>Calculations can be performed inside printf statements </li></ul></ul><ul><ul><ul><li>printf( &quot;Sum is %dn&quot;, integer1 + integer2 ); </li></ul></ul></ul>
  32. 32. 2.4 Memory Concepts <ul><li>Variables </li></ul><ul><ul><li>Variable names correspond to locations in the computer's memory </li></ul></ul><ul><ul><li>Every variable has a name, a type, a size and a value </li></ul></ul><ul><ul><li>Whenever a new value is placed into a variable (through scanf , for example), it replaces (and destroys) the previous value </li></ul></ul><ul><ul><li>Reading variables from memory does not change them </li></ul></ul><ul><li>A visual representation </li></ul>integer1 45
  33. 33. 2.5 Arithmetic <ul><li>Arithmetic calculations </li></ul><ul><ul><li>Use * for multiplication and / for division </li></ul></ul><ul><ul><li>Integer division truncates remainder </li></ul></ul><ul><ul><ul><li>7 / 5 evaluates to 1 </li></ul></ul></ul><ul><ul><li>Modulus operator( % ) returns the remainder </li></ul></ul><ul><ul><ul><li>7 % 5 evaluates to 2 </li></ul></ul></ul><ul><li>Operator precedence </li></ul><ul><ul><li>Some arithmetic operators act before others (i.e., multiplication before addition) </li></ul></ul><ul><ul><ul><li>Use parenthesis when needed </li></ul></ul></ul><ul><ul><li>Example: Find the average of three variables a , b and c </li></ul></ul><ul><ul><ul><li>Do not use: a + b + c / 3 </li></ul></ul></ul><ul><ul><ul><li>Use: (a + b + c ) / 3 </li></ul></ul></ul>
  34. 34. 2.5 Arithmetic <ul><li>Arithmetic operators: </li></ul><ul><li>Rules of operator precedence: </li></ul>
  35. 35. 2.6 Decision Making: Equality and Relational Operators <ul><li>Executable statements </li></ul><ul><ul><li>Perform actions (calculations, input/output of data) </li></ul></ul><ul><ul><li>Perform decisions </li></ul></ul><ul><ul><ul><li>May want to print &quot;pass&quot; or &quot;fail&quot; given the value of a test grade </li></ul></ul></ul><ul><li>if control structure </li></ul><ul><ul><li>Simple version in this section, more detail later </li></ul></ul><ul><ul><li>If a condition is true , then the body of the if statement executed </li></ul></ul><ul><ul><ul><li>0 is false , non-zero is true </li></ul></ul></ul><ul><ul><li>Control always resumes after the if structure </li></ul></ul><ul><li>Keywords </li></ul><ul><ul><li>Special words reserved for C </li></ul></ul><ul><ul><li>Cannot be used as identifiers or variable names </li></ul></ul>
  36. 36. 2.6 Decision Making: Equality and Relational Operators
  37. 37. 2.6 Decision Making: Equality and Relational Operators
  38. 38. 1. Declare variables 2. Input 2.1 if statements 3. Print 1 /* Fig. 2.13: fig02_13.c 2 Using if statements, relational 3 operators, and equality operators */ 4 #include <stdio.h> 5 6 int main() 7 { 8 int num1, num2; 9 10 printf( &quot;Enter two integers, and I will tell youn&quot; ); 11 printf( &quot;the relationships they satisfy: &quot; ); 12 scanf( &quot;%d%d&quot;, &num1, &num2 ); /* read two integers */ 13 14 if ( num1 == num2 ) 15 printf( &quot;%d is equal to %dn&quot;, num1, num2 ); 16 17 if ( num1 != num2 ) 18 printf( &quot;%d is not equal to %dn&quot;, num1, num2 ); 19 20 if ( num1 < num2 ) 21 printf( &quot;%d is less than %dn&quot;, num1, num2 ); 22 23 if ( num1 > num2 ) 24 printf( &quot;%d is greater than %dn&quot;, num1, num2 ); 25 26 if ( num1 <= num2 ) 27 printf( &quot;%d is less than or equal to %dn&quot;, 28 num1, num2 );
  39. 39. 3.1 Exit main Program Output Enter two integers, and I will tell you the relationships they satisfy: 3 7 3 is not equal to 7 3 is less than 7 3 is less than or equal to 7 Enter two integers, and I will tell you the relationships they satisfy: 22 12 22 is not equal to 12 22 is greater than 12 22 is greater than or equal to 12 29 30 if ( num1 >= num2 ) 31 printf( &quot;%d is greater than or equal to %dn&quot;, 32 num1, num2 ); 33 34 return 0; /* indicate program ended successfully */ 35 }
  40. 40. Chapter 3 - Structured Program Development Outline 3.1 Introduction 3.2 Algorithms 3.3 Pseudocode 3.4 Control Structures 3.5 The If Selection Structure 3.6 The If/Else Selection Structure 3.7 The While Repetition Structure 3.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) 3.9 Formulating Algorithms with Top-down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) 3.10 Formulating Algorithms with Top-down, Stepwise Refinement: Case Study 3 (Nested Control Structures) 3.11 Assignment Operators 3.12 Increment and Decrement Operators
  41. 41. 3 .1 Introduction <ul><li>Before writing a program: </li></ul><ul><ul><li>Have a thorough understanding of the problem </li></ul></ul><ul><ul><li>Carefully plan an approach for solving it </li></ul></ul><ul><li>While writing a program: </li></ul><ul><ul><li>Know what “building blocks” are available </li></ul></ul><ul><ul><li>Use good programming principles </li></ul></ul>
  42. 42. 3 .2 Algorithms <ul><li>Computing problems </li></ul><ul><ul><li>All can be solved by executing a series of actions in a specific order </li></ul></ul><ul><li>Algorithm: procedure in terms of </li></ul><ul><ul><li>Actions to be executed </li></ul></ul><ul><ul><li>The order in which these actions are to be executed </li></ul></ul><ul><li>Program control </li></ul><ul><ul><li>Specify order in which statements are to executed </li></ul></ul>
  43. 43. 3 .3 Pseudocode <ul><li>Pseudocode </li></ul><ul><ul><li>Artificial, informal language that helps us develop algorithms </li></ul></ul><ul><ul><li>Similar to everyday English </li></ul></ul><ul><ul><li>Not actually executed on computers </li></ul></ul><ul><ul><li>Helps us “think out” a program before writing it </li></ul></ul><ul><ul><ul><li>Easy to convert into a corresponding C++ program </li></ul></ul></ul><ul><ul><ul><li>Consists only of executable statements </li></ul></ul></ul>
  44. 44. 3 .4 Control Structures <ul><li>Sequential execution </li></ul><ul><ul><li>Statements executed one after the other in the order written </li></ul></ul><ul><li>Transfer of control </li></ul><ul><ul><li>When the next statement executed is not the next one in sequence </li></ul></ul><ul><ul><li>Overuse of goto statements led to many problems </li></ul></ul><ul><li>Bohm and Jacopini </li></ul><ul><ul><li>All programs written in terms of 3 control structures </li></ul></ul><ul><ul><ul><li>Sequence structures: Built into C. Programs executed sequentially by default </li></ul></ul></ul><ul><ul><ul><li>Selection structures: C has three types: if , if / else , and switch </li></ul></ul></ul><ul><ul><ul><li>Repetition structures: C has three types: while , do / while and for </li></ul></ul></ul>
  45. 45. 3 .4 Control Structures <ul><li>Flowchart </li></ul><ul><ul><li>Graphical representation of an algorithm </li></ul></ul><ul><ul><li>Drawn using certain special-purpose symbols connected by arrows called flowlines </li></ul></ul><ul><ul><li>Rectangle symbol (action symbol): </li></ul></ul><ul><ul><ul><li>Indicates any type of action </li></ul></ul></ul><ul><ul><li>Oval symbol: </li></ul></ul><ul><ul><ul><li>Indicates the beginning or end of a program or a section of code </li></ul></ul></ul><ul><li>Single-entry/single-exit control structures </li></ul><ul><ul><li>Connect exit point of one control structure to entry point of the next (control-structure stacking) </li></ul></ul><ul><ul><li>Makes programs easy to build </li></ul></ul>
  46. 46. 3 .5 The if Selection Structure <ul><li>Selection structure: </li></ul><ul><ul><li>Used to choose among alternative courses of action </li></ul></ul><ul><ul><li>Pseudocode: </li></ul></ul><ul><ul><ul><li>If student’s grade is greater than or equal to 60 Print “Passed” </li></ul></ul></ul><ul><li>If condition true </li></ul><ul><ul><li>Print statement executed and program goes on to next statement </li></ul></ul><ul><ul><li>If false , print statement is ignored and the program goes onto the next statement </li></ul></ul><ul><ul><li>Indenting makes programs easier to read </li></ul></ul><ul><ul><ul><li>C ignores whitespace characters </li></ul></ul></ul>
  47. 47. 3 .5 The if Selection Structure <ul><li>Pseudocode statement in C: </li></ul><ul><ul><ul><li>if ( grade >= 60 ) printf( &quot;Passedn&quot; ); </li></ul></ul></ul><ul><ul><li>C code corresponds closely to the pseudocode </li></ul></ul><ul><li>Diamond symbol (decision symbol) </li></ul><ul><ul><li>Indicates decision is to be made </li></ul></ul><ul><ul><li>Contains an expression that can be true or false </li></ul></ul><ul><ul><li>Test the condition, follow appropriate path </li></ul></ul>
  48. 48. 3 .5 The if Selection Structure <ul><li>if structure is a single-entry/single-exit structure </li></ul>  A decision can be made on any expression. zero - false nonzero - true Example: 3 - 4 is true true false grade >= 60 print “Passed”
  49. 49. 3 .6 The if / else Selection Structure <ul><li>if </li></ul><ul><ul><li>Only performs an action if the condition is true </li></ul></ul><ul><li>if / else </li></ul><ul><ul><li>Specifies an action to be performed both when the condition is true and when it is false </li></ul></ul><ul><li>Psuedocode: </li></ul><ul><ul><ul><li>If student’s grade is greater than or equal to 60 Print “Passed” </li></ul></ul></ul><ul><ul><ul><li>else Print “Failed” </li></ul></ul></ul><ul><ul><li>Note spacing/indentation conventions </li></ul></ul> 
  50. 50. 3 .6 The if / else Selection Structure <ul><li>C code: </li></ul><ul><ul><ul><li>if ( grade >= 60 ) </li></ul></ul></ul><ul><ul><ul><li>printf( &quot;Passedn&quot;); </li></ul></ul></ul><ul><ul><ul><li>else </li></ul></ul></ul><ul><ul><ul><li>printf( &quot;Failedn&quot;); </li></ul></ul></ul><ul><li>Ternary conditional operator ( ?: ) </li></ul><ul><ul><li>Takes three arguments (condition, value if true , value if false ) </li></ul></ul><ul><ul><li>Our pseudocode could be written: </li></ul></ul><ul><ul><ul><li>printf( &quot;%sn&quot;, grade >= 60 ? &quot;Passed&quot; : &quot;Failed&quot; ); </li></ul></ul></ul><ul><ul><li>Or it could have been written: </li></ul></ul><ul><ul><ul><li>grade >= 60 ? printf( “Passedn” ) : printf( “Failedn” ); </li></ul></ul></ul>
  51. 51. 3 .6 The if / else Selection Structure <ul><li>Flow chart of the if / else selection structure </li></ul><ul><li>Nested if / else structures </li></ul><ul><ul><li>Test for multiple cases by placing if / else selection structures inside if / else selection structures </li></ul></ul><ul><ul><li>Once condition is met, rest of statements skipped </li></ul></ul><ul><ul><li>Deep indentation usually not used in practice </li></ul></ul>true false print “Failed” print “Passed” grade >= 60
  52. 52. 3 .6 The if / else Selection Structure <ul><ul><li>Pseudocode for a nested if / else structure </li></ul></ul><ul><ul><li>If student’s grade is greater than or equal to 90 Print “A” else If student’s grade is greater than or equal to 80 Print “B” else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F” </li></ul></ul>
  53. 53. 3 .6 The if / else Selection Structure <ul><li>Compound statement: </li></ul><ul><ul><li>Set of statements within a pair of braces </li></ul></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>if ( grade >= 60 ) </li></ul></ul></ul><ul><ul><ul><li>printf( &quot;Passed.n&quot; ); </li></ul></ul></ul><ul><ul><ul><li>else { </li></ul></ul></ul><ul><ul><ul><li>printf( &quot;Failed.n&quot; ); </li></ul></ul></ul><ul><ul><ul><li>printf( &quot;You must take this course again.n&quot; ); } </li></ul></ul></ul><ul><ul><li>Without the braces, the statement </li></ul></ul><ul><ul><ul><ul><li>printf( &quot;You must take this course again.n&quot; ); </li></ul></ul></ul></ul><ul><ul><ul><li>would be executed automatically </li></ul></ul></ul>
  54. 54. 3 .6 The if / else Selection Structure <ul><li>Block: </li></ul><ul><ul><li>Compound statements with declarations </li></ul></ul><ul><li>Syntax errors </li></ul><ul><ul><li>Caught by compiler </li></ul></ul><ul><li>Logic errors: </li></ul><ul><ul><li>Have their effect at execution time </li></ul></ul><ul><ul><li>Non-fatal: program runs, but has incorrect output </li></ul></ul><ul><ul><li>Fatal: program exits prematurely </li></ul></ul>
  55. 55. 3 .7 The while Repetition Structure <ul><li>Repetition structure </li></ul><ul><ul><li>Programmer specifies an action to be repeated while some condition remains true </li></ul></ul><ul><ul><li>Psuedocode: </li></ul></ul><ul><ul><ul><li>While there are more items on my shopping list Purchase next item and cross it off my list </li></ul></ul></ul><ul><ul><li>while loop repeated until condition becomes false </li></ul></ul> 
  56. 56. 3 .7 The while Repetition Structure <ul><li>Example: </li></ul><ul><ul><ul><li>int product = 2; </li></ul></ul></ul><ul><ul><ul><li>while ( product <= 1000 ) product = 2 * product; </li></ul></ul></ul>product <= 1000 product = 2 * product true false
  57. 57. 3 .8 Formulating Algorithms (Counter-Controlled Repetition) <ul><li>Counter-controlled repetition </li></ul><ul><ul><li>Loop repeated until counter reaches a certain value </li></ul></ul><ul><ul><li>Definite repetition: number of repetitions is known </li></ul></ul><ul><ul><li>Example: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz </li></ul></ul><ul><ul><li>Pseudocode: </li></ul></ul><ul><ul><ul><li>Set total to zero Set grade counter to one </li></ul></ul></ul><ul><ul><ul><li>While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter </li></ul></ul></ul><ul><ul><ul><li>Set the class average to the total divided by ten Print the class average </li></ul></ul></ul>
  58. 58. 1. Initialize Variables 2. Execute Loop 3. Output results 1 /* Fig. 3.6: fig03_06.c 2 Class average program with 3 counter-controlled repetition */ 4 #include <stdio.h> 5 6 int main() 7 { 8 int counter, grade, total, average; 9 10 /* initialization phase */ 11 total = 0; 12 counter = 1; 13 14 /* processing phase */ 15 while ( counter <= 10 ) { 16 printf( &quot;Enter grade: &quot; ); 17 scanf( &quot;%d&quot;, &grade ); 18 total = total + grade; 19 counter = counter + 1; 20 } 21 22 /* termination phase */ 23 average = total / 10; 24 printf( &quot;Class average is %dn&quot;, average ); 25 26 return 0; /* indicate program ended successfully */ 27 }
  59. 59. Program Output Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81
  60. 60. 3 .9 Formulating Algorithms with Top-Down, Stepwise Refinement <ul><li>Problem becomes: </li></ul><ul><ul><li>Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. </li></ul></ul><ul><ul><li>Unknown number of students </li></ul></ul><ul><ul><li>How will the program know to end? </li></ul></ul><ul><li>Use sentinel value </li></ul><ul><ul><li>Also called signal value, dummy value, or flag value </li></ul></ul><ul><ul><li>Indicates “end of data entry.” </li></ul></ul><ul><ul><li>Loop ends when user inputs the sentinel value </li></ul></ul><ul><ul><li>Sentinel value chosen so it cannot be confused with a regular input (such as -1 in this case) </li></ul></ul>
  61. 61. 3 .9 Formulating Algorithms with Top-Down, Stepwise Refinement <ul><li>Top-down, stepwise refinement </li></ul><ul><ul><li>Begin with a pseudocode representation of the top : </li></ul></ul><ul><ul><ul><li>Determine the class average for the quiz </li></ul></ul></ul><ul><ul><li>Divide top into smaller tasks and list them in order: </li></ul></ul><ul><ul><ul><li>Initialize variables Input, sum and count the quiz grades Calculate and print the class average </li></ul></ul></ul><ul><li>Many programs have three phases: </li></ul><ul><ul><li>Initialization: initializes the program variables </li></ul></ul><ul><ul><li>Processing: inputs data values and adjusts program variables accordingly </li></ul></ul><ul><ul><li>Termination: calculates and prints the final results </li></ul></ul>
  62. 62. 3 .9 Formulating Algorithms with Top-Down, Stepwise Refinement <ul><li>Refine the initialization phase from Initialize variables to: </li></ul><ul><ul><ul><li>Initialize total to zero Initialize counter to zero </li></ul></ul></ul><ul><li>Refine Input, sum and count the quiz grades to </li></ul><ul><ul><ul><li>Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) </li></ul></ul></ul>
  63. 63. 3 .9 Formulating Algorithms with Top-Down, Stepwise Refinement <ul><li>Refine Calculate and print the class average to </li></ul><ul><ul><ul><li>If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “No grades were entered” </li></ul></ul></ul>
  64. 64. 1. Initialize Variables 2. Get user input 2.1 Perform Loop 1 /* Fig. 3.8: fig03_08.c 2 Class average program with 3 sentinel-controlled repetition */ 4 #include <stdio.h> 5 6 int main() 7 { 8 float average; /* new data type */ 9 int counter, grade, total; 10 11 /* initialization phase */ 12 total = 0; 13 counter = 0; 14 15 /* processing phase */ 16 printf( &quot;Enter grade, -1 to end: &quot; ); 17 scanf( &quot;%d&quot;, &grade ); 18 19 while ( grade != -1 ) { 20 total = total + grade; 21 counter = counter + 1; 22 printf( &quot;Enter grade, -1 to end: &quot; ); 23 scanf( &quot;%d&quot;, &grade ); 24 }
  65. 65. 3. Calculate Average 3.1 Print Results Program Output Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.50 25 26 /* termination phase */ 27 if ( counter != 0 ) { 28 average = ( float ) total / counter; 29 printf( &quot;Class average is %.2f&quot;, average ); 30 } 31 else 32 printf( &quot;No grades were enteredn&quot; ); 33 34 return 0; /* indicate program ended successfully */ 35 }
  66. 66. 3.10 Nested control structures <ul><li>Problem </li></ul><ul><ul><li>A college has a list of test results ( 1 = pass, 2 = fail) for 10 students </li></ul></ul><ul><ul><li>Write a program that analyzes the results </li></ul></ul><ul><ul><ul><li>If more than 8 students pass, print &quot;Raise Tuition&quot; </li></ul></ul></ul><ul><li>Notice that </li></ul><ul><ul><li>The program must process 10 test results </li></ul></ul><ul><ul><ul><li>Counter-controlled loop will be used </li></ul></ul></ul><ul><ul><li>Two counters can be used </li></ul></ul><ul><ul><ul><li>One for number of passes, one for number of fails </li></ul></ul></ul><ul><ul><li>Each test result is a number—either a 1 or a 2 </li></ul></ul><ul><ul><ul><li>If the number is not a 1 , we assume that it is a 2 </li></ul></ul></ul>
  67. 67. 3.10 Nested control structures <ul><li>Top level outline </li></ul><ul><ul><ul><li>Analyze exam results and decide if tuition should be raised </li></ul></ul></ul><ul><li>First Refinement </li></ul><ul><ul><ul><li>Initialize variables </li></ul></ul></ul><ul><ul><ul><li>Input the ten quiz grades and count passes and failures </li></ul></ul></ul><ul><ul><ul><li>Print a summary of the exam results and decide if tuition should be raised </li></ul></ul></ul><ul><li>Refine Initialize variables to </li></ul><ul><ul><ul><li>Initialize passes to zero </li></ul></ul></ul><ul><ul><ul><li>Initialize failures to zero </li></ul></ul></ul><ul><ul><ul><li>Initialize student counter to one </li></ul></ul></ul>
  68. 68. 3.10 Nested control structures <ul><li>Refine Input the ten quiz grades and count passes and failures to </li></ul><ul><ul><ul><li>While student counter is less than or equal to ten Input the next exam result </li></ul></ul></ul><ul><ul><ul><li>If the student passed </li></ul></ul></ul><ul><ul><ul><li> Add one to passes else Add one to failures </li></ul></ul></ul><ul><ul><ul><li>Add one to student counter </li></ul></ul></ul><ul><li>Refine Print a summary of the exam results and decide if tuition should be raised to </li></ul><ul><ul><ul><li>Print the number of passes </li></ul></ul></ul><ul><ul><ul><li>Print the number of failures </li></ul></ul></ul><ul><ul><ul><li>If more than eight students passed Print “Raise tuition” </li></ul></ul></ul>
  69. 69. 1. Initialize variables 2. Input data and count passes/failures 3. Print results 1 /* Fig. 3.10: fig03_10.c 2 Analysis of examination results */ 3 #include <stdio.h> 4 5 int main() 6 { 7 /* initializing variables in declarations */ 8 int passes = 0, failures = 0, student = 1, result; 9 10 /* process 10 students; counter-controlled loop */ 11 while ( student <= 10 ) { 12 printf( &quot;Enter result ( 1=pass,2=fail ): &quot; ); 13 scanf( &quot;%d&quot;, &result ); 14 15 if ( result == 1 ) /* if/else nested in while */ 16 passes = passes + 1; 17 else 18 failures = failures + 1; 19 20 student = student + 1; 21 } 22 23 printf( &quot;Passed %dn&quot;, passes ); 24 printf( &quot;Failed %dn&quot;, failures ); 25 26 if ( passes > 8 ) 27 printf( &quot;Raise tuitionn&quot; ); 28 29 return 0; /* successful termination */ 30 }
  70. 70. Program Output Enter Result (1=pass,2=fail): 1 Enter Result (1=pass,2=fail): 2 Enter Result (1=pass,2=fail): 2 Enter Result (1=pass,2=fail): 1 Enter Result (1=pass,2=fail): 1 Enter Result (1=pass,2=fail): 1 Enter Result (1=pass,2=fail): 2 Enter Result (1=pass,2=fail): 1 Enter Result (1=pass,2=fail): 1 Enter Result (1=pass,2=fail): 2 Passed 6 Failed 4
  71. 71. 3 .11 Assignment Operators <ul><li>Assignment operators abbreviate assignment expressions </li></ul><ul><ul><ul><li>c = c + 3; </li></ul></ul></ul><ul><ul><li>can be abbreviated as c += 3; using the addition assignment operator </li></ul></ul><ul><li>Statements of the form </li></ul><ul><ul><ul><li>variable = variable operator expression ; </li></ul></ul></ul><ul><ul><li>can be rewritten as </li></ul></ul><ul><ul><ul><li>variable operator = expression ; </li></ul></ul></ul><ul><li>Examples of other assignment operators: </li></ul><ul><ul><ul><li>d -= 4 (d = d - 4) </li></ul></ul></ul><ul><ul><ul><li>e *= 5 (e = e * 5) </li></ul></ul></ul><ul><ul><ul><li>f /= 3 (f = f / 3) </li></ul></ul></ul><ul><ul><ul><li>g %= 9 (g = g % 9) </li></ul></ul></ul>
  72. 72. 3 .12 Increment and Decrement Operators <ul><li>Increment operator ( ++ ) </li></ul><ul><ul><li>Can be used instead of c+=1 </li></ul></ul><ul><li>Decrement operator ( -- ) </li></ul><ul><ul><li>Can be used instead of c-=1 </li></ul></ul><ul><li>Preincrement </li></ul><ul><ul><li>Operator is used before the variable ( ++c or --c ) </li></ul></ul><ul><ul><li>Variable is changed before the expression it is in is evaluated </li></ul></ul><ul><li>Postincrement </li></ul><ul><ul><li>Operator is used after the variable ( c++ or c-- ) </li></ul></ul><ul><ul><li>Expression executes before the variable is changed </li></ul></ul>
  73. 73. 3 .12 Increment and Decrement Operators <ul><li>If c equals 5 , then </li></ul><ul><ul><ul><li>printf( &quot;%d&quot;, ++c ); </li></ul></ul></ul><ul><ul><li>Prints 6 </li></ul></ul><ul><ul><ul><li>printf( &quot;%d&quot;, c++ ); </li></ul></ul></ul><ul><ul><li>Prints 5 </li></ul></ul><ul><ul><li>In either case, c now has the value of 6 </li></ul></ul><ul><li>When variable not in an expression </li></ul><ul><ul><li>Preincrementing and postincrementing have the same effect </li></ul></ul><ul><ul><ul><li>++c; </li></ul></ul></ul><ul><ul><ul><li>printf( “%d”, c ); </li></ul></ul></ul><ul><ul><li>Has the same effect as </li></ul></ul><ul><ul><ul><li>c++; </li></ul></ul></ul><ul><ul><ul><li>printf( “%d”, c ); </li></ul></ul></ul>
  74. 74. Chapter 5 - Functions Outline 5.1 Introduction 5.2 Program Modules in C 5.3 Math Library Functions 5.4 Functions 5.5 Function Definitions 5.6 Function Prototypes 5.7 Header Files 5.8 Calling Functions: Call by Value and Call by Reference 5.9 Random Number Generation 5.10 Example: A Game of Chance 5.11 Storage Classes 5.12 Scope Rules 5.13 Recursion 5.14 Example Using Recursion: The Fibonacci Series 5.15 Recursion vs. Iteration
  75. 75. 5.1 Introduction <ul><li>Divide and conquer </li></ul><ul><ul><li>Construct a program from smaller pieces or components </li></ul></ul><ul><ul><ul><li>These smaller pieces are called modules </li></ul></ul></ul><ul><ul><li>Each piece more manageable than the original program </li></ul></ul>
  76. 76. 5.2 Program Modules in C <ul><li>Functions </li></ul><ul><ul><li>Modules in C </li></ul></ul><ul><ul><li>Programs combine user-defined functions with library functions </li></ul></ul><ul><ul><ul><li>C standard library has a wide variety of functions </li></ul></ul></ul><ul><li>Function calls </li></ul><ul><ul><li>Invoking functions </li></ul></ul><ul><ul><ul><li>Provide function name and arguments (data) </li></ul></ul></ul><ul><ul><ul><li>Function performs operations or manipulations </li></ul></ul></ul><ul><ul><ul><li>Function returns results </li></ul></ul></ul><ul><ul><li>Function call analogy: </li></ul></ul><ul><ul><ul><li>Boss asks worker to complete task </li></ul></ul></ul><ul><ul><ul><ul><li>Worker gets information, does task, returns result </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Information hiding: boss does not know details </li></ul></ul></ul></ul>
  77. 77. 5.3 Math Library Functions <ul><li>Math library functions </li></ul><ul><ul><li>perform common mathematical calculations </li></ul></ul><ul><ul><li>#include <math.h> </li></ul></ul><ul><li>Format for calling functions </li></ul><ul><ul><li>FunctionName( argument ); </li></ul></ul><ul><ul><ul><li>If multiple arguments, use comma-separated list </li></ul></ul></ul><ul><ul><li>printf( &quot;%.2f&quot;, sqrt( 900.0 ) ); </li></ul></ul><ul><ul><ul><li>Calls function sqrt , which returns the square root of its argument </li></ul></ul></ul><ul><ul><ul><li>All math functions return data type double </li></ul></ul></ul><ul><ul><li>Arguments may be constants, variables, or expressions </li></ul></ul>
  78. 78. 5.4 Functions <ul><li>Functions </li></ul><ul><ul><li>Modularize a program </li></ul></ul><ul><ul><li>All variables declared inside functions are local variables </li></ul></ul><ul><ul><ul><li>Known only in function defined </li></ul></ul></ul><ul><ul><li>Parameters </li></ul></ul><ul><ul><ul><li>Communicate information between functions </li></ul></ul></ul><ul><ul><ul><li>Local variables </li></ul></ul></ul><ul><li>Benefits of functions </li></ul><ul><ul><li>Divide and conquer </li></ul></ul><ul><ul><ul><li>Manageable program development </li></ul></ul></ul><ul><ul><li>Software reusability </li></ul></ul><ul><ul><ul><li>Use existing functions as building blocks for new programs </li></ul></ul></ul><ul><ul><ul><li>Abstraction - hide internal details (library functions) </li></ul></ul></ul><ul><ul><li>Avoid code repetition </li></ul></ul>
  79. 79. 5.5 Function Definitions <ul><li>Function definition format </li></ul><ul><ul><ul><li>return-value-type function-name( parameter-list ) { declarations and statements } </li></ul></ul></ul><ul><ul><li>Function-name: any valid identifier </li></ul></ul><ul><ul><li>Return-value-type: data type of the result (default int ) </li></ul></ul><ul><ul><ul><li>void – indicates that the function returns nothing </li></ul></ul></ul><ul><ul><li>Parameter-list: comma separated list, declares parameters </li></ul></ul><ul><ul><ul><li>A type must be listed explicitly for each parameter unless, the parameter is of type int </li></ul></ul></ul>
  80. 80. 5.5 Function Definitions <ul><li>Function definition format (continued) </li></ul><ul><ul><ul><li>return-value-type function-name( parameter-list ) { declarations and statements } </li></ul></ul></ul><ul><ul><li>Declarations and statements: function body (block) </li></ul></ul><ul><ul><ul><li>Variables can be declared inside blocks (can be nested) </li></ul></ul></ul><ul><ul><ul><li>Functions can not be defined inside other functions </li></ul></ul></ul><ul><ul><li>Returning control </li></ul></ul><ul><ul><ul><li>If nothing returned </li></ul></ul></ul><ul><ul><ul><ul><li>return; </li></ul></ul></ul></ul><ul><ul><ul><ul><li>or, until reaches right brace </li></ul></ul></ul></ul><ul><ul><ul><li>If something returned </li></ul></ul></ul><ul><ul><ul><ul><li>return expression ; </li></ul></ul></ul></ul>
  81. 81. <ul><li>1. Function prototype (3 parameters) </li></ul><ul><li>2. Input values </li></ul><ul><li>2.1 Call function </li></ul><ul><li>Function definition </li></ul><ul><li>Program Output </li></ul>Enter three integers: 22 85 17 Maximum is: 85 1 /* Fig. 5.4: fig05_04.c 2 Finding the maximum of three integers */ 3 #include <stdio.h> 4 5 int maximum( int , int , int ); /* function prototype */ 6 7 int main() 8 { 9 int a, b, c; 10 11 printf( &quot;Enter three integers: &quot; ); 12 scanf( &quot;%d%d%d&quot;, &a, &b, &c ); 13 printf( &quot;Maximum is: %dn&quot;, maximum( a, b, c ) ); 14 15 return 0; 16 } 17 18 /* Function maximum definition */ 19 int maximum( int x, int y, int z ) 20 { 21 int max = x; 22 23 if ( y > max ) 24 max = y; 25 26 if ( z > max ) 27 max = z; 28 29 return max; 30 }
  82. 82. 5.6 Function Prototypes <ul><li>Function prototype </li></ul><ul><ul><li>Function name </li></ul></ul><ul><ul><li>Parameters – what the function takes in </li></ul></ul><ul><ul><li>Return type – data type function returns (default int ) </li></ul></ul><ul><ul><li>Used to validate functions </li></ul></ul><ul><ul><li>Prototype only needed if function definition comes after use in program </li></ul></ul><ul><ul><li>The function with the prototype </li></ul></ul><ul><ul><ul><li>int maximum( int, int, int ); </li></ul></ul></ul><ul><ul><ul><li>Takes in 3 int s </li></ul></ul></ul><ul><ul><ul><li>Returns an int </li></ul></ul></ul><ul><li>Promotion rules and conversions </li></ul><ul><ul><li>Converting to lower types can lead to errors </li></ul></ul>
  83. 83. 5.7 Header Files <ul><li>Header files </li></ul><ul><ul><li>Contain function prototypes for library functions </li></ul></ul><ul><ul><li><stdlib.h> , <math.h> , etc </li></ul></ul><ul><ul><li>Load with #include <filename> </li></ul></ul><ul><ul><ul><li>#include <math.h> </li></ul></ul></ul><ul><li>Custom header files </li></ul><ul><ul><li>Create file with functions </li></ul></ul><ul><ul><li>Save as filename.h </li></ul></ul><ul><ul><li>Load in other files with #include &quot;filename.h&quot; </li></ul></ul><ul><ul><li>Reuse functions </li></ul></ul>
  84. 84. 5.8 Calling Functions: Call by Value and Call by Reference <ul><li>Used when invoking functions </li></ul><ul><li>Call by value </li></ul><ul><ul><li>Copy of argument passed to function </li></ul></ul><ul><ul><li>Changes in function do not effect original </li></ul></ul><ul><ul><li>Use when function does not need to modify argument </li></ul></ul><ul><ul><ul><li>Avoids accidental changes </li></ul></ul></ul><ul><li>Call by reference </li></ul><ul><ul><li>Passes original argument </li></ul></ul><ul><ul><li>Changes in function effect original </li></ul></ul><ul><ul><li>Only used with trusted functions </li></ul></ul><ul><li>For now, we focus on call by value </li></ul>
  85. 85. 5.9 Random Number Generation <ul><li>rand function </li></ul><ul><ul><li>Load <stdlib.h> </li></ul></ul><ul><ul><li>Returns &quot;random&quot; number between 0 and RAND_MAX (at least 32767 ) </li></ul></ul><ul><ul><ul><ul><li>i = rand(); </li></ul></ul></ul></ul><ul><ul><li>Pseudorandom </li></ul></ul><ul><ul><ul><li>Preset sequence of &quot;random&quot; numbers </li></ul></ul></ul><ul><ul><ul><li>Same sequence for every function call </li></ul></ul></ul><ul><li>Scaling </li></ul><ul><ul><li>To get a random number between 1 and n </li></ul></ul><ul><ul><ul><ul><li>1 + ( rand() % n ) </li></ul></ul></ul></ul><ul><ul><ul><li>rand() % n returns a number between 0 and n - 1 </li></ul></ul></ul><ul><ul><ul><li>Add 1 to make random number between 1 and n </li></ul></ul></ul><ul><ul><ul><ul><li>1 + ( rand() % 6) </li></ul></ul></ul></ul><ul><ul><ul><ul><li>number between 1 and 6 </li></ul></ul></ul></ul>
  86. 86. 5.9 Random Number Generation <ul><li>srand function </li></ul><ul><ul><li><stdlib.h> </li></ul></ul><ul><ul><li>Takes an integer seed and jumps to that location in its &quot;random&quot; sequence </li></ul></ul><ul><ul><ul><li>srand( seed ); </li></ul></ul></ul><ul><ul><li>srand( time( NULL ) ); //load <time.h> </li></ul></ul><ul><ul><ul><li>time( NULL ) </li></ul></ul></ul><ul><ul><ul><ul><li>Returns the time at which the program was compiled in seconds </li></ul></ul></ul></ul><ul><ul><ul><ul><li>“ Randomizes&quot; the seed </li></ul></ul></ul></ul>
  87. 87. 1. Initialize seed 2. Input value for seed 2.1 Use srand to change random sequence 2.2 Define Loop 3. Generate and output random numbers 1 /* Fig. 5.9: fig05_09.c 2 Randomizing die-rolling program */ 3 #include <stdlib.h> 4 #include <stdio.h> 5 6 int main() 7 { 8 int i; 9 unsigned seed; 10 11 printf( &quot;Enter seed: &quot; ); 12 scanf( &quot;%u&quot;, &seed ); 13 srand( seed ); 14 15 for ( i = 1; i <= 10; i++ ) { 16 printf( &quot;%10d&quot;, 1 + ( rand() % 6 ) ); 17 18 if ( i % 5 == 0 ) 19 printf( &quot;n&quot; ); 20 } 21 22 return 0; 23 }
  88. 88. Program Output Enter seed: 867 2 4 6 1 6 1 1 3 6 2   Enter seed: 67 6 1 4 6 2 1 6 1 6 4 Enter seed: 67 6 1 4 6 2 1 6 1 6 4
  89. 89. 5.10 Example: A Game of Chance <ul><li>Craps simulator </li></ul><ul><li>Rules </li></ul><ul><ul><li>Roll two dice </li></ul></ul><ul><ul><ul><li>7 or 11 on first throw, player wins </li></ul></ul></ul><ul><ul><ul><li>2, 3, or 12 on first throw, player loses </li></ul></ul></ul><ul><ul><ul><li>4, 5, 6, 8, 9, 10 - value becomes player's &quot;point&quot; </li></ul></ul></ul><ul><ul><li>Player must roll his point before rolling 7 to win </li></ul></ul>
  90. 90. 1. rollDice prototype 1.1 Initialize variables 1.2 Seed srand 2. Define switch statement for win/loss/continue 2.1 Loop 1 /* Fig. 5.10: fig05_10.c 2 Craps */ 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <time.h> 6 7 int rollDice( void ); 8 9 int main() 10 { 11 int gameStatus, sum, myPoint; 12 13 srand( time( NULL ) ); 14 sum = rollDice(); /* first roll of the dice */ 15 16 switch ( sum ) { 17 case 7: case 11: /* win on first roll */ 18 gameStatus = 1; 19 break ; 20 case 2: case 3: case 12: /* lose on first roll */ 21 gameStatus = 2; 22 break ; 23 default : /* remember point */ 24 gameStatus = 0; 25 myPoint = sum; 26 printf( &quot;Point is %dn&quot;, myPoint ); 27 break ; 28 } 29 30 while ( gameStatus == 0 ) { /* keep rolling */ 31 sum = rollDice(); 32
  91. 91. 2.2 Print win/loss Program Output Player rolled 6 + 5 = 11 Player wins 33 if ( sum == myPoint ) /* win by making point */ 34 gameStatus = 1; 35 else 36 if ( sum == 7 ) /* lose by rolling 7 */ 37 gameStatus = 2; 38 } 39 40 if ( gameStatus == 1 ) 41 printf( &quot;Player winsn&quot; ); 42 else 43 printf( &quot;Player losesn&quot; ); 44 45 return 0; 46 } 47 48 int rollDice( void ) 49 { 50 int die1, die2, workSum; 51 52 die1 = 1 + ( rand() % 6 ); 53 die2 = 1 + ( rand() % 6 ); 54 workSum = die1 + die2; 55 printf( &quot;Player rolled %d + %d = %dn&quot;, die1, die2, workSum ); 56 return workSum; 57 }
  92. 92. Program Output Player rolled 6 + 6 = 12 Player loses Player rolled 4 + 6 = 10 Point is 10 Player rolled 2 + 4 = 6 Player rolled 6 + 5 = 11 Player rolled 3 + 3 = 6 Player rolled 6 + 4 = 10 Player wins Player rolled 1 + 3 = 4 Point is 4 Player rolled 1 + 4 = 5 Player rolled 5 + 4 = 9 Player rolled 4 + 6 = 10 Player rolled 6 + 3 = 9 Player rolled 1 + 2 = 3 Player rolled 5 + 2 = 7 Player loses
  93. 93. 5.11 Storage Classes <ul><li>Storage class specifiers </li></ul><ul><ul><li>Storage duration – how long an object exists in memory </li></ul></ul><ul><ul><li>Scope – where object can be referenced in program </li></ul></ul><ul><ul><li>Linkage – specifies the files in which an identifier is known (more in Chapter 14) </li></ul></ul><ul><li>Automatic storage </li></ul><ul><ul><li>Object created and destroyed within its block </li></ul></ul><ul><ul><li>auto : default for local variables </li></ul></ul><ul><ul><ul><ul><li>auto double x, y; </li></ul></ul></ul></ul><ul><ul><li>register : tries to put variable into high-speed registers </li></ul></ul><ul><ul><ul><li>Can only be used for automatic variables </li></ul></ul></ul><ul><ul><ul><ul><li>register int counter = 1; </li></ul></ul></ul></ul>
  94. 94. 5.11 Storage Classes <ul><li>Static storage </li></ul><ul><ul><li>Variables exist for entire program execution </li></ul></ul><ul><ul><li>Default value of zero </li></ul></ul><ul><ul><li>static : local variables defined in functions. </li></ul></ul><ul><ul><ul><li>Keep value after function ends </li></ul></ul></ul><ul><ul><ul><li>Only known in their own function </li></ul></ul></ul><ul><ul><li>extern : default for global variables and functions </li></ul></ul><ul><ul><ul><li>Known in any function </li></ul></ul></ul>
  95. 95. 5.12 Scope Rules <ul><li>File scope </li></ul><ul><ul><li>Identifier defined outside function, known in all functions </li></ul></ul><ul><ul><li>Used for global variables, function definitions, function prototypes </li></ul></ul><ul><li>Function scope </li></ul><ul><ul><li>Can only be referenced inside a function body </li></ul></ul><ul><ul><li>Used only for labels ( start: , case: , etc.) </li></ul></ul>
  96. 96. 5.12 Scope Rules <ul><li>Block scope </li></ul><ul><ul><li>Identifier declared inside a block </li></ul></ul><ul><ul><ul><li>Block scope begins at declaration, ends at right brace </li></ul></ul></ul><ul><ul><li>Used for variables, function parameters (local variables of function) </li></ul></ul><ul><ul><li>Outer blocks &quot;hidden&quot; from inner blocks if there is a variable with the same name in the inner block </li></ul></ul><ul><li>Function prototype scope </li></ul><ul><ul><li>Used for identifiers in parameter list </li></ul></ul>
  97. 97. 1. Function prototypes 1.1 Initialize global variable 1.2 Initialize local variable 1.3 Initialize local variable in block 2. Call functions 3. Output results 1 /* Fig. 5.12: fig05_12.c 2 A scoping example */ 3 #include <stdio.h> 4 5 void a( void ); /* function prototype */ 6 void b( void ); /* function prototype */ 7 void c( void ); /* function prototype */ 8 9 int x = 1; /* global variable */ 10 11 int main() 12 { 13 int x = 5; /* local variable to main */ 14 15 printf(&quot;local x in outer scope of main is %dn&quot;, x ); 16 17 { /* start new scope */ 18 int x = 7; 19 20 printf( &quot;local x in inner scope of main is %dn&quot;, x ); 21 } /* end new scope */ 22 23 printf( &quot;local x in outer scope of main is %dn&quot;, x ); 24 25 a(); /* a has automatic local x */ 26 b(); /* b has static local x */ 27 c(); /* c uses global x */ 28 a(); /* a reinitializes automatic local x */ 29 b(); /* static local x retains its previous value */ 30 c(); /* global x also retains its value */
  98. 98. 3.1 Function definitions 31 32 printf( &quot;local x in main is %dn&quot;, x ); 33 return 0; 34 } 35 36 void a( void ) 37 { 38 int x = 25; /* initialized each time a is called */ 39 40 printf( &quot;nlocal x in a is %d after entering an&quot;, x ); 41 ++x; 42 printf( &quot;local x in a is %d before exiting an&quot;, x ); 43 } 44 45 void b( void ) 46 { 47 static int x = 50; /* static initialization only */ 48 /* first time b is called */ 49 printf( &quot;nlocal static x is %d on entering bn&quot;, x ); 50 ++x; 51 printf( &quot;local static x is %d on exiting bn&quot;, x ); 52 } 53 54 void c( void ) 55 { 56 printf( &quot;nglobal x is %d on entering cn&quot;, x ); 57 x *= 10; 58 printf( &quot;global x is %d on exiting cn&quot;, x ); 59 }
  99. 99. Program Output local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5 local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 50 on entering b local static x is 51 on exiting b global x is 1 on entering c global x is 10 on exiting c local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 51 on entering b local static x is 52 on exiting b global x is 10 on entering c global x is 100 on exiting c local x in main is 5
  100. 100. 5.13 Recursion <ul><li>Recursive functions </li></ul><ul><ul><li>Functions that call themselves </li></ul></ul><ul><ul><li>Can only solve a base case </li></ul></ul><ul><ul><li>Divide a problem up into </li></ul></ul><ul><ul><ul><li>What it can do </li></ul></ul></ul><ul><ul><ul><li>What it cannot do </li></ul></ul></ul><ul><ul><ul><ul><li>What it cannot do resembles original problem </li></ul></ul></ul></ul><ul><ul><ul><ul><li>The function launches a new copy of itself (recursion step) to solve what it cannot do </li></ul></ul></ul></ul><ul><ul><li>Eventually base case gets solved </li></ul></ul><ul><ul><ul><li>Gets plugged in, works its way up and solves whole problem </li></ul></ul></ul>
  101. 101. 5.13 Recursion <ul><li>Example: factorials </li></ul><ul><ul><li>5! = 5 * 4 * 3 * 2 * 1 </li></ul></ul><ul><ul><li>Notice that </li></ul></ul><ul><ul><ul><li>5! = 5 * 4! </li></ul></ul></ul><ul><ul><ul><li>4! = 4 * 3! ... </li></ul></ul></ul><ul><ul><li>Can compute factorials recursively </li></ul></ul><ul><ul><li>Solve base case ( 1! = 0! = 1 ) then plug in </li></ul></ul><ul><ul><ul><li>2! = 2 * 1! = 2 * 1 = 2; </li></ul></ul></ul><ul><ul><ul><li>3! = 3 * 2! = 3 * 2 = 6; </li></ul></ul></ul>
  102. 102. 5.14 Example Using Recursion: The Fibonacci Series <ul><li>Fibonacci series: 0, 1, 1, 2, 3, 5, 8... </li></ul><ul><ul><li>Each number is the sum of the previous two </li></ul></ul><ul><ul><li>Can be solved recursively: </li></ul></ul><ul><ul><ul><li>fib( n ) = fib( n - 1 ) + fib( n – 2 ) </li></ul></ul></ul><ul><ul><li>Code for the fibaonacci function </li></ul></ul><ul><ul><ul><li>long fibonacci( long n ) </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>if (n == 0 || n == 1) // base case </li></ul></ul></ul><ul><ul><ul><li>return n; </li></ul></ul></ul><ul><ul><ul><li>else </li></ul></ul></ul><ul><ul><ul><li>return fibonacci( n - 1) + fibonacci( n – 2 ); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul> 
  103. 103. 5.14 Example Using Recursion: The Fibonacci Series <ul><li>Set of recursive calls to function fibonacci </li></ul>  f( 3 ) f( 1 ) f( 2 ) f( 1 ) f( 0 ) return 1 return 1 return 0 return + + return
  104. 104. 1. Function prototype 1.1 Initialize variables 2. Input an integer 2.1 Call function fibonacci 2.2 Output results. 3. Define fibonacci recursively Program Output Enter an integer: 0 Fibonacci(0) = 0 Enter an integer: 1 Fibonacci(1) = 1 1 /* Fig. 5.15: fig05_15.c 2 Recursive fibonacci function */ 3 #include <stdio.h> 4 5 long fibonacci( long ); 6 7 int main() 8 { 9 long result, number; 10 11 printf( &quot;Enter an integer: &quot; ); 12 scanf( &quot;%ld&quot;, &number ); 13 result = fibonacci( number ); 14 printf( &quot;Fibonacci( %ld ) = %ldn&quot;, number, result ); 15 return 0; 16 } 17 18 /* Recursive definition of function fibonacci */ 19 long fibonacci( long n ) 20 { 21 if ( n == 0 || n == 1 ) 22 return n; 23 else 24 return fibonacci( n - 1 ) + fibonacci( n - 2 ); 25 }
  105. 105. Program Output Enter an integer: 2 Fibonacci(2) = 1 Enter an integer: 3 Fibonacci(3) = 2 Enter an integer: 4 Fibonacci(4) = 3 Enter an integer: 5 Fibonacci(5) = 5 Enter an integer: 6 Fibonacci(6) = 8 Enter an integer: 10 Fibonacci(10) = 55 Enter an integer: 20 Fibonacci(20) = 6765 Enter an integer: 30 Fibonacci(30) = 832040 Enter an integer: 35 Fibonacci(35) = 9227465
  106. 106. 5.15 Recursion vs. Iteration <ul><li>Repetition </li></ul><ul><ul><li>Iteration: explicit loop </li></ul></ul><ul><ul><li>Recursion: repeated function calls </li></ul></ul><ul><li>Termination </li></ul><ul><ul><li>Iteration: loop condition fails </li></ul></ul><ul><ul><li>Recursion: base case recognized </li></ul></ul><ul><li>Both can have infinite loops </li></ul><ul><li>Balance </li></ul><ul><ul><li>Choice between performance (iteration) and good software engineering (recursion) </li></ul></ul>
  107. 107. Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays 6.3 Declaring Arrays 6.4 Examples Using Arrays 6.5 Passing Arrays to Functions 6.6 Sorting Arrays 6.7 Case Study: Computing Mean, Median and Mode Using Arrays 6.8 Searching Arrays 6.9 Multiple-Subscripted Arrays
  108. 108. 6.1 Introduction <ul><li>Arrays </li></ul><ul><ul><li>Structures of related data items </li></ul></ul><ul><ul><li>Static entity – same size throughout program </li></ul></ul><ul><ul><li>Dynamic data structures discussed in Chapter 12 </li></ul></ul>
  109. 109. 6.2 Arrays <ul><li>Array </li></ul><ul><ul><li>Group of consecutive memory locations </li></ul></ul><ul><ul><li>Same name and type </li></ul></ul><ul><li>To refer to an element, specify </li></ul><ul><ul><li>Array name </li></ul></ul><ul><ul><li>Position number </li></ul></ul><ul><li>Format: </li></ul><ul><ul><ul><li>arrayname [ position number ] </li></ul></ul></ul><ul><ul><li>First element at position 0 </li></ul></ul><ul><ul><li>n element array named c : </li></ul></ul><ul><ul><ul><li>c[ 0 ] , c[ 1 ] ... c[ n – 1 ] </li></ul></ul></ul>Name of array (Note that all elements of this array have the same name, c ) Position number of the element within array c c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4]
  110. 110. 6.2 Arrays <ul><li>Array elements are like normal variables </li></ul><ul><ul><ul><li>c[ 0 ] = 3; </li></ul></ul></ul><ul><ul><ul><li>printf( &quot;%d&quot;, c[ 0 ] ); </li></ul></ul></ul><ul><ul><li>Perform operations in subscript. If x equals 3 </li></ul></ul><ul><ul><ul><li>c[ 5 - 2 ] == c[ 3 ] == c[ x ] </li></ul></ul></ul>
  111. 111. 6.3 Declaring Arrays <ul><li>When declaring arrays, specify </li></ul><ul><ul><li>Name </li></ul></ul><ul><ul><li>Type of array </li></ul></ul><ul><ul><li>Number of elements </li></ul></ul><ul><ul><ul><li>arrayType arrayName[ numberOfElements ]; </li></ul></ul></ul><ul><ul><li>Examples: </li></ul></ul><ul><ul><ul><li>int c[ 10 ]; </li></ul></ul></ul><ul><ul><ul><li>float myArray[ 3284 ]; </li></ul></ul></ul><ul><li>Declaring multiple arrays of same type </li></ul><ul><ul><li>Format similar to regular variables </li></ul></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>int b[ 100 ], x[ 27 ]; </li></ul></ul></ul>
  112. 112. 6.4 Examples Using Arrays <ul><li>Initializers </li></ul><ul><ul><ul><li>int n[ 5 ] = { 1, 2, 3, 4, 5 }; </li></ul></ul></ul><ul><ul><li>If not enough initializers, rightmost elements become 0 </li></ul></ul><ul><ul><ul><ul><li>int n[ 5 ] = { 0 } </li></ul></ul></ul></ul><ul><ul><ul><li>All elements 0 </li></ul></ul></ul><ul><ul><li>If too many a syntax error is produced syntax error </li></ul></ul><ul><ul><li>C arrays have no bounds checking </li></ul></ul><ul><li>If size omitted, initializers determine it </li></ul><ul><ul><ul><li>int n[ ] = { 1, 2, 3, 4, 5 }; </li></ul></ul></ul><ul><ul><li>5 initializers, therefore 5 element array </li></ul></ul>
  113. 113. 1. Initialize array 2. Loop 3. Print 1 /* Fig. 6.8: fig06_08.c 2 Histogram printing program */ 3 #include <stdio.h> 4 #define SIZE 10 5 6 int main() 7 { 8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 9 int i, j; 10 11 printf( &quot;%s%13s%17sn&quot;, &quot;Element&quot;, &quot;Value&quot;, &quot;Histogram&quot; ); 12 13 for ( i = 0; i <= SIZE - 1; i++ ) { 14 printf( &quot;%7d%13d &quot;, i, n[ i ]) ; 15 16 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */ 17 printf( &quot;%c&quot;, '*' ); 18 19 printf( &quot;n&quot; ); 20 } 21 22 return 0; 23 }
  114. 114. Program Output Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *
  115. 115. 6.4 Examples Using Arrays <ul><li>Character arrays </li></ul><ul><ul><li>String “first” is really a static array of characters </li></ul></ul><ul><ul><li>Character arrays can be initialized using string literals </li></ul></ul><ul><ul><ul><ul><li>char string1[] = &quot;first&quot;; </li></ul></ul></ul></ul><ul><ul><ul><li>Null character '0' terminates strings </li></ul></ul></ul><ul><ul><ul><li>string1 actually has 6 elements </li></ul></ul></ul><ul><ul><ul><ul><li>It is equivalent to </li></ul></ul></ul></ul><ul><ul><li>char string1[] = { 'f', 'i', 'r', 's', 't', '0' }; </li></ul></ul><ul><ul><li>Can access individual characters </li></ul></ul><ul><ul><ul><li>string1[ 3 ] is character ‘s’ </li></ul></ul></ul><ul><ul><li>Array name is address of array, so & not needed for scanf </li></ul></ul><ul><ul><ul><ul><li>scanf( &quot;%s&quot;, string2 ); </li></ul></ul></ul></ul><ul><ul><ul><li>Reads characters until whitespace encountered </li></ul></ul></ul><ul><ul><ul><li>Can write beyond end of array, be careful </li></ul></ul></ul>
  116. 116. 1. Initialize strings 2. Print strings 2.1 Define loop 2.2 Print characters individually 2.3 Input string 3. Print string Program Output Enter a string: Hello there string1 is: Hello string2 is: string literal string1 with spaces between characters is: H e l l o 1 /* Fig. 6.10: fig06_10.c 2 Treating character arrays as strings */ 3 #include <stdio.h> 4 5 int main() 6 { 7 char string1[ 20 ], string2[] = &quot;string literal&quot;; 8 int i; 9 10 printf(&quot; Enter a string: &quot;); 11 scanf( &quot;%s&quot;, string1 ); 12 printf( &quot;string1 is: %snstring2: is %sn&quot; 13 &quot;string1 with spaces between characters is:n&quot;, 14 string1, string2 ); 15 16 for ( i = 0; string1[ i ] != '0'; i++ ) 17 printf( &quot;%c &quot;, string1[ i ] ); 18 19 printf( &quot;n&quot; ); 20 return 0; 21 }
  117. 117. 6.5 Passing Arrays to Functions <ul><li>Passing arrays </li></ul><ul><ul><li>To pass an array argument to a function, specify the name of the array without any brackets </li></ul></ul><ul><ul><ul><ul><li>int myArray[ 24 ]; </li></ul></ul></ul></ul><ul><ul><ul><ul><li>myFunction( myArray, 24 ); </li></ul></ul></ul></ul><ul><ul><ul><li>Array size usually passed to function </li></ul></ul></ul><ul><ul><li>Arrays passed call-by-reference </li></ul></ul><ul><ul><li>Name of array is address of first element </li></ul></ul><ul><ul><li>Function knows where the array is stored </li></ul></ul><ul><ul><ul><li>Modifies original memory locations </li></ul></ul></ul><ul><li>Passing array elements </li></ul><ul><ul><li>Passed by call-by-value </li></ul></ul><ul><ul><li>Pass subscripted name (i.e., myArray[ 3 ] ) to function </li></ul></ul>
  118. 118. 6.5 Passing Arrays to Functions <ul><li>Function prototype </li></ul><ul><ul><ul><li>void modifyArray( int b[], int arraySize ); </li></ul></ul></ul><ul><ul><li>Parameter names optional in prototype </li></ul></ul><ul><ul><ul><li>int b[] could be written int [] </li></ul></ul></ul><ul><ul><ul><li>int arraySize could be simply int </li></ul></ul></ul>
  119. 119. 1. Function definitions 2. Pass array to a function 2.1 Pass array element to a function 3. Print 1 /* Fig. 6.13: fig06_13.c 2 Passing arrays and individual array elements to functions */ 3 #include <stdio.h> 4 #define SIZE 5 5 6 void modifyArray( int [], int ); /* appears strange */ 7 void modifyElement( int ); 8 9 int main() 10 { 11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i; 12 13 printf( &quot;Effects of passing entire array call &quot; 14 &quot;by reference:nnThe values of the &quot; 15 &quot;original array are:n&quot; ); 16 17 for ( i = 0; i <= SIZE - 1; i++ ) 18 printf( &quot;%3d&quot;, a[ i ] ); 19 20 printf( &quot;n&quot; ); 21 modifyArray( a, SIZE ); /* passed call by reference */ 22 printf( &quot;The values of the modified array are:n&quot; ); 23 24 for ( i = 0; i <= SIZE - 1; i++ ) 25 printf( &quot;%3d&quot;, a[ i ] ); 26 27 printf( &quot;nnnEffects of passing array element call &quot; 28 &quot;by value:nnThe value of a[3] is %dn&quot;, a[ 3 ] ); 29 modifyElement( a[ 3 ] ); 30 printf( &quot;The value of a[ 3 ] is %dn&quot;, a[ 3 ] ); 31 return 0; 32 } Entire arrays passed call-by-reference, and can be modified Array elements passed call-by-value, and cannot be modified
  120. 120. 3.1 Function definitions Program Output Effects of passing entire array call by reference: The values of the original array are: 0 1 2 3 4 The values of the modified array are: 0 2 4 6 8 Effects of passing array element call by value: The value of a[3] is 6 Value in modifyElement is 12 The value of a[3] is 6 33 34 void modifyArray( int b[], int size ) 35 { 36 int j; 37 38 for ( j = 0; j <= size - 1; j++ ) 39 b[ j ] *= 2; 40 } 41 42 void modifyElement( int e ) 43 { 44 printf( &quot;Value in modifyElement is %dn&quot;, e *= 2 ); 45 }
  121. 121. 6.6 Sorting Arrays <ul><li>Sorting data </li></ul><ul><ul><li>Important computing application </li></ul></ul><ul><ul><li>Virtually every organization must sort some data </li></ul></ul><ul><li>Bubble sort (sinking sort) </li></ul><ul><ul><li>Several passes through the array </li></ul></ul><ul><ul><li>Successive pairs of elements are compared </li></ul></ul><ul><ul><ul><li>If increasing order (or identical ), no change </li></ul></ul></ul><ul><ul><ul><li>If decreasing order, elements exchanged </li></ul></ul></ul><ul><ul><li>Repeat </li></ul></ul><ul><li>Example: </li></ul><ul><ul><li>original: 3 4 2 6 7 </li></ul></ul><ul><ul><li>pass 1: 3 2 4 6 7 </li></ul></ul><ul><ul><li>pass 2: 2 3 4 6 7 </li></ul></ul><ul><ul><li>Small elements &quot;bubble&quot; to the top </li></ul></ul>
  122. 122. 6.7 Case Study: Computing Mean, Median and Mode Using Arrays <ul><li>Mean – average </li></ul><ul><li>Median – number in middle of sorted list </li></ul><ul><ul><li>1, 2, 3, 4, 5 </li></ul></ul><ul><ul><li>3 is the median </li></ul></ul><ul><li>Mode – number that occurs most often </li></ul><ul><ul><li>1, 1, 1, 2, 3, 3, 4, 5 </li></ul></ul><ul><ul><li>1 is the mode </li></ul></ul>
  123. 123. 1. Function prototypes 1.1 Initialize array 2. Call functions mean , median , and mode 1 /* Fig. 6.16: fig06_16.c 2 This program introduces the topic of survey data analysis. 3 It computes the mean, median, and mode of the data */ 4 #include <stdio.h> 5 #define SIZE 99 6 7 void mean( const int [] ); 8 void median( int [] ); 9 void mode( int [], const int [] ) ; 10 void bubbleSort( int [] ); 11 void printArray( const int [] ); 12 13 int main() 14 { 15 int frequency[ 10 ] = { 0 }; 16 int response[ SIZE ] = 17 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9, 18 7, 8, 9, 5, 9, 8, 7, 8, 7, 8, 19 6, 7, 8, 9, 3, 9, 8, 7, 8, 7, 20 7, 8, 9, 8, 9, 8, 9, 7, 8, 9, 21 6, 7, 8, 7, 8, 7, 9, 8, 9, 2, 22 7, 8, 9, 8, 9, 8, 9, 7, 5, 3, 23 5, 6, 7, 2, 5, 3, 9, 4, 6, 4, 24 7, 8, 9, 6, 8, 7, 8, 9, 7, 8, 25 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 26 4, 5, 6, 1, 6, 5, 7, 8, 7 }; 27 28 mean( response ); 29 median( response ); 30 mode( frequency, response ); 31 return 0; 32 }
  124. 124. 3. Define function mean 3.1 Define function median 3.1.1 Sort Array 3.1.2 Print middle element 33 34 void mean( const int answer[] ) 35 { 36 int j, total = 0; 37 38 printf( &quot;%sn%sn%sn&quot;, &quot;********&quot;, &quot; Mean&quot;, &quot;********&quot; ); 39 40 for ( j = 0; j <= SIZE - 1; j++ ) 41 total += answer[ j ]; 42 43 printf( &quot;The mean is the average value of the datan&quot; 44 &quot;items. The mean is equal to the total ofn&quot; 45 &quot;all the data items divided by the numbern&quot; 46 &quot;of data items ( %d ). The mean value forn&quot; 47 &quot;this run is: %d / %d = %.4fnn&quot;, 48 SIZE, total, SIZE, ( double ) total / SIZE ); 49 } 50 51 void median( int answer[] ) 52 { 53 printf( &quot;n%sn%sn%sn%s&quot;, 54 &quot;********&quot;, &quot; Median&quot;, &quot;********&quot;, 55 &quot;The unsorted array of responses is&quot; ); 56 57 printArray( answer ); 58 bubbleSort( answer ); 59 printf( &quot;nnThe sorted array is&quot; ); 60 printArray( answer ); 61 printf( &quot;nnThe median is element %d ofn&quot; 62 &quot;the sorted %d element array.n&quot; 63 &quot;For this run the median is %dnn&quot;, 64 SIZE / 2, SIZE, answer[ SIZE / 2 ] );
  125. 125. 3.2 Define function mode 3.2.1 Increase frequency[] depending on response[] 65 } 66 67 void mode( int freq[], const int answer[] ) 68 { 69 int rating, j, h, largest = 0, modeValue = 0; 70 71 printf( &quot;n%sn%sn%sn&quot;, 72 &quot;********&quot;, &quot; Mode&quot;, &quot;********&quot; ); 73 74 for ( rating = 1; rating <= 9; rating++ ) 75 freq[ rating ] = 0; 76 77 for ( j = 0; j <= SIZE - 1; j++ ) 78 ++freq[ answer[ j ] ]; 79 80 printf( &quot;%s%11s%19snn%54sn%54snn&quot;, 81 &quot;Response&quot;, &quot;Frequency&quot;, &quot;Histogram&quot;, 82 &quot;1 1 2 2&quot;, &quot;5 0 5 0 5&quot; ); 83 84 for ( rating = 1; rating <= 9; rating++ ) { 85 printf( &quot;%8d%11d &quot;, rating, freq[ rating ] ); 86 87 if ( freq[ rating ] > largest ) { 88 largest = freq[ rating ]; 89 modeValue = rating; 90 } 91 92 for ( h = 1; h <= freq[ rating ]; h++ ) 93 printf( &quot;*&quot; ); 94 Notice how the subscript in frequency[] is the value of an element in response[] ( answer[] ) Print stars depending on value of frequency[]
  126. 126. 3.3 Define bubbleSort 3.3 Define printArray 95 printf( &quot;n&quot; ); 96 } 97 98 printf( &quot;The mode is the most frequent value.n&quot; 99 &quot;For this run the mode is %d which occurred&quot; 100 &quot; %d times.n&quot;, modeValue, largest ); 101 } 102 103 void bubbleSort( int a[] ) 104 { 105 int pass, j, hold; 106 107 for ( pass = 1; pass <= SIZE - 1; pass++ ) 108 109 for ( j = 0; j <= SIZE - 2; j++ ) 110 111 if ( a[ j ] > a[ j + 1 ] ) { 112 hold = a[ j ]; 113 a[ j ] = a[ j + 1 ]; 114 a[ j + 1 ] = hold; 115 } 116 } 117 118 void printArray( const int a[] ) 119 { 120 int j; 121 122 for ( j = 0; j <= SIZE - 1; j++ ) { 123 124 if ( j % 20 == 0 ) 125 printf( &quot;n&quot; ); Bubble sort: if elements out of order, swap them.
  127. 127. Program Output ******** Mean ******** The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number of data items (99). The mean value for this run is: 681 / 99 = 6.8788   ******** Median ******** The unsorted array of responses is 7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8 6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9 6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3 5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8 7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7   The sorted array is 1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9   The median is element 49 of the sorted 99 element array. For this run the median is 7 126 127 printf( &quot;%2d&quot;, a[ j ] ); 128 } 129 }
  128. 128. Program Output ******** Mode ******** Response Frequency Histogram   1 1 2 2 5 0 5 0 5   1 1 * 2 3 *** 3 4 **** 4 5 ***** 5 8 ******** 6 9 ********* 7 23 *********************** 8 27 *************************** 9 19 ******************* The mode is the most frequent value. For this run the mode is 8 which occurred 27 times.
  129. 129. 6.8 Searching Arrays: Linear Search and Binary Search <ul><li>Search an array for a key value </li></ul><ul><li>Linear search </li></ul><ul><ul><li>Simple </li></ul></ul><ul><ul><li>Compare each element of array with key value </li></ul></ul><ul><ul><li>Useful for small and unsorted arrays </li></ul></ul>
  130. 130. 6.8 Searching Arrays: Linear Search and Binary Search <ul><li>Binary search </li></ul><ul><ul><li>For sorted arrays </li></ul></ul><ul><ul><li>Compares middle element with key </li></ul></ul><ul><ul><ul><li>If equal, match found </li></ul></ul></ul><ul><ul><ul><li>If key < middle , looks in first half of array </li></ul></ul></ul><ul><ul><ul><li>If key > middle , looks in last half </li></ul></ul></ul><ul><ul><ul><li>Repeat </li></ul></ul></ul><ul><ul><li>Very fast; at most n steps, where 2 n > number of elements </li></ul></ul><ul><ul><ul><li>30 element array takes at most 5 steps </li></ul></ul></ul><ul><ul><ul><ul><li>2 5 > 30 so at most 5 steps </li></ul></ul></ul></ul>5
  131. 131. 6.9 Multiple-Subscripted Arrays <ul><li>Multiple subscripted arrays </li></ul><ul><ul><li>Tables with rows and columns ( m by n array) </li></ul></ul><ul><ul><li>Like matrices: specify row, then column </li></ul></ul>Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript Array name Column subscript
  132. 132. 6.9 Multiple-Subscripted Arrays <ul><li>Initialization </li></ul><ul><ul><li>int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; </li></ul></ul><ul><ul><li>Initializers grouped by row in braces </li></ul></ul><ul><ul><li>If not enough, unspecified elements set to zero </li></ul></ul><ul><ul><ul><li>int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; </li></ul></ul></ul><ul><li>Referencing elements </li></ul><ul><ul><li>Specify row, then column </li></ul></ul><ul><ul><ul><li>printf( &quot;%d&quot;, b[ 0 ][ 1 ] ); </li></ul></ul></ul>  1 2 3 4 1 0 3 4
  133. 133. 1. Initialize variables 1.1 Define functions to take double scripted arrays 1.2 Initialize studentgrades[][] 2. Call functions minimum , maximum , and average 1 /* Fig. 6.22: fig06_22.c 2 Double-subscripted array example */ 3 #include <stdio.h> 4 #define STUDENTS 3 5 #define EXAMS 4 6 7 int minimum( const int [][ EXAMS ], int , int ); 8 int maximum( const int [][ EXAMS ], int , int ); 9 double average( const int [], int ); 10 void printArray( const int [][ EXAMS ], int , int ); 11 12 int main() 13 { 14 int student; 15 const int studentGrades[ STUDENTS ][ EXAMS ] = 16 { { 77, 68, 86, 73 }, 17 { 96, 87, 89, 78 }, 18 { 70, 90, 86, 81 } }; 19 20 printf( &quot;The array is:n&quot; ); 21 printArray( studentGrades, STUDENTS, EXAMS ); 22 printf( &quot;nnLowest grade: %dnHighest grade: %dn&quot;, 23 minimum( studentGrades, STUDENTS, EXAMS ), 24 maximum( studentGrades, STUDENTS, EXAMS ) ); 25 26 for ( student = 0; student <= STUDENTS - 1; student++ ) 27 printf( &quot;The average grade for student %d is %.2fn&quot;, 28 student, 29 average( studentGrades[ student ], EXAMS ) ); 30 31 return 0; 32 } Each row is a particular student, each column is the grades on the exam.
  134. 134. 3. Define functions 33 34 /* Find the minimum grade */ 35 int minimum( const int grades[][ EXAMS ], 36 int pupils, int tests ) 37 { 38 int i, j, lowGrade = 100; 39 40 for ( i = 0; i <= pupils - 1; i++ ) 41 for ( j = 0; j <= tests - 1; j++ ) 42 if ( grades[ i ][ j ] < lowGrade ) 43 lowGrade = grades[ i ][ j ]; 44 45 return lowGrade; 46 } 47 48 /* Find the maximum grade */ 49 int maximum( const int grades[][ EXAMS ], 50 int pupils, int tests ) 51 { 52 int i, j, highGrade = 0; 53 54 for ( i = 0; i <= pupils - 1; i++ ) 55 for ( j = 0; j <= tests - 1; j++ ) 56 if ( grades[ i ][ j ] > highGrade ) 57 highGrade = grades[ i ][ j ]; 58 59 return highGrade; 60 } 61 62 /* Determine the average grade for a particular exam */ 63 double average( const int setOfGrades[], int tests ) 64 {
  135. 135. 3. Define functions 65 int i, total = 0; 66 67 for ( i = 0; i <= tests - 1; i++ ) 68 total += setOfGrades[ i ]; 69 70 return ( double ) total / tests; 71 } 72 73 /* Print the array */ 74 void printArray( const int grades[][ EXAMS ], 75 int pupils, int tests ) 76 { 77 int i, j; 78 79 printf( &quot; [0] [1] [2] [3]&quot; ); 80 81 for ( i = 0; i <= pupils - 1; i++ ) { 82 printf( &quot;nstudentGrades[%d] &quot;, i ); 83 84 for ( j = 0; j <= tests - 1; j++ ) 85 printf( &quot;%-5d&quot;, grades[ i ][ j ] ); 86 } 87 }
  136. 136. Program Output The array is: [0] [1] [2] [3] studentGrades[0] 77 68 86 73 studentGrades[1] 96 87 89 78 studentGrades[2] 70 90 86 81 Lowest grade: 68 Highest grade: 96 The average grade for student 0 is 76.00 The average grade for student 1 is 87.50 The average grade for student 2 is 81.75
  137. 137. Chapter 7 - Pointers Outline 7.1 Introduction 7.2 Pointer Variable Declarations and Initialization 7.3 Pointer Operators 7.4 Calling Functions by Reference 7.5 Using the const Qualifier with Pointers 7.6 Bubble Sort Using Call by Reference 7.7 Pointer Expressions and Pointer Arithmetic 7.8 The Relationship between Pointers and Arrays 7.9 Arrays of Pointers 7.10 Case Study: A Card Shuffling and Dealing Simulation 7.11 Pointers to Functions
  138. 138. 7.1 Introduction <ul><li>Pointers </li></ul><ul><ul><li>Powerful, but difficult to master </li></ul></ul><ul><ul><li>Simulate call-by-reference </li></ul></ul><ul><ul><li>Close relationship with arrays and strings </li></ul></ul>
  139. 139. 7.2 Pointer Variable Declarations and Initialization <ul><li>Pointer variables </li></ul><ul><ul><li>Contain memory addresses as their values </li></ul></ul><ul><ul><li>Normal variables contain a specific value (direct reference) </li></ul></ul><ul><ul><li>Pointers contain address of a variable that has a specific value (indirect reference) </li></ul></ul><ul><ul><li>Indirection – referencing a pointer value </li></ul></ul>  count 7 count 7 countPtr
  140. 140. 7.2 Pointer Variable Declarations and Initialization <ul><li>Pointer declarations </li></ul><ul><ul><li>* used with pointer variables </li></ul></ul><ul><ul><ul><ul><li>int *myPtr; </li></ul></ul></ul></ul><ul><ul><li>Declares a pointer to an int (pointer of type int * ) </li></ul></ul><ul><ul><li>Multiple pointers require using a * before each variable declaration </li></ul></ul><ul><ul><ul><ul><li>int *myPtr1, *myPtr2; </li></ul></ul></ul></ul><ul><ul><li>Can declare pointers to any data type </li></ul></ul><ul><ul><li>Initialize pointers to 0 , NULL , or an address </li></ul></ul><ul><ul><ul><li>0 or NULL – points to nothing ( NULL preferred) </li></ul></ul></ul>
  141. 141. 7.3 Pointer Operators <ul><li>& (address operator) </li></ul><ul><ul><li>Returns address of operand </li></ul></ul><ul><ul><ul><li>int y = 5; </li></ul></ul></ul><ul><ul><ul><li>int *yPtr; </li></ul></ul></ul><ul><ul><ul><li>yPtr = &y; // yPtr gets address of y </li></ul></ul></ul><ul><ul><ul><li>yPtr “points to” y </li></ul></ul></ul>yPtr y 5 yptr 500000 600000 y 600000 5 Address of y is value of yptr
  142. 142. 7.3 Pointer Operators <ul><li>* (indirection/dereferencing operator) </li></ul><ul><ul><li>Returns a synonym/alias of what its operand points to </li></ul></ul><ul><ul><li>*yptr returns y (because yptr points to y ) </li></ul></ul><ul><ul><li>* can be used for assignment </li></ul></ul><ul><ul><ul><li>Returns alias to an object </li></ul></ul></ul><ul><ul><ul><ul><li>*yptr = 7; // changes y to 7 </li></ul></ul></ul></ul><ul><ul><li>Dereferenced pointer (operand of * ) must be an lvalue (no constants) </li></ul></ul><ul><li>* and & are inverses </li></ul><ul><ul><li>They cancel each other out </li></ul></ul>
  143. 143. 1. Declare variables 2 Initialize variables 3. Print Program Output The address of a is 0012FF88 The value of aPtr is 0012FF88 The value of a is 7 The value of *aPtr is 7 Proving that * and & are complements of each other. &*aPtr = 0012FF88 *&aPtr = 0012FF88 1 /* Fig. 7.4: fig07_04.c 2 Using the & and * operators */ 3 #include <stdio.h> 4 5 int main() 6 { 7 int a; /* a is an integer */ 8 int *aPtr; /* aPtr is a pointer to an integer */ 9 10 a = 7; 11 aPtr = &a; /* aPtr set to address of a */ 12 13 printf( &quot;The address of a is %p&quot; 14 &quot;nThe value of aPtr is %p&quot;, &a, aPtr ); 15 16 printf( &quot;nnThe value of a is %d&quot; 17 &quot;nThe value of *aPtr is %d&quot;, a, *aPtr ); 18 19 printf( &quot;nnShowing that * and & are inverses of &quot; 20 &quot;each other.n&*aPtr = %p&quot; 21 &quot;n*&aPtr = %pn&quot;, &*aPtr, *&aPtr ); 22 23 return 0; 24 } The address of a is the value of aPtr. The * operator returns an alias to what its operand points to. aPtr points to a , so *aPtr returns a . Notice how * and & are inverses
  144. 144. 7.4 Calling Functions by Reference <ul><li>Call by reference with pointer arguments </li></ul><ul><ul><li>Pass address of argument using & operator </li></ul></ul><ul><ul><li>Allows you to change actual location in memory </li></ul></ul><ul><ul><li>Arrays are not passed with & because the array name is already a pointer </li></ul></ul><ul><li>* operator </li></ul><ul><ul><li>Used as alias/nickname for variable inside of function </li></ul></ul><ul><ul><ul><ul><li>void double( int *number ) </li></ul></ul></ul></ul><ul><ul><ul><ul><li>{ </li></ul></ul></ul></ul><ul><ul><ul><ul><li>*number = 2 * ( *number ); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul><ul><ul><li>*number used as nickname for the variable passed </li></ul></ul>
  145. 145. <ul><li>Function prototype </li></ul><ul><li>1.1 Initialize variables </li></ul><ul><li>2. Call function </li></ul><ul><li>3. Define function </li></ul><ul><li>Program Output </li></ul>The original value of number is 5 The new value of number is 125 Notice that the function prototype takes a pointer to an integer ( int * ). 1 /* Fig. 7.7: fig07_07.c 2 Cube a variable using call-by-reference 3 with a pointer argument */ 4 5 #include <stdio.h> 6 7 void cubeByReference( int * ); /* prototype */ 8 9 int main() 10 { 11 int number = 5; 12 13 printf( &quot;The original value of number is %d&quot;, number ); 14 cubeByReference( &number ); 15 printf( &quot;nThe new value of number is %dn&quot;, number ); 16 17 return 0; 18 } 19 20 void cubeByReference( int *nPtr ) 21 { 22 *nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */ 23 } Notice how the address of number is given - cubeByReference expects a pointer (an address of a variable). Inside cubeByReference , *nPtr is used ( *nPtr is number ).
  146. 146. 7.5 Using the const Qualifier with Pointers <ul><li>const qualifier </li></ul><ul><ul><li>Variable cannot be changed </li></ul></ul><ul><ul><li>Use const if function does not need to change a variable </li></ul></ul><ul><ul><li>Attempting to change a const variable produces an error </li></ul></ul><ul><li>const pointers </li></ul><ul><ul><li>Point to a constant memory location </li></ul></ul><ul><ul><li>Must be initialized when declared </li></ul></ul><ul><ul><li>int *const myPtr = &x; </li></ul></ul><ul><ul><ul><li>Type int *const – constant pointer to an int </li></ul></ul></ul><ul><ul><li>const int *myPtr = &x; </li></ul></ul><ul><ul><ul><li>Regular pointer to a const int </li></ul></ul></ul><ul><ul><li>const int *const Ptr = &x; </li></ul></ul><ul><ul><ul><li>const pointer to a const int </li></ul></ul></ul><ul><ul><ul><li>x can be changed, but not *Ptr </li></ul></ul></ul>
  147. 147. 1. Declare variables 1.1 Declare const pointer to an int 2. Change *ptr (which is x ) 2.1 Attempt to change ptr 3. Output Program Output FIG07_13.c: Error E2024 FIG07_13.c 16: Cannot modify a const object in function main *** 1 errors in Compile *** 1 /* Fig. 7.13: fig07_13.c 2 Attempting to modify a constant pointer to 3 non-constant data */ 4 5 #include <stdio.h> 6 7 int main() 8 { 9 int x, y; 10 11 int * const ptr = &x; /* ptr is a constant pointer to an 12 integer. An integer can be modified 13 through ptr, but ptr always points 14 to the same memory location. */ 15 *ptr = 7; 16 ptr = &y; 17 18 return 0; 19 } Changing *ptr is allowed – x is not a constant. Changing ptr is an error – ptr is a constant pointer.
  148. 148. 7.6 Bubble Sort Using Call-by-reference <ul><li>Implement bubblesort using pointers </li></ul><ul><ul><li>Swap two elements </li></ul></ul><ul><ul><li>swap function must receive address (using & ) of array elements </li></ul></ul><ul><ul><ul><li>Array elements have call-by-value default </li></ul></ul></ul><ul><ul><li>Using pointers and the * operator, swap can switch array elements </li></ul></ul><ul><li>Psuedocode </li></ul><ul><ul><ul><li>Initialize array </li></ul></ul></ul><ul><ul><ul><li>print data in original order </li></ul></ul></ul><ul><ul><ul><li>Call function bubblesort </li></ul></ul></ul><ul><ul><ul><li>print sorted array </li></ul></ul></ul><ul><ul><ul><li>Define bubblesort </li></ul></ul></ul>
  149. 149. 7.6 Bubble Sort Using Call-by-reference <ul><li>sizeof </li></ul><ul><ul><li>Returns size of operand in bytes </li></ul></ul><ul><ul><li>For arrays: size of 1 element * number of elements </li></ul></ul><ul><ul><li>if sizeof( int ) equals 4 bytes, then </li></ul></ul><ul><ul><ul><ul><li>int myArray[ 10 ]; </li></ul></ul></ul></ul><ul><ul><ul><ul><li>printf( &quot;%d&quot;, sizeof( myArray ) ); </li></ul></ul></ul></ul><ul><ul><ul><li>will print 40 </li></ul></ul></ul><ul><li>sizeof can be used with </li></ul><ul><ul><li>Variable names </li></ul></ul><ul><ul><li>Type name </li></ul></ul><ul><ul><li>Constant values </li></ul></ul>
  150. 150. 1. Initialize array 1.1 Declare variables 2. Print array 2.1 Call bubbleSort 2.2 Print array 1 /* Fig. 7.15: fig07_15.c 2 This program puts values into an array, sorts the values into 3 ascending order, and prints the resulting array. */ 4 #include <stdio.h> 5 #define SIZE 10 6 void bubbleSort( int *, const int ); 7 8 int main() 9 { 10 11 int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 12 int i; 13 14 printf( &quot;Data items in original ordern&quot; ); 15 16 for ( i = 0; i < SIZE; i++ ) 17 printf( &quot;%4d&quot;, a[ i ] ); 18 19 bubbleSort( a, SIZE ); /* sort the array */ 20 printf( &quot;nData items in ascending ordern&quot; ); 21 22 for ( i = 0; i < SIZE; i++ ) 23 printf( &quot;%4d&quot;, a[ i ] ); 24 25 printf( &quot;n&quot; ); 26 27 return 0; 28 } 29 30 void bubbleSort( int *array, const int size ) 31 { 32 void swap( int *, int * ); Bubblesort gets passed the address of array elements (pointers). The name of an array is a pointer.
  151. 151. 3. Function definitions Program Output Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items in ascending order 2 4 6 8 10 12 37 45 33 int pass, j; 34 for ( pass = 0; pass < size - 1; pass++ ) 35 36 for ( j = 0; j < size - 1; j++ ) 37 38 if ( array[ j ] > array[ j + 1 ] ) 39 swap( &array[ j ], &array[ j + 1 ] ); 40 } 41 42 void swap( int *element1Ptr, int *element2Ptr ) 43 { 44 int hold = *element1Ptr; 45 *element1Ptr = *element2Ptr; 46 *element2Ptr = hold; 47 }
  152. 152. 7.7 Pointer Expressions and Pointer Arithmetic <ul><li>Arithmetic operations can be performed on pointers </li></ul><ul><ul><li>Increment/decrement pointer ( ++ or -- ) </li></ul></ul><ul><ul><li>Add an integer to a pointer( + or += , - or -= ) </li></ul></ul><ul><ul><li>Pointers may be subtracted from each other </li></ul></ul><ul><ul><li>Operations meaningless unless performed on an array </li></ul></ul> 
  153. 153. 7.7 Pointer Expressions and Pointer Arithmetic <ul><li>5 element int array on machine with 4 byte int s </li></ul><ul><ul><li>vPtr points to first element v[ 0 ] </li></ul></ul><ul><ul><ul><li>at location 3000 ( vPtr = 3000 ) </li></ul></ul></ul><ul><ul><li>vPtr += 2; sets vPtr to 3008 </li></ul></ul><ul><ul><ul><li>vPtr points to v[ 2 ] (incremented by 2), but the machine has 4 byte int s, so it points to address 3008 </li></ul></ul></ul>  pointer variable vPtr v[0] v[1] v[2] v[4] v[3] 3000 3004 3008 3012 3016 location
  154. 154. 7.7 Pointer Expressions and Pointer Arithmetic <ul><li>Subtracting pointers </li></ul><ul><ul><li>Returns number of elements from one to the other. If </li></ul></ul><ul><ul><ul><li>vPtr2 = v[ 2 ]; </li></ul></ul></ul><ul><ul><ul><li>vPtr = v[ 0 ]; </li></ul></ul></ul><ul><ul><li>vPtr2 - vPtr would produce 2 </li></ul></ul><ul><li>Pointer comparison ( < , == , > ) </li></ul><ul><ul><li>See which pointer points to the higher numbered array element </li></ul></ul><ul><ul><li>Also, see if a pointer points to 0 </li></ul></ul>
  155. 155. 7.7 Pointer Expressions and Pointer Arithmetic <ul><li>Pointers of the same type can be assigned to each other </li></ul><ul><ul><li>If not the same type, a cast operator must be used </li></ul></ul><ul><ul><li>Exception: pointer to void (type void * ) </li></ul></ul><ul><ul><ul><li>Generic pointer, represents any type </li></ul></ul></ul><ul><ul><ul><li>No casting needed to convert a pointer to void pointer </li></ul></ul></ul><ul><ul><ul><li>void pointers cannot be dereferenced </li></ul></ul></ul>
  156. 156. 7.8 The Relationship Between Pointers and Arrays <ul><li>Arrays and pointers closely related </li></ul><ul><ul><li>Array name like a constant pointer </li></ul></ul><ul><ul><li>Pointers can do array subscripting operations </li></ul></ul><ul><li>Declare an array b[ 5 ] and a pointer bPtr </li></ul><ul><ul><li>To set them equal to one another use: </li></ul></ul><ul><ul><ul><ul><li>bPtr = b; </li></ul></ul></ul></ul><ul><ul><ul><li>The array name ( b ) is actually the address of first element of the array b[ 5 ] </li></ul></ul></ul><ul><ul><ul><ul><li>bPtr = &b[ 0 ] </li></ul></ul></ul></ul><ul><ul><ul><li>Explicitly assigns bPtr to address of first element of b </li></ul></ul></ul>
  157. 157. 7.8 The Relationship Between Pointers and Arrays <ul><ul><li>Element b[ 3 ] </li></ul></ul><ul><ul><ul><li>Can be accessed by *( bPtr + 3 ) </li></ul></ul></ul><ul><ul><ul><ul><li>Where n is the offset. Called pointer/offset notation </li></ul></ul></ul></ul><ul><ul><ul><li>Can be accessed by bptr[ 3 ] </li></ul></ul></ul><ul><ul><ul><ul><li>Called pointer/subscript notation </li></ul></ul></ul></ul><ul><ul><ul><ul><li>bPtr[ 3 ] same as b[ 3 ] </li></ul></ul></ul></ul><ul><ul><ul><li>Can be accessed by performing pointer arithmetic on the array itself </li></ul></ul></ul><ul><ul><ul><ul><li>*( b + 3 ) </li></ul></ul></ul></ul>
  158. 158. 7.9 Arrays of Pointers <ul><li>Arrays can contain pointers </li></ul><ul><li>For example: an array of strings </li></ul><ul><ul><ul><li>char *suit[ 4 ] = { &quot;Hearts&quot;, &quot;Diamonds&quot;, &quot;Clubs&quot;, &quot;Spades&quot; }; </li></ul></ul></ul><ul><ul><li>Strings are pointers to the first character </li></ul></ul><ul><ul><li>char * – each element of suit is a pointer to a char </li></ul></ul><ul><ul><li>The strings are not actually stored in the array suit , only pointers to the strings are stored </li></ul></ul><ul><ul><li>suit array has a fixed size, but strings can be of any size </li></ul></ul>  suit[3] suit[2] suit[1] suit[0] ’ H’ ’ e’ ’ a’ ’ r’ ’ t’ ’ s’ ’ 0’ ’ D’ ’ i’ ’ a’ ’ m’ ’ o’ ’ n’ ’ d’ ’ s’ ’ 0’ ’ C’ ’ l’ ’ u’ ’ b’ ’ s’ ’ 0’ ’ S’ ’ p’ ’ a’ ’ d’ ’ e’
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×