尝试按照下面给出的算法以相反的顺序打印元素-
步骤1-声明大小为5的数组
步骤2-使用for循环输入内存中的5个元素
步骤3-以相反的顺序显示元素
通过递减循环
唯一的逻辑是反转元素是For循环-
for(i=4;i>=0;i--) { //Displaying O/p// printf("array[%d] :",i); printf("%d\n",array[i]); }
以下是反转元素的C程序-
#include<stdio.h> 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