Example of Pointer & Array

 Here are four examples demonstrating Pointers and Arrays in C++.


1️⃣ Basic Example of Pointer & Array

📌 Explanation: The pointer points to the first element of the array, and we use pointer arithmetic to access other elements.

#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int* ptr = arr;  // Pointer to the first element of the array

    cout << "Array values using pointer: ";
    for (int i = 0; i < 5; i++) {
        cout << *(ptr + i) << " ";  // Accessing elements using pointer
    }
    cout << endl;

    return 0;
}

📝 Output:

Array values using pointer: 10 20 30 40 50

2️⃣ Print Character using Pointer & Array

📌 Explanation: Using a pointer to traverse a character array (string).

#include <iostream>
using namespace std;

int main() {
    char str[] = "Hello";
    char* ptr = str;  // Pointer to the character array

    cout << "Characters in string: ";
    while (*ptr != '\0') {
        cout << *ptr << " ";
        ptr++;  // Move to the next character
    }
    cout << endl;

    return 0;
}

📝 Output:

Characters in string: H e l l o

3️⃣ Print Floating Values Example in C++

📌 Explanation: Using a pointer to traverse a float array.

#include <iostream>
using namespace std;

int main() {
    float numbers[] = {1.1, 2.2, 3.3, 4.4, 5.5};
    float* ptr = numbers;  // Pointer to the float array

    cout << "Floating point numbers: ";
    for (int i = 0; i < 5; i++) {
        cout << *(ptr + i) << " ";
    }
    cout << endl;

    return 0;
}

📝 Output:

Floating point numbers: 1.1 2.2 3.3 4.4 5.5

4️⃣ Print Array Values Example in C++

📌 Explanation: Another way to print an array using pointer notation.

#include <iostream>
using namespace std;

void printArray(int* arr, int size) {
    cout << "Array elements: ";
    for (int i = 0; i < size; i++) {
        cout << *(arr + i) << " ";
    }
    cout << endl;
}

int main() {
    int arr[] = {5, 10, 15, 20, 25};
    int size = sizeof(arr) / sizeof(arr[0]);

    printArray(arr, size);  // Passing pointer to the function

    return 0;
}

📝 Output:

Array elements: 5 10 15 20 25

Let me know if you need more examples! 🚀

Post a Comment

0 Comments