You are on page 1of 86

Conditional Constructs

Shivani Varshney/RCET/Programming with C


The if Selection Structure

Selection structure:
 Used to choose among alternative courses of action
 Pseudocode:
If student’s grade is greater than or equal to 60
Print “Passed”
If condition true
 Print statement executed and program goes on to next statement
 If false, print statement is ignored and the program goes onto the next
statement
 Indenting makes programs easier to read
 C ignores whitespace characters

Shivani Varshney/RCET/Programming with C


The if Selection Structure

Pseudocode statement in C:
if ( grade >= 60 )
printf( "Passed\n" );
 C code corresponds closely to the pseudocode
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

Shivani Varshney/RCET/Programming with C


The if Selection Structure

if structure is a single-entry/single-exit structure

A decision can be made on 
any expression. 
zero - false 

  nonzero - true
true Example:
grade >= print “Passed”
60 3 - 4 is true

false

Shivani Varshney/RCET/Programming with C


The if/else Selection Structure

if
Only performs an action if the condition is true
 if/else
 Specifies an action to be performed both when the condition is true and when it
is false
 Psuedocode:
 
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
 Note spacing/indentation conventions

Shivani Varshney/RCET/Programming with C


The if/else Selection Structure

C code:
if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");
 Ternary conditional operator (?:)
 Takes three arguments (condition, value if true, value if false)
 Our pseudocode could be written:
printf( "%s\n", grade >= 60 ? "Passed" :
"Failed" );
 Or it could have been written:
grade >= 60 ? printf( “Passed\n” ) :
printf( “Failed\n” );

Shivani Varshney/RCET/Programming with C


The if/else Selection Structure

Flow chart of the if/else selection structure

false true
grade >= 60

print “Failed” print “Passed”

 Nested if/else structures


 Test for multiple cases by placing if/else selection structures inside if/else
selection structures
 Once condition is met, rest of statements skipped
 Deep indentation usually not used in practice

Shivani Varshney/RCET/Programming with C


The if/else Selection Structure
 Compound statement:
 Set of statements within a pair of braces
 Example:
