Chapter 7

Introduction to Programming for Engineers

  • Lecture 7 focuses on one-dimensional arrays.

    • Instructor: Dr. Abeer Badawi

    • Additional Lectures by: Dr. Khalid Elgazzar

Course Outline

  • Arrays

  • Statistical Measurements

  • Sorting and Search Algorithms

  • Character Strings

  • The String Class

  • The Vector Class

Learning Objectives

  • Develop solutions in C++ using:

    • One-dimensional arrays and vectors

    • Programmer-defined modules for statistical analysis

    • Functions for sorting and searching data

    • Probability functions

    • Character strings and string objects

    • Standard library functions (cstring, string) and custom header files

Understanding Arrays

  • Definition: An array is a data structure that stores a contiguous block of data.

    • All elements in an array are of the same type.

    • Access elements using an array name and an offset (index), starting at 0.

Example Syntax
  • Declaration Syntax: dataextunderscoretypeextidentifier[arrayextunderscoresize]data extunderscore type ext{ identifier[ array extunderscore size ] }

    • Example:

    • intdata[5]int data[5]

    • charvowels[5]=′a′,′e′,′i′,′o′,′u′char vowels[5] = {'a', 'e', 'i', 'o', 'u'}

    • doublet[100]=0.0double t[100] = {0.0}

Array Characteristics

  • Single Type Holding: All elements must be of the same type.

  • Memory Allocation: Arrays allocate memory for a fixed number of values; size declarators must be a positive integer constant.

    • Example:

    • constintSIZE=7;const int SIZE = 7;

    • stringWeekDays[SIZE];string WeekDays[SIZE];

Initializing Arrays
  • Initialization Syntax combines with declaration:

    • Example:

    • charvowels[5]=′a′,′e′,′i′,′o′,′u′;char vowels[5] = {'a', 'e', 'i', 'o', 'u'};

    • boolansKey[]=true,false,true;bool ansKey[] = {true, false, true};

    • stringword[]="Hello";string word[] = "Hello";

Accessing Array Elements

  • General format to access:
    arrayextunderscoreidentifier[offset]array extunderscore identifier[offset]

  • Ex:

    • for(inti=0;i<10;++i)m[i]=double(i)+0.5;for (int i=0; i<10; ++i) { m[i] = double(i) + 0.5; }

Element Modification
  • Example of accessing and modifying:

    • values[4]=17.7;values[4] = 17.7;

Bugs to Avoid

  • Array Bounds: C++ does not enforce bounds checking on arrays; this can lead to segmentation faults or unpredictable behavior.

Functions and Arrays

  • When passing arrays, the reference to the starting address (first element) is passed without size information.

Problem-Solving Techniques

  • Filling an Array: Example to initialize with zeros
    for(inti=0;i<sizeof(values)/sizeof(values[0]);i++)values[i]=0;for (int i = 0; i < sizeof(values)/sizeof(values[0]); i++) { values[i] = 0; }

Copying Arrays
  • Using a loop to copy arrays:

    • Example:
      for(inti=0;i<5;i++)squaresB[i]=squaresA[i];for (int i = 0; i < 5; i++) { squaresB[i] = squaresA[i]; }

Finding Maximum and Minimum in Arrays
  • To find the largest:
    doublelargest=values[0];double largest = values[0];
    for(inti=1;i<size;i++)if(values[i]>largest)largest=values[i];for (int i = 1; i < size; i++) { if (values[i] > largest) { largest = values[i]; } }

Arrays in Functions

  • Arrays cannot be returned directly but can be passed to define behavior.

  • Example of calculating mean:
    doubleMean(constdoublea[],intsize)<br>doublesum=0;<br>for(inti=0;i<size;++i)sum+=a[i];<br>returnsum/size;<br>double Mean(const double a[], int size) { <br>double sum = 0; <br>for (int i = 0; i < size; ++i) { sum += a[i]; } <br>return sum/size; <br>}

Sorting Algorithms

  • Selection Sort:

    1. Find the smallest item from the unsorted part and swap it with the first unsorted item.

    2. Repeat for the next unsorted elements until sorted.

Example of Selection Sort Implementation

voidsort(doublex[],intn)<br>for(intk=0;k<n−1;++k)<br>intm=k;<br>for(intj=k+1;j<n;++j)<br>if(x[j]<x[m])m=j;<br><br>doublehold=x[m];x[m]=x[k];x[k]=hold;<br><br>void sort(double x[], int n) { <br>for (int k=0; k<n-1; ++k) { <br>int m = k; <br>for (int j=k+1; j<n; ++j) { <br>if (x[j] < x[m]) m = j; <br>} <br>double hold = x[m]; x[m] = x[k]; x[k] = hold; <br>} <br>}

