编写一个 C 程序,使用 for 循环将数组元素左移指定的次数。此示例允许用户输入数组需要左移的次数、大小和元素。
#include<stdio.h>
void PrintArray(int a[], int Size)
{
for(int i = 0; i < Size; i++)
{
printf("%d ", a[i]);
}
}
int main()
{
int Size, i, j, num, temp;
printf("Please Enter the Size of an Array = ");
scanf("%d", &Size);
int a[Size];
printf("Please Enter the Array Elements = ");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
printf("\nNumber of Times to Left Rotate an Array = ");
scanf("%d", &num);
for(i = 0; i < num; i++)
{
temp = a[0];
for(j = 0; j < Size - 1; j++)
{
a[j] = a[j + 1];
}
a[Size - 1] = temp;
}
printf("\nArray Elements After Left Rotating Array : ");
PrintArray(a, Size);
return 0;
}

使用 while 循环左移数组元素的 C 程序
#include<stdio.h>
void PrintArray(int a[], int Size)
{
int i = 0;
while(i < Size)
{
printf("%d \t ", a[i]);
i++;
}
}
int main()
{
int Size, i, j, num, temp;
printf("\n Please Enter the Size = ");
scanf("%d", &Size);
int a[Size];
printf("\n Please Enter the Elements = ");
i = 0;
while(i < Size) {
scanf("%d", &a[i]);
i++;
}
printf("\n Number of Times to Left Rotate an Array = ");
scanf("%d", &num);
i = 0;
while(i < num)
{
temp = a[0];
j = 0;
while(j < Size - 1)
{
a[j] = a[j + 1];
j++;
}
a[Size - 1] = temp;
i++;
}
printf("\n Elements After Left Rotating Array : ");
PrintArray(a, Size);
return 0;
}
Please Enter the Size = 8
Please Enter the Elements = 22 33 44 55 66 77 88 99
Number of Times to Left Rotate an Array = 6
Elements After Left Rotating Array : 88 99 22 33 44 55 66 77
此 程序 使用函数将数组元素左移用户指定的次数。
#include<stdio.h>
void PrintArray(int *a, int Size)
{
for(int i = 0; i < Size; i++)
{
printf("%d ", *(a + i));
}
printf("\n");
}
void leftRotateArray(int a[], int size, int num)
{
for(int i = 0; i < num; i++)
{
int temp = a[0];
for(int j = 0; j < size - 1; j++)
{
a[j] = a[j + 1];
}
a[size - 1] = temp;
}
}
int main()
{
int size, num;
printf("\nPlease Enter the Size = ");
scanf("%d", &size);
int a[size];
printf("\nPlease Enter the Elements = ");
for(int i = 0; i < size; i++) {
scanf("%d", &a[i]);
}
printf("\nNumber of Times to Left Rotate an Array = ");
scanf("%d", &num);
leftRotateArray(a, size, num);
printf("\nElements After Left Rotating Array = ");
PrintArray(a, size);
}
Please Enter the Size = 10
Please Enter the Elements = 10 20 30 40 50 60 70 80 90 100
Number of Times to Left Rotate an Array = 4
Elements After Left Rotating Array = 50 60 70 80 90 100 10 20 30 40