#include<iostream>
using namespace std;
void reverse(int arr[],int n){
int start=0,end=n-1;
int temp;
while(start<=end){
temp=arr[end];
arr[end]=arr[start];
arr[start]=temp;
}
start ;
end--;
}
void print(int arr[],int n){
for(int i=0;i<n;i ){
cout<<arr;
}
cout<<endl;
}
int main(){
int arr[5]={1,2,3,4,5};
int brr[6]={3,6,8,2,1,0};
reverse(arr,5);
reverse(brr,6);
print(arr,5);
print(brr,6);
}
I am not able to run this code at any compiler, can anyone tell me where I am making the mistake after running it I am getting nothing
CodePudding user response:
I am not to happy about the material that is teaching you C .
For one it still uses "C" style arrays, and it is learning you to write
using namespace std;
which will lead to problems (name clashes) in big projects. So if you have a teacher tell him about this.
Here is a more C oriented example :
#include <algorithm>
#include <iostream>
#include <vector>
// Using namespace std; <-- No unlearn this
// don't use "C" style arrays, use std::array or std::vector
// "C" style arrays are inherently more "buggy" to use.
// for one it easy to get mismatch array size and the size you pass.
void reverse(std::vector<int>& values)
{
//std::reverse(values.begin(), values.end()); C has this out of the box for you
std::size_t left_pos = 0ul;
std::size_t right_pos = values.size() - 1; // last index in array
/// manually, you start with first and last element and swap them
// then move left position one to the right, and right position one to the left
// repeat until left_pos and right_pos cross.
for (; left_pos < right_pos; left_pos, --right_pos)
{
// c has a swap method to swap values
std::swap(values[left_pos], values[right_pos]);
}
}
// prints the content of the vector
std::ostream& operator<<(std::ostream& os, const std::vector<int>& values)
{
bool print_comma{ false };
for (const int value : values)
{
if (print_comma) std::cout << ",";
std::cout << value;
print_comma = true;
}
std::cout << "\n";
return os;
}
int main()
{
std::vector<int> arr1{ 1,2,3,4,5 };
reverse(arr1);
std::cout << arr1;
return 0;
}
CodePudding user response:
Just for your information: I would recommend you to just use std::reverse()
for the concrete example. Also, do not use raw arrays.
#include <algorithm>
#include <iostream>
template <typename T>
void print(const T& arr) {
for (auto &value: arr) {
std::cout << value << " ";
}
std::cout << "\n";
}
int main(){
std::array arr={1,2,3,4,5}; // Or just use a std::vector
std::array brr={3,6,8,2,1,0};
std::reverse(arr.begin(), arr.end());
std::reverse(brr.begin(), brr.end());
print(arr);
print(brr);
}