C++ Arrays | Find output programs | Set 2

This section contains the C++ find output programs with their explanations on C++ Arrays (set 2).
Submitted by Nidhi, on June 09, 2020

Program 1:

#include <iostream>
using namespace std;

int main()
{
    int A[5] = { '1', '2', '3', '4', '5' };
    int K = 0;
    int* PTR;

    PTR = &A[0];

    K = *(PTR + 0) + *(PTR + 2) + *(PTR + 4);

    cout << K;

    return 0;
}

Output:

153

Explanation:

Here, we declared an array with 5 elements. We initialized the array with character values. But array will store the following values,

A[0] = 49; // because integer equivalent of '1' is 49.
A[1] = 50; // because integer equivalent of '2' is 50.
A[2] = 51; // because integer equivalent of '3' is 51.
A[3] = 52; // because integer equivalent of '4' is 52.
A[4] = 53; // because integer equivalent of '5' is 53.

Then we initialized pointer with the address of the first element of the array. Other elements of the array can be accessed by pointer arithmetic.

Evaluate the expression,

K = 49 + 51 +53;

Then the final value of K is 153.

Program 2:

#include <iostream>
using namespace std;

int main()
{
    int A[5] = { '1', '2', '3', '4', '5' };
    int K = 0;
    int* PTR;

    PTR = A;

    K = PTR[0] + PTR[2] + PTR[4];

    cout << K;

    return 0;
}

Output:

153

Explanation:

Here, we declared an array with 5 elements. We initialized the array with character values. But array will store the following values,

A[0] = 49; // because integer equivalent of '1' is 49.
A[1] = 50; // because integer equivalent of '2' is 50.
A[2] = 51; // because integer equivalent of '3' is 51.
A[3] = 52; // because integer equivalent of '4' is 52.
A[4] = 53; // because integer equivalent of '5' is 53.

Then we initialized pointer with the address of the first element of the array. Because the name of the array represents the base address of the array. The address of the 1st element of the array is known as the base address.

We can also use the pointer in an array fashion. Because the subscript "[]" operator can also be used with pointer also.

*(PTR+1), PTR[1], 1[PTR] and *(1+PTR) 

These will do the same work.

Program 3:

#include <iostream>
using namespace std;

int main()
{
    int A[5] = { 10, 20, 30, 40, 50 };
    int V = 0;
    int* PTR;

    PTR = A;

    PTR += 2;

    V = PTR[0] + PTR[2] + *(PTR - 1);

    cout << V;

    return 0;
}

Output:

100

Explanation:

Here, we created and initialized an array with 5 elements. And created a pointer that is pointing to the array.

PTR +=2;

Here, we moved the pointer to 2 positions ahead. It means now PTR is a pointer to arr[2].

Evaluate the expression,

V = PTR[0]+PTR[2]+*(PTR-1);
V = 30 + 50 + 20;
V = 100

Then the final value of V is 100.






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.