Introduction
In this lab, you will learn how to manipulate array elements in C programming. The lab covers the fundamental skills of declaring and initializing arrays, accessing and modifying array elements, iterating through arrays, performing array calculations, and dynamically allocating array memory. You will explore various techniques for working with arrays, including declaring and initializing arrays with specific values, partially initializing arrays, and dynamically assigning values to array elements. By the end of the lab, you will have a solid understanding of how to effectively manage and manipulate array data structures in C.
Declare and Initialize an Array
In this step, you'll learn how to declare and initialize arrays in C programming. Arrays are fundamental data structures that allow you to store multiple elements of the same type in a contiguous memory location.
Let's start by creating a new C file to explore array declaration and initialization:
cd ~/project
touch array_basics.c
Now, let's write a program that demonstrates different ways to declare and initialize arrays:
#include <stdio.h>
int main() {
// Method 1: Declare and initialize an array with specific values
int numbers[5] = {10, 20, 30, 40, 50};
// Method 2: Declare an array and initialize later
int scores[3];
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;
// Method 3: Partially initialize an array (remaining elements set to 0)
int grades[4] = {100, 95};
// Print the arrays to verify initialization
printf("Numbers array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
printf("Scores array: ");
for (int i = 0; i < 3; i++) {
printf("%d ", scores[i]);
}
printf("\n");
printf("Grades array: ");
for (int i = 0; i < 4; i++) {
printf("%d ", grades[i]);
}
printf("\n");
return 0;
}
Compile and run the program:
gcc array_basics.c -o array_basics
./array_basics
Example output:
Numbers array: 10 20 30 40 50
Scores array: 85 92 78
Grades array: 100 95 0 0
Let's break down the array initialization methods:
int numbers[5] = {10, 20, 30, 40, 50};- Declares an integer array with 5 elements
- Initializes all elements with specific values
- Size is determined by the number of elements in the initializer list
int scores[3];followed by individual element assignment- Declares an array first
- Assigns values to individual elements later
- Useful when you want to set values dynamically
int grades[4] = {100, 95};- Partially initializes an array
- Unspecified elements are automatically set to 0
- Helps save time when you only want to set some initial values
Key points to remember:
- Array indices start at 0
- You must specify the type of elements the array will store
- Arrays have a fixed size once declared
- Always ensure you don't access array elements beyond their declared size
Access and Modify Array Elements
In this step, you'll learn how to access and modify individual elements of an array in C programming. Building upon the previous step, we'll explore how to interact with array elements using indexing and demonstrate various ways to manipulate array contents.
Let's create a new C file to practice accessing and modifying array elements:
cd ~/project
touch array_access.c
Now, let's write a program that demonstrates array element access and modification:
#include <stdio.h>
int main() {
// Declare and initialize an array
int temperatures[5] = {72, 68, 75, 80, 65};
// Accessing individual array elements
printf("First temperature: %d\n", temperatures[0]);
printf("Third temperature: %d\n", temperatures[2]);
// Modifying array elements
temperatures[1] = 70; // Change the second element
temperatures[4] = 73; // Change the last element
// Print the modified array
printf("Modified temperatures: ");
for (int i = 0; i < 5; i++) {
printf("%d ", temperatures[i]);
}
printf("\n");
// Demonstrate array element calculation
int average = (temperatures[0] + temperatures[1] + temperatures[2] +
temperatures[3] + temperatures[4]) / 5;
printf("Average temperature: %d\n", average);
return 0;
}
Compile and run the program:
gcc array_access.c -o array_access
./array_access
Example output:
First temperature: 72
Third temperature: 75
Modified temperatures: 72 70 75 80 73
Average temperature: 74
Let's break down the key concepts:
Array Indexing
- Arrays are accessed using zero-based indexing
temperatures[0]refers to the first elementtemperatures[4]refers to the last element in a 5-element array
Modifying Array Elements
- Individual elements can be changed directly using their index
temperatures[1] = 70;replaces the second element with 70- You can modify elements at any valid index
Array Element Calculations
- You can perform calculations using individual array elements
- In the example, we calculated the average temperature
- Access elements directly by their index in mathematical operations
Common Pitfalls to Avoid:
- Never access an array index outside its bounds
- Array indices start at 0, not 1
- Be careful not to exceed the array's declared size
Iterate Through an Array
In this step, you'll learn different methods to iterate through arrays in C programming. Iteration is crucial for processing array elements efficiently and performing various operations on array contents.
Let's create a new C file to explore array iteration techniques:
cd ~/project
touch array_iteration.c
Now, let's write a program demonstrating multiple ways to iterate through an array:
#include <stdio.h>
int main() {
// Declare and initialize an array of student scores
int scores[6] = {85, 92, 78, 90, 88, 95};
int total = 0;
// Method 1: Using a standard for loop
printf("Method 1 - Standard For Loop:\n");
for (int i = 0; i < 6; i++) {
printf("Score %d: %d\n", i + 1, scores[i]);
total += scores[i];
}
// Calculate and print average
float average = (float)total / 6;
printf("\nTotal Score: %d\n", total);
printf("Average Score: %.2f\n", average);
// Method 2: Reverse iteration
printf("\nMethod 2 - Reverse Iteration:\n");
printf("Scores in reverse order:\n");
for (int i = 5; i >= 0; i--) {
printf("Score %d: %d\n", i + 1, scores[i]);
}
// Method 3: While loop iteration
printf("\nMethod 3 - While Loop Iteration:\n");
int j = 0;
while (j < 6) {
if (scores[j] >= 90) {
printf("High score detected: %d\n", scores[j]);
}
j++;
}
return 0;
}
Compile and run the program:
gcc array_iteration.c -o array_iteration
./array_iteration
Example output:
Method 1 - Standard For Loop:
Score 1: 85
Score 2: 92
Score 3: 78
Score 4: 90
Score 5: 88
Score 6: 95
Total Score: 528
Average Score: 88.00
Method 2 - Reverse Iteration:
Scores in reverse order:
Score 6: 95
Score 5: 88
Score 4: 90
Score 3: 78
Score 2: 92
Score 1: 85
Method 3 - While Loop Iteration:
High score detected: 92
High score detected: 90
High score detected: 95
Key Iteration Techniques:
Standard For Loop
- Most common method for array iteration
- Allows precise control over index
- Ideal for forward processing
Reverse Iteration
- Iterate from the last element to the first
- Useful for specific processing requirements
- Uses a descending loop counter
While Loop Iteration
- Provides flexible iteration control
- Can include conditional processing
- Useful for complex iteration logic
Important Iteration Principles:
- Always define clear loop boundaries
- Use array length to prevent out-of-bounds access
- Choose the most appropriate iteration method for your specific task
Perform Array Calculations
In this step, you'll learn how to perform various calculations on arrays in C programming. We'll explore techniques for finding maximum and minimum values, calculating sums, averages, and applying mathematical transformations to array elements.
Let's create a new C file to practice array calculations:
cd ~/project
touch array_calculations.c
Now, let's write a program that demonstrates different array calculation techniques:
#include <stdio.h>
#include <limits.h>
int main() {
// Declare and initialize an array of sales data
int sales[7] = {1200, 1500, 980, 1750, 1100, 1300, 1600};
// Calculate Total Sales
int total_sales = 0;
for (int i = 0; i < 7; i++) {
total_sales += sales[i];
}
printf("Total Weekly Sales: $%d\n", total_sales);
// Calculate Average Sales
float average_sales = (float)total_sales / 7;
printf("Average Daily Sales: $%.2f\n", average_sales);
// Find Maximum Sales
int max_sales = sales[0]; // Start with first element
for (int i = 1; i < 7; i++) {
if (sales[i] > max_sales) {
max_sales = sales[i];
}
}
printf("Highest Daily Sales: $%d\n", max_sales);
// Find Minimum Sales
int min_sales = sales[0]; // Start with first element
for (int i = 1; i < 7; i++) {
if (sales[i] < min_sales) {
min_sales = sales[i];
}
}
printf("Lowest Daily Sales: $%d\n", min_sales);
// Apply Percentage Increase
float increase_percentage = 1.1; // 10% increase
printf("\nSales After 10%% Increase:\n");
for (int i = 0; i < 7; i++) {
float increased_sale = sales[i] * increase_percentage;
printf("Day %d: $%.2f\n", i + 1, increased_sale);
}
return 0;
}
Compile and run the program:
gcc array_calculations.c -o array_calculations
./array_calculations
Example output:
Total Weekly Sales: $9430
Average Daily Sales: $1347.14
Highest Daily Sales: $1750
Lowest Daily Sales: $980
Sales After 10% Increase:
Day 1: $1320.00
Day 2: $1650.00
Day 3: $1078.00
Day 4: $1925.00
Day 5: $1210.00
Day 6: $1430.00
Day 7: $1760.00
Key Array Calculation Techniques:
Total Calculation
- Use a loop to sum all array elements
- Accumulate values in a separate variable
- Useful for finding total sum
Average Calculation
- Divide total sum by number of elements
- Use type casting for floating-point precision
- Provides mean value of array elements
Finding Maximum/Minimum
- Initialize with first array element
- Compare each subsequent element
- Update max/min value when a new extreme is found
Element-wise Transformations
- Apply mathematical operations to each element
- Can modify array values based on specific rules
- Useful for scaling, adjusting, or transforming data
Important Calculation Principles:
- Always consider array bounds
- Use appropriate data types
- Be careful with integer division
- Initialize accumulator variables before calculations
Dynamically Allocate Array Memory
In this step, you'll learn how to dynamically allocate memory for arrays in C programming using malloc(), realloc(), and free() functions. Dynamic memory allocation allows you to create arrays with sizes determined at runtime.
Let's create a new C file to explore dynamic memory allocation:
cd ~/project
touch dynamic_array.c
Now, let's write a program demonstrating dynamic array memory allocation:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Dynamic memory allocation for an integer array
int array_size;
printf("Enter the number of elements: ");
scanf("%d", &array_size);
// Allocate memory dynamically
int *dynamic_array = (int *)malloc(array_size * sizeof(int));
// Check if memory allocation was successful
if (dynamic_array == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input array elements
printf("Enter %d integers:\n", array_size);
for (int i = 0; i < array_size; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &dynamic_array[i]);
}
// Print array elements
printf("\nArray elements:\n");
for (int i = 0; i < array_size; i++) {
printf("%d ", dynamic_array[i]);
}
printf("\n");
// Dynamically resize the array
int new_size;
printf("\nEnter new array size: ");
scanf("%d", &new_size);
// Reallocate memory
int *resized_array = (int *)realloc(dynamic_array, new_size * sizeof(int));
// Check if reallocation was successful
if (resized_array == NULL) {
printf("Memory reallocation failed!\n");
free(dynamic_array);
return 1;
}
dynamic_array = resized_array;
// If new size is larger, initialize new elements
if (new_size > array_size) {
for (int i = array_size; i < new_size; i++) {
dynamic_array[i] = 0;
}
}
// Print resized array
printf("Resized array:\n");
for (int i = 0; i < new_size; i++) {
printf("%d ", dynamic_array[i]);
}
printf("\n");
// Free dynamically allocated memory
free(dynamic_array);
return 0;
}
Compile and run the program:
gcc dynamic_array.c -o dynamic_array
./dynamic_array
Example interaction:
Enter the number of elements: 3
Enter 3 integers:
Element 1: 10
Element 2: 20
Element 3: 30
Array elements:
10 20 30
Enter new array size: 5
Resized array:
10 20 30 0 0
Key Dynamic Memory Allocation Concepts:
malloc()Function- Allocates requested memory and returns a pointer
- Syntax:
pointer = (type *)malloc(size * sizeof(type)) - Always check for NULL to ensure successful allocation
realloc()Function- Resizes previously allocated memory block
- Can increase or decrease array size
- Preserves existing data when expanding
free()Function- Deallocates dynamically allocated memory
- Prevents memory leaks
- Must be called for each malloc()/realloc() allocation
Important Memory Allocation Principles:
- Always check allocation success
- Free dynamically allocated memory when no longer needed
- Be careful when resizing arrays
- Handle potential allocation failures gracefully
Summary
In this lab, you learned how to declare and initialize arrays in C programming, access and modify array elements, iterate through arrays, perform array calculations, and dynamically allocate array memory. You explored different methods for declaring and initializing arrays, including specifying values directly, assigning values later, and partially initializing arrays. You also learned how to print the contents of arrays to verify their initialization. These fundamental array operations are essential for working with data structures in C and form the building blocks for more complex array manipulations.



