如何使用for循环反转数组? -不使用任何功能。 这是我的代码
int num, i, reversed;
cout << "enter your original array size: \n" << endl;
cin >> num;
int arr[num], arrC[num];
cout << "enter original array items: \n" << endl;
for (int i = 0; i < num; i++)
cin >> arr[i];
cout << "your array items are: \n";
for (int i = 0; i < num; i++)
cout << arr[i] << endl;
cout << "index: \n";
for (int i = 0; i < num; i++)
cout << i << endl;
cout << "original array: \n";
for (int i = 0; i < num; i++)
cout << arr[i] << endl;
cout << "reversed array:" << endl;
for (int i = 0; i < num; i--)
我在这一点上停了下来。你能帮我吗?
答案 0 :(得分:2)
我认为你快到了。您的循环:
cout<<"reversed array:"<<endl;
for(int i=0;i<num;i--)
应该是
for(int i=num-1;i>=0;i--)
答案 1 :(得分:0)
for循环中的普通数组(C风格):
char arr[5] = {'a', 'b', 'c', 'd', 'e'};
for (int i = 0; i < (sizeof(arr)/sizeof(*arr)); i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
for循环中的反转数组(C风格):
for (int i = (sizeof(arr)/sizeof(*arr)) - 1; i >= 0; i--) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;