MS Rumi. Powered by Blogger.

Thursday 8 May 2014

Structure in C++ With Example

By Unknown  |  08:24 1 comment

What is Structure?

Collection of variable under same name and these variable can be different type (int, float, char etc) and each have a name that is used to selected from structure. Structure is user define data type which can combine different data types.

How to create structure in c++?

To create structure you must use struct statement and also called keyword after that there is a tag which is user defined, structure Name. Then there are structure member with their data type and variable name. At the end close the struct body with braces and semicolon };.

Example of Structure

Write A Program to get 4 students data (Name, Course, Age, GPA) and print average age, average GPA  and maximum GPA.

#include<iostream.h>
void main ()
{
//Struct Defination 
struct Student
{
char name[20];
char course[10];
int age;
float gpa;
};

float sumage=0,sumgpa=0,max=0,avgGpa,avgAge;
int sno;
//Struct Variable as array
Student std[4];
cout<<"Enter Students Data"<<endl;

for(int i=0; i<4; i++)
{
cout<<"**Student No "<<i+1<<"**"<<endl;

cout<<"Enter Name:";
cin>>std[i].name;

cout<<"Enter course:";
cin>>std[i].course;

cout<<"Enter age:";
cin>>std[i].age;
//Suming Age for average
sumage=std[i].age+sumage;

cout<<"Enter GPA:";
cin>>std[i].gpa;
//Sum GPA for average
sumgpa=std[i].gpa+sumgpa;
//For Maximum GPA
if(max<std[i].gpa)
{
max=std[i].gpa;
sno=i;
}
}

//Average 
avgAge=sumage/4;
avgGpa=sumgpa/4;

cout<<"Age Average Is:"<<avgAge<<endl;
cout<<"GPA Average Is:"<<avgGpa<<endl;
cout<<std[sno].name<<" Got Maximum GPA Is:"<<max;
}

OutPut of Example 



Author: Unknown

Hello, I am Author, thanks for visiting my blog. Bookmark this....

1 comment:

E-mail Newsletter

Sign up now to receive breaking news and to hear what's new with us.

Recent Articles

TOP