if ( grade >= 60 )
printf( "Passed.\n" );
else {
printf( "Failed.\n" );
printf( "You must take this course
again.\n" );
}
 Without the braces, the statement
printf( "You must take this course
again.\n" );
would be executed automatically
Shivani Varshney/RCET/Programming with C
Conditional Operator

Shivani Varshney/RCET/Programming with C


?:
operator

The C language has an unusual operator, useful for making two-
way decisions. This operator is a combination of ? And : and takes 
three operands. This operator is popularly known as conditional 
operator.
The general form of conditional operator is :

conditional expression ? expression1 : expression2 
The conditional expression is evaluated first. If the result is 
nonzero, expression1 is evaluated and is returned as the value of 
the conditional expression. Otherwise, expression2 is evaluated and 
its value is returned.

Shivani Varshney/RCET/Programming with C


4x + 100         for x < 40

Salary =  300                 for x = 40

4.5x + 150      for x> 40

Can be written as :
Salary=(x<40) ? (4*x+100):(x>40)?(4.5x+150):300;

Shivani Varshney/RCET/Programming with C


Nested if……….else
statement

When a series of decisions are involved, we may have to use more than
one if……….else statement in nested form.

Shivani Varshney/RCET/Programming with C


if(test condition-1)
{
if(test condition-2)
{
statement-1;
}
else
{
statement-2;
}
else
{
statement-3;
}
statement-x;
Shivani Varshney/RCET/Programming with C
Entry

False True
Test condition1
?
statement-3 False True
Test condition 2
?
statement-2 statement-1

statement -
x

Next
statement
Shivani Varshney/RCET/Programming with C
else if ladder
This is used when multipath decisions are involved. A multipath decision is
a chain of ifs in which the statement associated with each else is an if.

if(condition 1)
statement –1;
else if(condition 2)
statement – 2;
else if(condition 3)
statement – 3;
else if(condition n)
statement – n;
else
default - statement;
Shivani Varshney/RCET/Programming with C
Statement – x;
Entry
True false
condition1

false
statement-1 true condition 2

statement-2 true false


condition 3

statement-3 false
true
condition n

statement-n Default
statement

statement -
x
Next
Shivani Varshney/RCET/Programming with C
Switch Case Construct

Shivani Varshney/RCET/Programming with C


The switch Multiple-Selection Structure

switch
 Useful when a variable or expression is tested for all the values it can assume and
different actions are taken
 Format
 Series of case labels and an optional default case
 
switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}
 break; exits from structure

Shivani Varshney/RCET/Programming with C


4.7 The switch Multiple-Selection Structure
 Flowchart of the switch structure

true
case a case a action(s) break

false

true
case b case b action(s) break
false

.
.
.

true
case z case z action(s) break
false

default action(s)

Shivani Varshney/RCET/Programming with C


1
2 Counting letter grades */
3 #include <stdio.h>
4
5 int main()  Initialize
6
7
{
int grade;
variables
8 int aCount = 0, bCount = 0, cCount = 0,
9 dCount = 0, fCount = 0;
10
11 printf( "Enter the letter grades.\n" );
12 printf( "Enter the EOF character to end input.\n" );
13
14 while ( ( grade = getchar() ) != EOF ) {
15
16 switch ( grade ) { /* switch nested in while */  Use switch loop
17
18 case 'A': case 'a': /* grade was uppercase A */ to update count
19 ++aCount; /* or lowercase a */
20 break;
21
22 case 'B': case 'b': /* grade was uppercase B */
23 ++bCount; /* or lowercase b */
24 break;
25
26 case 'C': case 'c': /* grade was uppercase C */
27 ++cCount; /* or lowercase c */
28 break;
29
30 case 'D': case 'd': /* grade was uppercase D */
31 Shivani Varshney/RCET/Programming
++dCount; with
/* orC lowercase d */
32 break;
33
34 case 'F': case 'f': /* grade was uppercase F */
35 ++fCount; /* or lowercase f */
36 break;  Use switch loop
37 to update count
38 case '\n': case' ': /* ignore these in input */
39 break;
40
41 default: /* catch all other characters */
42 printf( "Incorrect letter grade entered." );
43 printf( " Enter a new grade.\n" );
44 break;
45 }
46 }
47
48 printf( "\nTotals for each letter grade are:\n" );
49 printf( "A: %d\n", aCount );  Print results
50 printf( "B: %d\n", bCount );
51 printf( "C: %d\n", cCount );
52 printf( "D: %d\n", dCount );
53 printf( "F: %d\n", fCount );
54
55 return 0;
56 }
Shivani Varshney/RCET/Programming with C
Enter the letter grades.
Enter the EOF character to end input.
A
B
 Program Output
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

Shivani Varshney/RCET/Programming with C


Loop Control Structure

Shivani Varshney/RCET/Programming with C


Loop:
Group of instructions computer executes repeatedly while some condition
remains true

ENTRY CONTROLLED EXIT CONTROLLED

Shivani Varshney/RCET/Programming with C


Entry

Entry controlled false


Test condition
loop control
structure

True

Body of the loop

Shivani Varshney/RCET/Programming with C


Entry

Exit controlled Body of the loop


loop control
structure

false
Test condition

True

Shivani Varshney/RCET/Programming with C


The Essentials of Repetition

 Counter-controlled repetition
Definite repetition: know how many times loop will execute
 Control variable used to count repetitions

 Sentinel-controlled repetition
 Indefinite repetition

 Used when number of repetitions not known

 Sentinel value indicates "end of data"

Shivani Varshney/RCET/Programming with C


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
 A condition that tests for the final value of the control variable
(i.e., whether looping should continue)
 An increment (or decrement) by which the control variable is
modified each time through the loop

Shivani Varshney/RCET/Programming with C


Essentials of Counter-Controlled Repetition

Example:
int counter = 1; //
initialization
while ( counter <= 10 ) { // repetition
condition
printf( "%d\n", counter );
++counter; // increment
}
 The statement
int counter = 1;
 Names counter
 Declares it to be an integer
 Reserves space for it in memory
Shivani Varshney/RCET/Programming with C
 Sets it to an initial value of 1
The for Repetition Structure

Format when using for loops


  for ( initialization; loopContinuationTest;
increment )
statement

Example:
No 
for( int counter = 1; counter <= 10;
semicolon 
counter++ ) (;) after last 
expression
printf( "%d\n", counter );
 Prints the integers from one to ten
Shivani Varshney/RCET/Programming with C
The for Repetition Structure

For loops can usually be rewritten as while loops:


initialization;
while ( loopContinuationTest ) {
statement;
increment;
}
Initialization and increment
 Can be comma-separated lists
 Example:
for (int i = 0, j = 0; j + i <= 10;
j++, i++)
printf(with"%d\n",
Shivani Varshney/RCET/Programming C j + i );
The for Structure: Notes and Observations

 Arithmetic expressions
 Initialization, loop-continuation, and increment can contain
arithmetic expressions. If x equals 2 and y equals 10
for ( j = x; j <= 4 * x * y; j += y /
x )
is equivalent to
for ( j = 2; j <= 80; j += 5 )
 Notes about the for structure:
 "Increment" may be negative (decrement)
 If the loop continuation condition is initially false
 The body of the for structure is not performed
 Control proceeds with the next statement after the for structure
 Control variable
 Often printed or used inside for body, but not necessary
Shivani Varshney/RCET/Programming with C
1 /* Fig. 4.5: fig04_05.c
2 Summation with for */
3 #include <stdio.h>
4  Initialize
5 int main() variables
6 {
7 int sum = 0, number;
8
 for repetition
9 for ( number = 2; number <= 100; number += 2 )
10 sum += number; structure
11
12 printf( "Sum is %d\n", sum );
13
14 return 0;
15 }

Sum is 2550
 Program Output

Shivani Varshney/RCET/Programming with C


The do/while Repetition Structure

The do/while repetition structure


 Similar to the while structure
 Condition for repetition tested after the body of the loop is
performed
   All actions are performed at least once
 Format:
do {
statement;
} while ( condition );

Shivani Varshney/RCET/Programming with C


The do/while Repetition Structure

Example (letting counter = 1):


do {
printf( "%d ", counter );
 
} while (++counter <= 10);
 Prints the integers from 1 to 10

Shivani Varshney/RCET/Programming with C


1 /* Fig. 4.9: fig04_09.c
2 Using the do/while repetition structure */
3 #include <stdio.h>
 Initialize variable
4
5 int main()
6 {
7 int counter = 1;
8
9 do {
 Loop

10 printf( "%d ", counter );  Print


11 } while ( ++counter <= 10 );
12
13 return 0;
14 }

1 2 3 4 5 6 7 8 9 10
 Program Output

Shivani Varshney/RCET/Programming with C


Goto Statement

Shivani Varshney/RCET/Programming with C


Goto Statement

 C supports the goto statement to branch unconditionally from one 
point to another in the program. 
 The goto requires a label in order to identify the place where the 
branch  is  to  be  made.  A  label  is  any  valid  variable  name,  and 
must  be  followed  by  a  colon.  The  label  is  placed  immediately 
before the statement where the control is to be transferred.

Shivani Varshney/RCET/Programming with C


goto label; label:
……………. statement;
…………….
…………….
…………….
label:
goto label;
statement;

The  label  can  be  anywhere  in  the  program  either  before  or  after  the 
goto label: statement.
If  the  label  is  before  the  statement  goto  label;  a  loop  will  be  formed 
and  some  statement  will  be  executed  repeatedly.  Such  a  jump  is 
known as a backward jump. 
If    the  label:  is  placed  after  the  goto  label;  some  statements  will  be 
skipped and the jump is known as a forward jump.
Shivani Varshney/RCET/Programming with C
Break Statement

Shivani Varshney/RCET/Programming with C


The break statement has two uses.
 To terminate a case in the switch statement
 Termination of a loop, bypassing the normal loop conditional
test.
When the break statement is encountered inside a
loop, the loop is immediately terminated, and
program control resumes at the next statement
following the loop.

Shivani Varshney/RCET/Programming with C


Example
#include <stdio.h>
int main (void)
{
int t;
for(t=0; t < 100; t++) {
printf(''%d ", t);
if(t == 10) break;
}
return 0;
}
 It prints the numbers 0 through 10 on the screen. Then the loop
terminates because break causes immediate exit from the loop,
overriding the conditional test t<100.

Shivani Varshney/RCET/Programming with C


Continue Statement

Shivani Varshney/RCET/Programming with C


 The continue statement works somewhat like the break
statement. Instead of forcing termination, it continue forces
the next iteration of the loop to take place, skipping any
code in between.
 For the for loop, continue causes the increment and then
the conditional test portions of the loop to execute.
 For the while and do-while loops, program control passes to
the conditional tests.

Shivani Varshney/RCET/Programming with C


Example

/* Count spaces */
#include <stdio.h>
int main(void)
{
char s[80], *str;
int space;
printf("Enter a string: ");
gets(s);
str = s;
for(space=0; *str; str++) {
if(*str != ' ') continue;
space++;
}
printf(''%d spaces\n", space);
return 0;
}

Shivani Varshney/RCET/Programming with C


Arrays

Shivani Varshney/RCET/Programming with C


Introduction

Arrays
 Structures of related data items
 Static entity – same size throughout program
 Dynamic data structures discussed in Chapter 12

Shivani Varshney/RCET/Programming with C


Name of array
Arrays (Note that all
elements of this
array have the
same name, c)
Array
 Group of consecutive memory locations c[0 -
 Same name and type c[1
] 456
]
c[2 0
To refer to an element, specify c[3
] 7
 Array name ]
c[4 154
2
 Position number
]
c[5 3-
c[6
] 890
Format: ]
c[7 6
]
c[8 2
-
arrayname[ position number ] c[9
] 31
 First element at position 0 c[10
] 645
]
c[11 37
 n element array named c:
] 8
 c[ 0 ], c[ 1 ]...c[ n – 1 ]
Position number
of the element
Shivani Varshney/RCET/Programming with C within array c
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 ]

Shivani Varshney/RCET/Programming with C


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

Shivani Varshney/RCET/Programming with C


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

Shivani Varshney/RCET/Programming with C


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 };  Initialize array
9 int i, j;
10
11 printf( "%s%13s%17s\n", "Element", "Value",
"Histogram" );
12
13 for ( i = 0; i <= SIZE - 1; i++ ) {
 Loop
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" );  Print
20 }
21
22 return 0;
23 }

Shivani Varshney/RCET/Programming with C


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

Shivani Varshney/RCET/Programming with C


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

Shivani Varshney/RCET/Programming with C


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
 Function definitions
6 void modifyArray( int [], int ); /* appears strange */
7 void modifyElement( int );  Pass array to a
8 function
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:\n\nThe values of the "
15 "original array are:\n" );
16 Entire arrays passed call-by-
17 for ( i = 0; i <= SIZE - 1; i++ )
18 printf( "%3d", a[ i ] );
reference, and can be
19 modified
20 printf( "\n" );  Pass array element to
21 modifyArray( a, SIZE ); /* passed call by reference */
22 printf( "The values of the modified array are:\n" );
a function
23
24 for ( i = 0; i <= SIZE - 1; i++ ) Array elements passed call-
25 printf( "%3d", a[ i ] ); by-value, and cannot be
26 modified
27 printf( "\n\n\nEffects of passing array element call "  Print
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 Shivani Varshney/RCET/Programming
return 0; with C
33
34 void modifyArray( int b[], int size )
35 {
 Function definitions
36 int j;
37
38 for ( j = 0; j <= size - 1; j++ )
39 b[ j ] *= 2;
40 }
41
42 void modifyElement( int e )
43 {
44 printf( "Value in modifyElement is %d\n", e *= 2 );
45 }

Effects of passing entire array call by reference:


 Program Output
The values of the original array are:
0 1 2 3 4
The values of the modified array are:
0 2 4 6 8

Effects of passing array element call by value:

The value of a[3] is 6


Value in modifyElement is 12
TheShivani
value of a[3] is 6
Varshney/RCET/Programming with C
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

Shivani Varshney/RCET/Programming with C


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

Shivani Varshney/RCET/Programming with C


1 /* Fig. 6.16: fig06_16.c
2 This program introduces the topic of survey data
analysis.
3 It computes the mean, median, and mode of the data */
4 #include <stdio.h>
5 #define SIZE 99
6
 Function
7 void mean( const int [] );
8 void median( int [] ); prototypes
9 void mode( int [], const int [] ) ;
10 void bubbleSort( int [] );
11 void printArray( const int [] );
12
13 int main()
14 {
15 int frequency[ 10 ] = { 0 };
16 int response[ SIZE ] =
17 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9,
18 7, 8, 9, 5, 9, 8, 7, 8, 7, 8,  Initialize array
19 6, 7, 8, 9, 3, 9, 8, 7, 8, 7,
20 7, 8, 9, 8, 9, 8, 9, 7, 8, 9,
21 6, 7, 8, 7, 8, 7, 9, 8, 9, 2,
22 7, 8, 9, 8, 9, 8, 9, 7, 5, 3,
23 5, 6, 7, 2, 5, 3, 9, 4, 6, 4,
24 7, 8, 9, 6, 8, 7, 8, 9, 7, 8,
25 7, 4, 4, 2, 5, 3, 8, 7, 5, 6,
26 4, 5, 6, 1, 6, 5, 7, 8, 7 };
27
28 mean( response );
 Call functions
29 median( response );
30 mode( frequency, response ); mean, median,
31 Shivani Varshney/RCET/Programming
return 0; with C
and mode
33
34 void mean( const int answer[] )  Define function
35 { mean
36 int j, total = 0;
37
38 printf( "%s\n%s\n%s\n", "********", " 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 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 }
50
 Define function
51 void median( int answer[] )
52 { median
53 printf( "\n%s\n%s\n%s\n%s",
54 "********", " Median", "********",
55 "The unsorted array of responses is" );
56
57 printArray( answer );
58 bubbleSort( answer );  Sort Array
59 printf( "\n\nThe sorted array is" );
60 printArray( answer );
61 printf( "\n\nThe median is element %d of\n"  Print middle
62 "the sorted %d element array.\n"
63 Shivani Varshney/RCET/Programming
"For this run the with Cmedian is %d\n\n", element
65 }
66
67 void mode( int freq[], const int answer[] )
68 {
Define function
69 int rating, j, h, largest = 0, modeValue = 0;
mode
70
71 printf( "\n%s\n%s\n%s\n",
72 "********", " Mode", "********" );
73
74 for ( rating = 1; rating <= 9; rating++ )
75 freq[ rating ] = 0;
76 Notice how the subscript in
77 for ( j = 0; j <= SIZE - 1; j++ frequency[]
) is the value of an
78 ++freq[ answer[ j ] ]; element in response[]
79 (answer[])
80 printf( "%s%11s%19s\n\n%54s\n%54s\n\n",
81 "Response", "Frequency", "Histogram", Increase
82 "1 1 2 2", "5 0 5 0 5" ); frequency[]
83 depending on
84 for ( rating = 1; rating <= 9; rating++ ) {
response[]
85 printf( "%8d%11d ", rating,
freq[ rating ] );
86
87 if ( freq[ rating ] > largest ) {
88 largest = freq[ rating ];
89 modeValue = rating;
90 }
91 Print stars depending on value of
92 for ( h = 1; h <= freq[ rating ]; h++ )
frequency[]
93 Shivani Varshney/RCET/Programming
printf( "*" ); with C
94
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[] )  Define
104 {
bubbleSort
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 ]; Bubble sort: if elements out of
114 a[ j + 1 ] = hold; order, swap them.
115 }
116 }
117
118 void printArray( const int a[] )
119 {  Define
120 int j;
121 printArray
122 for ( j = 0; j <= SIZE - 1; j++ ) {
123
124Shivani Varshney/RCET/Programming
if ( j % 20 ==with
0 C)
126
127 printf( "%2d", a[ j ] );
128 }
129 }
********
Mean
********  Program Output
The mean is the average value of the data
items. The mean is equal to the total of
all the data items divided by the number
of data items (99). The mean value for
this run is: 681 / 99 = 6.8788

********
Median
********
The unsorted array of responses is
7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8
6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9
6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3
5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8
7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7

The sorted array is


1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5
5 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
Shivani Varshney/RCET/Programming with C
The median is element 49 of
********
Mode
********
 Program Output
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.

Shivani Varshney/RCET/Programming with C


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

Shivani Varshney/RCET/Programming with C


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; at5 most n steps, where 2n > number of elements


 30 element array takes at most 5 steps
 25 > 30 so at most 5 steps

Shivani Varshney/RCET/Programming with C


Multiple-Subscripted Arrays

Multiple subscripted arrays


 Tables with rows and columns (m by n array)
 Like matrices: specify row, then column
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript
Array
name Row subscript

Shivani Varshney/RCET/Programming with C


Multiple-Subscripted Arrays

1 2
Initialization 3 4
 int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
 Initializers grouped by row in braces
 If not enough, unspecified elements set to zero 1 0
3 4
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Referencing elements
 Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );

Shivani Varshney/RCET/Programming with C


1 /* Fig. 6.22: fig06_22.c
2 Double-subscripted array example */
3 #include <stdio.h>
4 #define STUDENTS 3
5 #define EXAMS 4
 Initialize variables
6
7 int minimum( const int [][ EXAMS ], int, int );  Define functions to
8 int maximum( const int [][ EXAMS ], int, int ); take double scripted
9 double average( const int [], int ); arrays
10 void printArray( const int [][ EXAMS ], int, Each
int );
row is a particular
11
student, each column is the
12 int main()
13 { grades on the exam.
14 int student;
15 const int studentGrades[ STUDENTS ][ EXAMS ] =
16 { { 77, 68, 86, 73 },
 Initialize
17 { 96, 87, 89, 78 }, studentgrades[
18 { 70, 90, 86, 81 } }; ][]
19
20 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 ) );  Call functions
25
26 for ( student = 0; student <= STUDENTS - 1; student++ )
minimum,
27 printf( "The average grade for student %d is %.2f\n", maximum, and
28 student, average
29 average( studentGrades[ student ], EXAMS ) );
30
31 Shivani Varshney/RCET/Programming
return 0; with C
33
34 /* Find the minimum grade */
35 int minimum( const int grades[][ EXAMS ],
36 int pupils, int tests )
37 {  Define functions
38 int i, j, lowGrade = 100;
39
40 for ( i = 0; i <= pupils - 1; i++ )
41 for ( j = 0; j <= tests - 1; j++ )
42 if ( grades[ i ][ j ] < lowGrade )
43 lowGrade = grades[ i ][ j ];
44
45 return lowGrade;
46 }
47
48 /* Find the maximum grade */
49 int maximum( const int grades[][ EXAMS ],
50 int pupils, int tests )
51 {
52 int i, j, highGrade = 0;
53
54 for ( i = 0; i <= pupils - 1; i++ )
55 for ( j = 0; j <= tests - 1; j++ )
56 if ( grades[ i ][ j ] > highGrade )
57 highGrade = grades[ i ][ j ];
58
59 return highGrade;
60 }
61
62 /* Determine the average grade for a particular exam */
63 Shivani Varshney/RCET/Programming
double average( const int with C
setOfGrades[], int tests )
65 int i, total = 0;
66
67 for ( i = 0; i <= tests - 1; i++ )
68 total += setOfGrades[ i ];
69
70 return ( double ) total / tests;
71 }
72
73 /* Print the array */
74 void printArray( const int grades[][ EXAMS ],
75 int pupils, int tests )
76 {
 Define functions
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 }

