Lecture-28 (5-12-2023)
Lecture-28 (5-12-2023)
MA144:
Computer Programming
Lecture-28
Structures-2
Array of Structures
Once a structure data-type has been defined, we can
declare an array of structures.
struct ECE
{
int rollNo;
char name[20];
int marks;
};
ECE student[55];
return 0;
}
void sum(complex z0,complex z1)
{ complex w;
w.real=z0.real+z1.real;
w.img=z0.img+z1.img;
cout<<"sum of "<<z0.real<<"+i("<<z0.img<<") and
"<<z1.real<<"+i("<<z1.img<<") is "<<endl;
cout<<w.real<<"+i"<<w.img;
}
Structures can be returned from functions
#include<iostream>
using namespace std;
struct complex
{ int real;
int img;
};
complex sum(complex,complex);
int main()
{ complex z[2],w;
int i;
for(i=0;i<2;i++){
cout<<"enter complext number "<<i+1<<": ";
cin>>z[i].real>>z[i].img;
}
w=sum(z[0],z[1]);
cout<<"sum of "<<z[0].real<<"+i("<<z[0].img<<")
and "<<z[1].real<<"+i("<<z[1].img<<") is "<<endl;
cout<<w.real<<"+i"<<w.img;
return 0;
}
complex sum(complex z0,complex z1)
{ complex w;
w.real=z0.real+z1.real;
w.img=z0.img+z1.img;
return w;
}
Structures are passed by reference to functions
struct complex
{ int real;
int img;
};
void swap(complex&,complex&);
int main()
{ complex z[2],w;
int i;
for(i=0;i<2;i++){
cout<<"enter complext number "<<i+1<<": ";
cin>>z[i].real>>z[i].img;
}
cout<<"z[0] = "<<z[0].real<<"+i("<<z[0].img<<") "
<<endl;
cout<<"z[1] = "<<z[1].real<<"+i("<<z[1].img<<") "
<<endl;
swap(z[0],z[1]);
cout<<"after swapping:"<<endl;
cout<<"z[0] = "<<z[0].real<<"+I
("<<z[0].img<<")"<<endl;
cout<<"z[1] = "<<z[1].real<<"+I
("<<z[1].img<<")"<<endl;
return 0;
}
void swap(complex& z0,complex& z1)
{ complex w;
w=z0;
z0=z1;
z1=w;
}
Pointers to Structures
struct complex
{ int real; z–>real and (*z).real are same.
int img; *z.real will lead to error
};
int main()
{ complex *z,w;
z=&w;
cout<<"enter complext number : ";
cin>>(*z).real>>(*z).img;
cout<<"The entered complex number is ";
cout<<(*z).real<<"+i("<<(*z).img<<")";
cout<<endl;
cout<<z->real<<"+i("<<z->img<<")";
return 0;
}
#include<iostream> Sum of complex numbers using
using namespace std; pointers and functions
struct complex
{ int real;
int img;
};
void sum(complex*,complex*, complex*);
int main()
{ complex z[2],w;
int i;
for(i=0;i<2;i++){
cout<<"enter complext number "<<i+1<<": ";
cin>>z[i].real>>z[i].img;
}
sum(&z[0],&z[1],&w);
cout<<"sum of "<<z[0].real<<"+i("<<z[0].img<<")
and "<<z[1].real<<"+i("<<z[1].img<<") is "<<endl;
cout<<w.real<<"+i("<<w.img<<")";
return 0;
}
void sum(complex* z0,complex* z1, complex *w1)
{
w1->real=z0->real+z1->real;
w1->img=z0->img+z1->img;
}
A Warning