+ All Categories
Home > Engineering > control statements of clangauge (ii unit)

control statements of clangauge (ii unit)

Date post: 14-Apr-2017
Category:
Upload: prashant-sharma
View: 341 times
Download: 0 times
Share this document with a friend
115
MAHARSHI ARVIND INSTITUTE OF ENGINEERING TECHNOLOGY, JAIPUR B.TECH II SEM FUNDAMENTAL OF COMPUTER PROGRAMMING Presented by Er. PRASHANT KUMAR SHARMA( CSE DEPT)
Transcript
Page 1: control statements of clangauge (ii unit)

MAHARSHI ARVIND INSTITUTE OF ENGINEERING TECHNOLOGY, JAIPUR

B.TECH II SEM

FUNDAMENTAL OF COMPUTER PROGRAMMING

Presented by

Er. PRASHANT KUMAR SHARMA( CSE DEPT)

Page 2: control statements of clangauge (ii unit)

Unit-2

Page 3: control statements of clangauge (ii unit)

Control StructuresOutline2.1 Introduction2.2 Algorithms2.3 Pseudocode2.4 Control Structures2.5 The if Selection Structure2.6 The if/else Selection Structure2.7 The while Repetition Structure2.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 Operators2.12 Increment and Decrement Operators2.13 Essentials of Counter-Controlled Repetition2.14 The for Repetition Structure2.15 Examples Using the for Structure

Page 4: control statements of clangauge (ii unit)

Control Structures

Outline2.16 The switch Multiple-Selection Structure2.17 The do/while Repetition Structure2.18 The break and continue Statements2.19 Logical Operators2.20 Confusing Equality (==) and Assignment (=) Operators2.21 Structured-Programming Summary

Page 5: control statements of clangauge (ii unit)

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 availableUse good programming principles

Page 6: control statements of clangauge (ii unit)

Algorithms

All computing problemscan 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 controlSpecifies the order in which statements are to

executed

Page 7: control statements of clangauge (ii unit)

Pseudocode

PseudocodeArtificial, informal language used to develop

algorithmsSimilar to everyday EnglishNot actually executed on computers Allows us to “think out” a program before

writing the code for itEasy to convert into a corresponding C++

programConsists only of executable statements

Page 8: control statements of clangauge (ii unit)

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

Page 9: control statements of clangauge (ii unit)

Control Structures C++ keywords

Cannot be used as identifiers or variable names.C++ Keywords

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

Page 10: control statements of clangauge (ii unit)

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.

Page 11: control statements of clangauge (ii unit)

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 characters

Page 12: control statements of clangauge (ii unit)

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

 

Page 13: control statements of clangauge (ii unit)

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 - trueExample:3 - 4 is true

Page 14: control statements of clangauge (ii unit)

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

Psuedocodeif 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";

 

Page 15: control statements of clangauge (ii unit)

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

Page 16: control statements of clangauge (ii unit)

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

Page 17: control statements of clangauge (ii unit)

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

Page 18: control statements of clangauge (ii unit)

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

Page 19: control statements of clangauge (ii unit)

The while Repetition Structure Repetition structure

Programmer specifies an action to be repeated while some condition remains true

Psuedocodewhile there are more items on my shopping list Purchase next item and cross it off my list

while loop repeated until condition becomes false.

Exampleint product = 2;while ( product <= 1000 ) product = 2 * product;

 

Page 20: control statements of clangauge (ii unit)

The while Repetition Structure

Flowchart of while loop

product <= 1000

product = 2 * product

true

false

Page 21: control statements of clangauge (ii unit)

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.

Page 22: control statements of clangauge (ii unit)

Formulating Algorithms (Counter-Controlled Repetition) Pseudocode for example:

Set total to zeroSet grade counter to oneWhile grade counter is less than or equal to ten

Input the next gradeAdd the grade into the totalAdd one to the grade counter

