(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
control statements of clangauge (ii unit)
1. MAHARSHI ARVIND INSTITUTE OF
ENGINEERING TECHNOLOGY, JAIPUR
B.TECH II SEM
FUNDAMENTAL OF COMPUTER PROGRAMMING
Presented by
Er. PRASHANT KUMAR SHARMA( CSE DEPT)
3. 3
Control Structures
Outline
2.1 Introduction
2.2 Algorithms
2.3 Pseudocode
2.4 Control Structures
2.5 The if Selection Structure
2.6 The if/else Selection Structure
2.7 The while Repetition Structure
2.8 Formulating Algorithms: Case Study 1
(Counter-Controlled Repetition)
2.9 Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 2 (Sentinel-Controlled Repetition)
2.10 Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 3 (Nested Control Structures)
2.11 Assignment Operators
2.12 Increment and Decrement Operators
2.13 Essentials of Counter-Controlled Repetition
2.14 The for Repetition Structure
2.15 Examples Using the for Structure
4. 4
Control Structures
Outline
2.16 The switch Multiple-Selection Structure
2.17 The do/while Repetition Structure
2.18 The break and continue Statements
2.19 Logical Operators
2.20 Confusing Equality (==) and Assignment (=) Operators
2.21 Structured-Programming Summary
5. 5
Introduction
Before writing a program:
Have a thorough understanding of problem
Carefully plan your approach for solving it
While writing a program:
Know what “building blocks” are available
Use good programming principles
6. 6
Algorithms
All computing problems
can be solved by executing a series of actions
in a specific order
Algorithm
A procedure determining the
Actions to be executed
Order in which these actions are to be executed
Program control
Specifies the order in which statements are to
7. 7
Pseudocode
Pseudocode
Artificial, informal language used to develop
algorithms
Similar to everyday English
Not actually executed on computers
Allows us to “think out” a program before
writing the code for it
Easy to convert into a corresponding C++
program
Consists only of executable statements
8. 8
Control Structures
Sequential execution
Statements executed one after the other in the order written
Transfer of control
When the next statement executed is not the next one in
sequence
Bohm and Jacopini: all programs written in terms of 3 control
structures
Sequence structure
Built into C++. Programs executed sequentially by default.
Selection structures
C++ has three types - if, if/else, and switch
Repetition structures
C++ has three types - while, do/while, and for
9. 9
Control Structures
C++ keywords
Cannot be used as identifiers or variable
names.C++ Keyword s
Keywords common to the
C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
10. 10
Control Structures
Flowchart
Graphical representation of an algorithm
Drawn using certain special-purpose symbols connected by
arrows called flowlines.
Rectangle symbol (action symbol)
Indicates any type of action.
Oval symbol
indicates beginning or end of a program, or a section of code
(circles).
single-entry/single-exit control structures
Connect exit point of one control structure to entry point of the
next (control-structure stacking).
Makes programs easy to build.
11. The if Selection Structure
Selection structure
used to choose among alternative courses of action
Pseudocode example:
If student’s grade is greater than or equal to 60
Print “Passed”
If the condition is true
print statement executed and program goes on to next
statement
If the condition is false
print statement is ignored and the program goes onto the
next statement
Indenting makes programs easier to read
C++ ignores whitespace characters11
12. 12
The if Selection Structure
Translation of pseudocode statement into C++:
if ( grade >= 60 )
cout << "Passed";
Diamond symbol (decision symbol)
indicates decision is to be made
Contains an expression that can be true or false.
Test the condition, follow appropriate path
if structure is a single-entry/single-exit structure
13. 13
The if Selection Structure
Flowchart of pseudocode statement
true
false
grade >= 60 print “Passed”
A decision can be made
on any expression.
zero - false
nonzero - true
Example:
3 - 4 is true
14. The if/else Selection Structure
if
Only performs an action if the condition is true
if/else
A different action is performed when condition is true and
when condition is false
Psuedocode
if student’s grade is greater than or equal to 60
print “Passed”
else
print “Failed”
C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
15. 15
The if/else Selection Structure
Ternary conditional operator (?:)
Takes three arguments (condition, value if true, value if
false)
Our pseudocode could be written:
cout << ( grade >= 60 ? “Passed” :
“Failed” );
truefalse
print “Failed” print “Passed”
grade >= 60
16. 16
The if/else Selection Structure
Nested if/else structures
Test for multiple cases by placing if/else selection
structures inside if/else selection structures.
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”
Once a condition is met, the rest of the statements are
skipped
17. 17
The if/else Selection Structure
Compound statement:
Set of statements within a pair of braces
Example:
if ( grade >= 60 )
cout << "Passed.n";
else {
cout << "Failed.n";
cout << "You must take this course
again.n";
}
Without the braces,
cout << "You must take this course again.n";
would be automatically executed
Block
Compound statements with declarations
18. 18
The if/else Selection
Structure
Syntax errors
Errors caught by compiler
Logic errors
Errors which have their effect at execution
time
Non-fatal logic errors
program runs, but has incorrect output
Fatal logic errors
program exits prematurely
19. 19
The while Repetition Structure
Repetition structure
Programmer specifies an action to be
repeated while some condition remains true
Psuedocode
while there are more items on my shopping list
Purchase next item and cross it off my list
while loop repeated until condition becomes
false.
Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
20. 20
The while Repetition Structure
Flowchart of while loop
product <=
1000
product = 2 *
product
tru
e
fals
e
21. 21
Formulating Algorithms
(Counter-Controlled Repetition)
Counter-controlled repetition
Loop repeated until counter reaches a certain value.
Definite repetition
Number of repetitions is known
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.
22. 22
Formulating Algorithms
(Counter-Controlled Repetition)
Pseudocode for example:
Set total to zero
Set grade counter to one
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
Set the class average to the total divided by ten
Print the class average
Following is the C++ code for this example
23. 23
1. Initialize Variables
2. Execute Loop
3. Output results
1 // Fig. 2.7: fig02_07.cpp
2 // Class average program with counter-
controlled repetition3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10{
11 int total, // sum of grades
12 gradeCounter, // number of grades
entered13 grade, // one grade
14 average; // average of grades
15
16 // initialization phase
17 total = 0; //
clear total18 gradeCounter = 1; //
prepare to loop19
20 // processing phase
21 while ( gradeCounter <= 10 ) { //
loop 10 times22 cout << "Enter grade: "; //
prompt for input23 cin >> grade; //
input grade24 total = total + grade; // add
grade to total25 gradeCounter = gradeCounter + 1; //
increment counter26 }
27
28 // termination phase
29 average = total / 10; //
integer division30 cout << "Class average is " << average <<
endl;31
32 return 0; // indicate program ended
33}
The counter gets incremented each
time the loop executes. Eventually,
the counter causes the loop to end.
24. 24
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
25. 25
Formulating Algorithms with Top-Down,
Stepwise Refinement (Sentinel-Controlled
Repetition)
Suppose the problem becomes:
Develop a class-averaging program that will process an arbitrary
number of grades each time the program is run.
Unknown number of students - how will the program know to
end?
Sentinel value
Indicates “end of data entry”
Loop ends when sentinel inputted
Sentinel value chosen so it cannot be confused with a regular
input (such as -1 in this case)
26. 26
Formulating Algorithms with Top-
Down, Stepwise Refinement (Sentinel-
Controlled Repetition)
Top-down, stepwise refinement
begin with a pseudocode representation of
the top:
Determine the class average for the quiz
Divide top into smaller tasks and list them in
order:
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
27. 27
Formulating Algorithms with Top-Down,
Stepwise Refinement
Many programs can be divided into three phases:
Initialization
Initializes the program variables
Processing
Inputs data values and adjusts program variables accordingly
Termination
Calculates and prints the final results.
Helps the breakup of programs for top-down refinement.
Refine the initialization phase from
Initialize variables
to
Initialize total to zero
Initialize counter to zero
28. 28
Nested control structures
Problem:
A college has a list of test results (1 = pass, 2 = fail) for 10
students. Write a program that analyzes the results. If more
than 8 students pass, print "Raise Tuition".
We can see that
The program must process 10 test results. A counter-controlled
loop will be used.
Two counters can be used—one to count the number of students
who passed the exam and one to count the number of students
who failed the exam.
Each test result is a number—either a 1 or a 2. If the number is
not a 1, we assume that it is a 2.
Top level outline:
Analyze exam results and decide if tuition should be raised
29. 29
Assignment Operators
Assignment expression abbreviations
c = c + 3; can be abbreviated as c += 3; using the
addition assignment operator
Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
Examples of other assignment operators include:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
30. 30
Increment and Decrement Operators
Increment operator (++) - can be used instead of c += 1
Decrement operator (--) - can be used instead of c -= 1
Preincrement
When the operator is used before the variable (++c or –c)
Variable is changed, then the expression it is in is evaluated.
Posincrement
When the operator is used after the variable (c++ or c--)
Expression the variable is in executes, then the variable is changed.
If c = 5, then
cout << ++c; prints out 6 (c is changed before cout is executed)
cout << c++; prints out 5 (cout is executed before the increment. c
now has the value of 6)
31. 31
Increment and Decrement
Operators
When Variable is not in an expression
Preincrementing and postincrementing have
the same effect.
++c;
cout << c;
and
c++;
cout << c;
have the same effect.
32. 32
Essentials of Counter-
Controlled Repetition
Counter-controlled repetition requires:
The name of a control variable (or loop counter).
The initial value of the control variable.
The condition that tests for the final value of the control variable (i.e.,
whether looping should continue).
The increment (or decrement) by which the control variable is modified
each time through the loop.
Example:
int counter =1; //initialization
while (counter <= 10){ //repetition condition
cout << counter << endl;
++counter; //increment
}
33. 33
Essentials of Counter-
Controlled Repetition
The declaration
int counter = 1;
Names counter
Declares counter to be an integer
Reserves space for counter in memory
Sets counter to an initial value of 1
34. 34
The for Repetition Structure
The general format when using for loops
is
for ( initialization; LoopContinuationTest;
increment )
statement
Example:
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
Prints the integers from one to ten
No
semicolo
n after
last
statemen
t
35. 35
The for Repetition Structure
For loops can usually be rewritten as
while loops:
initialization;
while ( loopContinuationTest){
statement
increment;
}
Initialization and increment as comma-
separated lists
for (int i = 0, j = 0; j + i <= 10;
j++, i++)
cout << j + i << endl;
36. 36
Using the for Structure
1 // Fig. 2.20: fig02_20.cpp
2 // Summation with for
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 int sum = 0;
11
12 for ( int number = 2; number <= 100;
number += 2 )13 sum += number;
14
15 cout << "Sum is " << sum << endl;
16
17 return 0;
18}
Sum is 2550
• Program to sum the even numbers from 2 to
100
37. 37
The switch Multiple-Selection Structure
switch
Useful when variable or expression is tested for multiple values
Consists of a series of case labels and an optional default case
true
false
.
.
.
case a case a action(s) break
case b case b action(s) break
false
false
case z case z action(s) break
true
true
default action(s)
38. 38
1. Initialize variables
2. Input data
2.1 Use switch loop to
update count
1 // Fig. 2.22: fig02_22.cpp
2 // Counting letter grades
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10{
11 int grade, // one grade
12 aCount = 0, // number of A's
13 bCount = 0, // number of B's
14 cCount = 0, // number of C's
15 dCount = 0, // number of D's
16 fCount = 0; // number of F's
17
18 cout << "Enter the letter grades." << endl
19 << "Enter the EOF character to end
input." << endl;20
21 while ( ( grade = cin.get() ) != EOF ) {
22
23 switch ( grade ) { // switch nested
in while24
25 case 'A': // grade was uppercase A
26 case 'a': // or lowercase a
27 ++aCount;
28 break; // necessary to exit
switch29
30 case 'B': // grade was uppercase B
31 case 'b': // or lowercase b
32 ++bCount;
33 break;
Notice how the case statement is
used
39. 39
2.1 Use switch loop to
update count
3. Print results
35 case 'C': // grade was uppercase C
36 case 'c': // or lowercase c
37 ++cCount;
38 break;
39
40 case 'D': // grade was uppercase D
41 case 'd': // or lowercase d
42 ++dCount;
43 break;
44
45 case 'F': // grade was uppercase F
46 case 'f': // or lowercase f
47 ++fCount;
48 break;
49
50 case 'n': // ignore newlines,
51 case 't': // tabs,
52 case ' ': // and spaces in input
53 break;
54
55 default: // catch all other
characters56 cout << "Incorrect letter grade
entered."57 << " Enter a new grade." <<
endl;58 break; // optional
59 }
60 }
61
62 cout << "nnTotals for each letter grade
are:"63 << "nA: " << aCount
64 << "nB: " << bCount
65 << "nC: " << cCount
66 << "nD: " << dCount
67 << "nF: " << fCount << endl;
68
69 return 0;
break causes switch to end
and the program continues with the
first statement after the switch
structure.
Notice the default statement.
40. 40
Program Output
Enter the letter grades.
Enter the EOF character to end input.
a
B
c
C
A
d
f
C
E
Incorrect letter grade entered. Enter a new
grade.
D
A
b
Totals for each letter grade are:
A: 3
B: 2
C: 3
D: 2
F: 1
41. 41
The do/while Repetition Structure
The do/while repetition structure is similar to the while
structure,
Condition for repetition tested after the body of the loop is
executed
Format:
do {
statement
} while ( condition );
Example (letting counter = 1):
do {
cout << counter << " ";
} while (++counter <= 10);
This prints the integers from 1 to 10
All actions are performed at least once.
true
false
action(s)
condition
42. 42
The break and continue Statements
Break
Causes immediate exit from a while, for,
do/while or switch structure
Program execution continues with the first statement
after the structure
Common uses of the break statement:
Escape early from a loop
Skip the remainder of a switch structure
43. The break and continue Statements
Continue
Skips the remaining statements in the body of a
while, for or do/while structure and proceeds
with the next iteration of the loop
In while and do/while, the loop-continuation test is
evaluated immediately after the continue statement
is executed
In the for structure, the increment expression is
executed, then the loop-continuation test is evaluated
44. 44
Logical Operators
&& (logical AND)
Returns true if both conditions are true
|| (logical OR)
Returns true if either of its conditions are true
! (logical NOT, logical negation)
Reverses the truth/falsity of its condition
Returns true when its condition is false
Is a unary operator, only takes one condition
Logical operators used as conditions in loops
Expression Result
true && false false
true || false true
!false true
45. 45
Confusing Equality (==) and Assignment (=)
Operators
These errors are damaging because they do not ordinarily cause
syntax errors.
Recall that any expression that produces a value can be used in
control structures. Nonzero values are true, and zero values
are false
Example:
if ( payCode == 4 )
cout << "You get a bonus!" << endl;
Checks the paycode, and if it is 4 then a bonus is awarded
If == was replaced with =
if ( payCode = 4 )
cout << "You get a bonus!" << endl;
Sets paycode to 4
4 is nonzero, so the expression is true and a bonus is
awarded, regardless of paycode.
46. 46
Confusing Equality (==) and Assignment (=)
Operators
Lvalues
Expressions that can appear on the left side of an equation
Their values can be changed
Variable names are a common example (as in x = 4;)
Rvalues
Expressions that can only appear on the right side of an
equation
Constants, such as numbers (i.e. you cannot write 4 = x;)
Lvalues can be used as rvalues, but not vice versa
48. The main( ) function
So far, we have been defining the main()
function to receive no arguments.
Actually, the main( ) function can receive two
arguments.
To do that, the main( ) function should be
defined as below.
This is how arguments can be passed in at the
command line.
int main(int argc, char *argv[ ]) { … }
49. Command Line Arguments
From the command prompt, we can start running
a program by typing its name and pressing
ENTER.
To pass arguments, we type in the program’s
name followed by some arguments, then press
ENTER.
Below is an example from the Unix command
prompt.
% myprog
% myprog 5 23
50. argc and argv
When the program is called from the command
line with arguments, argc will contain the
number of arguments.
When the user types in arguments, the user
separates each argument with a space.
argv is an array of character strings.
argv[1] is the character string containing the first
argument, argv[2] the second, etc.
Note: argv[0] contains the character string that is
the name of the executable.
51. Example
int main(int argc, char *argv[]) {
int i;
for (i = 1; i < argc; i++) printf("%s ", argv[i]);
printf("n");
return 0;
}
52. Using sscanf to get floats and ints
Suppose you expect an integer and a floating point
number as command line arguments.
They will be put in argv[1] and argv[2] respectively.
Use sscanf to get their values.
int main(int argc, char *argv[]) {
int n;
float f;
sscanf(argv[1], ”%d”, &n);
sscanf(argv[2], ”%f”, &f);
…
}
55. 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
56. Arrays
Array
Group of consecutive memory locations
Same name and type
To refer to an element, specify
Array name
Position number
Format:
arrayname[ position number ]
First element at position 0
n element array named c:
c[ 0 ], c[ 1 ]...c[ n – 1 ]
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]
57. Arrays
Array elements are like normal variables
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );
Perform operations in subscript. If x equals 3
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
58. Declaring Arrays
When declaring arrays, specify
Name
Type of array
Number of elements
arrayType arrayName[ numberOfElements ];
Examples:
int c[ 10 ];
float myArray[ 3284 ];
Declaring multiple arrays of same type
Format similar to regular variables
Example:
int b[ 100 ], x[ 27 ];
59. 59
Examples Using Arrays
Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
All elements 0
If too many a syntax error is produced syntax error
C arrays have no bounds checking
If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
5 initializers, therefore 5 element array
60. 60
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( "%s%13s%17sn", "Element", "Value",
"Histogram" );12
13 for ( i = 0; i <= SIZE - 1; i++ ) {
14 printf( "%7d%13d ", i, n[ i ]) ;
15
16 for ( j = 1; j <= n[ i ]; j++ ) /*
print one bar */17 printf( "%c", '*' );
18
19 printf( "n" );
20 }
21
22 return 0;
23}
62. 62
Examples Using Arrays
Character arrays
String “first” is really a static array of characters
Character arrays can be initialized using string literals
char string1[] = "first";
Null character '0' terminates strings
string1 actually has 6 elements
It is equivalent to
char string1[] = { 'f', 'i', 'r', 's', 't', '0' };
Can access individual characters
string1[ 3 ] is character ‘s’
Array name is address of array, so & not needed for scanf
scanf( "%s", string2 );
Reads characters until whitespace encountered
Can write beyond end of array, be careful
63. 63
1. Initialize strings
2. Print strings
2.1 Define loop
2.2 Print characters
individually
2.3 Input string
3. Print string
Program Output
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[] = "string
literal";8 int i;
9
10 printf(" Enter a string: ");
11 scanf( "%s", string1 );
12 printf( "string1 is: %snstring2: is %sn"
13 "string1 with spaces between
characters is:n",14 string1, string2 );
15
16 for ( i = 0; string1[ i ] != '0'; i++ )
17 printf( "%c ", string1[ i ] );
18
19 printf( "n" );
20 return 0;
21}
Enter a string: Hello there
string1 is: Hello
string2 is: string literal
string1 with spaces between characters is:
64. 64
Passing Arrays to Functions
Passing arrays
To pass an array argument to a function, specify the name of the
array without any brackets
int myArray[ 24 ];
myFunction( myArray, 24 );
Array size usually passed to function
Arrays passed call-by-reference
Name of array is address of first element
Function knows where the array is stored
Modifies original memory locations
Passing array elements
Passed by call-by-value
Pass subscripted name (i.e., myArray[ 3 ]) to function
65. Passing Arrays to Functions
Function prototype
void modifyArray( int b[], int
arraySize );
Parameter names optional in prototype
int b[] could be written int []
int arraySize could be simply int
66. 66
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( "Effects of passing entire array
call "14 "by reference:nnThe values of the
"15 "original array are:n" );
16
17 for ( i = 0; i <= SIZE - 1; i++ )
18 printf( "%3d", a[ i ] );
19
20 printf( "n" );
21 modifyArray( a, SIZE ); /* passed call by
reference */22 printf( "The values of the modified array
are:n" );23
24 for ( i = 0; i <= SIZE - 1; i++ )
25 printf( "%3d", a[ i ] );
26
27 printf( "nnnEffects of passing array
element call "28 "by value:nnThe value of a[3] is
%dn", a[ 3 ] );29 modifyElement( a[ 3 ] );
30 printf( "The value of a[ 3 ] is %dn", a[ 3
Entire arrays passed call-by-
reference, and can be
modified
Array elements passed call-
by-value, and cannot be
modified
67. 67
3.1 Function definitions
Program Output
33
34void modifyArray( int b[], int size )
35{
36 int j;
37
38 for ( j = 0; j <= size - 1; j++ )
39 b[ j ] *= 2;
40}
41
42void modifyElement( int e )
43{
44 printf( "Value in modifyElement is %dn", e
*= 2 );45}
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:
68. 68
Sorting Arrays
Sorting data
Important computing application
Virtually every organization must sort some data
Bubble sort (sinking sort)
Several passes through the array
Successive pairs of elements are compared
If increasing order (or identical ), no change
If decreasing order, elements exchanged
Repeat
Example:
original: 3 4 2 6 7
pass 1: 3 2 4 6 7
pass 2: 2 3 4 6 7
Small elements "bubble" to the top
69. Case Study: Computing Mean, Median
and Mode Using Arrays
Mean – average
Median – number in middle of sorted list
1, 2, 3, 4, 5
3 is the median
Mode – number that occurs most often
1, 1, 1, 2, 3, 3, 4, 5
1 is the mode
71. 71
3. Define function mean
3.1 Define function median
3.1.1 Sort Array
3.1.2 Print middle element
33
34void mean( const int answer[] )
35{
36 int j, total = 0;
37
38 printf( "%sn%sn%sn", "********", "
Mean", "********" );39
40 for ( j = 0; j <= SIZE - 1; j++ )
41 total += answer[ j ];
42
43 printf( "The mean is the average value of
the datan"44 "items. The mean is equal to the
total ofn"45 "all the data items divided by the
numbern"46 "of data items ( %d ). The mean
value forn"47 "this run is: %d / %d = %.4fnn",
48 SIZE, total, SIZE, ( double )
total / SIZE );49}
50
51void median( int answer[] )
52{
53 printf( "n%sn%sn%sn%s",
54 "********", " Median", "********",
55 "The unsorted array of responses
is" );56
57 printArray( answer );
58 bubbleSort( answer );
59 printf( "nnThe sorted array is" );
60 printArray( answer );
61 printf( "nnThe median is element %d
72. 72
65}
66
67void mode( int freq[], const int answer[] )
68{
69 int rating, j, h, largest = 0, modeValue =
0;70
71 printf( "n%sn%sn%sn",
72 "********", " Mode", "********" );
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( "%s%11s%19snn%54sn%54snn",
81 "Response", "Frequency",
"Histogram",82 "1 1 2 2", "5 0 5
0 5" );83
84 for ( rating = 1; rating <= 9; rating++ ) {
85 printf( "%8d%11d ", 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( "*" );
3.2 Define function
mode
3.2.1 Increase
frequency[]
depending on
response[]
Notice how the subscript in
frequency[] is the value of an
element in response[]
(answer[])
Print stars depending on value of
frequency[]
73. 73
3.3 Define bubbleSort
3.3 Define printArray
95 printf( "n" );
96 }
97
98 printf( "The mode is the most frequent
value.n"99 "For this run the mode is %d which
occurred"100 " %d times.n", 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 )
Bubble sort: if elements out of
order, swap them.
74. 74
Program Output
126
127 printf( "%2d", a[ j ] );
128 }
129 }
********
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
75. 75
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.
76. 76
Searching Arrays: Linear
Search and Binary Search
Search an array for a key value
Linear search
Simple
Compare each element of array with key
value
Useful for small and unsorted arrays
77. 77
Searching Arrays: Linear
Search and Binary Search
Binary search
For sorted arrays
Compares middle element with key
If equal, match found
If key < middle, looks in first half of array
If key > middle, looks in last half
Repeat
Very fast; at most n steps, where 2n > number
of elements
30 element array takes at most 5 steps
5
79. 79
Multiple-Subscripted Arrays
Initialization
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
Initializers grouped by row in braces
If not enough, unspecified elements set to
zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Referencing elements
Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
1 2
3 4
1 0
3 4
80. 80
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 );
10void printArray( const int [][ EXAMS ], int,
int );11
12int 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( "The array is:n" );
21 printArray( studentGrades, STUDENTS, EXAMS
);22 printf( "nnLowest grade: %dnHighest
grade: %dn",23 minimum( studentGrades, STUDENTS,
EXAMS ),24 maximum( studentGrades, STUDENTS,
EXAMS ) );25
26 for ( student = 0; student <= STUDENTS - 1;
student++ )27 printf( "The average grade for student
%d is %.2fn",28 student,
29 average( studentGrades[ student
], EXAMS ) );30
31 return 0;
Each row is a particular
student, each column is the
grades on the exam.
81. 81
3. Define functions
33
34/* Find the minimum grade */
35int 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 */
49int 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 */63double average( const int setOfGrades[], int
82. 82
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 */
74void printArray( const int grades[][ EXAMS ],
75 int pupils, int tests )
76{
77 int i, j;
78
79 printf( " [0] [1] [2]
[3]" );80
81 for ( i = 0; i <= pupils - 1; i++ ) {
82 printf( "nstudentGrades[%d] ", i );
83
84 for ( j = 0; j <= tests - 1; j++ )
85 printf( "%-5d", grades[ i ][ j ] );
86 }
87}
83. 83
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
85. POINTERS
Pointers are variables that contain memory addresses as their values.
A variable name directly references a value.
A pointer indirectly references a value. Referencing a value through a
pointer is called indirection.
A pointer variable must be declared before it can be used.
86. Concept of Address and
Pointers
Memory can be
conceptualized as a
linear set of data
locations.
Variables reference the
contents of a locations
Pointers have a value of
the address of a given
location
Contents1
Contents11
Contents16
ADDR1
ADDR2
ADDR3
ADDR4
ADDR5
ADDR6
*
*
*
ADDR11
*
*
ADDR16
87. POINTERS
Examples of pointer declarations:
FILE *fptr;
int *a;
float *b;
char *c;
The asterisk, when used as above in the declaration, tells the
compiler that the variable is to be a pointer, and the type of data
that the pointer points to, but NOT the name of the variable
pointed to.
88. POINTERS
Consider the statements:
#include <stdio.h>
int main ( )
{
FILE *fptr1 , *fptr2 ; /* Declare two file pointers */
int *aptr ; /* Declare a pointer to an int */
float *bptr ; /* Declare a pointer to a float */
int a ; /* Declare an int variable */
float b ; /* Declare a float variable */
90. POINTERS
fprintf ( fptr2, "%d %dn" , aptr , bptr ) ;
fprintf ( fptr2, "%d %fn" , *aptr , *bptr ) ;
fprintf ( fptr2, "%d %fn" , a , b ) ;
fprintf ( fptr2, "%d %dn" , &a , &b ) ;
return 0 ;
}
Assuming that the above is part of a program that runs without
error and the the input file does open, what would be printed to
the file
By the first fprintf? By the second fprintf?
By the third fprintf? By the fourth fprintf?
91. Use of & and *
When is & used?
When is * used?
& -- "address operator" which gives or produces the memory
address of a data variable
* -- "dereferencing operator" which provides the contents in the
memory location specified by a pointer
93. Pointers and Functions
Pointers can be used to pass addresses of variables to called
functions, thus allowing the called function to alter the values stored
there.
We looked earlier at a swap function that did not change the values
stored in the main program because only the values were passed to
the function swap.
This is known as "call by value".
94. Pointers and Functions
If instead of passing the values of the variables to the
called function, we pass their addresses, so that the
called function can change the values stored in the
calling routine. This is known as "call by reference"
since we are referencing the variables.
The following shows the swap function modified from a
"call by value" to a "call by reference". Note that the
values are now actually swapped when the control is
returned to main function.
95. Pointers with Functions
(example)
#include <stdio.h>
void swap ( int *a, int *b ) ;
int main ( )
{
int a = 5, b = 6;
printf("a=%d b=%dn",a,b) ;
swap (&a, &b) ;
printf("a=%d b=%dn",a,b) ;
return 0 ;
}
void swap( int *a, int *b )
{
int temp;
temp= *a; *a= *b; *b = temp ;
printf ("a=%d b=%dn", *a, *b);
}
Results:
a=5 b=6
a=6 b=5
a=6 b=5
96. Arithmetic and Logical
Operations on Pointers
A pointer may be incremented or decremented
An integer may be added to or subtracted from a
pointer.
Pointer variables may be subtracted from one
another.
Pointer variables can be used in comparisons, but
usually only in a comparison to NULL.
97. Arithmetic Operations on
Pointers
When an integer is added to or subtracted from a
pointer, the new pointer value is changed by the integer
times the number of bytes in the data variable the pointer
is pointing to.
For example, if the pointer valptr contains the address of
a double precision variable and that address is
234567870, then the statement:
valptr = valptr + 2;
would change valptr to 234567886
98. Using the C Language Special
Keyword
sizeof
This keyword can be used to determine the number
of bytes in a data type, a variable, or an array
Example:
double array [10];
sizeof (double); /* Returns the value 8 */
sizeof (array); /* Returns the value 80 */
sizeof(array)/sizeof(double); /* Returns 10 */
99. 7/28/0999
Boy’s Names
A common use of an array of pointers is to create an array
of strings. The declaration below creates an initialized
array of strings (char *) for some boys names. The
diagram below illustrates the memory configuration.
char *name[] = { “Bobby”, “Jim”, Harold” };
B o b b y 0
J i m 0
H a r o l d 0
names:
0
1
2
101. Data Structures (struct)
Arrays require that all elements be of the same data
type. Many times it is necessary to group information
of different data types. An example is a materials list
for a product. The list typically includes a name for
each item, a part number, dimensions, weight, and
cost.
C and C++ support data structures that can store
combinations of character, integer floating point and
enumerated type data. They are called a structs.
102. Structures (struct)
A struct is a derived data type composed of members
that are each fundamental or derived data types.
A single struct would store the data for one object. An
array of structs would store the data for several objects.
A struct can be defined in several ways as illustrated in
the following examples:
103. Declaring Structures (struct)
Reserves Space
struct
my_example
{
int label;
char letter;
char name[20];
} mystruct ;
Does Not Reserve Space
struct my_example
{
int label;
char letter;
char name[20];
} ;
/* The name "my_example" is
called a structure tag */
104. User Defined Data Types
(typedef)
The C language provides a facility called typedef for creating
synonyms for previously defined data type names. For
example, the declaration:
typedef int Length;
makes the name Length a synonym (or alias) for the data type
int.
The data “type” name Length can now be used in declarations
in exactly the same way that the data type int can be used:
Length a, b, len ;
Length numbers[10] ;
105. Typedef & Struct
Often, typedef is used in combination with struct to declare a synonym
(or an alias) for a structure:
typedef struct /* Define a structure */
{
int label ;
char letter;
char name[20] ;
} Some_name ; /* The "alias" is Some_name */
Some_name mystruct ; /* Create a struct variable */
106. Accessing Struct Members
Individual members of a struct variable may be accessed
using the structure member operator (the dot, “.”):
mystruct.letter ;
Or , if a pointer to the struct has been declared and
initialized
Some_name *myptr = &mystruct ;
by using the structure pointer operator (the “->“):
myptr -> letter ;
which could also be written as:
(*myptr).letter ;
107. Sample Program With Structs
/* This program illustrates creating structs and then declaring
and using struct variables. Note that struct personal is an
included data type in struct "identity".
*/
#include <stdio.h>
struct personal //Create a struct but don’t reserve space.
{ long id;
float gpa;
} ;
struct identity //Create a second struct that includes the first
one.
{ char name[30];
struct personal person;
} ;
109. Structs with Union
/* The program on the next 3 slides
creates a union and makes it a member of
struct personal which is, in turn, a member
of struct identity. The union uses the
same memory location for either rank or a
character string (deg) depending on the
answer to the prompt for student status in
main( ) */
110. Structs with Union (cont.)
#include <stdio.h>
union status
{
int rank ;
char deg[4] ;
} ;
struct personal
{
long id ; float gpa ;
union status level ;
} ;
struct identity
{
char name[30] ;
struct personal student ;
} ;
111. Structs with Union (cont.)
int main( )
{ struct identity jb = {"Joe Brown"}, *ptr = &jb;
char u_g;
jb.student.id = 123456789 ;
jb.student.gpa = 3.4 ;
printf ("Enter student status - u or gn");
scanf ("%c", &u_g);
if (u_g == 'u')
{ printf ("Enter rank -- 1, 2, 3, 4 or 5n");
scanf ("%d", &jb.student.level.rank);
printf ("%s is level %dn” , jb.name ,
jb.student.level.rank);
} /* End of if statement */
112. Structs with Union (cont.)
else
{ printf ("Enter degree sought -- ms or phdn");
scanf ("%s", &jb.student.level.deg);
printf ("%s is a %s candidaten”,
jb.name , jb.student.level.deg );
} /* End of else statement */
printf ("%s %ld %fn” , jb.name , jb.student.id ,
jb.student.gpa );
printf ("%s%ld %fn” , ptr->name , ptr->student.id ,
ptr->student.gpa );
} /* End of program */
113. Enumeration
Enumeration is a user-defined data type. It is defined using
the keyword enum and the syntax is:
enum tag_name {name_0, …, name_n} ;
The tag_name is not used directly. The names in the braces
are symbolic constants that take on integer values from zero
through n. As an example, the statement:
enum colors { red, yellow, green } ;
creates three constants. red is assigned the value 0, yellow is
assigned 1 and green is assigned 2.
114. Enumeration
/* This program uses enumerated data types to
access the elements of an array */
#include <stdio.h>
int main( )
{
int March[5][7]={{0,0,1,2,3,4,5},{6,7,8,9,10,11,12},
{13,14,15,16,17,18,19},{20,21,22,23,24,25,26},
{27,28,29,30,31,0,0}};
enum days {Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday};
115. Enumeration
enum week {week_one, week_two,
week_three,
week_four, week_five};
printf ("Monday the third week "
"of March is March %dn",
March [week_three] [Monday] );
}