lecture 6: arrays - home | electrical and computer...

40
ECE15: Introduction to Computer Programming Using the C Language Lecture 6: Arrays A. Orlitsky and A. Vardy, based in part on slides by S. Arzi, G. Ruckenstein, E. Avior, S. Asmir, and M. Elad

Upload: lydiep

Post on 03-Jul-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

ECE15: Introduction to Computer Programming Using the C Language

Lecture 6: Arrays

A. Orlitsky and A. Vardy, based in part on slides by S. Arzi, G. Ruckenstein, E. Avior, S. Asmir, and M. Elad

❖ Introduction to Arrays

❖ Simple Examples

❖ Math Examples

❖ String Arrays

❖ Sorting

❖ Two-Dimensional ArraysLecture 6 ECE15: Introduction to Computer Programming Using the C Language 2

Outline

û Typing 800 names (in addition to values)

Why Arrays

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 3

Perhaps:double salary1, salary2, ..., salary800;

Solution: Arrays!

Observation: First need to determine average. Then # salaries above it. Need to go over numbers twice. Must remember all.

Task: A company has 800 employees. Read their salaries, compute the average, and determine how many salaries are above the average..

û Cannot be processed in a loopû Storing 800 names (in addition to values)

Ordered list of variables of the same type

What are Arrays

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 4

‣n-element array declared ‣First element has index 0 ‣Last element has index n-1

‣Array elements always stored in consecutive memory cells

double salaries[800];

Declaration:

Comments:

intintintintintintintintintintintintint

Accessing an element:salaries[5], salaries[i], salaries[2*i+j]

int salaries[n];

124 -85 913 666

int mynm[4];

mynm[0] mynm[1] mynm[3]mynm[2]

Assigning Values

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 5

❖ Array cells have arbitrary initial values ❖ Values can be assigned in a loop:

for (i = 0; i < 800; i++) scanf("%lf", &salaries[i]);

for (i = 0; i < 800; i++) salaries[i] = 3.5 * i;

double prices[3] = {7.49, 9.99, 1.49};

int grades[] = {100, 97, 79, 0, 0};

❖ Fixed-size arrays can also be initialized at declaration

❖ Can determine array size from initialization

❖ Missing values filled with 0’sint grades[5] = {100, 97, 79};

int grades[5] = {100, 97, 79, 0, 0};

❖ Different:

int grades[] = {100, 97, 79};

equivalent

int array[5] = {};

int array[5];

versus5-element array

3-element array

equivalent

all 0

uninitialized

Indices: 0..799

Run-time Array Declaration

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language

❖ Can declare an array whose size is determined at run time

❖ Cannot initialize at declaration

❖ Can initialize later

6

int array_size; scanf("%d",&array_size); int my_array[array_size];

int my_array[array_size]={};û

for (int i=0; i<array_size; i++) my_array[i]=0;

❖ Introduction to Arrays

❖ Simple Examples

❖ Math Examples

❖ String Arrays

❖ Sorting

❖ Two-Dimensional ArraysLecture 6 ECE15: Introduction to Computer Programming Using the C Language 7

Outline

Salaries

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 8

#include<stdio.h> #define NUM_EMPLOYEES 800

int main() { double salaries[NUM_EMPLOYEES], sum = 0.0, average; int i, above_average = 0;

for (i = 0; i < NUM_EMPLOYEES; i++) { scanf("%lf", &salaries[i]); sum += salaries[i]; }

average = sum/NUM_EMPLOYEES;

for (i = 0; i < NUM_EMPLOYEES; ++i) above_average += (salaries[i] > average); printf("Average is: %f\n", average); printf("%d salaries are above it\n", above_average); return 0; }

salaries.c

n-element array

Declared int name[n];

Elements numbered 0..n-1

Backwards (numbers)

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

❖ Read numbers and print them in reverse ❖ Seen for digits (mod and division by 10), now any numbers

9

