C++ Arrays | Find output programs | Set 1

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

Program 1:

#include <iostream>
using namespace std;

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

    K = A[0] + A[2] + A[4] * 10;

    cout << K;

    return 0;
}

Output:

4

Explanation:

Here, we declared a one-dimensional array A with size 5 and variable K with initial value 0.

The values of the array are,

A[0] = 1
A[1] = 2
A[2] = 3
A[3] = 0
A[4] = 0

Note: If we assign value to any element of the array, then other elements assigned by 0 if they not assigned explicitly in the program.  

Evaluate the expression,

K   = 1 + 3+ 0*10
    = 1 + 3 + 0
    = 4

Then the final value of K is 4.

Program 2:

#include <iostream>
using namespace std;

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

    K = (*(A + 0) + *(A + 2) + *(A + 4)) * 10;

    cout << K;

    return 0;
}

Output:

90

Explanation:

Here, we declared a one-dimensional array A with size 5 and variable K with initial value 0.

The values of the array are,

A[0] = 1
A[1] = 2
A[2] = 3
A[3] = 4
A[4] = 5

Note: Array are controlled pointers, we can access elements of an array using asterisk operator by de-referencing elements of the array.

*(A +0) is equivalent to the A[0] and *(A+2) is equivalent to the A[2] and so on.

Evaluate the expression,

K   = (1+3+5)*10
    = 9 * 10
    = 90

Then the final value of K is 90.

Program 3:

#include <iostream>
using namespace std;

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

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

    cout << K;

    return 0;
}

Output:

Segmentation fault (core dumped)

or

Print some garbage value.

Explanation:

Here, we declared an array with 5 elements and one integer variable K and an integer pointer PTR. Here, we did not assign any address to the pointer. Then the pointer PTR is pointing to the unknown location the expression will evaluate with some garbage values.

Then the final result will also a garbage value.





Comments and Discussions!

Load comments ↻





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