C and C++

Moderators: None (Apply to moderate this forum)
Number of threads: 28629
Number of posts: 94611

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
reversing the order of array Posted by ashishhawking on 16 Sept 2012 at 12:27 PM
i am really fed up. please help me where i am getting wrong. i just cant get my mistake..
for input 1,2,3,4,5 its giving 5,2,3,4,1....

#include<iostream.h>
#include<stdio.h>

void reverse(int a[], int k)
{


int j,i,t;
for (i=1; i<=k; i++)
{ cin>>a[i]; }

for (j=k; j>=k/2; j--)
{ t=a[j];

a[j]=a[k-j+1];

a[k-j+1]=t;
}
for (j=1; j<=k; j++)
{cout<<a[j]<<"\n"; }
}
void main()
{
int a[5];


reverse(a, 5);
}
Report
Re: reversing the order of array Posted by WaltP on 21 Sept 2012 at 10:04 PM
: #include<iostream.h>
: #include<stdio.h>
Why are you using iostream.h AND stdio.h? And iostream.h has been replaced ages ago. It's just iostream now.

: for (i=1; i<=k; i++)
: { cin>>a[i]; }
If your function is supposed to reverse the data, why does it input the data? A function should do one thing, and do it well.

: for (j=1; j<=k; j++)
Arrays in C++ start at 0, not 1

: void main()
main() is not and never has had a void definition. It is int.

Why don't you post your code in CODE tags so we can read it properly? Assuming of course you formatted it properly in the first place.

Last, you can easily debug your own code by outputting variable and equation values at key places so you can see if the values are correct.



 

Recent Jobs