Array I
Having covered the theoretical concepts of Arrays in our previous discussion, let's now dive into writing some basic programs to solidify our understanding of Arrays.
1. Write a program that takes an array as input and prints each element of the array along with its corresponding index.
Example:
Input: nums = [1, 2, 3, 5, 6]
Output:
Value at Index 0 is 1
Value at Index 1 is 2
Value at Index 2 is 3
Value at Index 3 is 5
Value at Index 4 is 6
Input: nums = [2, 1, 3, 3]
Output:
Value at Index 0 is 2
Value at Index 1 is 1
Value at Index 2 is 3
Value at Index 3 is 3
Approach
To solve this problem, we need to achieve two key tasks: retrieving the value of each element in the array and determining its corresponding index. Given that the array is 0-based, the current, loop control variable also known as an iterator during traversal represents the index of the array. The value at that index can be accessed directly using array[index] (where index is the current loop variable). By iterating through the array, we can print both the index and the corresponding value in the desired format.
Dry Run
- Array nums contains [1, 2, 3, 5, 6].
- The size of the array is calculated as size = 5.
- The for loop starts with index = 0 and continues until index < size (i.e., index < 5).
Iterations of the Loop:
- First Iteration (index = 0):
The value at nums[0] is 1.
Output: Value at Index 0 is 1 - Second Iteration (index = 1):
The value at nums[1] is 2.
Output: Value at Index 1 is 2 - Third Iteration (index = 2):
The value at nums[2] is 3.
Output: Value at Index 2 is 3 - Fourth Iteration (index = 3):
The value at nums[3] is 5.
Output: Value at Index 3 is 5 - Fifth Iteration (index = 4):
The value at nums[4] is 6.
Output: Value at Index 4 is 6
End of Loop: The loop terminates when index becomes 5, which is not less than size (5).
Code for All Languages
C++
// Program to Print Each Element of an Array Along with Its Corresponding Index
#include <iostream>
using namespace std;
// Function to print each element of the array along with its index
void printArrayWithIndices(int nums[], int size) {
// Loop through the array to print each element and its index
for (int index = 0; index < size; ++index) {
// Print the value at the current index
cout << "Value at Index " << index << " is " << nums[index] << endl;
}
}
Java
// Program to Print Each Element of an Array Along with Its Corresponding In
import java.util.Scanner;
// Function to print each element of the array along with its index
public static void printArrayWithIndices(int[] nums) {
for (int index = 0; index < nums.length; ++index) {
System.out.println("Value at Index " + index + " is " + nums[index]);
}
Python
# Program to Print Each Element of an Array Along with Its Corresponding In
# Function to print each element of the array along with its index
def print_array_with_indices(nums):
for index, value in enumerate(nums):
print(f"Value at Index {index} is {value}")
Javascript
// Program to Print Each Element of an Array Along with Its Corresponding In
// Function to print each element of the array along with its index
function printArrayWithIndices(nums) {
for (let index = 0; index < nums.length; ++index) {
console.log(`Value at Index ${index} is ${nums[index]}`);
}
}
Time Complexity : O(n)
The time complexity of this program is O(n), where n is the number of elements in the array. This is because the program iterates through the entire array exactly once, performing a constant-time operation (printing) for each element. Since the loop runs n times, the overall time complexity is linear with respect to the size of the array.
Space Complexity : O(1)
The space complexity of the program is O(1). This means that the amount of extra space required by the program is constant, regardless of the size of the input array. The program uses a fixed amount of memory for variables like the loop counter, but it does not allocate any additional space that grows with the input size. Therefore, the space complexity remains constant.
Now that we've seen how to traverse an array in a forward manner, there are many situations where we need to traverse and perform operations on an array in reverse order as well. Let's explore how this is done with the below problem.
2. Write a program that takes an array as input and prints each element of the array in reverse order.
Example
Input: nums = [1, 2, 3, 5, 6]
Output: [6, 5, 3, 2, 1]
Input: nums = [1, 2, 9, 5, 6, 7, 8, 2, 3]
Output: [3, 2, 8, 7, 6, 5, 9, 2, 1]
Approach
To solve this problem, we need to modify the loop from the previous code. Instead of iterating from 0 to n-1 (where n is the size of the array), we will iterate from n-1 down to 0. By decrementing the loop variable in each iteration, we can access and print the elements in reverse order, achieving the desired result of printing the array in reverse.
Dry Run
Input:
nums = [1, 2, 3, 5, 6]
size = 5
Output:
[6, 5, 3, 2, 1]
- Initialization:
- The input array
nums
is [1, 2, 3, 5, 6]. - The size of the array is 5.
- The input array
- Iterations of the Loop:
- First Iteration (index = 4):
- The value at nums[4] is 6.
- This value is printed, resulting in partial output: 6
- Second Iteration (index = 3):
- The value at nums[3] is 5.
- This value is printed, resulting in partial output: 6 5
- Third Iteration (index = 2):
- The value at nums[2] is 3.
- This value is printed, resulting in partial output: 6 5 3
- Fourth Iteration (index = 1):
- The value at nums[1] is 2.
- This value is printed, resulting in partial output: 6 5 3 2
- Fifth Iteration (index = 0):
- The value at nums[0] is 1.
- This value is printed, resulting in partial output: 6 5 3 2 1
- End of Loop: The loop terminates when index = -1, which is less than 0.
Code for All Languages
C++
// Function to print each element of the array in reverse order
void printArrayInReverse(int nums[], int size) {
for (int index = size - 1; index >= 0; --index) {
cout << nums[index] << " ";
}
cout << endl; // Newline for better output formatting
}
Java
// Function to print each element of the array in reverse order
public static void printArrayInReverse(int[] nums, int size) {
for (int index = size - 1; index >= 0; --index) {
System.out.print(nums[index] + " ");
}
System.out.println(); // Newline for better output formatting
}
Python
# Function to print each element of the array in reverse order
def print_array_in_reverse(nums, size):
for index in range(size - 1, -1, -1):
print(nums[index], end=" ")
print() # Newline for better output formatting
Time Complexity : O(n)
The time complexity of this program is O(n), where n is the number of elements in the array. This is because the program iterates through the array once, but in reverse order. Whether iterating forward or backward, the loop still runs n times, performing a constant-time operation (printing) for each element. Therefore, the time complexity remains linear, O(n).
Space Complexity : O(1)
The space complexity is O(1). This means the program uses a constant amount of extra space, regardless of the size of the input array. The only additional memory used is for the loop counter and a few other fixed variables, which do not depend on the size of the array. Since no extra space is required that scales with the input size, the space complexity is constant.
In certain scenarios, it's necessary to access elements at specific intervals, such as accessing only alternate elements or focusing on elements at odd or even indexes. Let's explore how this can be done
3. Write a program that takes an array as input and prints the alternate elements of the array.
Example
Input: nums = [1, 2, 3, 5, 6]
Output: [1, 3, 6]
Explanation: Starting from first element, we access the 1st, 3rd, and 5th element while skipping the 2nd and 4th element.
Input: nums = [1, 2, 9, 5, 6, 7, 8, 2, 3]
Output: [1, 9, 6, 8, 3]
Approach
To print the values of an array nums alternately, starting from the first element (index 0), we can utilize two approaches:
- Incremental Loop Approach: Typically, we increment our loop variable by 1 for normal traversal. However, in this case, we increment the loop variable by 2. By doing so, we skip one index after each iteration, effectively printing every other element.
- Even Index Approach: If we observe the printed values in the example (i.e., nums[0], nums[2], nums[4]), it's clear that we need to print elements located at even indices. An index is even if it satisfies the condition index % 2 == 0. By checking this condition, we can selectively print only the elements at even positions in the array.
Dry Run
Input:
nums = [1, 2, 3, 5, 6]
size = 5
Output (Expected):
[1, 3, 6]
Incremental Loop Approach:
- Start with index = 0. The loop increments index by 2 in each iteration.
- First iteration: index = 0,
Element at nums[0] is 1. Add 1 to the output. - Second iteration: index = 2,
Element at nums[2] is 3. Add 3 to the output. - Third iteration: index = 4,
Element at nums[4] is 6. Add 6 to the output. - Fourth iteration: index = 6, which is out of bounds. The loop terminates.
Final output: [1, 3, 6]
Even Index Approach:
- Start with index = 0. The loop increments index by 1 in each iteration.
- First iteration: index = 0, 0 % 2 == 0.
Element at nums[0] is 1.
Add 1 to the output. - Second iteration: index = 1, 1 % 2 != 0.
Skip this index. - Third iteration: index = 2, 2 % 2 == 0.
Element at nums[2] is 3. Add 3 to the output. - Fourth iteration: index = 3, 3 % 2 != 0.
Skip this index. - Fifth iteration: index = 4, 4 % 2 == 0.
Element at nums[4] is 6. Add 6 to the output.
Final output: [1, 3, 6]
Code for All Languages
C++
// Program to Print Each alternate elements of an Array
#include <iostream>
using namespace std;
// Incremental Loop Approach: Print alternate elements by incrementing the index by 2
void printAlternateByIncrement(int nums[], int size) {
// Loop through the array, incrementing the index by 2 each time
for (int index = 0; index < size; index += 2) {
// Print the element at the current index
cout << nums[index] << " ";
}
cout << endl;
}
// Even Index Approach: Print elements at even indices
void printAlternateByEvenIndex(int nums[], int size) {
// Loop through the entire array
for (int index = 0; index < size; ++index) {
// Check if the current index is even
if (index % 2 == 0) {
// Print the element at the current index if it's even
cout << nums[index] << " ";
}
}
cout << endl;
}
Java
import java.util.*;
public class LearnYard {
// Incremental Loop Approach: Print alternate elements by incrementing the index by 2
static void printAlternateByIncrement(int[] nums, int size) {
// Loop through the array, incrementing the index by 2 each time
for (int index = 0; index < size; index += 2) {
// Print the element at the current index
System.out.print(nums[index] + " ");
}
System.out.println();
}
// Even Index Approach: Print elements at even indices
static void printAlternateByEvenIndex(int[] nums, int size) {
// Loop through the entire array
for (int index = 0; index < size; ++index) {
// Check if the current index is even
if (index % 2 == 0) {
// Print the element at the current index if it's even
System.out.print(nums[index] + " ");
}
}
System.out.println();
}
}
Python
def print_alternate_by_increment(nums, size):
# Incremental Loop Approach: Print alternate elements by incrementing the index by 2
for index in range(0, size, 2):
# Print the element at the current index
print(nums[index], end=" ")
# Move to the next line after printing all elements
print()
def print_alternate_by_even_index(nums, size):
# Even Index Approach: Print elements at even indices
for index in range(size):
# Check if the current index is even
if index % 2 == 0:
# Print the element at the current index if it's even
print(nums[index], end=" ")
# Move to the next line after printing all elements
print()
Javascript
function printAlternateByIncrement(nums, size) {
// Incremental Loop Approach: Print alternate elements by incrementing the index by 2
for (let index = 0; index < size; index += 2) {
// Print the element at the current index
process.stdout.write(nums[index] + " ");
}
// Move to the next line after printing all elements
console.log();
}
function printAlternateByEvenIndex(nums, size) {
// Even Index Approach: Print elements at even indices
for (let index = 0; index < size; ++index) {
// Check if the current index is even
if (index % 2 === 0) {
// Print the element at the current index if it's even
process.stdout.write(nums[index] + " ");
}
}
// Move to the next line after printing all elements
console.log();
}
Time Complexity
Both approaches involve traversing the array, either by incrementing the index by 2 or by checking if the index is even. In either case, we are visiting roughly half of the elements in the array. The time complexity is therefore O(n/2), which simplifies to O(n), where n is the number of elements in the array.
Space Complexity
Both approaches only require a constant amount of extra space, mainly for loop variables and any temporary storage for results. Thus, the space complexity is O(1).