Reversing an array In place - c
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
Related
Im trying to find the max and min value and its respective index. However I cant get the indexmin
Find the minimum element of the array and its corresponding index. I can't get the the minimum index to work. Do I add else statement under each if statement? #include<stdio.h> int main() { int array[10]={1,2,3,4,5,6,7,8,9,10} , i; **//finding max and min, and its respective index** int max = array[0] , min = array[0]; int indmin , indmax; for( i = 0 ; i < 10 ; i++ ) { if(array[i] > max) { max = array[i]; indmax = i; } if(array[i] < min) { min = array[i]; indmin = i; } } //print the max and min value and its indexs printf("\nMaximum element is %d\t index is %d", max , indmax); printf("\nMinimum element is %d\t index is %d", min , indmin); }
Initialize indmin and indmax. When defining the array leave out the size so it's derived from the data. When iterating over the array use sizeof(array) / sizeof(*array) to let compiler determine the size of the array instead of hard-coding it. Minimize scope of variable i. Use a function to print output for less duplication: #include <stdio.h> void print(const char *prompt, int value, int index) { printf("%s element is %d\t index is %d\n", prompt, value, index); } int main() { int array[]={1,2,3,4,5,6,7,8,9,10}; int min = array[0]; int indmin = 0; int max = array[0]; int indmax = 0; for(int i = 0; i < sizeof(array) / sizeof(*array); i++) { if(array[i] > max) { max = array[i]; indmax = i; } if(array[i] < min) { min = array[i]; indmin = i; } } print("Maximum", max, indmax); print("Minimum", min, indmin); } You could refactor this by creating a struct to keep the value and index together: #include <stdio.h> struct value_index { int value; int index; }; void print(const char *prompt, struct value_index *vi) { printf("%s element is %d\t index is %d\n", prompt, vi->value, vi->index); } int main() { int array[]={1,2,3,4,5,6,7,8,9,10}; struct value_index min = { array[0], 0 }; struct value_index max = { array[0], 0 }; for(int i = 0; i < sizeof(array) / sizeof(*array); i++) { if(array[i] > max.value) { max.value = array[i]; max.index = i; } if(array[i] < min.value) { min.value = array[i]; min.index = i; } } print("Maximum", &max); print("Minimum", &min); } Or you could realize that you only need the original array along with the two indices. To make my version even better than #Fe2O3's answer, I used a macro to make mine smaller (and if bait works then I will claim mine is easier to read) :-) #include <stdio.h> void print(const char *prompt, int *arr, int index) { printf("%s element is %d\t index is %d\n", prompt, arr[index], index); } int main() { int array[]={1,2,3,4,5,6,7,8,9,10}; int indmin = 0; int indmax = 0; for(int i = 0; i < sizeof(array) / sizeof(*array); i++) { #define CMP_AND_SET(OP, V) if(array[i] OP array[V]) V = i CMP_AND_SET(<, indmin); CMP_AND_SET(>, indmax); #unset CMP_AND_SET } print("Maximum", array, indmax); print("Minimum", array, indmin); } Building on #Fe2O3's branchless idea combined with an initialized array which I find to compact and quite readable: indmin = (int[]) { indmin, i }[array[i] < array[indmin]]; indmax = (int[]) { indmax, i }[array[i] > array[indmax]]; By using (a < b) <=> -1 * (-a > -b) you can write the last one as (note: UB if array contains INT_MIN): indmax = (int[]) { indmax, i }[-array[i] < -array[indmax]]; I would use a local macro to reduce code duplication by using macro to generate either the first version by passing in the operator (see above) or the 2nd version by passing in a factor F: #define MINMAX(V, F) V = (int[]) { V, i }[F * array[i] < F * array[V]] indmin = MINMAX(indmin, 1); indmax = MINMAX(indmax, -1); I am totally cheating but you can shuffle the min and max elements to fixed positions within the source array. No storage overhead. This would be the opposite of branchless. #include <stdio.h> void print(const char *prompt, int value) { printf("%8s = %3d\n", prompt, value); } int swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; return 0; } int main(void) { int arr[] = { 1, 2, 3, 4, 42, 5, -42, 6, 7, 8, 9, 10 }; const int min = 0; const int max = sizeof arr/sizeof *arr - 1; for(int i = 1; i < max + 1; i++ ) arr[i] < arr[min] && swap(arr + i, arr + min) || arr[i] > arr[max] && swap(arr + i, arr + max); print("min", arr[min]); print("max", arr[max]); }
Leaving variables uninitialised is asking Demon of Hard-To-Find Bugs to co-author your code. Define variables close to where they are used to increase clarity. And, don't define more variables than you need. (Common beginner mistake to make another copy "just in case"...) // use the spacebar to increase readability #include <stdio.h> int main() { // let the compiler assign the size of an initialised array int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // use fewer variables int indmin = 0, indmax = 0; // don't compare an element (arr[0]) to itself for( int i = 1 ; i < sizeof array/sizeof array[0]; i++ ) if( array[ i ] > array[ indmax ] ) indmax = i; // updated else if( array[ i ] < array[ indmin ] ) indmin = i; // updated // don't add unnecessary braces (imho) // this isn't the 17th century in need of needless filligree. // use '\n' at the END of output. sometimes needed to 'flush' output buffer printf("Maximum element is %d\t index is %d\n", array[ indmax ] , indmax); printf("Minimum element is %d\t index is %d\n", array[ indmin ] , indmin); return 0; } Maximum element is 10 index is 9 Minimum element is 1 index is 0 EDIT: So, there's a friendly competition going on in this question... :-) How's this: #include <stdio.h> int main() { // let the compiler assign the size of an initialised array // use shorter names to expose operations (not lengthy variable names) int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int iMin = 0, iMax = 0; // don't compare an element to itself for( int i = 1; i < sizeof arr/sizeof arr[0]; i++ ) { // use "branchless" coding for speed. int n = arr[i] > arr[iMax]; iMax = n*i + !n*iMax; n = arr[i] < arr[iMin]; iMin = n*i + !n*iMin; } // reduce duplication of static data char *fmt = "%s element is %d\t index is %d\n"; printf( fmt, "Maximum", arr[ iMax ], iMax ); printf( fmt, "Minimum", arr[ iMin ], iMin ); return 0; } Same output. Ball's in your court #Allan :-) EDIT: There has been an advance on the last offering that needs to be addressed... Here we go whole-hog, splurging-out with a third 'container' (mm[0]) to catch all those indexes that satisfy neither conditional ('<' & '>'). AND, a 4th 'container' (mm[3]) that doesn't change from being initialised to 0, the index of the 1st element. Besides being cryptic (not advised), this may-or-may-not be more expensive with its multiple array offset calculations... But, it's fun to look at... #include <stdio.h> int main() { // added two elements to show 0 and nElem are not 'flukes' // this really does find and report the min/max values int arr[] = { 1, 2, 3, 4, 42, 5, -42, 6, 7, 8, 9, 10 }; int i, mm[1 + 2 + 1] = { 0 }; // assign 'i' to mm[ 0 or 1 or 2 ]. 0=latest, 1=max, 2=min, (3 unaffected) for( i = 1; i < sizeof arr/sizeof arr[0]; i++ ) mm[ (arr[i] > arr[mm[1]]) + 2*(arr[i] < arr[mm[2]]) ] = i; mm[ 0 ] = i-1; // always pick up the last index. Thanks #A Wind! // now... this is getting silly!! char *fmt = "%5s = %3d # arr[%d]\n"; char *type[] = { "last", "max", "min", "first" }; i = 3; do printf( fmt, type[i], arr[ mm[i] ], mm[i] ); while( --i >= 0 ); return 0; } first = 1 # arr[0] min = -42 # arr[6] max = 42 # arr[4] last = 10 # arr[11] Y'know... This might be interesting to try to apply to 3-way branching as is needed for binary searching; determining '<', '=' or '>'... Hmmm... EDIT: (another variation on a theme at the suggestion of a worthy competitor :-) #include <stdio.h> int main() { struct { char *label; int ind; } mm[] = { { "last" }, { "maximum" }, { "minimum" }, { "first" }, }; int i, arr[] = { 1, 2, 3, 4, 42, 5, -42, 6, 7, 8, 9, 10 }; for( i = 1; i < sizeof arr/sizeof arr[0]; i++ ) mm[ (arr[i] > arr[mm[1].ind]) + 2*(arr[i] < arr[mm[2].ind]) ].ind = i; mm[ 0 ].ind = --i; // always pick up the last index. Thanks #A Wind! for( i = sizeof mm/sizeof mm[0]; --i >= 0; /* space for rent */ ) printf( "%8s = %3d # arr[%d]\n", mm[i].label, arr[ mm[i].ind ], mm[i].ind ); return 0; } EDIT: Trying to cover ALL the bases, here are three more ways to skin a cat /* Minimalist */ #include <stdio.h> int main() { int mm[3] = { 0 }, arr[] = { 1, 2, 3, 4, 42, 5, 6, 7, 8, 9, 10 }, i = sizeof arr/sizeof arr[0]; while( --i ) mm[ 2*(arr[i] > arr[mm[2]]) + (arr[i] < arr[mm[1]]) ] = i; char *fmt = "arr[%d] = %3d M%simum\n"; printf( fmt, mm[1], arr[mm[1]], "in" ); printf( fmt, mm[2], arr[mm[2]], "ax" ); return 0; } /* Recursive - for brevity, excluding the index; just reporting two values */ #include <stdio.h> int amin( int a[], int i ) { // NB: "amin", not "main" int j = --i ? amin( a, i ) : i; return (a[j]<a[i])*j + (a[j] > a[i])*i; } int amax( int a[], int i ) { int j = --i ? amax( a, i ) : i; return (a[j]>a[i])*j + (a[j]<a[i])*i; } int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }, sz = sizeof arr/sizeof arr[0]; char *fmt = "M%simum: %3d\n"; printf( fmt, "in", arr[ amin(arr, sz) ] ); printf( fmt, "ax", arr[ amax(arr, sz) ] ); return 0; } /* And, simply brute force using a library function */ #include <stdio.h> #include <stdlib.h> int cmp( const void *a, const void *b ) { return *(int*)a - *(int*)b; } int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, sz = sizeof arr/sizeof arr[0]; qsort( arr, sz, sizeof arr[0], cmp ); char *fmt = "M%simum: %3d\n"; printf( fmt, "in", arr[ 0 ] ); printf( fmt, "ax", arr[ --sz ] ); // again, thanks to #A Wind return 0; } Many ways to skin a cat.
Write a C function GetEvenNumber
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; }
My code doesn't returns an output. It returns only exit code
I wanted to reverse half of the arrays inputs with the other half. #include <stdio.h> #include <math.h> void main() { double size = 5; int array[5] = {1, 2, 3, 4, 5}; int half_size = ceil(size / 2); for(int i = 0; i < half_size; i++){ int a; int rev = size - (i + 1); array[i] = a; array[i] = array[rev]; array[rev] = a;`enter code here` } printf("%d", array[5]); }
I agree with #Eugene Sh.'s and #FredK's suggestions. The line array[5] in the line printf("%d", array[5]); is out of bound since array only have indexes from 0 to 4. Since I assume you want to print out the last element in the array, you should change it to printf("%d", array[4]);. Another thing is that your assignment expression array[i] = a; is wrong. I assume the expression is part of the swapping process from element in index i with element in index rev. If that was the case then you should change it to a = array[i]; instead. I update you code according to my suggestion and it outputs the correct result. I added the for loop to verify that the array values are reversed for testing purpose. You can delete it after you're done testing. #include <math.h> int main() { double size = 5; int array[5] = {1, 2, 3, 4, 5}; int half_size = ceil(size / 2); for(int i = 0; i < half_size; i++){ int a; int rev = size - (i + 1); a = array[i]; array[i] = array[rev]; array[rev] = a; } for (int i = 0; i < size; ++i) { printf("%d ", array[i]); } printf("\n"); printf("%d", array[4]); }
palindrome checker algorithm
i'm having problems writing this excercise. this should evaluate if a given array contains a palindrome sequence of numbers, the program builds correctly but doesn't run (console remains black). where am i wrong on this? thanks for all help! #include <stdio.h> #include <stdlib.h> #define SIZE 15 //i'm using const int as exercise demand for it //should i declare size as int when giving it to function? also if it's been declared? //i'm a bit confused about that int palindrome(const int a[], int p, int size); int main() { int a[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0}; int p = 1; //i'm not using boolean values, but i think should work anyway, right? p = palindrome(a, p, SIZE); if (p) printf("\nseries is palindrome\n"); else printf("\nseries isn't palindrome\n"); return 0; } int palindrome(const int a[], int p, int size) { int mid, j; mid = size / 2; while (p) { for (j = 0; j < (SIZE / 2); j++){ if (a[mid + (j + 1)] != a[mid - (j + 1)]) //i think i might be wrong on this, but don't know where i'm in fault p = 0; } } return p; } p.s. how can i activate debugger "watches" on Code Blocks to look at others function variables? (i put a stop on main function)
You don't need while (p) { loop. It is possible to have infinite loop here (and you have it!), because if you don't change p, this loop never stops. You mix size and SIZE in the implementation of palindrome() (mid is half of size, but the whole loop is from 0 to SIZE-1). Also it is better to move int p = 1; in the beginning of implementation of palindrome() (and to remove int p from list of it's parameters).
Just try this: int palindrome(const int a[], int p, int size) { int mid, j; mid = size / 2; for (j = 0; j < (size / 2); j++){ if (a[mid + (j + 1)] != a[mid - (j + 1)]); p = 0; break; } } return p; }
here's an alternative without p where palindrome returns 0 or 1 int palindrome(const int a[], int size) { int j , k , ret; for (j = 0 , k = size - 1 ; j < k; j++ , k--) { if (a[j)] != a[k]) { ret = 0; break; } } if(j >= k) ret = 1; return ret; } you can call palindrome in the if statement in main like this : if(palindrome(a , SIZE)) printf("\nseries is palindrome\n"); else printf("\nseries isn't palindrome\n");
unexpected result in array element with C
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); } }