Homework Assignment 8 - Arrays
and Pointers
Assignment Overview
Welcome to Homework Assignment 8! This assignment focuses on mastering C-style arrays and
introducing basic pointer concepts. You’ll create a C++ program with a theme of YOUR choice
that demonstrates your ability to work with arrays, understand memory addresses, and process
data efficiently.
Your Mission:
Create a C++ program with a theme of YOUR choice that incorporates ALL ten required coding
tasks listed below. Your program should:
- Use C-style arrays to store and process collections of data
- Pass arrays to functions for modular code organization
- Demonstrate understanding of pointers and memory addresses
- Use parallel arrays to maintain related data
- Process arrays efficiently with loops and functions
CRITICAL RESTRICTION:
You may NOT use vectors in this assignment. This assignment focuses on traditional C-style
arrays to help you understand how data structures work at a lower level. Use only C-style arrays
declared with square brackets: int myArray[SIZE];
Note on Functions:
You should continue using functions to organize your code. Arrays work differently than other
data types when passed to functions, and understanding this is an important learning objective.
Standard Requirements:
Your program must include:
- Complete source file header with your name, date, assignment number (Homework Assignment
8), and description
- Program greeting
- Meaningful comments throughout your code
- Proper variable naming conventions
Required Technical Tasks
Your program MUST complete ALL ten of the following tasks. These tasks must be integrated
naturally into your chosen theme.
Task 1: Array Declaration and Initialization
Declare and initialize at least TWO arrays:
- At least one array must be initialized with values at declaration using brace notation
- At least one array must have a declared size using a named constant
- Use appropriate data types (int, double, char, string, etc.) for your theme
Requirements:
- Declare array size using a const variable: const int SIZE = 10;
- Initialize at least one array: int scores[5] = {90, 85, 92, 88, 95};
- Add comments explaining what each array stores
Task 2: Accessing Array Elements
Demonstrate accessing and modifying array elements:
- Access array elements using subscript notation (index in square brackets)
- Read from array elements
- Modify array elements by assignment
- Show understanding that array indices start at 0
Add comments showing the valid index range for your arrays.
Task 3: Array Input and Output
Implement input and output operations for arrays:
- Read data into at least one array from user input using a loop
- Display array contents using a loop
- Format output clearly so users understand the data
Requirements:
- Use a loop to input multiple values into an array
- Use a loop to display all elements in an array
- Provide clear prompts and labels for output
Task 4: Processing Array Contents
Perform at least TWO different processing operations on array data:
- Find minimum or maximum value
- Calculate sum or average
- Search for a specific value
- Count elements meeting certain criteria
- Sort elements (if appropriate for your theme)
Each operation should be meaningful for your program’s purpose.
Task 5: Parallel Arrays
Create and use at least TWO parallel arrays:
- Arrays must store related data at corresponding indices
- Arrays must be the same size
- Each array must contain at least 5 elements
- Process both arrays together using the same index
Requirements:
- Maintain synchronized indices
- Use parallel arrays in at least one processing operation (display, calculate, search, etc.)
- Add comment explaining the relationship between the arrays
Task 6: Arrays as Function Arguments
Create at least TWO functions that accept arrays as parameters:
- At least one function must modify array contents (demonstrate that changes persist after
function returns)
- At least one function must process array contents and return a calculated result (find max/min,
calculate average, etc.)
- Pass the array size as a separate parameter
Requirements:
- Function prototypes must include array parameters
- Functions must use the passed arrays
- Show that modifications made to arrays in functions persist in the calling code
- Add comments explaining what each function does
Task 7: Pointer Basics
Demonstrate basic pointer concepts:
- Declare at least one pointer variable
- Use the address-of operator (&) to get a variable’s memory address
- Use the dereference operator (*) to access the value at a pointer’s address
- Display both the address and the value
Requirements:
- Show pointer declaration: int* ptr; or int *ptr;
- Show getting address: ptr = &variable;
- Show dereferencing: cout << *ptr;
- Add comments explaining what each operation does
Task 8: Array and Pointer Relationship
Demonstrate the relationship between arrays and pointers:
- Show that an array name is a pointer to the first element
- Display the memory address stored in the array name (just the array name without brackets)
- Display the memory address of the first element using &arrayName[0]
- Show that these two addresses are the same
- Display the memory addresses of multiple array elements to show they’re sequential
Requirements:
- Show: arrayName and &arrayName[0] produce the same address
- Display addresses of at least 3 array elements
- Add comments explaining that the array name is a constant pointer to the first element
Task 9: Counters and Running Totals
Use counter and accumulator variables when processing arrays:
- Use a counter variable to count elements meeting certain criteria
- Use a running total (accumulator) to sum values from an array
- Initialize counters/accumulators before loops
- Update them inside loops
- Use the final values after loops
Add comments identifying your counter and accumulator variables.
Task 10: Nested Loops with Arrays
Use at least ONE nested loop structure with arrays:
- At least one of the loops must iterate through an array
- Nested loops should perform a meaningful operation (comparing array elements, processing
parallel arrays, multi-step calculations)
- Both loops must have distinct purposes
Add comments explaining what each loop level does and how they work together.
Mandatory Requirements
Your program must compile and run
Your program must generate logically correct output
Your plagiarism score should be less than 50%
NO VECTORS ALLOWED - Arrays only
All arrays must be C-style arrays with declared sizes
Array bounds must be respected (no out-of-bounds access)
Array Fundamentals
Array Declaration Syntax
// Declare array with size
const int SIZE = 10;
int numbers[SIZE];
// Declare and initialize
double prices[5] = {19.99, 24.50, 15.75, 32.00, 28.25};
// Partial initialization (remaining elements become 0)
int values[10] = {1, 2, 3}; // First 3 set, rest are 0
// String array
string names[3] = {"Alice", "Bob", "Charlie"};
Accessing Elements
int scores[5] = {90, 85, 92, 88, 95};
// Access elements (indices 0 to size-1)
cout << scores[0]; // First element: 90
cout << scores[4]; // Last element: 95
// Modify elements
scores[1] = 87; // Change second element
scores[0] += 5; // Add to first element
Processing Arrays with Loops
const int SIZE = 5;
int data[SIZE] = {10, 20, 30, 40, 50};
// Display all elements
for (int i = 0; i < SIZE; i++) {
cout << data[i] << " ";
}
// Calculate sum
int total = 0;
for (int i = 0; i < SIZE; i++) {
total += data[i];
}
Passing Arrays to Functions
Function Syntax
// Function prototype - array parameter
void displayArray(int arr[], int size);
double calculateAverage(double values[], int size);
void modifyArray(int numbers[], int size);
// Function definition
void displayArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
// In main - calling with array
const int SIZE = 5;
int myArray[SIZE] = {1, 2, 3, 4, 5};
displayArray(myArray, SIZE); // Pass array name and size
Important Note About Array Parameters
Note: In function prototypes and parameters, any size specified in brackets is ignored by the
compiler:
void func(int arr[10], int size); // Size 10 is ignored
void func(int arr[], int size); // Treated the same by compiler
void func(int arr[100], int size); // Size 100 is also ignored
The compiler treats all of these as int arr[]. This is why you must always pass the size
separately as a parameter—the array doesn’t “know” its size when passed to a function.
Key Points About Arrays and Functions
Arrays are automatically passed by reference (not copied)
Changes made to array in function persist after function returns
Must pass array size separately - array doesn’t “know” its size
Array name without brackets is a pointer to first element
Parallel Arrays
Concept
const int SIZE = 4;
string studentNames[SIZE] = {"Alice", "Bob", "Charlie", "Diana"};
int studentGrades[SIZE] = {95, 87, 92, 88};
// Access related data using same index
for (int i = 0; i < SIZE; i++) {
cout << studentNames[i] << ": " << studentGrades[i] << endl;
}
Maintaining Synchronization
Always keep parallel arrays the same size
Use the same index to access related data
When adding data, update all parallel arrays together
Use const SIZE for all parallel arrays
Pointer Basics
Pointer Declaration and Basic Operations
int value = 42;
int* ptr; // Declare pointer to int
ptr = &value; // Store address of value in ptr
cout << "Address: " << ptr << endl; // Display address
cout << "Value: " << *ptr << endl; // Display value at address (42)
*ptr = 100; // Modify value through pointer
cout << value; // value is now 100
Address-of Operator (&)
int num = 25;
cout << # // Displays memory address of num
int* p = # // Store address in pointer
Dereference Operator (*)
int value = 10;
int* ptr = &value;
cout << *ptr; // Access value through pointer (prints 10)
*ptr = 20; // Modify value through pointer
Array and Pointer Relationship
Arrays Are Pointers
int numbers[5] = {10, 20, 30, 40, 50};
// The array name is a pointer to the first element
cout << "Array name address: " << numbers << endl;
cout << "First element address: " << &numbers[0] << endl;
// These print the same address!
// Displaying addresses of elements
for (int i = 0; i < 5; i++) {
cout << "Address of element " << i << ": " << &numbers[i] << endl;
cout << "Value of element " << i << ": " << numbers[i] << endl;
}
Key Understanding
Array name is a constant pointer to the first element
numbers and &numbers[0] give the same memory address
Array elements are stored sequentially in memory
Each element’s address is offset from the start based on element size
Counters and Accumulators with Arrays
Counter Example
const int SIZE = 10;
int scores[SIZE] = {85, 92, 78, 95, 88, 91, 76, 89, 93, 87};
int countAbove90 = 0; // Counter initialized to 0
for (int i = 0; i < SIZE; i++) {
if (scores[i] > 90) {
countAbove90++; // Increment counter
}
}
cout << "Scores above 90: " << countAbove90 << endl;
Accumulator Example
const int SIZE = 5;
double prices[SIZE] = {19.99, 24.50, 15.75, 32.00, 28.25};
double total = 0.0; // Accumulator initialized to 0
for (int i = 0; i < SIZE; i++) {
total += prices[i]; // Add to running total
}
double average = total / SIZE;
cout << "Average price: $" << average << endl;
Nested Loops with Arrays
Comparing Elements
const int SIZE = 5;
int data[SIZE] = {3, 7, 2, 9, 5};
// Find all pairs where first element is less than second
for (int i = 0; i < SIZE - 1; i++) {
for (int j = i + 1; j < SIZE; j++) {
if (data[i] < data[j]) {
cout << data[i] << " < " << data[j] << endl;
}
}
}
Processing Parallel Arrays
const int STUDENTS = 3;
const int TESTS = 4;
string names[STUDENTS] = {"Alice", "Bob", "Charlie"};
int test1[STUDENTS] = {85, 90, 78};
int test2[STUDENTS] = {92, 88, 85};
int test3[STUDENTS] = {88, 92, 90};
int test4[STUDENTS] = {95, 87, 92};
// Calculate average for each student
for (int i = 0; i < STUDENTS; i++) {
int total = test1[i] + test2[i] + test3[i] + test4[i];
double avg = total / 4.0;
cout << names[i] << " average: " << avg << endl;
}
Important Array Concepts
Array Size Must Be Constant
// CORRECT - using const
const int SIZE = 10;
int array[SIZE];
// CORRECT - literal value
int values[20];
// WRONG - variable size (not allowed in standard C++)
int n = 10;
int data[n]; // Error in standard C++
Tracking Used Elements
Arrays have a fixed size, but you may not always fill them completely:
const int MAX_SIZE = 100;
int scores[MAX_SIZE];
int numScores = 0; // Track how many elements actually used
// Input data
cout << "How many scores? ";
cin >> numScores;
if (numScores > MAX_SIZE) {
cout << "Too many! Maximum is " << MAX_SIZE << endl;
numScores = MAX_SIZE;
}
for (int i = 0; i < numScores; i++) {
cout << "Enter score " << (i + 1) << ": ";
cin >> scores[i];
}
// Process only the used portion
for (int i = 0; i < numScores; i++) {
cout << scores[i] << " ";
}
Always track how many elements you’re actually using in a separate variable.
Valid Index Range
int numbers[10]; // Valid indices: 0 to 9
numbers[0] = 5; // OK - first element
numbers[9] = 10; // OK - last element
numbers[10] = 15; // ERROR - out of bounds!
numbers[-1] = 20; // ERROR - negative index!
Arrays Cannot Be Assigned
int array1[5] = {1, 2, 3, 4, 5};
int array2[5];
array2 = array1; // ERROR - cannot assign arrays
// Must copy element by element
for (int i = 0; i < 5; i++) {
array2[i] = array1[i]; // OK
}
Arrays Don’t Know Their Own Size
void processArray(int arr[], int size) {
// sizeof(arr) does NOT give array size here!
// Always pass size as separate parameter
for (int i = 0; i < size; i++) {
// Process arr[i]
}
}
Input Validation with Arrays
Apply your input validation skills from previous assignments:
- Validate that array indices are within bounds (0 to size–1)
- Validate input data before storing in arrays
- Check that user doesn’t try to input more items than array can hold
- Use [Link]() and [Link]() to handle input errors
Example Program Structure
/*
* Student Name: [Your Name]
* Date: [Date]
* Assignment: Homework Assignment 8
* Program Description: [Description]
*/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// Named constants for array sizes
const int MAX_ITEMS = 10;
const int MAX_STUDENTS = 5;
// Function prototypes
void displayArray(int arr[], int size);
double calculateAverage(double values[], int size);
int findMaximum(int data[], int size);
int main() {
// Program greeting
cout << "================================" << endl;
cout << "Welcome to [Your Program]" << endl;
cout << "================================" << endl;
// Declare arrays
const int SIZE = 5;
int numbers[SIZE] = {10, 20, 30, 40, 50};
double values[SIZE];
// Parallel arrays
string names[SIZE];
int scores[SIZE];
// Pointer variables
int* ptr;
// Counter and accumulator
int count = 0;
double total = 0.0;
// Your program logic here
return 0;
}
// Function definitions
void displayArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
double calculateAverage(double values[], int size) {
double sum = 0.0;
for (int i = 0; i < size; i++) {
sum += values[i];
}
return sum / size;
}
int findMaximum(int data[], int size) {
int max = data[0];
for (int i = 1; i < size; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
Academic Integrity
What You May Do:
Discuss general concepts with classmates
Use course materials and textbook
Ask AI tools to explain array and pointer concepts
Seek help during office hours
Read C++ documentation
What You May NOT Do:
Copy code from anyone
Have AI tools write your code
Submit someone else’s work
Share your code with other students
Use code you don’t understand
Use vectors (arrays only for this assignment)
Your theme should be your own original choice. Your code should be written by you.
Submission Instructions
Step 1: Test Your Program
g++ -std=c++11 [Link] -o test
./test
Test with various inputs to ensure arrays are processed correctly.
Step 2: Change the File Type
Rename your .cpp file to .txt for Canvas upload.
Step 3: Upload to Canvas
- Go to Homework Assignment 8 submission page
- Upload your .txt file
- Verify upload completed successfully
Remember:
- Use only C-style arrays (no vectors)
- All 10 tasks must be completed
- Test thoroughly
- Submit on time
Good luck mastering arrays and pointers!