#include <stdio.h>

int main() { int num_numbers, i; printf("Number of numbers: "); scanf("%d", &num_numbers);

int array[num_numbers];

for (i=0; i<num_numbers; i++) scanf("%d", &array[i]);

for (i=num_numbers-1; i>=0; i--) printf("%d", array[i]);

printf("\n"); return 0; } backwards_numbers.c

Which Digits

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language

❖ Read digits ❖ Print each seen digit once ❖ In order of appearance ❖ 3 1 3 4 1 7 7 → 3 1 4 7

❖ seen[10] Array for all digits ❖ Initially, all marked unseen ❖ Read digits ‣ If unseen - print, mark seen ‣ If seen - do nothing

10

#include <stdio.h> #include <stdbool.h>

int main() { int num_digits, i, digit; bool seen[10]={};

printf("# digits: "); scanf("%d", &num_digits); printf("%d digits: ",num_digits);

for (i=0; i<num_digits; i++) { scanf("%d", &digit);

if (!seen[digit]) { printf("%d ", digit); seen[digit]=true; }

} printf("\n"); return 0; }

digits.c

❖ Introduction to Arrays

❖ Simple Examples

❖ Math Examples

❖ String Arrays

❖ Sorting

❖ Two-Dimensional ArraysLecture 6 ECE15: Introduction to Computer Programming Using the C Language 11

Outline

Decimal to Binary - with Arrays

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 12

❖ What is decimal 10 in binary?

5 10210 div:2

remainder

01 00 1 01 0 1 0

2022 212325 24

0 0 1 0 1 0

remainder remainderremainder

quotient quotient quotient quotient

div:2 div:2 div:2

❖ Same answer, different method:

10 2

32 16 1248

0

Decimal to Binary - Second Method

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 13

#include <stdio.h> int main() { int decimal, i=0, bits[32]; printf("Nonnegative decimal: "); scanf("%d", &decimal); printf("(%d)_10 = (", decimal);

do { bits[i++]=decimal%2; decimal /= 2; } while (decimal);

while(--i >= 0) printf("%d", bits[i]);

printf(")_2\n"); return 0; }

dec2bin2.c

û ü

Observation: The median is often more useful than average. For example, if salaries are 35, 40, 45, 50, 55, 60, 65, 70, 10000000

The Median

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 14

The median of a set of numbers is the number that cuts the set in half: Half the numbers are above the median, and half are below it. Example:

4 3 7 10 9

6 5

5 5 7

9 half of the numbers

half of the numbers

median

Definition: Arrange n numbers in increasing order:

If n is odd, then the median is the middle element of the ordered sequence: x(n+1)/2. If n is even, the median is the average of the two middle elements: (xn/2 + xn/2+1)/2.

x1 ≤ x2 ≤ x3 ≤ ⋅ ⋅ ⋅ ≤ xn-1 ≤ xn

average = 1,111,157.7 median = 55

3 4 5 5 5 6 7 7 9 9 10

Computing the Median

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 15

3 7 9 4 55 5 10 9 76

3

7 9

4

5

5

5

10976

0 0 0 0 1 2 5 6

Method A: Sort the n numbers in increasing order, then take the middle one (or average middle two).

Sorting n numbers requires about n log2 n operations, hence inefficient.

Method B: Suppose the numbers can take at most m values. Make a histogram of the values observed (n operations). Then sum the histogram bars from left to right, till the sum exceeds n/2 (at most m operations).

321 7654 980 10

Median11 values

Median 6th

Computing the Histogram

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 16

#include <stdio.h>

#define NUM_GRADES 85 #define MAX_GRADE 100

int main() { int histogram[MAX_GRADE + 1] = {}; int i, grade;

for (i = 0; i < NUM_GRADES; i++) { scanf("%d", &grade); histogram[grade]++; } ... return 0; }

Example: The input consists of n = 85 exam grades, each an integer in 0,1,...,100. Count # times each grade occur

