C语言数据结构在数组的开头插入

#include stdio.h#define MAX 5void main() {int array[MAX] = {2, 3, 4, 5};int N = 4;// number of elements in array

编程学习网为您整理以下代码实例,主要实现:C语言数据结构在数组的开头插入,希望可以帮到各位朋友。

#include <stdio.h>

#define MAX 5

voID main() {
   int array[MAX] = {2, 3, 4, 5};
   int N = 4;        // number of elements in array
   int i = 0;        // loop variable
   int value = 1;    // new data element to be stored in array

   // print array before insertion
   printf("Printing array before insertion −\n");

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

   // Now shift rest of the elements downwards   
   for(i = N; i >= 0; i--) {
      array[i+1] = array[i];
   }

   // add new element at first position
   array[0] = value;

   // increase N to reflect number of elements
   N++;

   // print to confirm
   printf("Printing array after insertion −\n");

   for(i = 0; i < N; i++) {
      printf("array[%d] = %d\n", i, array[i]);
   }
}
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