Set the class average to the total divided by tenPrint the class average

Following is the C++ code for this example

Page 23: control statements of clangauge (ii unit)

1. Initialize Variables

2. Execute Loop

3. Output results

1 // Fig. 2.7: fig02_07.cpp2 // Class average program with counter-controlled repetition3 #include <iostream>45 using std::cout;6 using std::cin;7 using std::endl;89 int main()10{11 int total, // sum of grades 12 gradeCounter, // number of grades entered13 grade, // one grade14 average; // average of grades1516 // initialization phase17 total = 0; // clear total18 gradeCounter = 1; // prepare to loop1920 // processing phase21 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 }2728 // termination phase29 average = total / 10; // integer division30 cout << "Class average is " << average << endl;3132 return 0; // indicate program ended successfully33}

The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.

Page 24: control statements of clangauge (ii unit)

Program Output

Enter grade: 98Enter grade: 76Enter grade: 71Enter grade: 87Enter grade: 83Enter grade: 90Enter grade: 57Enter grade: 79Enter grade: 82Enter grade: 94Class average is 81

Page 25: control statements of clangauge (ii unit)

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)

Page 26: control statements of clangauge (ii unit)

Formulating Algorithms with Top-Down, Stepwise Refinement (Sentinel-Controlled Repetition)

Top-down, stepwise refinementbegin 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 variablesInput, sum and count the quiz gradesCalculate and print the class average

Page 27: control statements of clangauge (ii unit)

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 fromInitialize variables

toInitialize total to zeroInitialize counter to zero

Page 28: control statements of clangauge (ii unit)

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

Page 29: control statements of clangauge (ii unit)

Assignment Operators Assignment expression abbreviations

c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

Statements of the formvariable = variable operator expression;

can be rewritten asvariable 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)

Page 30: control statements of clangauge (ii unit)

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)

Page 31: control statements of clangauge (ii unit)

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.

Page 32: control statements of clangauge (ii unit)

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; //initializationwhile (counter <= 10){ //repetition condition cout << counter << endl; ++counter; //increment

}

Page 33: control statements of clangauge (ii unit)

Essentials of Counter-Controlled Repetition The declaration

int counter = 1;Names counterDeclares counter to be an integerReserves space for counter in memorySets counter to an initial value of 1

Page 34: control statements of clangauge (ii unit)

The for Repetition Structure The general format when using for loops

isfor ( initialization; LoopContinuationTest;

increment )

statement Example:

for( int counter = 1; counter <= 10; counter++ )cout << counter << endl;

Prints the integers from one to ten

 

No semicolon after last statement

Page 35: control statements of clangauge (ii unit)

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;

Page 36: control statements of clangauge (ii unit)

Using the for Structure1 // Fig. 2.20: fig02_20.cpp2 // Summation with for3 #include <iostream>45 using std::cout;6 using std::endl;78 int main()9 {10 int sum = 0;1112 for ( int number = 2; number <= 100; number += 2 )13 sum += number;1415 cout << "Sum is " << sum << endl;1617 return 0;18}

 Sum is 2550

• Program to sum the even numbers from 2 to 100

Page 37: control statements of clangauge (ii unit)

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)

 

Page 38: control statements of clangauge (ii unit)

1. Initialize variables

2. Input data

2.1 Use switch loop to update count

1 // Fig. 2.22: fig02_22.cpp2 // Counting letter grades3 #include <iostream>45 using std::cout;6 using std::cin;7 using std::endl;89 int main()10{11 int grade, // one grade12 aCount = 0, // number of A's13 bCount = 0, // number of B's14 cCount = 0, // number of C's15 dCount = 0, // number of D's16 fCount = 0; // number of F's1718 cout << "Enter the letter grades." << endl19 << "Enter the EOF character to end input." << endl;2021 while ( ( grade = cin.get() ) != EOF ) {2223 switch ( grade ) { // switch nested in while2425 case 'A': // grade was uppercase A26 case 'a': // or lowercase a27 ++aCount; 28 break; // necessary to exit switch2930 case 'B': // grade was uppercase B31 case 'b': // or lowercase b32 ++bCount; 33 break;34