0,1,… MAX_GRADE

The Median Grade

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 17

#include<stdio.h>

#define NUM_GRADES 85 // Assumed to be odd! #define MAX_GRADE 100

int main() { int histogram[MAX_GRADE + 1] = {}; int i, grade, bar_sum;

for (i = 0; i < NUM_GRADES; i++) { scanf("%d", &grade); histogram[grade]++; }

bar_sum = grade = 0;

while (bar_sum <= NUM_GRADES/2) bar_sum += histogram[grade++]; printf("Median is %d\n", grade-1); return 0; }

median.c

Create Histogram

Stop when sum exceeds half

Incremented grade

The Eratosthenes Sieve: First, pretend that all the integers in the range 2,3,...,N are prime. Then proceed as follows:

All the Primes up to N

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 18

Possible Solution: Test all integers in the range 2,3,...,N for primality. This is very inefficient even with the best primality testing methods.

➡ 2 is prime, mark all multiples of 2 as not prime➡ 3 is prime, mark all multiples of 3 as not prime ➡ 4 was already marked as not prime, just skip it ➡ 5 is prime, mark all multiples of 5 as not prime ➡ 6 was already marked as not prime, just skip it and so on ...

After at most square root of N such steps, all the numbers in the range 2,3,...,N that remain unmarked must be prime.

Problem: Find all primes between 2 and a large positive integer N

Sieve of Eratosthenes Animation

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 19

Computing the Sieve of Eratosthenes for primes up to 120

Program

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 20

int main() { int n, i, p, sqrt_n=0;

printf("Find primes up to: "); scanf("%d", &n);

char prime[n+1];

while ((sqrt_n+1)*(sqrt_n+1)<=n) sqrt_n++;

for (i = 2; i <= n; i++) prime[i] = 1;

for (p = 2; p <= sqrt_n; p++) if (prime[p]) for (i = 2; i <= n/p; i++) prime[i*p] = 0;

printf("Primes between 2 and %d:\n", n); for (i = 2; i <= n; i++) if (prime[i]) printf("%d\n", i);

return 0; }

sieve.c

Integers represented in array, 1 indicates prime, 0 non-prime

So sieve[n] represents n

floor(sqrt(n))

Start by assuming all prime

Not eliminated - indeed prime

All multiples of p are not prime

Comparison with Primality Testing

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 21

... int prime = 1, n, i, sqrt_n; ... if (n == 1 || (n != 2 && n%2 == 0)) prime = 0; else { while ((sqrt_n+1)*(sqrt_n+1)<=n) sqrt_n++;

for (i = 3; i <= sqrt_n; i += 2) if (n%i == 0) { prime = 0; break; } } printf("%d is %sa prime\n", prime ? "" : "not ", n); ...

A short program can compare Eratosthenes’ Sieve with testing every integer in the range using the improved primality testing algorithm. Parameters:

N = 1,000,000 Repeated 100 times in a loop Results: Eratosthenes’ Sieve: 2 sec Primality testing: 18 sec

Sieve of Eratosthenes > 10 times faster

compare_sieve_primes.c

❖ Introduction to Arrays

❖ Simple Examples

❖ Math Examples

❖ String Arrays

❖ Sorting

❖ Two-Dimensional ArraysLecture 6 ECE15: Introduction to Computer Programming Using the C Language 22

Outline

Declaration and Initialization

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

Strings of characters

string of 5 characters

empty string

Stored in character arrays

23

...

// Proper:

char class1[]="ece15"; // array

// Possible, but risky as we’ll soon see:

char class2[] = {'e','c','e','1','5'};

...

"ece15"

""

Input / Output

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 24

#include <stdio.h> int main() { printf("My fav class: %s\n", "ece15");

char word1[50], word2[50]; printf("One word: "); scanf("%s", word1); printf("word1: %s\n", word1)

