如何从C中的数组以相反的顺序打印元素?
尝试按照下面给出的算法以相反的顺序打印元素-
Step1-声明一个大小为5的数组
步骤2-使用for循环在内存中输入5个元素
步骤3-以相反的顺序显示元素
通过递减for循环
唯一的逻辑是反转元素是For循环-
for(i=4;i>=0;i--){ //Displaying O/p// printf("array[%d] :",i); printf("%d\n",array[i]); }
示例
以下是反转元素的C程序-
#include输出结果void main(){ //Declaring the array - run time// int array[5],i; //Reading elements into the array// printf("Enter elements into the array: \n"); //For loop// for(i=0;i<5;i++){ //Reading User I/p// printf("array[%d] :",i); scanf("%d",&array[i]); } //Displaying reverse order of elements in the array// printf("The elements from the array displayed in the reverse order are :\n"); for(i=4;i>=0;i--){ //Displaying O/p// printf("array[%d] :",i); printf("%d\n",array[i]); } }
执行上述程序时,会产生以下结果-
Enter elements into the array: array[0] :23 array[1] :13 array[2] :56 array[3] :78 array[4] :34 The elements from the array displayed in the reverse order are: array[4] :34 array[3] :78 array[2] :56 array[1] :13 array[0] :23