Structures in C++

Fractional Calculator in C++

0670360302013The concept of structure in C++ comes when we need our own defined data types, it is a bit different from the classes, so don’t confuse it, it is the one where the concept of Object Oriented Programming  starts and it is the main feature which makes a difference between C and C++, object oriented programming have just amazing factors. Now lets come to the point , for creating  structures in C++ we write the keyword “struct” and then its name and use its attributes inside braces just like functions but with a semi colon at the end, we can define variables and functions inside a structure.  lets have a look at the below example:

  1. // Simple Example of structures in C++
  2. //Student Records In C++ using structures
  4. #include<iostream>
  5. using namespace std;
  6. struct student
  7. {    int roll_no;
  8.     char name[20],city[20];
  9.     int phone;
  10. };
  11. int main()
  12. {    student std;
  13.     cout<<“Enter roll number?”<<endl;     cin>>std.roll_no;
  14.     cout<<“Enter name of student?”<<endl;     cin>>;
  15.     cout<<“Enter name of city of student?”<<endl;     cin>>;
  16.     cout<<“Enter phone of student?”<<endl;     cin>>;
  17.     cout<<endl;
  18.     cout<<“Roll no. : “<<std.roll_no<<endl;
  19.     cout<<“Name: “<<<<endl;
  20.     cout<<“City: “<<<<endl;
  21.     cout<<“Phone: “<<<<endl;
  23.     return 0;
  24. }

Now lets have an explanation of the above code, we defined a structure named “ student ” which contains the details of a student defined in different variables in it, now we can use it in our main() function with a “ . ” used after the self-defined variable “std “of datatype “student” . We can use the “ cin ” and ” cout ” operations with it. So simply structure makes our main() function much easier.

Fractional Calculator in C++

Leave a Reply