printf("Two words: "); scanf("%s%s", word1, word2); printf("word1: %s\n", word1); printf("word2: %s\n", word2); return 0; }

Read & write -- %s

string_io.c

%s reads till space

Never read! Need to store string.

No &

- why? Array!

array a must

Printed strings before

Free ASCII Chart

Char Desc Dec Hex Key Char Dec Hex HTML Char Dec Hex Char Dec Hex Char HTML Code

!"# NULL 0 00 ^@ $%&'( 32 20 ) 64 40 * 96 60 $%&'( &nbsp;

$+, Start of Heading 1 01 ^A - 33 21 . 65 41 & 97 61 / &amp;

$01 Start of Text 2 02 ^B 2 34 22 &quot; 3 66 42 4 98 62 5 &lt;

601 End of Text 3 03 ^C 7 35 23 8 67 43 ' 99 63 9 &gt;

6+0 End of Transmission 4 04 ^D : 36 24 ; 68 44 < 100 64 = &copy;

6!> Enquiry 5 05 ^E ? 37 25 6 69 45 ( 101 65 @ &reg;

.8A Acknoledge 6 06 ^F / 38 26 &amp; B 70 46 C 102 66 D &sup1;

36# Bell 7 07 ^G E 39 27 F 71 47 G 103 67 H &sup2;

3$ Backspace 8 08 ^H I 40 28 , 72 48 J 104 68 K &sup3;

0.3 Horizontal Tab 9 09 ^I L 41 29 M 73 49 M 105 69 E &apos;

#B Line Feed 10 0A ^J N 42 2A O 74 4A P 106 6A 2 &quot;

Q0 Home 11 0B ^K R 43 2B A 75 4B S 107 6B T &frac14;BB Form Feed 12 0C ^L U 44 2C # 76 4C V 108 6C W &frac12;8X Carriage Return 13 0D ^M Y 45 2D Z 77 4D [ 109 6D \ &frac34;$+ Shift Out 14 0E ^N ] 46 2E ! 78 4E ^ 110 6E ! &pi;

$M Shift In 15 0F ^O _ 47 2F + 79 4F ` 111 6F a &trade;

;#6 Data Link Escape 16 10 ^P b 48 30 c 80 50 % 112 70 " &infin;

;8d Device Control 1 17 11 ^Q d 49 31 > 81 51 e 113 71 # &ne;

;8f Device Control 2 18 12 ^R f 50 32 X 82 52 g 114 72 $ &le;

;8h Device Control 3 19 13 ^S h 51 33 $ 83 53 i 115 73 % &ge;

;8j Device Control 4 20 14 ^T j 52 34 0 84 54 k 116 74 & &asymp;

!.A Negative Acknowledge 21 15 ^U l 53 35 " 85 55 m 117 75 ! &equiv;

$n! Syncronous Idle 22 16 ^V o 54 36 Q 86 56 p 118 76 ' &sum;

603 End of trans. Block 23 17 ^W q 55 37 r 87 57 s 119 77 t &bull;

8.! Cancel 24 18 ^X u 56 38 1 88 58 v 120 78 w &hellip;

6Z End of Medium 25 19 ^Y x 57 39 n 89 59 y 121 79 ( &Delta;

$"3 Substitute 26 1A ^Z z 58 3A { 90 5A | 122 7A " &larr;

6$8 Escape 27 1B ^[ } 59 3B ~ 91 5B � 123 7B # &uarr;

B$ Cursor Right (File Seperator) 28 1C ^\ 5 60 3C &lt; Ä 92 5C Å 124 7C $ &rarr;

F$ Cursor Left (Group Seperator) 29 1D ^] Ç 61 3D É 93 5D Ñ 125 7D % &darr;

X$ Cursor Up (Record Seperator) 30 1E ^^ 9 62 3E &gt; Ö 94 5E Ü 126 7E & &harr;

"$ Cursor Down (Unit Seperator) 31 1F ^_ á 63 3F à 95 5F ;6# 127 7F â &fnof;

HTML Codes use the #& with the decimal value followed by a semi colon. Example: &#64; for the @ symbol.

HTML Post Operation use the % sign and the hex value. Example: Space would be %20

To obtain codes 0-31, console Control Key is pressed while simultaneously pressing the Letter Key.

www.kellermansoftware.com Free quick reference sheets and .net components

Strings stored with '\0' at end (Null char whose ASCII value is 0)

String Delimiter

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 25

for(int i=0; string[i]; i++) printf("%c", string[i]);

printf("\n");

c e 1 5 \0 % @e

Print string without %s

char class2[]={'e','c','e','1','5','\0'};

Correct array definition

print_string.c

How does printf know when to stop printing? (string had length 50, word was shorter)

char class1[]=”ECE15”;

Free ASCII Chart

Char Desc Dec Hex Key Char Dec Hex HTML Char Dec Hex Char Dec Hex Char HTML Code

!"# NULL 0 00 ^@ $%&'( 32 20 ) 64 40 * 96 60 $%&'( &nbsp;

$+, Start of Heading 1 01 ^A - 33 21 . 65 41 & 97 61 / &amp;

$01 Start of Text 2 02 ^B 2 34 22 &quot; 3 66 42 4 98 62 5 &lt;

601 End of Text 3 03 ^C 7 35 23 8 67 43 ' 99 63 9 &gt;

6+0 End of Transmission 4 04 ^D : 36 24 ; 68 44 < 100 64 = &copy;

6!> Enquiry 5 05 ^E ? 37 25 6 69 45 ( 101 65 @ &reg;

.8A Acknoledge 6 06 ^F / 38 26 &amp; B 70 46 C 102 66 D &sup1;

36# Bell 7 07 ^G E 39 27 F 71 47 G 103 67 H &sup2;

3$ Backspace 8 08 ^H I 40 28 , 72 48 J 104 68 K &sup3;

0.3 Horizontal Tab 9 09 ^I L 41 29 M 73 49 M 105 69 E &apos;

#B Line Feed 10 0A ^J N 42 2A O 74 4A P 106 6A 2 &quot;

Q0 Home 11 0B ^K R 43 2B A 75 4B S 107 6B T &frac14;BB Form Feed 12 0C ^L U 44 2C # 76 4C V 108 6C W &frac12;8X Carriage Return 13 0D ^M Y 45 2D Z 77 4D [ 109 6D \ &frac34;$+ Shift Out 14 0E ^N ] 46 2E ! 78 4E ^ 110 6E ! &pi;

$M Shift In 15 0F ^O _ 47 2F + 79 4F ` 111 6F a &trade;

;#6 Data Link Escape 16 10 ^P b 48 30 c 80 50 % 112 70 " &infin;

;8d Device Control 1 17 11 ^Q d 49 31 > 81 51 e 113 71 # &ne;

;8f Device Control 2 18 12 ^R f 50 32 X 82 52 g 114 72 $ &le;

;8h Device Control 3 19 13 ^S h 51 33 $ 83 53 i 115 73 % &ge;

;8j Device Control 4 20 14 ^T j 52 34 0 84 54 k 116 74 & &asymp;

!.A Negative Acknowledge 21 15 ^U l 53 35 " 85 55 m 117 75 ! &equiv;

$n! Syncronous Idle 22 16 ^V o 54 36 Q 86 56 p 118 76 ' &sum;

603 End of trans. Block 23 17 ^W q 55 37 r 87 57 s 119 77 t &bull;

8.! Cancel 24 18 ^X u 56 38 1 88 58 v 120 78 w &hellip;

6Z End of Medium 25 19 ^Y x 57 39 n 89 59 y 121 79 ( &Delta;

$"3 Substitute 26 1A ^Z z 58 3A { 90 5A | 122 7A " &larr;

6$8 Escape 27 1B ^[ } 59 3B ~ 91 5B � 123 7B # &uarr;

B$ Cursor Right (File Seperator) 28 1C ^\ 5 60 3C &lt; Ä 92 5C Å 124 7C $ &rarr;

F$ Cursor Left (Group Seperator) 29 1D ^] Ç 61 3D É 93 5D Ñ 125 7D % &darr;

X$ Cursor Up (Record Seperator) 30 1E ^^ 9 62 3E &gt; Ö 94 5E Ü 126 7E & &harr;

"$ Cursor Down (Unit Seperator) 31 1F ^_ á 63 3F à 95 5F ;6# 127 7F â &fnof;

HTML Codes use the #& with the decimal value followed by a semi colon. Example: &#64; for the @ symbol.

HTML Post Operation use the % sign and the hex value. Example: Space would be %20

To obtain codes 0-31, console Control Key is pressed while simultaneously pressing the Letter Key.

www.kellermansoftware.com Free quick reference sheets and .net components

char class[5]; allocates 6 cells

char class[5]={}; initializes all to \0

Two Things that Require Work

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

❖ Copying

‣For numbers and characters can write: var2=var1;

‣Does not work for strings ‣Need loop

26

#include <stdio.h> int main() { char word1[50], word2[50]; int i=0; printf("Word: "); scanf("%s", word1); for (i=0; word1[i]; i++) word2[i]=word1[i]; word2[i]='\0'; printf("Copy: %s\n", word2); return 0; }

copy.c

Later see a function

for this

Two Things that Require Work (2)

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

❖ Comparing

‣For numbers and characters can write: if(var2==var1)

‣Does not work for strings ‣Need loop

27

#include <stdio.h> #include <stdbool.h> int main() { char word1[50], word2[50]; int i=0; bool same=true; printf("First word: "); scanf("%s", word1); printf("Second word: "); scanf("%s", word2); do if (word2[i] != word1[i]) same = false; while (word1[i] && word2[i++]); printf("%s\n", same ? "same" : "different"); return 0; }

compare.c

Later see a function for

this too..

Backwards (characters)

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

❖ Read word and print it in reverse

28

#include <stdio.h> int main() { int i, j; char word[50];

printf("Word: "); scanf("%s", word);

for (i=0; word[i]; i++) ;

printf("Reverse: "); for (j=i-1; j>=0; j--) printf("%c", word[j]);

printf("\n"); return 0; } backwards_letters.c

