Search in array of char* in c - c

I am trying to work out what is wrong with the process of scanning the char* star value.
struct Property {
unsigned int shift;
int mask;
char * str[4];
}
human [] = {
{0, 1, {"fe", "ma"}},
{1, 1, {"du", "cl"}},
{2, 1, {"nh", "ha"}},
{3, 1, {"sk", "tr"}},
{4, 3, {"bn", "rd", "bw", "bk"}},
{6, 3, {"bu", "ge", "gy", "da"}},
};
int find(char* w){
int i;
int j;
for (i = 0; i < (sizeof(human)/ sizeof(struct Property)); i++){
for (j = 0; j < 4 ; j++){
if (human[i].str[j] == w)
return i;
}
}
}
int main(){
char* w ;
scanf("%s", w);
int k = find(w);
printf("k is %d", k);
return 0;
}
Clion compiler says that 'pointer parameter w can be pointer to const'. So in my main() I tried to use my function scanning w as array or char*.
Upd with suggestions.
struct Property {
unsigned int shift;
int mask;
char * st[4];
} human [] = {
{0, 1, {"fe", "ma"}},
{1, 1, {"du", "cl"}},
{2, 1, {"nh", "ha"}},
{3, 1, {"sk", "tr"}},
{4, 3, {"bn", "rd", "bw", "bk"}},
{6, 3, {"bu", "ge", "gy", "da"}},
};
int find(char* w)
{
int i;
int j;
for (i = 0; i < (sizeof(human)/ sizeof(struct Property)); i++)
{
for (j = 0; j < 4 ; j++)
{
if ((strcmp(human[i].st[j], w)) == 0)
return i;
else
continue;
}
}
return -1;
}
int main()
{
char* w = malloc(sizeof(char*));
scanf("%99s", w);
int k = find(w);
if (k != -1 )
printf("k is %d", k);
if (k == -1) { printf("%s","Error");}
return 0;
}
Still no output.I truly believe, that something is still wrong

There are couple of problems -
Allocate memory to w. Other wise passing an uninitialized pointer to scanf is Undefined behavior. (You can allocate the memory dynamically too)
char w[100];
if( scanf("%99s",w) != 1 ){
/* Handle error */
}
Comparing two strings can be done using strcmp. Using == operator is not the correct way.
if ( strcmp(human[i].str[j], w) == 0 )
Also you should always return something from the function. It is supposed to return something even if nothing matches. But you didn't follow that contract. Compiler complained.
for(..){
...
}
return -1; /* denoting invalid index - search failed*/
You can easily make the argument passed as const char * because you are not changing it's value (the content of the string).

Related

How to insert an element at the last position in an array dynamically in C?