Search Algorithms

  • Unordered datasets can be searched sequentially (Simple Search), and ordered datasets may use Sequential or Binary Search for efficiency.

Example of Binary Search

intbSearch(constintlist[],intn,intvalue)<br>inttop=0;<br>intbottom=n−1;<br>intmid;<br>while(top<=bottom)mid=(top+bottom)/2;if(list[mid]==value)returnmid;elseif(list[mid]>value)bottom=mid−1;<br>elsetop=mid+1;<br><br>return−1;<br>int bSearch(const int list[], int n, int value) { <br>int top = 0; <br>int bottom = n - 1; <br>int mid; <br>while (top <= bottom) { mid = (top + bottom) / 2; if (list[mid] == value) return mid; else if (list[mid] > value) bottom = mid - 1; <br>else top = mid + 1; <br>} <br>return -1; <br>}

Character Strings and String Class

  • C-style Strings: Are arrays of characters ended with a null character.

  • String Class: Dynamically sized and has many operators and methods including:

    • Size and empty checks: size(), empty().

    • Accessing substrings: substr(int start, int len).

Vectors

  • Definition: A vector can grow dynamically, unlike arrays.

  • Manipulation: Use push_back() to add or pop_back() to remove elements.

Example of Vector Usage

vectornumbers;<br>numbers.push<em>back(10);numbers.pop</em>back();<br>cout<<"Size:"<<numbers.size();vector numbers; <br>numbers.push<em>back(10); numbers.pop</em>back(); <br>cout << "Size: " << numbers.size();

Passing Vectors to Functions

  • Vectors passed by reference can be modified inside functions; otherwise, they are passed by value.

Conclusion

  • One-dimensional arrays and vectors are fundamental data structures in C++ used for numerous programming tasks, including sorting, searching, and statistical analysis. Understanding their mechanics is crucial for effective programming in engineering applications.













More detailed version

Introduction to Programming for Engineers

Lecture 7 focuses on one-dimensional arrays, integral components in programming that allow for efficient data manipulation and storage.
Instructor: Dr. Abeer Badawi
Additional Lectures by: Dr. Khalid Elgazzar

Course Outline
  1. Arrays

    • Definition and characteristics

    • Syntax and declarations

    • Initialization, modification, and accessing elements

    • Functions that utilize arrays

  2. Statistical Measurements

    • Mean, median, mode calculations using arrays

  3. Sorting and Search Algorithms

    • Detailed methods for sorting (Selection, Bubble, Insertion)

    • Efficient searching techniques (Linear and Binary Search)

  4. Character Strings

    • The distinction between C-style strings and the String class in C++

  5. The String Class

    • Operators and methods available in the String class

    • Memory management of string objects

  6. The Vector Class

    • Dynamic array behavior and manipulation in vectors

    • Memory and performance considerations

Learning Objectives
  • Develop solutions in C++ using:

    • One-dimensional arrays and vectors

    • Programmer-defined modules for statistical analysis

    • Functions for sorting and searching data

    • Probability functions

    • Character strings and string objects

    • Standard library functions (cstring, string) and custom header files

Understanding Arrays
  • Definition: An array is a data structure that stores a contiguous block of data. All elements in an array must be of the same type to ensure data consistency.

  • Access: Elements are accessed using an array name and an offset (index), starting from 0, allowing random access to any element in constant time.

Example Syntax
  • Declaration Syntax:
    dataextunderscoretypeextidentifier[arrayextunderscoresize]data extunderscore type ext{ identifier[ array extunderscore size ] }
    Example:
    intdata[5];int data[5];
    charvowels[5]=′a′,′e′,′i′,′o′,′u′;char vowels[5] = {'a', 'e', 'i', 'o', 'u'};
    doublet[100]=0.0;double t[100] = {0.0};

Array Characteristics
  1. Single Type Holding: All elements must be of the same type, enforcing type safety.

  2. Memory Allocation: Arrays allocate memory for a fixed number of values. The size declarators must be a positive integer constant.
    Example:
    constintSIZE=7;const int SIZE = 7;
    stringWeekDays[SIZE];string WeekDays[SIZE];

Initializing Arrays
  • Syntax: Initialization can occur at the time of declaration, ensuring elements are assigned initial values.
    Example:
    charvowels[5]=′a′,′e′,′i′,′o′,′u′;char vowels[5] = {'a', 'e', 'i', 'o', 'u'};
    boolansKey[]=true,false,true;bool ansKey[] = {true, false, true};
    stringword[]="Hello";string word[] = "Hello";

Accessing Array Elements
  • General format to access array elements:
    arrayextunderscoreidentifier[offset]array extunderscore identifier[offset]
    Example:
    for(inti=0;i<10;++i)m[i]=double(i)+0.5;for (int i=0; i<10; ++i) { m[i] = double(i) + 0.5; }

