Cố gắng in các phần tử theo thứ tự ngược lại bằng cách làm theo một thuật toán đưa ra bên dưới -
Bước 1 - Khai báo một mảng có kích thước 5
Bước 2 - Nhập 5 phần tử vào bộ nhớ bằng vòng lặp for
Bước 3 - Hiển thị các phần tử theo thứ tự ngược lại
Bằng cách giảm dần vòng lặp for
Logic duy nhất là đảo ngược các phần tử là vòng lặp For -
for(i=4;i>=0;i--){
//Displaying O/p//
printf("array[%d] :",i);
printf("%d\n",array[i]);
} Ví dụ
Sau đây là chương trình C để đảo ngược các phần tử -
#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]);
}
} Đầu ra
Khi chương trình trên được thực thi, nó tạo ra kết quả sau -
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