❖ Introduction to Arrays

❖ Simple Examples

❖ Math Examples

❖ String Arrays

❖ Sorting

❖ Two-Dimensional ArraysLecture 6 ECE15: Introduction to Computer Programming Using the C Language 29

Outline

❖ Two variables: x and y ❖ Exchange their values

û

Swapping Two Numbers

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 30

x y

before 0 1x=y 1 1y=x 1 1

x y temp

before 0 1 ?temp=x 0 1 0

x=y 1 1 0y=temp 1 0 0

x y

before 0 1after 1 0

Attempt

x=y; y=x;

correct

temp=x; x=y; y=temp;

ü

before

after

❖ Can we exchange two numbers without an extra variable?

❖ Yes!

❖ Two variables:

❖ Swap their values

❖ But risky!

❖ floating-point arithmetic not always 100% accurate

Quiz

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 31

x ya ba+b ba+b ab a

x=x+yy=x-yx=x-y

Sorting

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language

❖ Arranging elements in ascending (or descending) order ❖ One of the most important computer operations ❖ Helps find: ‣Entries ‣Largest ‣Duplicates

❖ In past ~25% of computer time

32

Bubble Sort Illustration

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 33

43

21

5

43

21

5

43

21

5

43

21

5

43

21

5

43

21

5

