มาดูแนวคิดของอาร์เรย์เกี่ยวกับการเริ่มต้นเวลาคอมไพล์และรันไทม์กัน −
อาร์เรย์
Array คือคอลเล็กชันของรายการที่จัดเก็บไว้ในตำแหน่งหน่วยความจำที่อยู่ติดกัน และองค์ประกอบต่างๆ สามารถเข้าถึงได้โดยใช้ดัชนี
คอมไพล์การเริ่มต้นอาร์เรย์เวลา
ในการเริ่มต้นเวลาคอมไพล์ ผู้ใช้ต้องป้อนรายละเอียดในโปรแกรมเอง
การเริ่มต้นเวลาคอมไพล์เหมือนกับการเริ่มต้นตัวแปร รูปแบบทั่วไปของการเริ่มต้นอาร์เรย์มีดังนี้ −
ไวยากรณ์
type name[size] = { list_of_values };
//integer array initialization
int rollnumbers[4]={ 2, 5, 6, 7};
//float array initialization
float area[5]={ 23.4, 6.8, 5.5,7.3,2.4 };
//character array initialization
char name[9]={ 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', '\0' }; ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C เพื่อแสดงอาร์เรย์ -
#include<stdio.h>
void main(){
//Declaring array with compile time initialization//
int array[5]={1,2,3,4,5};
//Declaring variables//
int i;
//Printing O/p using for loop//
printf("Displaying array of elements :");
for(i=0;i<5;i++){
printf("%d ",array[i]);
}
} ผลลัพธ์
Displaying array of elements :1 2 3 4 5
รันไทม์เริ่มต้นอาร์เรย์
การใช้การเริ่มต้นรันไทม์ ผู้ใช้จะได้รับโอกาสในการยอมรับหรือป้อนค่าต่างๆ ในระหว่างการรันโปรแกรมต่างๆ
นอกจากนี้ยังใช้สำหรับการเริ่มต้นอาร์เรย์ขนาดใหญ่หรืออาร์เรย์ด้วยค่าที่ผู้ใช้ระบุ อาร์เรย์ยังสามารถเริ่มต้นที่รันไทม์ได้โดยใช้ฟังก์ชัน scanf()
ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C เพื่อคำนวณผลรวมและผลิตภัณฑ์ขององค์ประกอบทั้งหมดในอาร์เรย์โดยใช้การรวบรวมรันไทม์ -
#include<stdio.h>
void main(){
//Declaring the array - run time//
int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];
//Reading elements into the array's A and B using for loop//
printf("Enter elements into the array A: \n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf("A[%d][%d] :",i,j);
scanf("%d",&A[i][j]);
}
printf("\n");
}
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf("B[%d][%d] :",i,j);
scanf("%d",&B[i][j]);
}
printf("\n");
}
//Calculating sum and printing output//
printf("Sum array is : \n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
sum[i][j]=A[i][j]+B[i][j];
printf("%d\t",sum[i][j]);
}
printf("\n");
}
//Calculating product and printing output//
printf("Product array is : \n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
product[i][j]=A[i][j]*B[i][j];
printf("%d\t",product[i][j]);
}
printf("\n");
}
} ผลลัพธ์
Enter elements into the array A: A[0][0] :A[0][1] :A[0][2] : A[1][0] :A[1][1] :A[1][2] : B[0][0] :B[0][1] :B[0][2] : B[1][0] :B[1][1] :B[1][2] : Sum array is : 000 000 Product array is : 000 000