Search This Blog

Monday, December 23, 2013

Objects as function arguements

#include <iostream>
using namespace std;
class time
{
    int hour, minute, second;
public:
    void input()
    {
        cin>>hour>>minute>>second;
    }
    void display()
    {
        cout<<hour<<" hour ";
        cout<<minute<<" minute and ";
        cout<<second<<" seconds"<<endl;
    }
    void add(time t1,time t2)
    {
        second=t1.second+t2.second;
        minute=t1.minute+t2.minute+second/60;
        second=second%60;
        hour=t1.hour+t2.hour+minute/60;
        minute=minute%60;

    }
};
int  main()
{
    time t1, t2, t3;
    cout<<" enter start time : ";
    t1.input();
    cout<<" enter end time : ";
    t2.input();
    t3.add(t1,t2);
    t3.display();
    return 0;
}

Array of an object

#include <iostream>
using namespace std;
class student
{
    int roll;
    char name[15];
    int marks[5];
public:
    void input();
    void display();
};
void student :: input()
{
    cout<<"please enter your name ";
    cin>>name;
    cout<<endl<<"now enter your roll no";
    cin>>roll;
    cout<<endl<<"now enter your marks"<<endl;
    for(int i=0;i<5;i++)
    {
        cin>>marks[i];
    }

}
void student :: display()
{
    cout<<"\n name "<<name<<endl;
    cout<<"\n roll no "<<roll<<endl;
    cout<<"\n marks \n --------------------------------------------- "<<endl;
    for(int i=0;i<5;i++)
    {
        cout<<marks[i]<<"   ";
    }
    cout<<" \n -------------------------------------------- \n";
}
int main()
{
    student s[5];
    cout<<"enter student record \n";
    cout<<"----------------------------------- \n";
    for(int i=0;i<5;i++)
    {
        s[i].input();
    }
    for(int i=0;i<5;i++)
    {
        s[i].display();
    }
    return 0;

}

Working of friend function

#include <iostream>
using namespace std;
class array
{
    int a[10];
public:
    void input();
    friend float average(array);
};
void array::input()
{
    for(int i=0;i<10;i++)
    {
        cin>>a[i];
    }
}
float average(array a1)
{
    float sum=0;
    for(int i=0;i<10;i++)
    {
        sum=sum+a1.a[i];
    }
    return (sum/10);
}
int main()
{
    array a1;
    cout<<endl<<"enter 10 elements of an array";
    a1.input();
    float avg;
    avg=average(a1);
    cout<<endl<<avg;
    return 0;
}