Notice how the case statement is used

Page 39: control statements of clangauge (ii unit)

2.1 Use switch loop to update count

3. Print results

35 case 'C': // grade was uppercase C36 case 'c': // or lowercase c37 ++cCount; 38 break;3940 case 'D': // grade was uppercase D41 case 'd': // or lowercase d42 ++dCount; 43 break;4445 case 'F': // grade was uppercase F46 case 'f': // or lowercase f47 ++fCount; 48 break;4950 case '\n': // ignore newlines, 51 case '\t': // tabs, 52 case ' ': // and spaces in input53 break;5455 default: // catch all other characters56 cout << "Incorrect letter grade entered."57 << " Enter a new grade." << endl;58 break; // optional59 }60 }6162 cout << "\n\nTotals for each letter grade are:" 63 << "\nA: " << aCount 64 << "\nB: " << bCount 65 << "\nC: " << cCount 66 << "\nD: " << dCount67 << "\nF: " << fCount << endl;6869 return 0;70}

break causes switch to end and the program continues with the first statement after the switch structure.

Notice the default statement.

Page 40: control statements of clangauge (ii unit)

Program OutputEnter the letter grades.Enter the EOF character to end input.aBcCAdfCEIncorrect letter grade entered. Enter a new grade.DAb Totals for each letter grade are: A: 3B: 2C: 3D: 2F: 1

Page 41: control statements of clangauge (ii unit)

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

 

Page 42: control statements of clangauge (ii unit)

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

Page 43: control statements of clangauge (ii unit)

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

Page 44: control statements of clangauge (ii unit)

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 Resulttrue && false falsetrue || false true!false true

Page 45: control statements of clangauge (ii unit)

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.

Page 46: control statements of clangauge (ii unit)

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

Page 47: control statements of clangauge (ii unit)

Command Line Arguments

Page 48: control statements of clangauge (ii unit)

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[ ]) { … }

Page 49: control statements of clangauge (ii unit)

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

Page 50: control statements of clangauge (ii unit)

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.

Page 51: control statements of clangauge (ii unit)

Example

int main(int argc, char *argv[]) {

int i;

for (i = 1; i < argc; i++) printf("%s ", argv[i]); printf("\n");

return 0;

}

Page 52: control statements of clangauge (ii unit)

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

…}

Page 53: control statements of clangauge (ii unit)

ARRAYS IN C

Page 54: control statements of clangauge (ii unit)

6.1 Introduction

Arrays Structures of related data itemsStatic entity – same size throughout programDynamic data structures discussed in Chapter

12

Page 55: control statements of clangauge (ii unit)

Arrays

Outline6.1 Introduction6.2 Arrays6.3 Declaring Arrays6.4 Examples Using Arrays6.5 Passing Arrays to Functions6.6 Sorting Arrays6.7 Case Study: Computing Mean, Median and Mode Using Arrays6.8 Searching Arrays6.9 Multiple-Subscripted Arrays

Page 56: control statements of clangauge (ii unit)

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]

-456072

1543-89062-31

645378

c[0]c[1]c[2]c[3]

c[11]c[10]c[9]c[8]c[7]

c[5]c[4]

Page 57: control statements of clangauge (ii unit)

Arrays

Array elements are like normal variablesc[ 0 ] = 3;printf( "%d", c[ 0 ] );

Perform operations in subscript. If x equals 3c[ 5 - 2 ] == c[ 3 ] == c[ x ]

Page 58: control statements of clangauge (ii unit)

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

Page 59: control statements of clangauge (ii unit)

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 itint n[ ] = { 1, 2, 3, 4, 5 };

5 initializers, therefore 5 element array

