Array Pointer Arithmetic
C
Easy
4 views
Problem Description
Create an array and traverse it using pointers without bracket notation. Using only pointer increment/decrement. Both forward and backward directions
Official Solution
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int *ptr;
printf("Array elements (forward traversal):n");
/* Forward traversal */
ptr = arr; // pointer to first element
for (int i = 0; i < n; i++) {
printf("%d ", *ptr); // access value using pointer
ptr++; // move to next element
}
printf("n");
printf("Array elements (backward traversal):n");
/* Backward traversal */
ptr = arr + n - 1; // pointer to last element
for (int i = 0; i < n; i++) {
printf("%d ", *ptr); // access value using pointer
ptr--; // move to previous element
}
printf("n");
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!