I'm a newbie in C and trying to insert a number at the last position in C such that, the size of the array is changed over time.
The first array is like this:
temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
Now how can we insert those values in temp that are != 0 to a new array which has a defined length of 5: tmp
Here's what I'm trying:
void push(int arr[], int value, int current){
arr[current] = value;
}
int main(void) {
int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
int tmp[5];
for(int i=0;;i++){
if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
// I don't put i < 10 int the loop initialization. Since the tmp's length is just 5
}
// I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
// it's length will change (increase by 1).
// So next loop round, the new value will be added to the last position
// But I failed to do so
}
Current output:
exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens
Desired output:
tmp[5] = {1, 2, 5, 6, 8}
C does not have dynamic arrays. Arrays have a fixed size determined from their definition. You can allocate objects with malloc() that behave as arrays, but you must keep track of their allocated size separately. Appending an element requires reallocating the array so its address in memory may change.
In your code, tmp has a fixed size of 5 elements. You could maintain an index specifying how many elements are used and update that in the push function:
#include <stdio.h>
int push(int arr[], int value, size_t size, size_t *current) {
if (*current < size) {
arr[(*current)++] = value;
return 0;
} else {
/* array is full */
return -1;
}
}
int main(void) {
int temp[10] = { 1, 2, 0, 0, 5, 6, 0, 8, 0, 0 };
int tmp[5];
size_t pos = 0;
for (size_t i = 0; i < sizeof(temp) / sizeof(temp[0]); i++) {
if (temp[i])
push(tmp, temp[i], sizeof(tmp) / sizeof(tmp[0]), &pos);
}
printf("tmp:");
for (size_t i = 0; i < pos; i++) {
printf(" %d", tmp[i]);
}
printf("\n");
return 0;
}
Your definition of push requires the 3rd parameter to be the position to place the element. However, the expression sizeof(tmp)/sizeof(tmp[0]) provides the size of the array and it will thus index past the array's last element (because indexes in C go from 0..n-1). This in itself can cause a segmentation fault.
Neither did you provide a terminating condition for your loop. It will continue forever.
Your solution could simply be:
for(int i=0, j=0; i<10; i++)
if(temp[i]) push(tmp, temp[i], j++);
What is
trying to insert a number at the last position in C
Although you got an explanatory answer by David Ranieri, I want to show the simplest approach keeping in mind that you are a newbie. Look at this code:-
Code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
void push(int arr[], int value, int current){
arr[current] = value;
}
int main(void) {
int temp[SIZE] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
int *tmp = NULL, count = 0, i, j;
// Loop for counting non-zero values in temp array.
for (i = 0; i < SIZE; ++i)
if (temp[i])
count++;
// Dynamically allocating space for tmp along with checking errors if any.
if((tmp = (int *)malloc(count * sizeof(int))) == NULL)
{
printf("Memory Not Available.\n");
exit(-1);
}
for(i = 0, j = 0; i < SIZE; i++){
if(temp[i])
push(tmp, temp[i], j++);
}
// Printing your desired output.
for(i = 0; i < count; ++i)
printf("%d\t", tmp[i]);
free(tmp);
}
Here the size of tmp will change according to the non-zero elements of temp.
Now if you want to make the temp array a dynamic array, use the same approach as used for the tmp, just ask the user at run-time to input the size of temp and then its elements/values as well.
The problem is that you are accessing outside of the bounds of temp because you don't specify when to stop in the loop.
For a dynamic array, when you don't know the number of elements before hand, you can use realloc:
#include <stdio.h>
#include <stdlib.h>
void push(int **arr, size_t *size, int value)
{
int *ptr = realloc(*arr, sizeof(*ptr) * (*size + 1));
if (ptr == NULL)
{
free(*arr);
perror("push");
exit(EXIT_FAILURE);
}
ptr[*size] = value;
*size += 1;
*arr = ptr;
}
int main(void)
{
int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
int *arr = NULL;
size_t size = 0;
for (size_t i = 0; i < sizeof temp / sizeof temp[0]; i++)
{
if (temp[i])
{
push(&arr, &size, temp[i]);
}
}
for (size_t i = 0; i < size; i++)
{
printf("%d\n", arr[i]);
}
free(arr);
}
Notice that even if it ilustrates the use of a growable array, this example is considered bad code, a more robust design will take care of the size and is able to manage the allocation and deallocation by itself:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int *data;
size_t size;
} dyn_array;
dyn_array *create_dyn_array(void)
{
dyn_array *arr = calloc(1, sizeof *arr);
if (arr == NULL)
{
perror("create_dyn_array");
exit(EXIT_FAILURE);
}
return arr;
}
void destroy_dyn_array(dyn_array *arr)
{
free(arr->data);
free(arr);
}
void push_dyn_array(dyn_array *arr, int value)
{
int *ptr = realloc(arr->data, sizeof(*ptr) * (arr->size + 1));
if (ptr == NULL)
{
destroy_dyn_array(arr);
perror("push_dyn_array");
exit(EXIT_FAILURE);
}
ptr[arr->size++] = value;
arr->data = ptr;
}
int main(void)
{
int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
dyn_array *arr = create_dyn_array();
for (size_t i = 0; i < sizeof temp / sizeof temp[0]; i++)
{
if (temp[i])
{
push_dyn_array(arr, temp[i]);
}
}
for (size_t i = 0; i < arr->size; i++)
{
printf("%d\n", arr->data[i]);
}
destroy_dyn_array(arr);
}
This is better, but still not perfect because we are limited to a fixed type (int), with some extra memory we can adapt our code to support any type (using the generic type void *), as an optimization, the dynamic array grows by a factor of 2 instead of calling realloc on each iteration:
#include <stdio.h>
#include <stdlib.h>
/* Begin - This API is supposed to be in a header */
typedef struct
{
void **data;
size_t room;
size_t size;
} dynarray;
dynarray *dynarray_create(void)
{
dynarray *array = calloc(1, sizeof *array);
if (array == NULL)
{
return NULL;
}
array->data = malloc(sizeof(void *));
if (array->data == NULL)
{
free(array);
return NULL;
}
array->room = 1;
return array;
}
void *dynarray_push(dynarray *array, void *data)
{
if (data == NULL)
{
return NULL;
}
if (array->size == array->room)
{
array->room *= 2;
void *ptr = realloc(array->data, array->room * sizeof(void *));
if (ptr == NULL)
{
return NULL;
}
array->data = ptr;
}
array->data[array->size++] = data;
return data;
}
void *dynarray_get(dynarray *array, size_t index)
{
return array->data[index];
}
size_t dynarray_size(dynarray *array)
{
return array->size;
}
void dynarray_destroy(dynarray *array, void (*func)(void *data))
{
if (func != NULL)
{
for (size_t i = 0; i < array->size; i++)
{
func(array->data[i]);
}
}
free(array->data);
free(array);
}
/* End API */
int main(void)
{
int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
dynarray *array = dynarray_create();
if (array == NULL)
{
perror("dynarray_create");
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < sizeof temp / sizeof temp[0]; i++)
{
if (temp[i])
{
if (dynarray_push(array, &temp[i]) == NULL)
{
perror("dynarray_push");
exit(EXIT_FAILURE);
}
}
}
size_t size = dynarray_size(array);
for (size_t i = 0; i < size; i++)
{
int *data = dynarray_get(array, i);
printf("%d\n", *data);
}
dynarray_destroy(array, NULL);
}