Page 60: control statements of clangauge (ii unit)

1. Initialize array

2. Loop

3. Print

1 /* Fig. 6.8: fig06_08.c2 Histogram printing program */3 #include <stdio.h>4 #define SIZE 1056 int main()7 {8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };9 int i, j;1011 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );1213 for ( i = 0; i <= SIZE - 1; i++ ) {14 printf( "%7d%13d ", i, n[ i ]) ;1516 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */17 printf( "%c", '*' );1819 printf( "\n" );20 }2122 return 0;23}

Page 61: control statements of clangauge (ii unit)

Program OutputElement Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *

Page 62: control statements of clangauge (ii unit)

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

Page 63: control statements of clangauge (ii unit)

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.c2 Treating character arrays as strings */3 #include <stdio.h>45 int main()6 {7 char string1[ 20 ], string2[] = "string literal";8 int i;910 printf(" Enter a string: ");11 scanf( "%s", string1 );12 printf( "string1 is: %s\nstring2: is %s\n"13 "string1 with spaces between characters is:\n",14 string1, string2 );1516 for ( i = 0; string1[ i ] != '\0'; i++ )17 printf( "%c ", string1[ i ] );1819 printf( "\n" );20 return 0;21}Enter a string: Hello therestring1 is: Hellostring2 is: string literalstring1 with spaces between characters is:H e l l o

Page 64: control statements of clangauge (ii unit)

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

Page 65: control statements of clangauge (ii unit)

Passing Arrays to Functions

Function prototypevoid modifyArray( int b[], int arraySize );

Parameter names optional in prototype int b[] could be written int [] int arraySize could be simply int

Page 66: control statements of clangauge (ii unit)

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.c2 Passing arrays and individual array elements to functions */3 #include <stdio.h>4 #define SIZE 556 void modifyArray( int [], int ); /* appears strange */7 void modifyElement( int );89 int main()10{11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i; 1213 printf( "Effects of passing entire array call "14 "by reference:\n\nThe values of the "15 "original array are:\n" );1617 for ( i = 0; i <= SIZE - 1; i++ ) 18 printf( "%3d", a[ i ] );1920 printf( "\n" );21 modifyArray( a, SIZE ); /* passed call by reference */22 printf( "The values of the modified array are:\n" );2324 for ( i = 0; i <= SIZE - 1; i++ )25 printf( "%3d", a[ i ] );2627 printf( "\n\n\nEffects of passing array element call "28 "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] );29 modifyElement( a[ 3 ] );30 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] );31 return 0;

Entire arrays passed call-by-reference, and can be modified

Array elements passed call-by-value, and cannot be modified

Page 67: control statements of clangauge (ii unit)

3.1 Function definitions

Program Output

3334void modifyArray( int b[], int size )35{36 int j;3738 for ( j = 0; j <= size - 1; j++ )39 b[ j ] *= 2;40}4142void modifyElement( int e )43{44 printf( "Value in modifyElement is %d\n", e *= 2 );45}Effects of passing entire array call by reference: The values of the original array are: 0 1 2 3 4The 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 6Value in modifyElement is 12The value of a[3] is 6

Page 68: control statements of clangauge (ii unit)

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

Page 69: control statements of clangauge (ii unit)

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

Page 70: control statements of clangauge (ii unit)

1. Function prototypes

1.1 Initialize array

2. Call functions mean, median, and mode