43

21

5

43

21

5

43

21

5

43

21

5

43

21

5

✓ ✓ ✓ ✓ ✓ ✓

✓ ✓ ✓ ✓ ✓

• Assumes i-1 largest elements found and sorted at the end • Performs inner loop on elements 1, 2, …, n-(i-1) • Moves i’th largest element to location n-i+1

Outer and inner loops n-1 outer iterations

Outer iteration i (i=1… n-1)

Outer loop 2 3 41

Inne

r lo

op

1

2

3

4

Bubble Sort Program

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language

❖ n numbers: a0, a1, … an-1 ❖ Sort in increasing order ❖ move largest # to right ‣Compare a0 with a1

๏ if a0 > a1, exchange them

‣Compare a1 with a2

๏ if a1 > a2, exchange them

‣etc. till an is the largest ❖ move 2nd largest to 2nd from right ‣Exchange pairs as for largest

❖ Successively move next largest right ❖ Demo: Hungarian, Indian, Danish ❖ # comparisons

‣ (n-1) +(n-2)+…+1 = n(n-1)/2 ❖ Faster algor’s: n log n comparisons

34

#include <stdio.h> int main() { int number, i, j, temp; printf("Number of elements: "); scanf("%d", &number); int array[number]; for(i=0; i<number; i++) scanf("%d", &array[i]); for(i=0; i<number-1; i++) for (j=1; j<number-i; j++) if (array[j-1]>array[j]) { temp = array[j-1]; array[j-1] = array[j]; array[j] = temp; } for(i=0; i<number; i++) printf("%d ", array[i]); printf(“\n"); return 0; } sort.c

