数据结构&算法 数组

数组

数组是一个容器,可以容纳固定数量的项目,这些项目应为同一类型。大多数数据结构都利用数组来实现其算法。以下是了解数组概念的重要术语。

  • 元素 - 存储在数组中的每个项目称为元素。
  • 索引 - 数组中元素的每个位置都有一个数字索引,用于标识元素。

在C语言中,当使用size初始化数组时,它将按以下顺序为其元素分配默认值。

颜色名称效果
boolfalse
char0
int0
float0.0
double0.0f
void 
wchar_t0

遍历数组

此操作将遍历数组的元素。

以下程序遍历并打印数组的元素:


#include <stdio.h>
main() {
   int LA[] = {1,3,5,7,8};
   int item = 10, k = 3, n = 5;
   int i = 0, j = n;   
   printf("The original array elements are :\n");
   for(i = 0; i < n; i++) {
      printf("LA[%d] = %d \n", i, LA[i]);
   }
}

当我们编译并执行上述程序时,它将产生以下结果


The original array elements are :
LA[0] = 1 
LA[1] = 3 
LA[2] = 5 
LA[3] = 7 
LA[4] = 8 

插入操作

插入操作是将一个或多个数据元素插入数组。根据要求,可以在数组的开头,结尾或任何给定的索引处添加新元素。在这里,我们看到了插入操作的实际实现,我们在数组的末尾添加了数据-

以下是上述算法的实现-


#include <stdio.h>

main() {
   int LA[] = {1,3,5,7,8};
   int item = 10, k = 3, n = 5;
   int i = 0, j = n;
   
   printf("The original array elements are :\n");

   for(i = 0; i < n; i++) {
      printf("LA[%d] = %d \n", i, LA[i]);
   }

   n = n + 1;
  
   while( j >= k) {
      LA[j+1] = LA[j];
      j = j - 1;
   }

   LA[k] = item;

   printf("The array elements after insertion :\n");

   for(i = 0; i < n; i++) {
      printf("LA[%d] = %d \n", i, LA[i]);
   }
}

当我们编译并执行上述程序时,它将产生以下结果-


The original array elements are :
LA[0] = 1 
LA[1] = 3 
LA[2] = 5 
LA[3] = 7 
LA[4] = 8 
The array elements after insertion :
LA[0] = 1 
LA[1] = 3 
LA[2] = 5 
LA[3] = 10 
LA[4] = 7 
LA[5] = 8 

相关资料

更多数据结构与算法

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值