Shivani Varshney/RCET/Programming with C


The array is:
[0] [1] [2] [3]  Program Output
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

Shivani Varshney/RCET/Programming with C


Array of characters

 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

Shivani Varshney/RCET/Programming with C


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";  Initialize strings
8 int i;
9
10 printf(" Enter a string: ");
11 scanf( "%s", string1 );
12 printf( "string1 is: %s\nstring2: is %s\n"
 Print strings
13 "string1 with spaces between characters is:\n",
14 string1, string2 );
15
16 for ( i = 0; string1[ i ] != '\0'; i++ )  Define loop
17 printf( "%c ", string1[ i ] );  Print characters
18 individually
19 printf( "\n" );
20 return 0;  Print string
21 }
Enter a string: Hello there
string1 is: Hello
string2 is: string literal  Program Output
string1 with spaces between characters is:
H eShivani
l l Varshney/RCET/Programming
o with C
Multidimensional Array

Shivani Varshney/RCET/Programming with C


Multiple-Subscripted Arrays

Multiple subscripted arrays


 Tables with rows and columns (m by n array)
 Like matrices: specify row, then column

Column 0 Column 1 Column 2 Column 3

Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript
Array
name Row subscript

Shivani Varshney/RCET/Programming with C


Multiple-Subscripted Arrays

