Structures dalam bahaha C
Structures adalah tipe data untuk menyimpan sekelompok data dengan berbagai tipe data.
Komponen structures disebut anggota / bidang / elemen.
Heterogen (berbagai tipe data elemen).
Structures dalam bahasa pemrograman lain juga disebut record.
Deklarasi structures
Syntax
struct name_structure {
dataType1 name_field1;
dataType2 name_field2;
…
};
Variable can be defined at declaration time
struct name_structure {
dataType1 name_field1;
dataType2 name_field2;
…
} name_variable_structure ;
Structure variable declaration
Struct name_structure name_variable_structure;
Contoh 1:
struct Mahasiswa{
int Nim;
char name[20];
float IPK;
char gender;
};
Contoh 2:
struct account{
int accountNo;
char accountType;
char name[31];
long credit;
};
struct account customer1, customer2;
Structures dapat digunakan tanpa penamaan, variable structures dapat langsung dinyatakan bersama dengan deklarasi structures.
Contoh:
Mengakses structures.
Mengakses Elemen Structures (bidang) dari suatu structures dapat diakses menggunakan operator dot dari variabel structures.
Contoh :
# include <stdio.h>
# include <string.h>
struct mhs {
char nim[9];
char name[26];
float gpa;
};
int main (){
struct mhs lia;
float wgpa;
scanf("%s", &lia.nim);
fflush(stdin);
gets(lia.name);
scanf("%f", &wgpa);
lia.gpa = wgpa;
printf("%s %s %.2f",
lia.nim, lia.name, lia.gpa);
return 1;
}
Local structures.
#
include <stdio.h>
#
include <math.h>
void
main() {
struct
{
int x, y;
} tA, tB;
float dist;
printf(“A position: \n
");
printf(“x and y position?
");
scanf("%d %d", &tA.x, &tA.y);
printf("\nB position :
\n ");
printf(“x and y position? ");
scanf("%d %d", &tB.x, &tB.y);
dist = sqrt(pow((tA.x - tB.x), 2) +
pow((tA.y - tB.y), 2));
printf("\nDistance between A and B =
%.2f unit", dist);
}
Output:
A position:
x and y position? 5 10
B position :
x and y position? 15 15
Distance between A and B = 11.18 unit
Array
structures.
Tipe data structures hanya dapat berisi satu catatan. Masalah dunia nyata membutuhkan sekelompok catatan.
Dalam prakteknya, structures biasanya digunakan bersama dengan array.
struct Dob{
int date, month, year;
};
struct Account {
int accountNo;
char accountType;
char name[31];
long credit;
struct Dob lastTrans;
};
//Array of structure
struct Account customer[100];
Init Array of
Structure:
struct dob{
char name[31];
int date, month, year;
};
struct dob birthday[ ] = {
{“Tata”, 9, 7, 1984},
{“Titi”, 7, 9, 1986},
{“Tutu”, 9, 9, 1990}
};
Contoh:
# include <stdio.h>
# include <string.h>
struct tmhs {
char nim[9];
char name[26];
float gpa;
};
int main (){
struct tmhs arr[50], x;
...
scanf("%s", &arr[0].nim);
...
x = arr[0];
arr[0] = arr[1];
arr[1] = x;
for (i = 0; i < 50; i++) {
printf("%s %s %.2f",
arr[i].nim,
arr[i].name,
arr[i].gpa);
}
return 1;
}