I am trying to insert an integer if array position is equal to 3 but unfortunately when I am printing my array a I am getting absured results like this:
0
0
2
whereas, the result expected is:
0
0
128
0
0
My code is:
#include<stdio.h>
int substitute_and_sum(int *a, int len)
{
int sum = 0, i;
for (i = 0; i < 5; i++)
{
if (i == 3)
{
a[i] = 128;
}
}
printf("%d\n", *a);
return 0;
}
int main()
{
int arr[] = { 0, 0, 2, 0, 0 };
int j = 5, i;
for (i = 0; i < 5; i++)
{
substitute_and_sum(&arr[i], j);
}
}
You have two for loops which don't play well together. Remove one or the other. For example:
int main()
{
int arr[] = { 0, 0, 2, 0, 0 };
int j = 5;
substitute_and_sum(arr, j);
for (int i = 0; i < 5; i++)
{
printf("%d\n", a[i]);
}
}
Note that I moved the printf into main. Your existing program is pretty weird.
You just need to call like following
int main(){
int arr[]={0,0,2,0,0};
int j=5,i;
//for(i=0;i<5;i++)
//{
substitute_and_sum(arr,j);
//}
}
Or use :-
void substitute_and_sum(int *a)
{
*a = 128;
}
And in main :
for (i = 0; i < 5; i++)
{
if (i == 2) //Note its index 2, not 3
substitute_and_sum(&arr[i]);
}
one for loop is enough
#include<stdio.h>
int substitute_and_sum(int* a, int len) {
int sum =0, i;
for(i=0;i< len;i++)
{
if(i==3)
{
a[i] = 128;
}
printf("%d\n" , a[i]);
}
return 0;
}
int main(){
int arr[]={0,0,2,0,0};
int j=5,i;
substitute_and_sum(&arr[i],j);
}
replace 5 with len otherwise what is the point of the argument and the last printf() is pointless because it only prints the value of the first element;
You loop over your array in both functions, just do it in one of them.
this works, whenever you send individual value of the array make it an habit of sending its index, if required for example in case like yours.
#include<stdio.h>
int substitute_and_sum(int *a, int i)
{
if (i == 3)
{
*a = 128;
}
printf("%d\n", *a);
return 0;
}
int main()
{
int arr[] = { 0, 0, 2, 0, 0 };
int i;
for (i = 0; i < 5; i++)
{
substitute_and_sum(&arr[i], i);
}
}
Related
For my studies, I have to write a C function GetEvenNumber:
parameters: array with n integers + array size;
returns tr array which contains even integers from td.
I don't know a priori the length of the array tr.
My below code returns errors:
#include <stdio.h> // define the header file
int *GetEvenNumber(int t[], int size)
{
int tr[];
int j = 0;
for (int i = 0; i < size; i++)
{
if (t[i] % 2 == 0)
{
printf("%d is even \n", t[i]);
tr[j] = t[i];
j++;
}
}
return tr;
}
int main() // define the main function
{
int *t; // = {4, 3, 1, 8, 6 };
int *tr = GetEvenNumber(t, 5);
for (int i = 0; i < 5; i++)
printf("%d \n", tr[i]);
}
I get error:
error: array size missing in 'tr'
int tr[];
warning: function returns address of local variable [-Wreturn-local-addr]
return tr;
How do I fix that? Thanks.
You mentioned that you could not use malloc() to dynamically create tr within GetEvenNumber() to address the two issues raised by your copmiler. This leaves making tr a global variable, or as here pass in the result array tr to be filled out:
#include <stdio.h>
#include <stdlib.h>
void GetEvenNumber(size_t size, const int *td, size_t *size2, int *tr) {
*size2 = 0;
for(size_t i=0; i<size; i++)
if(td[i] % 2 == 0)
tr[(*size2)++] = td[i];
}
int main() {
int td[] = {4, 3, 1, 8, 6 };
size_t size = sizeof(td) / sizeof(*td);
int tr[size];
size_t size2;
GetEvenNumber(size, td, &size2, tr);
for (size_t i=0; i < size2; i++)
printf("%d \n", tr[i]);
}
If the input array td contains uneven elements, then the result array tr have fewer valid elements than the input. I used size2 here to tell caller how many elements are valid in tr. Your code did not assign any values to, in this example, last 3 elements. You don't tell us what should happen with those last elements.
In modern C, if you specify the size before the array in the argument, then you can use the size in array specification which help document what is going on.
The error is due to
int tr[];
because you have to specify the size of your array during its creation.
I suggest trying to add a function that returns the number of even numbers in the array:
int getEvenNum(int t[], int lent){
int numEven = 0; // initialize counter to zero
for(int i = 0; i < lent; i++){ // for each element of the array
if ((t[i] % 2) == 0){ // if it's even,
numEven++; // add 1 to counter
}
}
return(numEven); // finaly returns the value of the counter
}
and then you replace the int tr[]; by int tr[getEvenNum(t, size)]; (maybe there's a ; after the getEvenNum(t, size) but I'm not sure)
Since the array tr can have AT MOST the same number of elements as the original integer array, it would be safe to declare the array with the same size as the array 't[]'.
I have made some changes to your code. Try the following:
#include<stdio.h> // define the header file
void GetEvenNumber(int *t, int* tr, int size, int *pCountEven)
{
int i, j=0;
for (i=0; i < size; i++)
{
if(t[i]%2==0)
{
printf("%d is even \n", t[i]);
tr[j++] = t[i];
}
}
*pCountEven = j;
}
int main() // define the main function
{
int t[] = {4, 3, 1, 8, 6 };
int tr[5], countEven = 0, i;
GetEvenNumber(t, tr, 5, &countEven);
for (i=0; i < countEven; i++)
printf("%d\n", tr[i]);
return 0;
}
Edit: As #chqrlie (who is an experienced coder) pointed out, we can simply return the length of the array instead of taking the address of a variable.
So alternatively, you can try this:
#include <stdio.h> // define the header file
int GetEvenNumber(int *t, int *tr, int size) {
int i, j = 0;
for (i = 0; i < size; i++) {
if (t[i] % 2 == 0) {
printf("%d is even \n", t[i]);
tr[j++] = t[i];
}
}
return j;
}
int main() // define the main function
{
int t[] = { 4, 3, 1, 8, 6 };
int tr[5], countEven = 0, i;
countEven = GetEvenNumber(t, tr, 5);
for (i = 0; i < countEven; i++)
printf("%d\n", tr[i]);
return 0;
}
During recursion, once elements are changed in an array, this change persist. How to pass array so that changes are done according to the call stack ?
Once element at index 2 is set, its set in every function call.
Here's the code:
#include<stdio.h>
void recur(int flag[], int n, int idx){
if(idx==n){
for(int i=0; i<n; i++)
if(flag[i])
printf("%d ", i);
printf("\n");
return;
}
recur(flag, n, idx+1);
flag[idx] = 1;
recur(flag, n, idx+1);
}
int main(){
int flag[] = {0, 0, 0};
recur(flag, 3, 0);
return 0;
}
It gives me the following output:
2
1 2
1 2
0 1 2
0 1 2
0 1 2
0 1 2
If you want to keep the array intact, you need to revert any changes to the array you've made in your function. In this case you should store in a temporary variable the value of flag[idx] before changing it and then restore it:
#include <stdio.h>
void recur(int flag[], int n, int idx) {
if (idx == n) {
for (int i = 0; i < n; i++) {
if (flag[i]) {
printf("%d ", i);
}
}
printf("\n");
return;
}
recur(flag, n, idx + 1);
int temp = flag[idx]; // Change line 1
flag[idx] = 1;
recur(flag, n, idx + 1);
flag[idx] = temp; // Change line 2
}
int main() {
int flag[] = {0, 0, 0};
recur(flag, 3, 0);
return 0;
}
See it in ideone: https://ideone.com/Q6Vb7A
I want to find the number within a range in an array and must be in a recursive way. The function variables couldn't be modified.
Let's say in the range of 2 and 3
The input is : int a[] = {4, 1, 3, 1, 3, 2};
and the output will be = {3,3,2} , 3 found
Not sure how to code the recursive function in this case. The below I have tried not working.
int within(int a[], int N, int lower, int upper, int result[])
{
if(N == 1 && N <= upper && N>= lower)
return a[0];
return within(&a[1], N-1, lower, upper, result);
}
int main()
{
int a[] = {4, 1, 3, 1, 3, 2};
int result[6] = {0};
int i, nResult;
nResult = within(a, 6, 2, 3, result);
printf("%d data passed the bounds\n", nResult);
for (i = 0; i < nResult; i++){
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
I want to find the number within a range in an array
Let's say in the range of 2 and 3
Normally a for loop or similar would be so much easier here
If it has to be recursive....
// need to have another number - r - number in range
// r starts at zero
//
// normally lower case for variable and capitals for things you #define
// N starts at the number of elements of a less one
//
int within(int a[], int N, int lower, int upper, int r, int result[])
{
if(a[0] <= upper && a[0]>= lower) {
result[r]= a[0];
r++;
}
if(N==0) {
return r;
} else {
r = within(&a[1], N-1, lower, upper, r, result);
return r;
}
}
the function will give a return value of the number of values found within the range.
The code above is recursive, but so much more complicated and fragile than a simple loop... such as the fragment below
for (i=0;i<N;i++) {
if(a[i] <= upper && a[i]>= lower) {
result[r]= a[i];
r++;
}
}
If it has to be recursive wihtout r...
// need to have another number - result[0] - number in range
// result[0] starts at zero
//
// normally lower case for variable and capitals for things you #define
// N starts at the number of elements of a less one
//
int within(int a[], int N, int lower, int upper, int result[])
{
if(a[0] <= upper && a[0]>= lower) {
result[0]++;
result[result[0]]= a[0];
}
if(N==0) {
return result[0];
} else {
result[0] = within(&a[1], N-1, lower, upper, result);
return result[0];
}
}
now result conatins
{number in range, first number in range, second number in range....}
Something like this. If you want to implement a recursive function, try to do it in the way that the recursive call happens at the end.
#include <stdio.h>
int find_in_range(int* out, int const *in, int length, int from, int to)
{
if (length == 0)
{
return 0;
}
int addon;
if (*in >= from && *in <= to)
{
*out = *in;
++out;
addon = 1;
}
else
{
addon = 0;
}
return find_in_range(out, in + 1, length - 1, from, to) + addon;
}
#define N 6
int main()
{
int in[N] = {4, 1, 3, 1, 3, 2};
int out[N] = {0};
int num_found = find_in_range(out, in, N, 2, 3);
for (int i = 0; i < num_found; ++i)
{
printf("%d ", out[i]);
}
printf("\n");
return 0;
}
You can modify the following code as per your requirements. This is just a proof of concept code:
#include <stdio.h>
#include <stdlib.h>
static int result[4];
static int ctr1 = 0;
static int ctr2 = 0;
void recFind(int* arr, int* key){
if(ctr2 == 8)
return;
if(*arr >= key[0] && *arr <= key[1])
result[ctr1++] = *arr;
arr++;
ctr2++;
recFind(arr, key);
}
int main(){
int arr[] = {1,3,3,6,4,6,7,8};
int key[] = {1,4};
recFind(arr, key);
printf(" { ");
for(int i = 0; i < 4; i++){
printf("%d ", result[i]);
}
printf("}\n");
}
As it follows from the description of the assignment the function should provide two values: the number of elements that satisfy the condition and an array that contains the elements themselves.
It is evident that the array should be allocated dynamically. And it is logically consistent when the function itself returns the number of elements while the pointer to the generated array is passed by reference as an argument.
The recursive function can look the following way
#include <stdio.h>
#include <stdlib.h>
size_t get_range( const int a[], size_t n, int lower, int upper, int **out )
{
size_t m;
if ( n )
{
m = get_range( a, n - 1, lower, upper, out );
if ( lower <= a[n-1] && a[n-1] <= upper )
{
int *tmp = realloc( *out, ( m + 1 ) * sizeof( int ) );
if ( tmp )
{
tmp[m] = a[n-1];
*out = tmp;
++m;
}
}
}
else
{
*out = NULL;
m = 0;
}
return m;
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 4, 3, 2, 1 };
const size_t N = sizeof( a ) / sizeof( *a );
int lower = 2, high = 3;
int *out;
size_t n = get_range( a, N, lower, high, &out );
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", out[i] );
}
putchar( '\n' );
free( out );
return 0;
}
The program output is
2 3 3 2
Below codes will work for you in recursive way. If you don't want to print the numbers just comment out printf statement inside function printfRange. Hope you can understand the logic :-
int within(int *a, int rngH, int rngL, int length)
{
int len = length;
static int i = 0;
static int found = 0;
if(len <=0 )
{
return i;
}
if (*a == rngH)
{
printf("%d,",*a);
i++;
found = 1;
within(++a,rngH, rngL,--len);
}
else if(*a == rngL && found > 0)
{
printf("%d,",*a);
i++;
within(++a,rngH, rngL,--len);
}
else
{
within(++a,rngH, rngL,--len);
}
return i;
}
int main() {
int a[] = {4, 1, 3, 1, 3, 2};
int total = within(a,3,2,6);
printf("\n");
printf("Total :%d\n",total);
return 0;
}
I am trying to count the number of elements greater than the element on the right side of the array. Here my function goes.
int* SurpassersKing(int input1_size, int* input1,int* output_size)
{
int i,k;
int count[input1_size];
for (i = 0; i < input1_size; i++)
count[i] = 0;
for ( i = 0; i < input1_size; i++)
{
for ( k = i + 1; k <input1_size; k++)
{
if (input1[i] < input1[k]) {
count[i]++;
}
}
}
return count;
}
This is my function where I am counting greater elements in an array.
So in this following code snippet i have wriiten the main function , declaring all the veriable like output_size,counting array ,i ,k as an index for the arrays and printing the stuff , and calling counting function .
int main() {
int output_size;
int* output;
int ip1_size = 0;
int ip1_i;
scanf("%d\n", &ip1_size);
int ip1[ip1_size];
for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
int ip1_item;
scanf("%d", &ip1_item);
ip1[ip1_i] = ip1_item;
}
output = SurpassersKing(ip1_size,ip1,&output_size);
int output_i;
for(output_i=0; output_i < output_size; output_i++) {
printf("%d\n", output[output_i]);
}
return 0;
}
but i am not getting the output required so what can i do to improve this.
Your logic to calculate the count of the numbers to the right side is correct. Only problem is you can't return arrays like that from a function. Try following:
Replace
int count[input1_size];
with
int * count = malloc(input1_size*sizeof(int));
And then in the main function
Add
free(output);
just before the return statement.
Oso your code has a few errors i found when i tried to compile.
This is a c code so use #include
Inside the function SurpassersKing you are trying to return array count which is not allowed. Never return local variables unless it is dynamically created.
The output_size never gets initilized.
This is the final code:
#include <stdio.h>
#include<stdlib.h>
int* SurpassersKing(int input1_size, int* input1)
{
int i,k;
int * count = (int*)malloc(input1_size*sizeof(int));
for (i = 0; i < input1_size; i++)
*(count + i) = 0;
for ( i = 0; i < input1_size; i++)
{
for ( k = i + 1; k <input1_size; k++)
{
if (input1[i] < input1[k]) {
count[i]++;
}
}
}
return count;
}
int main() {
// your code goes here
int output_size;
int* output;
int ip1_size = 0;
int ip1_i;
int output_i;
printf("Enter the size:\n");
scanf("%d",&ip1_size);
int ip1[ip1_size];
for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
scanf("%d",%ip1[ip1_i]);
}
output = SurpassersKing(ip1_size,ip1);
output_size = ip1_size;
for(output_i=0; output_i < output_size; output_i++) {
printf("%d\n",output[output_i]");
}
return 0;
}
Okay so I've tried to print and Array and then reverse is using another array But I'm trying to create a For Loop that will take an array and reverse all of the elements in place without me having to go through the process of creating an entirely new array.
My for loop is running into some problems and I'm not sure where to go from here...i'm using i to take the element at the end and move it to the front and then j is being used as a counter to keep track of the elements...if there is an easier way to do this Any suggestions would be appreciated.
I'm New to this programming language so any extra info is greatly appreciated.
#include <stdlib.h>
#include <time.h>
int Random(int Max) {
return ( rand() % Max)+ 1;
}
void main() {
const int len = 8;
int a[len];
int i;
int j = 0;
Randomize() ;
srand(time(0));
//Fill the Array
for (i = 0; i < len; ++i) {
a[i] = rand() % 100;
}
//Print the array after filled
for (i = 0; i < len; ++i) {
printf("%d ", a[i]);
}
printf("\n");
getchar();
//Reversing the array in place.
for (i = a[len] -1; i >= 0, --i;) {
a[i] = a[j];
printf("%d ", a[j]);
j++;
}
}
A while loop may be easier to conceptualize. Think of it as starting from both ends and swapping the two elements until you hit the middle.
i = len - 1;
j = 0;
while(i > j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i--;
j++;
}
//Output contents of now-reversed array.
for(i = 0; i < len; i++)
printf("%d ", a[i])
void reverse_range(int* buffer, int left, int right)
{
while (left < right)
{
int temp = buffer[left];
buffer[left++] = buffer[right];
buffer[right--] = temp;
}
}
call it to reverse array
int a[3] = {1, 2, 3};
reverse_range(a, 0, 2);
You are on the right track but need to think about that last for loop a little more and the assignment operation inside. The loop initialization is off, since i = a[len] - 1 will copy the value of the last entry to i. Since that value is a random number, your index will probably start out of bounds.
Next, you're copying half of the array to the other half and then back. That loop does the following:
a[7] = a[0]
a[6] = a[1]
a[5] = a[2]
a[4] = a[3] ...
At this point you've lost all of the initial values in a[4] through a[7].
Try this:
for( i = 0; i < len / 2; i++ ){
int temp = a[i];
a[i] = a[len - i];
a[len - i] = temp;
}
Use a debugger and step through the loop watching the value of i, temp, and each element in the array
Just my 2 cents...
#include <stdlib.h>
#include <stdio.h>
int main() {
int arry[] = {0, 1, 2, 3, 4, 5};
int* s = arry;
int* e = arry + (sizeof(arry) / sizeof(arry[0])) - 1;
while (s < e) {
*e ^= *s;
*s ^= *e;
*e ^= *s;
s++;
e--;
}
for (size_t i = 0; i < (sizeof(arry) / sizeof(arry[0])); i++) {
fprintf(stderr, "%d, ", arry[i]);
}
fprintf(stderr, "\n");
}
For starters, instead of this:
for (i = a[len] -1; i >= 0, --i;) {
you want this:
for (i = len-1; i >= 0, --i;) {
but you also only want to go half-way through the array, so it would be
for (i = len-1; i > j, --i;) {
Try this;
#include <stdlib.h>
#include <time.h>
int Random(int Max) {
return ( rand() % Max)+ 1;
}
void main() {
const int len = 8;
int a[len];
int i,end;
int j = 0;
Randomize() ;
srand(time(0));
//Fill the Array
for (i = 0; i < len; ++i) {
a[i] = rand() % 100;
}
//Print the array after filled
for (i = 0; i < len; ++i) {
printf("%d ", a[i]);
}
printf("\n");
getchar();
for (i = 0; i < n/2; i++) {
t = a[i];
a[i] = a[end];
a[end] = t;
end--;
}
}
Hope this helps... :)
Just for suggestion. Try to use meaningful variable name instead of just i,a.... That will help you while writing a bigger code. :)
You can reverse an array in place you don't need an auxiliary array for that, Here is my C code to do that
#include <stdio.h>
int main(void)
{
int arr[5]={1,2,3,4,5};
int size=sizeof(arr)/sizeof(int);
int success= reverse(arr,size);
if(success==1)
printf("Array reversed properly");
else
printf("Array reversing failed");
return 0;
}
int reverse(int arr[], int size)
{
int temp=0;
int i=0;
if(size==0)
return 0;
if(size==1)
return 1;
int size1=size-1;
for( i=0;i<(size/2);i++)
{
temp=arr[i];
arr[i]=arr[size1-i];
arr[size1-i]=temp;
}
printf("Numbers after reversal are ");
for(i=0;i<size;i++)
{
printf("%d ",arr[i]);
}
return 1;
}
Here's an easy and clean function for flipping arrays of all sizes. Change the parameters according to your type of array:
void flipArray(int *a, int asize){
int b[asize];
int *b_p = b;
for(int i=0; i<asize; i++){
//backwardsOrientation = (arraySize-1)-increment
b_p[asize-1-i] = a[i];
}
for(int i=0; i<asize; i++){
a[i] = b_p[i];
}
}
If you are not interested in writing functions for any numeric type, try macros for this task. This code same working with any built-in numeric type: int, float, double.
It has not a support for strings, since any string is ending on the character the NULL character \0. More a controlled version my similar answer is here https://stackoverflow.com/a/42063309/6003870 and contains solution for reverse a string.
A full code
#include <stdio.h>
// print items of an array by a format
#define PRINT_ARRAY(array, length, format) \
{ \
putchar('['); \
for (size_t i = 0; i < length; ++i) { \
printf(format, array[i]); \
if (i < length - 1) printf(", "); \
} \
puts("]"); \
}
// reverse an array in place
#define REVERSE_ARRAY(array, length, status) \
if (length > 0) { \
for (int i = 0; i < length / 2; ++i) { \
double temp; \
temp = array[i]; \
array[i] = array[length - i - 1]; \
array[length - i - 1] = temp; \
} \
*status = 0; \
} \
else if (length < 0) *status = -1; \
else *status = 1;
#define SUCCESS_REVERSE_ARRAY_MSG "An array succefully reversed"
#define FAILED_REVERSE_ARRAY_MSG "Failed reverse for an array"
#define NO_CHANGED_REVERSE_ARRAY_MSG "An array no changed"
/*
Print message about status reverse an array
*/
static void
print_msg_reverse_array_status(const int status)
{
if (status == 0) printf("Status: %s\n", SUCCESS_REVERSE_ARRAY_MSG);
else if (status == -1) printf("Status: %s\n", FAILED_REVERSE_ARRAY_MSG);
else if (status == 1) printf("Status: %s\n", NO_CHANGED_REVERSE_ARRAY_MSG);
}
int
main (const int argc, const char *argv[])
{
// keep value of status
int status;
puts("\tExample reverse of an integer array");
int arr_int[5] = {1, 2, 3, 4, 5};
status = 0;
PRINT_ARRAY(arr_int, 5, "%d");
REVERSE_ARRAY(arr_int, -1, &status);
// will be an error, since a length is less 0, and the array is not changed
print_msg_reverse_array_status(status);
PRINT_ARRAY(arr_int, 5, "%d");
status = 0;
REVERSE_ARRAY(arr_int, 0, &status);
// a length is equal to 0, so an array is not changed
print_msg_reverse_array_status(status);
PRINT_ARRAY(arr_int, 5, "%d");
status = 0;
REVERSE_ARRAY(arr_int, 5, &status);
print_msg_reverse_array_status(status);
PRINT_ARRAY(arr_int, 5, "%d");
puts("\n\tExample reverse of an float array");
float arr_float[5] = {0.78, 2.1, -3.1, 4, 5.012};
status = 0;
PRINT_ARRAY(arr_float, 5, "%5.3f");
REVERSE_ARRAY(arr_float, 5, &status);
print_msg_reverse_array_status(status);
PRINT_ARRAY(arr_float, 5, "%5.3f");
puts("\n\tExample reverse of an double array");
double arr_double[5] = {0.00001, 20000.002, -3, 4, 5.29999999};
status = 0;
PRINT_ARRAY(arr_double, 5, "%8.5f");
REVERSE_ARRAY(arr_double, 5, &status);
print_msg_reverse_array_status(status);
PRINT_ARRAY(arr_double, 5, "%8.5f");
return 0;
}
I am used the GCC for compilation and your result must be as next
Example reverse of an integer array
[1, 2, 3, 4, 5]
Status: Failed reverse for an array
[1, 2, 3, 4, 5]
Status: An array no changed
[1, 2, 3, 4, 5]
Status: An array succefully reversed
[5, 4, 3, 2, 1]
Example reverse of an float array
[0.780, 2.100, -3.100, 4.000, 5.012]
Status: An array succefully reversed
[5.012, 4.000, -3.100, 2.100, 0.780]
Example reverse of an double array
[ 0.00001, 20000.00200, -3.00000, 4.00000, 5.30000]
Status: An array succefully reversed
[ 5.30000, 4.00000, -3.00000, 20000.00000, 0.00000]
Testing environment
$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 8.6 (jessie)
Release: 8.6
Codename: jessie
$ uname -a
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux
$ gcc --version
gcc (Debian 4.9.2-10) 4.9.2
public static void ReverseArrayInPlace()
{
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
int end = arr.Length - 1;
foreach (var item in arr)
{
Console.WriteLine(item);
}
for (int i = 0; i < arr.Length/2; i++)
{
var temp = arr[i];
arr[i] = arr[end];
arr[end] = temp;
end--;
}
Console.WriteLine("--------------------------");
foreach (var item in arr)
{
Console.WriteLine(item);
}
}
Here is how I did it in Java
It will be exactly same in C or C++ too
class Solution {
private void reverseHelper(char s[],int i, int j){
if(i >= j) return;
char temp = s[i];
s[i] = s[j];
s[j] = temp;
reverseHelper(s,i+1,j-1);
}
public void reverseString(char[] s) {
reverseHelper(s,0,s.length-1);
}
}
The space complexity here is O(1)
#include<Stdio.h>
#include<string.h>
#define max 25
int main()
{
char arr[max]="0123456789";
strrev(arr);
atoi(arr);
return 0;
}
//you can also use built in functions such as strrev(); string reverse atoi just
//changes string into integer