1 2
Initialization
3 4
 int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
 Initializers grouped by row in braces
 If not enough, unspecified elements set to zero 1 0

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

 
Referencing elements
 Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );

Shivani Varshney/RCET/Programming with C


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  Initialize variables
7 int minimum( const int [][ EXAMS ], int, int );  Define functions to take
8 int maximum( const int [][ EXAMS ], int, int ); double scripted arrays
9 double average( const int [], int );
10 void printArray( const int [][ EXAMS ], int, int );
11 Each row is a particular student, 
12 int main() each column is the grades on the 
13 { exam. 
14 int student;
15 const int studentGrades[ STUDENTS ][ EXAMS ] =
 Initialize
16 { { 77, 68, 86, 73 },
studentgrades[][]
17 { 96, 87, 89, 78 },
18 { 70, 90, 86, 81 } };
19
20 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 ),  Call functions minimum,
24 maximum( studentGrades, STUDENTS, EXAMS ) ); maximum, and average
25
26 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 ) );
30
31 Shivani Varshney/RCET/Programming
return 0; with C
32 }
33
34 /* Find the minimum grade */
35 int minimum( const int grades[][ EXAMS ],
36 int pupils, int tests )
37 {  Define functions
38 int i, j, lowGrade = 100;
39
40 for ( i = 0; i <= pupils - 1; i++ )
41 for ( j = 0; j <= tests - 1; j++ )
42 if ( grades[ i ][ j ] < lowGrade )
43 lowGrade = grades[ i ][ j ];
44
45 return lowGrade;
46 }
47
48 /* Find the maximum grade */
49 int maximum( const int grades[][ EXAMS ],
50 int pupils, int tests )
51 {
52 int i, j, highGrade = 0;
53
54 for ( i = 0; i <= pupils - 1; i++ )
55 for ( j = 0; j <= tests - 1; j++ )
56 if ( grades[ i ][ j ] > highGrade )
57 highGrade = grades[ i ][ j ];
58
59 return highGrade;
60 }
61
62 /* Determine the average grade for a particular exam */
63 Shivani Varshney/RCET/Programming
double with C
average( const int setOfGrades[], int tests )
64 {
65 int i, total = 0;
66
67 for ( i = 0; i <= tests - 1; i++ )
68 total += setOfGrades[ i ];
69  Define functions
70 return ( double ) total / tests;
71 }
72
73 /* Print the array */
74 void printArray( const int grades[][ EXAMS ],
75 int pupils, int tests )
76 {
77 int i, j;
78
79 printf( " [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 }

Shivani Varshney/RCET/Programming with C


The array is:
[0] [1] [2] [3]
studentGrades[0] 77 68 86 73
studentGrades[1] 96 87 89 78
 Program Output
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

Shivani Varshney/RCET/Programming with C


Pointers and Arrays
x++; y++; z++;
main()
{
int i=3,*x;  printf(“New value in x  = %u”,x);
float j=1.5,*y;  printf(“New value in y = %u”,y);
char k=‘c’,*z;  printf(“New value in z = %u”,z);
printf(“\nValue of i = %d”,i);
printf(“Value of j = %f”);
                                                  }
printf(“Value of k = %c”);

x=&i;
y=&j;
&k;

printf(“Original value in x  = %u”,x);
printf(“Original value in y = %u”,y);
printf(“Original value in z = %u”,z);

Shivani Varshney/RCET/Programming with C


Pointers to Array

main()
{
int a[ ]={15,17,23,43,22},i=0,*j;
j=&a[0];
while(i<5)
{
printf(“\nAddress = %u”,&a[i]);
printf(“\nElement = %d”,*j);
i++;
j++;
}
}

Shivani Varshney/RCET/Programming with C


Accessing array elements in different ways

main()
{
int a[ ]={15,17,23,43,22},i=0;
while(i<5)
{
printf(“\nAddress = %u”,&a[i]);
printf(“Element = %d ”,a[i]);
printf(“%d “,*(a+i));
printf(“%d “,*(i+a));
printf(“%d “,i[a]);
i++;
}
}

Shivani Varshney/RCET/Programming with C


Pointers and 2-D Array

main()
{
int arr[5][2] =  {
   {11,12},
   {21,22}, 
   {31,32}, 
   {41,42}, 
   {51,52}
};
int i,j;
for(i=0;i<=4;i++)
for(j=0;j<=1;j++)
printf(“%d ”,*(*(a+i)+j));
}
Shivani Varshney/RCET/Programming with C
Array of Pointers

main()
{
int *arr[5],i;
printf(“Enter 5 nos:\n”);
for(i=0;i<5;i++)
scanf(“%d”,(arr+i));
printf(“Entered nos.\n”);
for(i=0;i<5;i++)
printf(“%d ”,*(arr+i));
}

Shivani Varshney/RCET/Programming with C

You might also like