×

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++ Structures | Find output programs | Set 1

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

Program 1:

#include <iostream>
#include <math.h>
using namespace std;

struct st {
    int A = NULL;
    int B = abs(EOF + EOF);
} S;

int main()
{
    cout << S.A << " " << S.B;
    return 0;
}

Output:

0 2

Explanation:

Here, we created a structure that contains two integer variables. Here, we used NULL, EOF, and abs() function for initialization of structure elements.

The values of NULL and EOF are 0 and -1 respectively. And the function abs() returns positive value always.

A = NULL; //that is 0 
A = 0;
	
B = abs(EOF+EOF);
	= abs(-1+-1);
	= abs(-1-1);
	= abs(-2);
	= 2;

Then, the final value 0 and 2 will be printed on the console screen.

Program 2:

#include <iostream>
using namespace std;

typedef struct{
    int A = 10;
    int B = 20;
} S;

int main()
{
    cout << S.A << " " << S.B;
    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:11:14: error: expected primary-expression before ‘.’ token
     cout << S.A << " " << S.B;
              ^
main.cpp:11:28: error: expected primary-expression before ‘.’ token
     cout << S.A << " " << S.B;
                            ^

Explanation:

Here, we created a structure using typedef that contains two integer variables A and B. Consider the below statement,

cout <<S.A<<" "<<S.B;

Here, we accessed A using S. but S is not an object or variable of structure, we used typedef it means S is type, so we need to create an object of structure using S like, S ob;

Then, ob.A and ob.B will be the proper way to access A and B.

Program 3:

#include <iostream>
using namespace std;

typedef struct{
    int A;
    char* STR;
} S;

int main()
{
    S ob = { 10, "india" };

    S* ptr;
    ptr = &ob;

    cout << ptr->A << " " << ptr->STR;
    return 0;
}

Output:

10 india

Explanation:

Here, we created a structure with two members A and STR. In the main() function, we created the object that is ob, and  a pointer ptr and then assigned the address of ob to ptr. Accessing the elements using referential operator -> and then printed them on the console screen.

The final output "10 india" will be printed on the console screen.





Comments and Discussions!

Load comments ↻





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