1 /* Fig. 6.16: fig06_16.c2 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 9967 void mean( const int [] );8 void median( int [] );9 void mode( int [], const int [] ) ;10void bubbleSort( int [] );11void printArray( const int [] );1213int 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 };2728 mean( response );29 median( response );30 mode( frequency, response );31 return 0;32}

Page 71: control statements of clangauge (ii unit)

3. Define function mean

3.1 Define function median

3.1.1 Sort Array

3.1.2 Print middle element

3334void mean( const int answer[] )35{36 int j, total = 0;3738 printf( "%s\n%s\n%s\n", "********", " Mean", "********" );3940 for ( j = 0; j <= SIZE - 1; j++ )41 total += answer[ j ];4243 printf( "The mean is the average value of the data\n"44 "items. The mean is equal to the total of\n"45 "all the data items divided by the number\n"46 "of data items ( %d ). The mean value for\n"47 "this run is: %d / %d = %.4f\n\n",48 SIZE, total, SIZE, ( double ) total / SIZE );49}5051void median( int answer[] )52{53 printf( "\n%s\n%s\n%s\n%s", 54 "********", " Median", "********", 55 "The unsorted array of responses is" );5657 printArray( answer );58 bubbleSort( answer );59 printf( "\n\nThe sorted array is" );60 printArray( answer );61 printf( "\n\nThe median is element %d of\n"62 "the sorted %d element array.\n"

Page 72: control statements of clangauge (ii unit)

65}6667void mode( int freq[], const int answer[] )68{69 int rating, j, h, largest = 0, modeValue = 0;7071 printf( "\n%s\n%s\n%s\n", 72 "********", " Mode", "********" );7374 for ( rating = 1; rating <= 9; rating++ )75 freq[ rating ] = 0;7677 for ( j = 0; j <= SIZE - 1; j++ )78 ++freq[ answer[ j ] ];7980 printf( "%s%11s%19s\n\n%54s\n%54s\n\n",81 "Response", "Frequency", "Histogram",82 "1 1 2 2", "5 0 5 0 5" );8384 for ( rating = 1; rating <= 9; rating++ ) {85 printf( "%8d%11d ", rating, freq[ rating ] );8687 if ( freq[ rating ] > largest ) {88 largest = freq[ rating ];89 modeValue = rating;90 }9192 for ( h = 1; h <= freq[ rating ]; h++ )93 printf( "*" );94

3.2 Define function mode3.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[]

Page 73: control statements of clangauge (ii unit)

3.3 Define bubbleSort

3.3 Define printArray

95 printf( "\n" );96 }9798 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 }102103 void bubbleSort( int a[] )104 {105 int pass, j, hold;106107 for ( pass = 1; pass <= SIZE - 1; pass++ )108109 for ( j = 0; j <= SIZE - 2; j++ )110111 if ( a[ j ] > a[ j + 1 ] ) {112 hold = a[ j ];113 a[ j ] = a[ j + 1 ];114 a[ j + 1 ] = hold;115 }116 }117118 void printArray( const int a[] )119 {120 int j;121122 for ( j = 0; j <= SIZE - 1; j++ ) {123124 if ( j % 20 == 0 )125 printf( "\n" );

Bubble sort: if elements out of order, swap them.

Page 74: control statements of clangauge (ii unit)

Program Output

126127 printf( "%2d", a[ j ] );128 }129 }******** Mean********The mean is the average value of the dataitems. The mean is equal to the total ofall the data items divided by the numberof data items (99). The mean value forthis run is: 681 / 99 = 6.8788 ******** Median********The unsorted array of responses is7 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 ofthe sorted 99 element array.For this run the median is 7

Page 75: control statements of clangauge (ii unit)

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.

Page 76: control statements of clangauge (ii unit)

Searching Arrays: Linear Search and Binary Search Search an array for a key value Linear search

Simple Compare each element of array with key

valueUseful for small and unsorted arrays

Page 77: control statements of clangauge (ii unit)

Searching Arrays: Linear Search and Binary Search Binary search

For sorted arraysCompares 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 25 > 30 so at most 5 steps

5

Page 78: control statements of clangauge (ii unit)

6.9 Multiple-Subscripted Arrays

Multiple subscripted arrays Tables with rows and columns (m by n array)Like matrices: specify row, then column Row 0Row 1Row 2

Column 0 Column 1 Column 2 Column 3a[ 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 subscriptArray name

Column subscript

Page 79: control statements of clangauge (ii unit)

Multiple-Subscripted Arrays

Initializationint b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; Initializers grouped by row in braces If not enough, unspecified elements set to

zeroint b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

Referencing elementsSpecify row, then column

printf( "%d", b[ 0 ][ 1 ] );

 

1 23 4

1 03 4

Page 80: control statements of clangauge (ii unit)

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.c2 Double-subscripted array example */3 #include <stdio.h>4 #define STUDENTS 35 #define EXAMS 467 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 );1112int 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 } };1920 printf( "The array is:\n" );21 printArray( studentGrades, STUDENTS, EXAMS );22 printf( "\n\nLowest grade: %d\nHighest grade: %d\n",23 minimum( studentGrades, STUDENTS, EXAMS ),24 maximum( studentGrades, STUDENTS, EXAMS ) );2526 for ( student = 0; student <= STUDENTS - 1; student++ )27 printf( "The average grade for student %d is %.2f\n", 28 student, 29 average( studentGrades[ student ], EXAMS ) );3031 return 0;32}

