Funksiya va massivlar
Ko‘p o‘lchamli massivlarni parametr sifatida ishlatishda bir nechta usullardan foydalanish mumkin:
1-usul. Massivning ikkinchi o‘lchamini o‘zgarmas ifoda (son) bilan ko‘rsatish:
float sum (int n, float x[][10])
{float s=0.0;
for(int i=0;i
for(int j=0;j
s+=x[i][j];
return s;}
2-usul. Ikki o‘lchamli massiv ko‘rsatkichlar massivi ko‘ri-nishida aniqlangan holatlar uchun ko‘rsatkichlar massivini (matritsa satrlar adreslarini) berish orqali:
float sum (int n, float x[][10])
{float s=0.0;
for(int i=0;i
for(int j=0;j
s+=x[i][j];
return s;}
int main()
{ float x[][4]={{11,-12,13,14},{21,22,23,24},{31,32,33,34},{41,42,43,44}};
float *ptr[4];
for(int i=0;i<4;i++)
ptr[i]=(float*)&x[i];
cout<
3-usul. Ko‘rsatkichlarga ko‘rsatkich ko‘rinishida aniqlangan dinamik massivlarni ishlatish bilan:
float sum(int n,float **x)
{ float s=0.0;
for(int i=0;i
for(int j=0;j
s+=x[i][j];
return s;}
int main()
{float **ptr;
int n;
cin>>n;
ptr=new float * [n];
for(int i=0;i
{
ptr[i]=new float [n];
for(int j=0;j
ptr[i][j]=(float)((i+1)*10+j;
}
cout<
for(int i=0;i
delete ptr[i];
delete []ptr;
}
Dinamik matritsalar
Masala: Matritsani o’lchamini kiriting va unga dastur davomida xotiradan joy ajrating.
Muammo : Matritsa o’lchami oldindan ma’lum emas.
Yechish usullari:
Xar bir satr uchun xotira bloke
Matritsa adresi:
typedef int *pInt;
int main()
{
int M, N, i;
pInt *A;
A = new pInt[M];// Ko’rsatgichlar massivini ajratish
for ( i = 0; i < M; i ++ )
A[i] = new int[N];// Massivning har- bir satr uchun
for ( i = 0; i < M; i ++ )
delete A[i];// Har – bir satr o’chiriladi
delete A; // Massiv o’chiriladi
}
Masala 2: Bir o’lchovli massivni elementlarini yig’indisini funksiya yordamida toping
#include
using namespace std;
int sum(int a[], int n)
{
int s=0;
for(int i=0; is+=a[i];
return s;
}
int main()
{
int n,s=0;
cout<<"Massiv o'lchami: ";
cin>>n;
int a[n];
for(int i=0; icin>>a[i];
s=sum(a,n);
cout<<"Yig'indi = "<}
Do'stlaringiz bilan baham: |