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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.