×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

C++ Arrays | Find output programs | Set 3

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

Program 1:

#include <iostream>
using namespace std;

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

    PTR = A;

    PTR++;

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

    cout << V;

    return 0;
}

Output:

32825

Explanation:

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

PTR ++;

Here we moved the pointer to 1 position ahead. It means now PTR is a pointer to arr[1].

Evaluate the expression,

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

In the above expression, we are accessing elements out of bounds of the array using PTR[4], the pointer is pointing at index 5 in the array that does not exist in the array. So here the garbage value will be calculated in the expression, and then the final output will be a garbage value.

Program 2:

#include <iostream>
using namespace std;

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

    V = PTR[0] + PTR[2];

    cout << V;

    return 0;
}

Output:

80

Explanation:

Here, we created an array with 5 integer elements. And created a pointer PTR and assigned with (A+2).

A contains the address of the 1st element of the array and (A+2) represents the address of the 3rd element. It means pointer PTR is pointing to the element at index 2.

Evaluate the expression,

V = PTR[0]+PTR[2];
V = 30 + 50;
V = 80;

Then the final value of V is 80.

Program 3:

#include <iostream>
using namespace std;

int main()
{
    char A[5] = { 'H', 'E', 'L', 'L', 'O' };

    cout << A[1] - 0x30 << A[2] - 0x30 << A[4] - 0x30;

    return 0;
}

Output:

212831

Explanation:

Here, we create a character array and initialized with character values. Now look to the cout statement.

A[1] = 'E';  the ASCII value of 'E' is 69 and decimal value of 0x30 is 48.

69 - 48 = 21 then it will print 21.

Like that other values are also calculated then the final output is "212831".





Comments and Discussions!

Load comments ↻





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