Each row is a particular student, each column is the grades on the exam.

Page 81: control statements of clangauge (ii unit)

3. Define functions

3334/* Find the minimum grade */35int minimum( const int grades[][ EXAMS ], 36 int pupils, int tests )37{38 int i, j, lowGrade = 100;3940 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 ];4445 return lowGrade;46}4748/* Find the maximum grade */49int maximum( const int grades[][ EXAMS ], 50 int pupils, int tests )51{52 int i, j, highGrade = 0;5354 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 ];5859 return highGrade;60}6162/* Determine the average grade for a particular exam */63double average( const int setOfGrades[], int tests )64{

Page 82: control statements of clangauge (ii unit)

3. Define functions

65 int i, total = 0;6667 for ( i = 0; i <= tests - 1; i++ )68 total += setOfGrades[ i ];6970 return ( double ) total / tests;71}7273/* Print the array */74void printArray( const int grades[][ EXAMS ], 75 int pupils, int tests )76{77 int i, j;7879 printf( " [0] [1] [2] [3]" );8081 for ( i = 0; i <= pupils - 1; i++ ) {82 printf( "\nstudentGrades[%d] ", i );8384 for ( j = 0; j <= tests - 1; j++ )85 printf( "%-5d", grades[ i ][ j ] );86 }87}

Page 83: control statements of clangauge (ii unit)

Program OutputThe 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: 68Highest grade: 96The average grade for student 0 is 76.00The average grade for student 1 is 87.50The average grade for student 2 is 81.75

Page 84: control statements of clangauge (ii unit)

Pointers

Page 85: control statements of clangauge (ii unit)

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.

Page 86: control statements of clangauge (ii unit)

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

ADDR1ADDR2ADDR3ADDR4ADDR5ADDR6

***

ADDR11

**

ADDR16

Page 87: control statements of clangauge (ii unit)

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.

Page 88: control statements of clangauge (ii unit)

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 */

Page 89: control statements of clangauge (ii unit)

POINTERS/* Then consider the statements: */

aptr = &a ;bptr = &b ;