❖ Introduction to Arrays

❖ Simple Examples

❖ Math Examples

❖ String Arrays

❖ Sorting

❖ Two-Dimensional Arrays

Outline

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 35

int ar[][3]={1,0,2,3,9,7};

Stored consecutively row by row

Two-dimensional arrays

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 36

Array of 2 rows and 3 columnsint ar[2][3];

ar[i][j]; Element in row i, column j

1 0 23 9 7

ar[0][0]=1;

1 0 2 3 9 7

int ar[2][3]={{1,0,2},{3,9,7}};Initialization

int ar[][3]={{1,0,2},{3,9,7}};3 necessary

Addressing

0

0

1

1

2

ar[1][2]=7;

Row Column

Applications of 2 (and 3) dim arrays

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language

❖ Pictures ❖ Cars ❖ Planes ❖ Phones ❖ Video games

37

Matrix transposition

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language

❖ Matrix - two dimensional array of numbers

❖ M[i][j] - element at row i, column j ‣M[0][0]=1, M[1][2]=6

❖ Transposition - flip around diagonal ‣M[i][j] <---> M[j][i]

❖ Loop over i and j ‣Swap M[i][j] and M[j][i]

38

1 2 34 5 67 8 9

15

9

2

7

34

86

1 4 72 5 83 6 9

#include <stdio.h> #define SIZE 3 int main() { int ar[][SIZE] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int i, j, temp; printf("Matrix:\n"); for (i=0; i<SIZE; i++) for (j=0; j<SIZE; j++) printf("%d %s", ar[i][j], j==SIZE-1? "\n" : ""); for (i=1; i<SIZE; i++) for (j=0; j<i; j++) { temp = ar[i][j]; ar[i][j]=ar[j][i]; ar[j][i]=temp; }

printf("Transpose:\n"); for (i=0; i<SIZE; i++) for (j=0; j<SIZE; j++) printf("%d %s", ar[i][j], j==SIZE-1? "\n" : ""); return 0; }

Matrix Transposition - V. 1

Lecture 6 ECE15: Introduction to Computer Programming Using the C Language 39

int ar[][SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

Cleaner implementation with functions.

Next!

transpose1.c

❖ Introduction to Arrays

❖ Simple Examples

❖ Math Examples

❖ String Arrays

❖ Sorting

❖ Two-Dimensional ArraysLecture 6 ECE15: Introduction to Computer Programming Using the C Language 40

Outline