Element Modification
  • Modifying array elements can be done directly using their index:
    Example:
    values[4]=17.7;values[4] = 17.7;

Bugs to Avoid
  • Array Bounds: C++ does not enforce bounds checking on arrays, leading to segmentation faults or unpredictable behavior if out-of-bound indices are accessed.

Functions and Arrays
  • When passing arrays to functions, a reference to the starting address (first element) is passed, without size information. This affects how arrays are handled within functions.

Problem-Solving Techniques
  1. Filling an Array: Initialize an array with zeros efficiently.
    Example:
    for(inti=0;i<sizeof(values)/sizeof(values[0]);i++)values[i]=0;for (int i = 0; i < sizeof(values)/sizeof(values[0]); i++) { values[i] = 0; }

  2. Copying Arrays: Arrays can be copied using loops, maintaining data integrity.
    Example:
    for(inti=0;i<5;i++)squaresB[i]=squaresA[i];for (int i = 0; i < 5; i++) { squaresB[i] = squaresA[i]; }

  3. Finding Maximum and Minimum in Arrays: Find the largest/smallest element via iteration, ensuring efficiency.
    Example:
    doublelargest=values[0];double largest = values[0];
    for(inti=1;i<size;i++)if(values[i]>largest)largest=values[i];for (int i = 1; i < size; i++) { if (values[i] > largest) { largest = values[i]; } }

Arrays in Functions
  • Arrays are not directly returned but can be passed to functions to define behavior.
    Example of Calculating Mean:
    doubleMean(constdoublea[],intsize)<br>doublesum=0;<br>for(inti=0;i<size;++i)sum+=a[i];<br>returnsum/size;<br>double Mean(const double a[], int size) { <br>double sum = 0; <br>for (int i = 0; i < size; ++i) { sum += a[i]; } <br>return sum/size; <br>}

Sorting Algorithms
  • Selection Sort: A simple yet effective sorting algorithm that repeatedly selects the smallest item from the unsorted section and swaps it.

    • Step-by-step process leading to a sorted array.
      Example of Selection Sort Implementation:
      voidsort(doublex[],intn)<br>for(intk=0;k<n−1;++k)<br>intm=k;<br>for(intj=k+1;j<n;++j)<br>if(x[j]<x[m])m=j;<br><br>doublehold=x[m];x[m]=x[k];x[k]=hold;<br><br>void sort(double x[], int n) { <br>for (int k=0; k<n-1; ++k) { <br>int m = k; <br>for (int j=k+1; j<n; ++j) { <br>if (x[j] < x[m]) m = j; <br>} <br>double hold = x[m]; x[m] = x[k]; x[k] = hold; <br>} <br>}

Search Algorithms
  • Searching Techniques: Unordered datasets require sequential searching, while ordered datasets can utilize Sequential or Binary Search for improved performance.
    Example of Binary Search:
    intbSearch(constintlist[],intn,intvalue)<br>inttop=0;<br>intbottom=n−1;<br>intmid;<br>while(top<=bottom)mid=(top+bottom)/2;if(list[mid]==value)returnmid;elseif(list[mid]>value)bottom=mid−1;<br>elsetop=mid+1;<br><br>return−1;<br>int bSearch(const int list[], int n, int value) { <br>int top = 0; <br>int bottom = n - 1; <br>int mid; <br>while (top <= bottom) { mid = (top + bottom) / 2; if (list[mid] == value) return mid; else if (list[mid] > value) bottom = mid - 1; <br>else top = mid + 1; <br>} <br>return -1; <br>}

Character Strings and String Class
  • C-style Strings: Defined as arrays of characters terminated with a null character. This representation is crucial for legacy C code.

  • String Class: A modern C++ feature with dynamic sizing, equipped with various operators and methods such as size(), empty(), and substring access via substr().

Vectors
  • Definition: Vectors are dynamic arrays that can grow and shrink, overcoming the fixed-size limitation of regular arrays.

  • Manipulation: Utilize methods like pushback() to add elements and popback() to remove elements efficiently.
    Example of Vector Usage:
    vectornumbers;<br>numbers.push<em>back(10);numbers.pop</em>back();<br>cout<<"Size:"<<numbers.size();vector numbers; <br>numbers.push<em>back(10); numbers.pop</em>back(); <br>cout << "Size: " << numbers.size();

Passing Vectors to Functions
  • Vectors passed by reference can be modified inside functions, enhancing efficiency; otherwise, they are passed by value, which may incur a performance penalty.

Conclusion

One-dimensional arrays and vectors are fundamental data structures in C++ extensively utilized for sorting, searching, and statistical analysis. A deep understanding of their mechanics is essential for effective programming in engineering applications. Their implementation, optimization strategies, and potential pitfalls are crucial for coding proficiently in C++, paving the way for more advanced programming concepts.