recursive find number in between in C

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;
}

How to return largest two numbers in array in C?

So, I have this so far. I'm trying to find the two largest numbers in an array and return them. I looked up a lot of resources online, and most of them say "call by reference" is the way to go. But I've no idea how to make it work with my program. For example, I saw this example online:
void Calculate(int x, int y, int* prod, int* quot)
{
*prod = x*y;
*quot = x/y;
}
int x = 10,y = 2, prod, quot;
Calculate(x, y, &prod, &quot)
How does the above program actually "return"? How do I print the return values to the console?
#include "stdio.h"
void largest_two( int numbers[], int len, int *largest, int *next_largest){
int i, temp;
*largest = numbers[0];
*next_largest = numbers[1];
if(*largest < *next_largest){
temp = *next_largest;
*largest = *next_largest;
*next_largest = temp;
}
for (i=0; i<sizeof(numbers); i++) {
if(numbers[i]>= *largest){
*largest = numbers[i];
*next_largest = *largest;
}
else if ( numbers[i] > *next_largest){
*next_largest = numbers[i];
}
}
}
int main() {
int numbers[] = {3, 1, 2, 3, 6, 2, 8, 0, 0, 0};
int len = 3;
int largest, next_largest;
//==>??? printf("%d %d", largest_two(numbers, len, &largest, &next_largest));
}
Sides' from the pointer issues (you should read a tutorial / book on them), your main problem is that you're attempting to print the single return value of a function with return type void which means it won't return at all.
Your code:
int main() {
int numbers[] = {3, 1, 2, 3, 6, 2, 8, 0, 0, 0};
int len = 10; // sizeof(numbers)
int largest, next_largest;
largest_two(numbers, len, &largest, &next_largest);
printf("%d %d", largest, next_largest);
}
Keep in mind this is still not entirely correct, but it does adress your problem of printing the numbers.
Also, passing len means you shouldn't do this for (i=0; i<sizeof(numbers); i++) but this instead for (i=0; i<len; i++)
Firstly, this line:
for (i=0; i<sizeof(numbers); i++)
is not correct. You want this to be instead:
for (i=0; i<len; i++)
which should be passed to largest_two() as sizeof numbers/sizeof numbers[0], which is the actual length of the array.
I also suggest setting largest and next_largest to INT_MIN from <limits.h>, and then finding these values from their. It seems you are also having trouble with pointers, and it would be best to use them only when needed.
Here is an example which simplifies your approach, which finds the largest and second largest element in one loop of the array. It also only uses pointers when needed.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define ARRAYSIZE(x) (sizeof x/sizeof x[0])
void largest_two(int numbers[], size_t len, int *largest, int *next_largest);
int main(void) {
int numbers[] = {3, 1, 2, 3, 6, 2, 8, 0, 0, 0};
int largest, next_largest;
largest_two(numbers, ARRAYSIZE(numbers), &largest, &next_largest);
printf("largest = %d\nnext_largest = %d\n", largest, next_largest);
}
void largest_two(int numbers[], size_t len, int *largest, int *next_largest) {
int max, smax;
max = smax = INT_MIN;
for (size_t i = 0; i < len; i++) {
if (numbers[i] > max) {
smax = max;
max = numbers[i];
} else if (numbers[i] > smax && numbers[i] < max) {
smax = numbers[i];
}
}
*largest = max;
*next_largest = smax;
}
Output:
largest = 8
next_largest = 6
Second dataset:
int numbers[] = {3, 1, 6, 3, 6, 2, 8, 0, 8, 7};
Output:
largest = 8
next_largest = 7

Find count of missing elements in an unsorted array of integers

How can I find how many elements are missing from an array of integers in C, if some of the numbers are duplicated?
Assume the array is int array = {1, 2, 1, 5, 4} and there should be numbers up to 6. Then, the program/function should output/return 2, as there are 2 elements missing (3, 6).
Note: 0 is not counted as a missing number, nor can it be present in an array.
This way?
int countMissing(int *x, int arrLen, int bound)
{
int * y = malloc ((bound + 1) * sizeof(int));
int i = 0;
int missing = 0;
memset(y,0,sizeof(int)*(bound+1));
for(i = 0; i<arrLen; i++)
{
if(x[i]<=bound)
{
y[x[i]] = 1;
}else
{
// error handling e.g.
return -1;
}
}
for(i = 1; i<=bound; i++)
{
if(y[i]==0) missing++;
}
free(y);
return missing;
}
Usage:
int main(void)
{
int array [] = {1, 2, 1, 5, 4};
printf("%d", countMissing(array, 5, 10));
return 0;
}
Output: 6.

Reversing an array In place

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

Resources