Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

อาร์เรย์หนึ่งมิติในภาษา C คืออะไร?


อาร์เรย์คือกลุ่มของรายการที่เกี่ยวข้องกันซึ่งจัดเก็บด้วยชื่อสามัญ

ไวยากรณ์

ไวยากรณ์สำหรับการประกาศอาร์เรย์มีดังนี้ -

datatype array_name [size];

ประเภทของอาร์เรย์

Array แบ่งออกเป็น 3 ประเภทใหญ่ๆ ดังต่อไปนี้ −

  • อาร์เรย์หนึ่งมิติ
  • อาร์เรย์สองมิติ
  • อาร์เรย์หลายมิติ

อาร์เรย์หนึ่งมิติ

ไวยากรณ์มีดังนี้ -

datatype array name [size]

ตัวอย่างเช่น int a[5]

การเริ่มต้น

อาร์เรย์สามารถเริ่มต้นได้สองวิธี ได้แก่ −

  • คอมไพล์เวลาเริ่มต้น
  • การเริ่มต้นรันไทม์

ตัวอย่าง

ต่อไปนี้เป็นโปรแกรม C ในการเริ่มต้นเวลาคอมไพล์ -

#include<stdio.h>
int main ( ){
   int a[5] = {10,20,30,40,50};
   int i;
   printf ("elements of the array are");
   for ( i=0; i<5; i++)
      printf ("%d", a[i]);
}

ผลลัพธ์

เมื่อดำเนินการ คุณจะได้รับผลลัพธ์ต่อไปนี้ -

Elements of the array are
10 20 30 40 50

ตัวอย่าง

ต่อไปนี้เป็นโปรแกรม C ใน การเริ่มต้นรันไทม์

#include<stdio.h>
main ( ){
   int a[5],i;
   printf ("enter 5 elements");
   for ( i=0; i<5; i++)
      scanf("%d", &a[i]);
   printf("elements of the array are");
   for (i=0; i<5; i++)
      printf("%d", a[i]);
}

ผลลัพธ์

ผลลัพธ์จะเป็นดังนี้ −

enter 5 elements 10 20 30 40 50
elements of the array are : 10 20 30 40 50

หมายเหตุ

  • ผลลัพธ์ของเวลาคอมไพล์ที่เริ่มต้นโปรแกรมจะไม่เปลี่ยนแปลงในระหว่างการรันโปรแกรมที่แตกต่างกัน

  • ผลลัพธ์ของโปรแกรมรันไทม์ที่เริ่มต้นจะเปลี่ยนไปสำหรับการรันที่แตกต่างกัน เนื่องจากผู้ใช้จะได้รับโอกาสในการยอมรับค่าต่างๆ ในระหว่างการดำเนินการ

ตัวอย่าง

ต่อไปนี้เป็นโปรแกรม C อื่นสำหรับอาร์เรย์หนึ่งมิติ -

#include <stdio.h>
int main(void){
   int a[4];
   int b[4] = {1};
   int c[4] = {1,2,3,4};
   int i; //for loop counter
   //printing all elements of all arrays
   printf("\nArray a:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",i,a[i]);
      printf("\nArray b:\n");
   for( i=0; i<4; i++)
      printf("arr[%d]: %d\n",i,b[i]);
      printf("\nArray c:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",i, c[i]);
   return 0;
}

ผลลัพธ์

ผลลัพธ์ระบุไว้ด้านล่าง −

Array a:
arr[0]: 8
arr[1]: 0
arr[2]: 54
arr[3]: 0
Array b:
arr[0]: 1
arr[1]: 0
arr[2]: 0
arr[3]: 0
Array c:
arr[0]: 1
arr[1]: 2
arr[2]: 3
arr[3]: 4