### Create a StudySoup account

#### Be part of our community, it's free to join!

Already have a StudySoup account? Login here

# ENEE 140: Arrays continue ENEE140

Montgomery College

GPA 4.0

### View Full Document

## About this Document

## 29

## 1

## Popular in Introduction to programming concepts for engineers

## Popular in Electrical Engineering

This 11 page Class Notes was uploaded by Nhi Phan on Wednesday April 6, 2016. The Class Notes belongs to ENEE140 at Montgomery College taught by Dr.Lanxiang in Spring 2016. Since its upload, it has received 29 views. For similar materials see Introduction to programming concepts for engineers in Electrical Engineering at Montgomery College.

## Reviews for ENEE 140: Arrays continue

### What is Karma?

#### Karma is the currency of StudySoup.

#### You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 04/06/16

Lecture 7: Arrays An array variable is a set of variables share a common name and type all linked together int x[30]; /* 30 integers */ elements: x[0], x[1], ..., x[29] name of array is x array size: total 30 elements in array ‘x’ it has to be an integer with known value (to determine the memory needed to store the array) each element is int type starts from 0 Array Elements #include <stdio.h> int main( void ) { int i, n[10]; /* n is an array of 10 integers */ for( i = 0; i < 10; i ++ ) { /*loop 10 times*/ n[i]= 2; /* set all elements to 2 */ printf( "n[%d] = %d\n" , i, n[i] ); /*display value of n[i] */ } n[1] = 5; n[3] = n[1] + n[0]; printf( "Enter an integer value: " ); scanf( "%d", &n[5] ); printf( "Element 3 is %d\n", n[3]); /*display element 3 */ printf( "The sixth element is %d\n", n[5]); /*display 6th element*/ return 0; } Example 1: Find the minimum #include <stdio.h> #define SIZE 10 int main( void ) { int i, min, x[SIZE]; for( i = 0; i < SIZE; i ++ ) { /*loop 10 times*/ printf("Enter an integer: "); scanf( "%d", &x[i]); /* read each element */ } min = x[0]; for( i = 1; i < SIZE; i ++ ) { if (x[i] < min) min = x[i]; } printf( "The minimum is %d\n", min); return 0; } Initializing arrays type name[n] = {value0, value1, ... , value(n-1)}; double height[3] = {5.5, 6.3, 5.8}; int x[] = {1, 2, 3, 4, 5}; If all the initial values are given, the number of elements can be omitted. Compiler will count the number of elements and set size of array ‘x’ to 5 Three elements of array ‘height’ are initialized to 5.5, 6.3, and 5.8. Each element is double type. int y[5] = {1, 2}; First two elements y[0] and y[1] are initialized to 1 and 2. Remaining elements [2]-[4] are initialized to zero implicitly. Example 2 Design: --- How does the program read in five floating point numbers? One at time or all five at once? --- How to store each number in an array? --- How to add all the numbers together? Write a program to read in five floating point numbers, store them in an array and display the sum of all the numbers. Example 3 /*This program read in 5 floating point numbers, store them in an array and print the sum */ #include <stdio.h> int main( void ) { int i; double n[5], sum = 0; for( i = 0; i < 5; i ++ ) { printf( "Enter Number %d : ", i ); scanf( "%lf", &n[ i ] ); sum = sum + n[i]; /* add each number to sum */ } printf("Sum is %g\n", sum); return 0; } Can you modify the program such that the program will work on any set of numbers (not just five)? Limitations Can’t assign or compare arrays directly int x[10] = {1}; int y[10]; Ok. Assign each element of one array to the element of another array for (i=0; i<10; i++) y[i] = x[i]; Illegal! cannot copy one array to another array Illegal! cannot compare arrays y = x; if (x == y) statement; Passing Arrays to Functions When an array is passed to a function, what is actually passed is the address of the first element of the array. Only the name of the array needs to be specified in the called function. The called function will modify the element values in the original array directly. #include <stdio.h> void squareArray1 (int x[ ], int n) { int i; for (i = 0; i< n; i++) { x[i] = x[i] * x[i]; } } int main (void) { int i; int x[5] = { 1, 2, 3, 4, 5}; squareArray1 (x, 5); …… } Example 4 #include <stdio.h> void squareArray2(int x[], int y[], int n) { int i; for (i = 0; i< n; i++) { y[i] = x[i] * x[i]; } } void display (int x[], int n) { int i; for (i = 0; i< n; i++) { printf("x[%d] = %d\n", i, x[i]); } } int main (void) { int y[5], x[5] = { 1, 2, 3, 4, 5}; squareArray2 (x, y, 5); display (x, 5); display (y, 5); return 0; } input array output array Bubble sort algorithm Sorting: Rearrange all the elements in an array so that they appear in increasing (or decreasing) order Used in many applications: such as database design Bubble sort algorithm: Sort array ‘x’ with n elements in increasing order Elements: x[0], x[1], x[2], ...., x[n-2], x[n-1] 1. Compare the first element x[0] with each successive element x[j] from j=1 to n-1. If x[0]>x[j], swap values of x[0] and x[j] 2. Compare the second element x[1] with each successive element x[j] from j=2 to n-1. If x[1]>x[j], swap values of x[1] and x[j] 3. Continue the process for elements x[2], x[3], ... , x[n-2]. Each is compared with its successive elements. Example 4: bubble sort void bubble_sort( int x[ ] , int n ) { int i, j, temp; for( i = 0; i < n-1 ; i++ ) { for( j = i + 1; j < n ; j++ ) { if( x[i] > x[j] ) { temp = x[i] ; x[i] = x[j] ; x[j] = temp ; }}}} Function to sort an array of ‘n’ integers in increasing order function bubble_sort() has two arguments: • array x[ ] - int type • variable n - number of elements of array x, int type array as input argument Example 5 #include <stdio.h> /* please copy and paste the bubble sort function here */ int main( void ) { int i ; int num[ ] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; const int n = 10; bubble_sort( num, n ); /* sort the array */ for( i = 0; i < n; i ++ ){ /* display the sorted array */ printf("%d ", num[i]); } printf("\n"); return 0; } result: 0 1 2 3 4 5 6 7 8 9 pass array to a function: only use array name Example 6: Using bubble sort algorithm Write a program to read an array and calculate the median of the array. median_array(): 1. call bubble_sort() to sort the array 2. the median is the middle element of sorted array: -- If n is odd: x[n/2] -- If n is even: (x[(n-1)/2] + x[n/2])/2 /*Calculate the median of the array*/ double median_array (double x[ ], int n) { bubble_sort(x, n); /*sort the array*/ return ((x[(n-1)/2]+ x[n/2])/2); /*return the median value*/ } #include <stdio.h> /* insert bubble_sort function here */ /* insert median_array function here */ int main( void ) { double x[100], xmedian; int i, n; printf("Number of elements: "); scanf("%d", &n); for (i=0; i<n; i++) { printf( "Enter value of x[%d]: ", i); scanf( "%lf", &x[i]); } xmedian = median_array(x, n); printf("Median Value = %g\n", xmedian); return 0; } Linear search Search all the elements of an array to see if it contains a given data Compare the value of each element with the given value. If a match is found, return the index of that element. Otherwise, return -1. int linear_search ( int x[], int n, int key ) { int i; for (i=0; i<n; i++) { if (x[i]== key) return i; } return (-1); } For example: int x[]={10, 2, 4, 4, 6}, n=5; If key=4, linear_search() will return 2 If key=1, linear_search() will return -1 given data Example 6: linear search #include <stdio.h> /* put linear search function here */ int main( void ) { int data[9] = {1,4,9,11,13,19,23,26,29}; int index, key, n = 9; printf("Enter key value: "); scanf("%d", &key); //get the key index = linear_search(data, n, key); if (index != -1) printf("Key exists at element [%d]\n", index); else printf("Search doesn’t find a match\n"); return 0; } Search an sorted array to see if it contains a given value ‘key’ Compare the middle element of the array with ‘key’. Eliminate half of the elements from further consideration based on the following rule: If middle < key, keep the upper half of the elements. If middle > key, keep the lower half of the elements. If equal, a match is found, stop searching. Repeat the comparison and cutting the range by half until a match is found or only no element remains in the range. Binary search Compare to linear search: For sorted array, binary search is more efficient For unsorted array, if it is small, linear search is better; if it is big, binary search is better. Binary search algorithm 1. Array ‘data’ has n elements: data[0] to data[n-1], set lower=0, upper=n-1 2. Begin while (lower<=upper) middle (lower + upper)/2 If key< data[middle], upper middle-1 If key> data[middle], lower middle+1 If key= data[middle], return middle End while 3. No match is found, return -1 int data[10]={1, 3, 5, 7, 8, 11, 12, 14, 15, 20} lower=0, upper=9, middle=4, data[4]=8 key=11 11, 12, 14, 15, 20 lower=5, upper=9, middle=7, data[7]=14 11, 12 lower=5, upper=6, middle=5, data[5]=11 20 Example 7: binary searching int binary_search( int data[ ], int num, int key ) { int lower = 0, upper = num - 1, mid; while( lower <= upper ) { mid = (lower + upper) / 2; /* middle element */ if( key < data[mid]) upper = mid - 1; else if( key > data[mid]) lower = mid + 1; else /* a match is found */ return mid; } return (-1); /* data not found */ } 6 21 #include <stdio.h> /* Binary search function is defined here */ int main( void ) { int data[9] = {1,4,9,11,13,19,23,26,29}; int index, key, n = 9; printf("Enter key value: "); scanf("%d", &key); index = binary_search(data, n, key); if (index != -1) printf("Key exists at element [%d]\n", index); else printf("Data does no

### BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.

### You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

## Why people love StudySoup

#### "There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

#### "I bought an awesome study guide, which helped me get an A in my Math 34B class this quarter!"

#### "I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

#### "Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

### Refund Policy

#### STUDYSOUP CANCELLATION POLICY

All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email support@studysoup.com

#### STUDYSOUP REFUND POLICY

StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here: support@studysoup.com

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to support@studysoup.com

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.