Arrays - Texas A&M University



Arrays and For Loops

Arrays

0 1 2 3 4 5 6 7 8 9 10 11 …

x …

array name element index

NOTICE:

max_index + 1 = size

index starts at 0 not 1!!

Holds ONLY ONE value per element!!

Homogeneous -- all of the elements have to be of the same type, e.g., int, float, char, etc.

Declaration using different datatypes

• arrays need a NAME and a size

o name

▪ one word, CAMELCASE

▪ sodaPrice

▪ soda_Price

o size

▪ greater than 0

▪ extra is fine, but not too much!!!

▪ User can determine size using a variable

• arrays will have a value in EACH ELEMENT automatically!!!

o used before in Computer

o called garbage!!!

o good to set value (below) to your choice of a default

type arrayname[size];

|Issues with naming!! |

|int sodePrice = 23; // “setSodePrice” this is an integer |

|double sodePrice[3]; // “setSodePrice” this is an double ARRAY |

| |

|// a variable CANNOT be named the same as an array!! |

|Declaration of Multiple datatype arrays |

|Double |double sodaPrice[3]; |

| | |

| |[0] [1] [2] |

| |sodaPrice |

|Integer |int seasonPts[13]; |

|Char |char alphabet[26]; |

| |Draw what the “alphabet” array would look like |

Placing/Updating values in an element

• AFTER YOU HAVE DELCARED THE ARRAY!!!

• Slightly different syntax depending on data type

• notice DATATYPE is NOT placed in front of assignment

• YOU CAN CHANGE A VALUE AFTERWARD!! AT ANY TIME!!!

arrayname[index] = value;

|Placing values in multiple datatype arrays |

|Double |Integer |Char |

|//… declared here!!! |//… declared here!!! |//… declared here!!! |

| | |// … |

|double sodaPrice[0] = .65; | | |

|// incorrect code |seasonPts[0] = 13; |alphabet[0] = ‘A’; |

| |seasonPts[1] = 14; |alphabet[1] = ‘B’; |

|sodaPrice[0] = .65; |seasonPts[2] = 8; |alphabet[2] = ‘C’; |

|sodaPrice[1] = .85; |seasonPts[3] = 25; |… |

|sodaPrice[2] = .75; |seasonPts[4] = 3; |alphabet[25] = ‘Z’; |

| |… | |

| |seasonPts[12] = 26; | |

1. Draw what “SeasonPts” array would literally look like (no code)

2. In the alphabet array, why do we stop at 25?? (Other than last letter)

3. I made a mistake in seasonPts, the 3rd game should be 18, how do I fix it?

Displaying an element in an array (the long way)

• Display by each and every individual element

o THERE IS NO WAY TO DISPLAY THE ENTIRE ARRAY IN ONE LINE!!!

o printf(“%d\n”, sodaPrice); // that will not display the entire array

• Display code is the SAME for all datatypes

o notice I use printf() to print each ELEMENT on a separate line

|Displaying values in multiple datatype arrays |

|Double |Integer |Char |

|//… | |// … |