fptr2 = fopen ( "my_out_file.dat" , "w" ) ; fptr1 = fopen ( "my_in_file.dat" , "r" ) ;if ( fptr1 != NULL ){ fscanf ( fptr1, "%d%f" , aptr , bptr ) ;

Page 90: control statements of clangauge (ii unit)

POINTERS fprintf ( fptr2, "%d %d\n" , aptr , bptr ) ; fprintf ( fptr2, "%d %f\n" , *aptr , *bptr ) ; fprintf ( fptr2, "%d %f\n" , a , b ) ;

fprintf ( fptr2, "%d %d\n" , &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?

Page 91: control statements of clangauge (ii unit)

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

Page 92: control statements of clangauge (ii unit)

POINTERS aptr = &a ; bptr = &b ; fptr2 = fopen ( "my_out.dat" , "w" ) ; fptr1 = fopen ( "my_in.dat" , "r" ) ; if ( fptr1 != NULL ) { fscanf (fptr1, "%d%f", aptr, bptr); fprintf (fptr2, "%d %d\n", aptr, bptr ) ; fprintf (fptr2, "%d %f\n", *aptr, *bptr ) ; fprintf (fptr2, "%d %f\n", a , b ) ; fprintf (fptr2, "%d %d\n", &a , &b ) ; return 0 ; }}

/* input file */5 6.75

/* output file */ 1659178974 16591789765 6.7500005 6.7500001659178974 1659178976

Page 93: control statements of clangauge (ii unit)

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

Page 94: control statements of clangauge (ii unit)

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.

Page 95: control statements of clangauge (ii unit)

Pointers with Functions (example)

#include <stdio.h>void swap ( int *a, int *b ) ;int main ( ){ int a = 5, b = 6; printf("a=%d b=%d\n",a,b) ; swap (&a, &b) ; printf("a=%d b=%d\n",a,b) ; return 0 ;}

void swap( int *a, int *b ){ int temp; temp= *a; *a= *b; *b = temp ; printf ("a=%d b=%d\n", *a, *b);}Results:

a=5 b=6a=6 b=5a=6 b=5

Page 96: control statements of clangauge (ii unit)

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.

Page 97: control statements of clangauge (ii unit)

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

Page 98: control statements of clangauge (ii unit)

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 */

Page 99: control statements of clangauge (ii unit)

7/28/09 99

Boy’s NamesA 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

Page 100: control statements of clangauge (ii unit)

Structs

Page 101: control statements of clangauge (ii unit)

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.

Page 102: control statements of clangauge (ii unit)

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:

 

Page 103: control statements of clangauge (ii unit)

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 */

Page 104: control statements of clangauge (ii unit)

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

Page 105: control statements of clangauge (ii unit)

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 */

Page 106: control statements of clangauge (ii unit)

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 ;

Page 107: control statements of clangauge (ii unit)

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

Page 108: control statements of clangauge (ii unit)

Sample Program With Structs (cont.)int main ( ){ struct identity js = {"Joe Smith"}, *ptr = &js ;

js.person.id = 123456789 ; js.person.gpa = 3.4 ; printf ("%s %ld %f\n", js.name, js.person.id,

js.person.gpa) ; printf ("%s %ld %f\n", ptr->name, ptr->person.id,

ptr->person.gpa) ;}

Page 109: control statements of clangauge (ii unit)

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( ) */

 

Page 110: control statements of clangauge (ii unit)

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

Page 111: control statements of clangauge (ii unit)

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 g\n"); scanf ("%c", &u_g); if (u_g == 'u') { printf ("Enter rank -- 1, 2, 3, 4 or 5\n"); scanf ("%d", &jb.student.level.rank); printf ("%s is level %d\n” , jb.name , jb.student.level.rank); } /* End of if statement */

Page 112: control statements of clangauge (ii unit)

Structs with Union (cont.)

else { printf ("Enter degree sought -- ms or phd\n"); scanf ("%s", &jb.student.level.deg); printf ("%s is a %s candidate\n”, jb.name , jb.student.level.deg ); } /* End of else statement */ printf ("%s %ld %f\n” , jb.name , jb.student.id , jb.student.gpa ); printf ("%s%ld %f\n” , ptr->name , ptr->student.id , ptr->student.gpa );} /* End of program */

Page 113: control statements of clangauge (ii unit)

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.

Page 114: control statements of clangauge (ii unit)

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

Page 115: control statements of clangauge (ii unit)

Enumeration

enum week {week_one, week_two, week_three,

week_four, week_five};

printf ("Monday the third week " "of March is March %d\n",

March [week_three] [Monday] ); }


Recommended