| |same as ( | |

|printf(“%lf\n”, sodaPrice[0]); |but %d instead |printf(“%c\n”, alphabet[0]); |

|printf(“%lf\n”, sodaPrice[1]); | |printf(“%c\n”, alphabet[1]); |

|printf(“%lf\n”, sodaPrice[2]); | |printf(“%c\n”, alphabet[2]); |

| | |… |

| | |printf(“%c\n”, alphabet[26]); |

How many PrintLn statements would we need to display THE ENTIRE array of 150 elements??

Why MUST we place values in the array before we display them?

Using Repetition to display arrays

int data[10];

// values filled in here

To display our simple “data” array, we would have to display each line separately:

printf(“%d\n”, data[0]);

printf(“%d\n”, data[1]);

printf(“%d\n”, data[2]);

printf(“%d\n”, data[3]);

printf(“%d\n”, data[4]);



Introduction to the “For” Loop (non C99 mode)

• used for repetitious code, shortens typing and overall code

• used when you know EXACTLY when the loop should, or how many times the loop should run before it ends

• puts all three parts (testing, initialization, incrementing) in one line

declaration

for ( initialization; test; increment/decrement)

{

statements;

….

}

• The statements inside the {} are repeated until the condition of the test is met.

• ** Make sure { }’s are in Block Like structure!!!

• NONE of the three stages HAVE TO BE set, in order to work

|Follow the bouncing to ball to see a for loop at work |

| |

| |

|int i; |

| |

| |

|for(i = 0; i < 10; i++) |

|{ |

| |

|printf(“%d\n”, test[i]); |

|} |

| |

|= first round (1 – 4) |

|= second loop |

|= third loop |

|= fourth loop |

|…. |

Using Repetition to display arrays

• To display our simple “x” array, we would have to display each line separately:

• remember values have to be placed first before displaying!!!

|Displaying values into arrays using Loops |

|Non-loop |Loop |

| | |

|int test[10]; // 10 test scores |int test[10]; // 10 test scores |

| | |

|// after values are placed |// after values are placed |

| |int i; |

|printf(“%d\n”, test[0]); |for(int i = 0; i < sizeof(test)/ sizeof(*test); i++) |

|printf(“%d\n”, test[1]); |{ |

|printf(“%d\n”, test[2]); |printf(“%d\n”, test[i]); |

|printf(“%d\n”, test[3]); |} |

|printf(“%d\n”, test[4]); | |

|printf(“%d\n”, test[5]); | |

|… | |

|printf(“%d\n”, test[9]); | |

The sizeOf function

• “returns” the exact length (integer) of the array

• when creating arrays, there are features that come with it

• nice feature since you don’t have to remember!!! The computer will find out!!

• syntax

o sizeof(array_name)/ sizeof(*array_name)

• ONLY WORKS IN MAIN!! MUST PASS TO FUNCTIONS!!!

|Showing the Workings |

|in main() |in another function |

| |

|Examples of length in use |

|Double |int size = sizeof(sodaPrice)/ sizeof(*sodaPrice); |

| | |

| |What will size be? |

|Integer |for(i = 0; i < sizeof(seasonPts)/ sizeof(*seasonPts); i++) |

| | |

| |What will seasonPts.length be? |

|Char |if(sizeof(alphabet)/ sizeof(*alphabet)< 0) |

1. Create the loop to display the seasonPts values (Slip)

2. Create the loop to display the names values (Slip)

3. Now create a for loop to display the array “d” as such: (SLIP)

int d [30];

d[0] = 11;

d[1] = 12;

d[2] = 13;

d[3] = 14;

d[4] = 15;

d[5] = 16;

d[6] = 17;

d[7] = 18;

d[8] = 19;

d[9] = 20;

… // to d[29]

|11|12|13|14|15|… | Yes, all on ONE line, yes | at the front and | at the end.

Placing values into an array using loops

• we use loops since

o i++ incrementation

o can repeat code

|Placing values into arrays using Loops |

|Non-loop |Loop Example 1 |

| | |

|int test[10]; // 10 test scores |int test[10]; // 10 test scores |

| |printf(“Please enter values”); |

|scanf(“%d”, test[0] );// user types in any value | |

|scanf(“%d”, test[1] );// user types in any value |int i; |

|scanf(“%d”, test[2] );// user types in any value |for(i = 0; i < sizeof(test)/sizeof(*test); i++) |

|scanf(“%d”, test[3] );// user types in any value |{ |

|scanf(“%d”, test[4] );// user types in any value |printf(“Enter next value”); |

|scanf(“%d”, test[5] );// user types in any value |scanf(“%d”, &test[i] );// |

|scanf(“%d”, test[6] );// user types in any value |} |

|… | |

|Loop Example 2 |

| |

|int score[10]; |

|double average[10]; |

|char letter[10]; |

|int minutes[10]; |

| |

|int i; |

|for(i = 0; i < sizeof(score)/sizeof(*score); i++) |

|{ |

|scanf(“%d %lf, %c, %d”, &score[i] , &average[i] , &letter[i] , &minutes[i]);// |

|} |

Multiple For Loops (non C99 mode)

• using “i” is always convenient until you have many for loops

o depends on the position on the “i” (initialize), covered below

• but you will need to reset after each loop!!

|Using the same “i” for many loops |

|[pic] |

Error Checking

- checks subscripts

o You have to remember the size and name of the array

o Common Errors

▪ ex.

0 1 2 3 4 5 6 7 8 9

| |

|#include |

| |

|void display_scores1(int * data, int size); |

| |

|void main() |

|{ |

|int testscores[5]; |

|int testSize = 5; // or use sizeof |

| |

|testscores[0] = 100; |

|testscores[1] = 23; |

|testscores[2] = 78; |

|testscores[3] = 67; |

|testscores[4] = 87; |

| |

|// passing the array to a function |

|display_scores1(testscores, testSize); |

|} |

| |

|void display_scores1(int * data, int size) |

|{ |

|int i; |

|for(i = 0; i < size; i++) |

|{ |

|printf(“%d\n”, data[i]); |

|} |

|} |

Real Life Application – Read the Code

Using the array below, what is the code doing?? Determine EACH value for tests[i]

int tests[10];

tests[0] = 67;

tests[1] = 12;

tests[2] = 89;

tests[3] = 98;

tests[4] = 100;

tests[5] = 92;

tests[6] = 94;

tests[7] = 54;

tests[8] = 51;

tests[9] = 78;

|test[i] |value |

|0 = | |

|1 = | |

|2 = | |

|3 = | |

|4 = | |

|5 = | |

|6 = | |

|7 = | |

|8 = | |

|9 = | |

int m = 99999;

int i;

for(i = 0; i < 10; i++)

{

if(tests[i] < m) // reset m

{ m = tests[i]; }

} // Again, what is this function doing overall??

|M |

| |

Common Functions associated with Arrays

• When programming for many years, you will notice some functions that are used repeatedly for data inside of arrays

• that data can be anything of course

|Common Array Functions |

|Display |

|void display_array(char * array, int size) |

|{ |

|for(int i = 0; i < size; i++) { printf(“%c”, array[i]); } |

|} |

|Average data in an array function |

| |

|double find_average(int * array, int size) |

|{ |

|int sum = 0; |

|for(int i = 0; i < size; i++) |

|{ sum += array[i]; } // running total |

|return sum/size; |

|} |

|Frequency |

| |

|int frequency(int * data, int size, int numberToFind) |

|{ |

|// values already placed into array |

| |

|int frequency = 0, i; |

|for(i = 0; i < size; i++) |

|{ |

|if( data[i] = = numberToFind) // so we see how many “4”s are in the array |

|{ frequency++; } |

|} |

| |

|printf(“%d\n”, frequency); |

|return frequency; |

|} |

Searching through an array

• most simplest search through an array, is using the linear search

o starts from 0, and continues until it finds the target, OR ends at the end of the array

o you will learn more efficient searches later

• use a loop to

o iterate through the array since indices are integers and increment by 1 (i++)

o loop also checks to see if new index contains the target

o single loop ( array

|Array example |

|int data[10] = {1,1,2,3,4,2,4,6,7,8}; |

|int frequency = 0, i; |

|for(i = 0; i < sizeof(data)/sizeof(*data); i++) // this loop in MAIN()!! Notice sizeof |

|{ |

|if( data[i] = = 4) // so we see how many “4”s are in the array |

|{ frequency++; } |

|} |

| |

|printf(“%d\n”, frequency); |

|Searching for an Integer |

|IMPORTANT!! EACH spot in the ARRAY HAS TO BE SET/INITIALIZED!!! |

|int i; |

|for(i = 0; i < sizeof(roster)/sizeof(*roster); i++) // 100 is the size of THIS example |

|{ |

|if(target == roster[i]) // compares STRING target |

|{ |

|printf(“Found the target!!”); |

|printf(“It was at index %d in the array”, i); |

|// returns index found |

|} |

|else |

|{} // didn’t find it yet |

|} |

Parallel Arrays

• 2 or more separate arrays that are related by INDEX value AND data

setPrice[0] = getCost[0] * getMarkup[0];

totalPrice[i] = (.05 * price[i]) + price[i];

fullName[i] = fname[i] + “ “ + lname[i]; // For Strings

| |

|Employee |

| |

|Pay |

| |

|[0] |

|Lupoli, Shawn |

| |

|[0] |

|1,000,000 |

| |

|[1] |

|Martin, William |

| |

|[1] |

|50 |

| |

|[2] |

|Dill, Tina |

| |

|[2] |

|300,000 |

| |

|[3] |

|Akman, Sema |

| |

|[3] |

|2,000,000 |

| |

|[4] |

|Dudds, Kevin |

| |

|[4] |

|100,000 |

| |

|[5] |

|Harman, Christie |

| |

|[5] |

|275,000 |

| |

|[6] |

|Cornish, Mick |

| |

|[6] |

|-70,000 |

| |

|… |

|… |

| |

|… |

|… |

| |

| |

|Here are parallel arrays that show how much each employee is paid. |

|How much is Sema getting paid?? |

• Adding up arrays

setProfit[0] = getCost[0] * getMarkup[0];

totalPrice[i] = (.05 * price[i]) + price[i];

| |setProfit |getCost |getMarkup |

|[0] |??? |$10 |.10 |

|[1] | | | |

|[2] | | | |

|[3] | | | |

|… |… |… |… |

Other Applications w/ For Loops – “running total”

Remember the order in which an expression such as:

x = x + 1; ( ( (

x(new) = x(old) + 1

void main( )

{

int x = 0;

int y = 10;

( ( (

x = x + y; 10 = 0 + 10

// What will x =?? 10

This is EXTREMELY useful in Totaling if we have:

|Example of totaling |

|void main( ) | |

|{ | |

|int answer = 0, i; |answernew |

| |= |

|for (i = 0; i < 10; i++) |answerold + i |

|{ answer = answer + i; } | |

| |1 |

|printf(“%d\n”, answer); |0 |

|} |= |

| |0 + 0 |

| | |

| |2 |

| |1 |

| |= |

| |0 + 1 |

| | |

| |3 |

| |3 |

| |= |

| |1 + 2 |

| | |

| |4 |

| |6 |

| |= |

| |3 + 3 |

| | |

| |5 |

| |10 |

| |= |

| |6 + 4 |

| | |

| |6 |

| |… |

| |= |

| |… |

| | |

| |7 |

| |… |

| |= |

| |… |

| | |

| |8 |

| | |

| | |

| | |

| | |

| |9 |

| | |

| | |

| | |

| | |

| |10 |

| |45 |

| | |

| |36 + 9 |

| | |

| | |

| |total |

| |= |

| |45 |

| | |

Notice that x will keep a running count, or a “total” even though it is being used many many times.

Exercises in Totaling

|Exercise #1 |

|void main( ) | |

|{ | |

|int answer = 0, i; |answernew |

| |= |

|for (i = 10; i > 0; i--) |answerold + i |

|{ answer = answer + i; } | |

| |1 |

|printf(“%d\n”, answer); | |

|} |= |

| | |

| | |

| |2 |

| | |

| |= |

| | |

| | |

| |3 |

| | |

| |= |

| | |

| | |

| |4 |

| | |

| |= |

| | |

| | |

| |5 |

| | |

| |= |

| | |

| | |

| |6 |

| | |

| |= |

| | |

| | |

| |7 |

| | |

| |= |

| | |

| | |

| |8 |

| | |

| | |

| | |

| | |

| |9 |

| | |

| | |

| | |

| | |

| |10 |

| | |

| | |

| | |

| | |

| | |

| |total |

| |= |

| | |

| | |

|Exercise #2 |

|void main( ) | |

|{ | |

|int answer = 0, i; |answernew |

| |= |

|for (i = 0; i < 10; i++) |answerold + 10 |

|{ answer = answer + 10; } | |

| |1 |

|printf(“%d\n”, answer); | |

|} |= |

| | |

| | |

| |2 |

| | |

| |= |

| | |

| | |

| |3 |

| | |

| |= |

| | |

| | |

| |4 |

| | |

| |= |

| | |

| | |

| |5 |

| | |

| |= |

| | |

| | |

| |6 |

| | |

| |= |

| | |

| | |

| |7 |

| | |

| |= |

| | |

| | |

| |8 |

| | |

| | |

| | |

| | |

| |9 |

| | |

| | |

| | |

| | |

| |10 |

| | |

| | |

| | |

| | |

| | |

| |total |

| |= |

| | |

| | |

Placing Random value in Arrays

• need a random generator

o #include

o #include

• order

o use “srand” function to start random number generation

o use “rand” function to get next random value

o then place value into array

• use % to get a range of values

|Placing Random value in Arrays Example |

|Getting unarranged int values |

|int setArray[10]; |

|srand(time(0)); // seed (aka initialize or start) generator with current time, to make sure random |

| |

|int i; |

|for (i=0; i < 10 ; i++) |

|{ |

|r = rand ( ); // generates a random number from 0 to max int (aka 0 – 32765) |

|printf(“%d\n”, r); |

|setArray[i] = r; |

|} |

|Ranged values (0 – 25) |

|int setArray[10]; |

|srand(time(0)); // seed (aka initialize or start) generator with current time, to make sure random |

| |

|int i; |

|for (i=0; i < 10; i++) |

|{ |

|int r = rand ( )%26; // generates a random number from 0 to 25 |

|printf(“%d\n”, r); |

|setArray[i] = r; |

|} |

|double values |

|Same setup |

| |

|int r = (double)rand() / RAND_MAX; // generates a random number from 0 to 25 |

break/continue/return

only to be used inside a for or while loop (return can be used ANYWHERE)

- break ( used to break out of the loop and go to the next statement

o if inside of a double for/while loop, will “break” out of the innermost loop

- continue ( skips rest of statements in loop, increments, then goes to the next pass of the loop

- return ( will break out of the entire FUNCTION

o same as break, but it will return some value ( true/false/void or a value)

for (;;) { statement;} ( will only terminate with a break; or return;

Using a “Loop Tree”

|Loop Tree |

|i |Outcome |

|0 | |

|1 | |

|2 | |

|3 | |

|4 | |

|5 | |

|6 | |

|7 | |

|8 | |

|9 | |

void main()

{

for(int i = 0; i < 10; i++) // in C99 mode

{

if( (i > 3) && ( i < 7)) { printf(“Greater than 3\n”); continue; }

if (i < 5) { printf(“Less than 5\n”); }

if( i > 6) { printf(“See ya \n”); break; }

}

}

|Loop Tree Example for #1 |

|i |Outcome |

|0 |Less than 5 |

|1 |Less than 5 |

|2 |Less than 5 |

|3 |Less than 5 |

|4 |Greater than 3 |

|5 |Greater than 3 |

|6 |Greater than 3 |

|7 |See ya |

|8 |NOT DONE!!! |

|9 |NOT DONE!!! |

What will both of these examples below display?? (Values set already in for loop) Please use a decision table!!

|#1 |for(int i = 0; i < 10; i++) // in C99 mode |

| |{ |

| |if(i < 6) |

| |{ printf(“Mr. Lupoli Rocks!!\n”); continue; } |

| |if(i 8) |

| |{ printf( “Programming\n”); } |

| |} |

|#2 |for(int i = 0; i < 10; i++)// in C99 mode |

| |{ |

| |if(i 8) |

| |{ printf( “hello\n”); } |

| |if(i < 6) |

| |{ printf(“Mr. Lupoli Rocks!!\n”); } |

| |} |

|#3 |for (int i = 0; i < 10; i++) // in C99 mode |

| |{ |

| |if (i < 8) |

| |{ printf(“A\n”);} |

| |if ((i > 4) && (i < 8)) |

| |{ printf(“B\n”); } |

| |if (i < 10) |

| |{ printf(“C\n”); } |

| |} |

|#4 |for (int i = 0; i < 10; i++) |

| |{ |

| |if (i < 8) |

| |{ printf(“A\n”); continue;} |

| |if ((i > 4) && (i < 8)) |

| |{ printf(“B\n”); } |

| |if (i < 10) |

| |{ printf(“C\n”); } |

| |} |

|#5 |for (int i = 0; i < 10; i++) |

| |{ |

| |if (i < 8) |

| |{ printf(“A\n”); } |

| |if ((i > 4) && (i < 8)) |

| |{ printf(“B\n”); break; } |

| |if (i < 10) |

| |{ printf(“C\n”); } |

| |} |

FYI – Compiling in C99 mode

• for this set up notes, it changes the pattern of the for loop

• for loops can declare initializer inside the ( )

|How to compile with GCC in mode C99 |

|[pic] |

Multiple For Loops

• using “i” is always convenient until you have many for loops

o depends on the position on the “i” (initialize), covered below

• you CAN have multiple loops use the SAME variable!!

|Using the same “i” for many loops |

|[pic] |

The importance of the initialization’s position

• some books/profs may have the initialization variable in a different spot

• this is why this can be crucial

o initialization variable declared INSIDE a loop is ONLY alive when the loop is running (scope)

o initialization variable declared OUTSIDE a loop is alive even after the loop HAS STOPPED running

|Normal For Loop |Dangling For Loop |

|for(i = 0; i < 10; i++) |int i; // or int i = 0; |

|{ printf(“Mr. L is cool”); } |for(i = 0; i < 10; i++) |

| |{ printf(“Mr. L is not cool”); } |

|printf(“%d\n”, i); // gives an error | |

|// but you COULD reuse “i” |printf(“%d\n”, i); // outputs 10 |

-----------------------

11

13

10

8

7

5

4

2

1

12

9

6

3

1

5

8

11

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download