I want to reverse numbers of array,
but I can't understand why it didn't run.
Thanks for explaining what does Debug Error_ Run-Time Check Failure #2 -S mean..
Thanks,
#include <stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5 };
int size, i, j;
int temp = 0;
size = sizeof(arr) / sizeof(arr[0]); //use this for changing size
printf("first_array :");
for (i = 0; i < size; i++)
{
printf("%d", arr[i]);
}
printf("\n");
for (i = 0; i <= (size / 2); i++)
{
j = size - i;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
printf("Riv_array :");
for (i = 0; i < size; i++)
{
printf("%d", arr[i]);
}
return 0;
}
Array index starts from 0 in C and your array has 5 elements so arr[4] is the last element but your code:
j = size - i;
arr[j];
when i=0 access to arr[5], this is your code error: Array index out of bound.
you should use j = size - i-1; to point to the last element of array, not j = size - i;
see this working sample (your sample code with some edit):
#include <stdio.h>
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int size, i, j;
int temp = 0;
size = sizeof(arr) / sizeof(arr[0]); //use this for changing size
printf("first_array :");
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
for (i = 0; i <= (size / 2); i++)
{
j = size - i - 1;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
printf("Riv_array :");
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
another way to reverse array using pointers:
#include <stdio.h>
void reverse(int* p, int count){
int temp;
int* q = p + count - 1; // point to the end
count /= 2;
while (count--) {
temp = *p;
*p++ = *q;
*q-- = temp;
}
}
void print_array(int *p, int count){
while (count--) printf("%d ", *p++);
printf("\n");
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int count = ((&arr)[1] - arr);
print_array(arr, count);
reverse(arr, count);
print_array(arr, count);
return 0;
}
output:
1 2 3 4 5
5 4 3 2 1
Related
I'm trying to write an iterative function that computes all the permutations of an array of numbers given in input.
Here is the code I've written so far.
void permute(int *a, int size){
int j=0, i, h=0, m;
bool flag=true;
int f = factorial(size);
int *arr, *res;
int counter=0;
arr = malloc(f*sizeof(int));
for(i=0; i<f; i++)
arr[i] = 0;
while (j < f) {
if(arr[j]<j)
{
if(j%2 == 0)
{
swap(a[0],a[j]);
} else {
swap(a[arr[j]], a[j]);
}
arr[j]++;
j=0;
} else{
arr[j] = 0;
j++;
}
printf("%d\n",a[j] );
}
}
The code doesn't compute well all the permutations and goes into a long loop. Can someone help me, please? Thanks to everyone.
Your code is close but includes some problems. For instance, the while loop
while (j < f) will assign j to a value out of bound of the array a.
Instead would you please try:
#include <stdio.h>
#include <stdlib.h>
int factorial(int x)
{
int i;
int y = 1;
for (i = 1; i <= x; i++) {
y *= i;
}
return y;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(int *a, int size)
{
int i, j = 0;
int f = factorial(size);
int *arr;
arr = calloc(f, sizeof(int)); // the members are initialized to 0
// print the original array
for (i = 0; i < size; i++) {
printf("%d%s", a[i], i == size - 1 ? "\n" : " ");
}
while (j < size) {
if (arr[j] < j) {
if (j % 2 == 0) {
swap(a + 0, a + j);
} else {
swap(a + arr[j], a + j);
}
// print the rearranged array
for (i = 0; i < size; i++) {
printf("%d%s", a[i], i == size - 1 ? "\n" : " ");
}
arr[j]++;
j = 0;
} else {
arr[j] = 0;
j++;
}
}
free(arr);
}
int main()
{
int a[] = {1, 2, 3}; // example
permute(a, sizeof a / sizeof a[0]); // the 2nd argument is the array length
return 0;
}
Output of the example:
1 2 3
2 1 3
3 1 2
1 3 2
2 3 1
3 2 1
Here is my code. While choosing values, if I try to put 9 values it dumps garbage value. It has happened while doing quick sort as well
#include <stdio.h>
void printArray(int* A, int n) {
for (int i = 0; i < n; i++) {
printf("%d ", A[i]);
}
printf("\n");
}
int maximum(int A[],int n) {
int i, max = A[0];
for (i = 1; i < n; i++) {
if (A[i] > max) {
max = A[i];
}
}
return max;
}
void countSort(int A[], int n) {
int i, max = maximum(A, n);
int count[max + 1], B[n];
for (i = 0; i < max + 1; i++) {
count[i] = 0;
}
for (i = 0; i < max + 1; i++) {
count[A[i]]++;
}
for (i = 1; i < n; i++) {
count[i] += count[i - 1];
}
for (i = n - 1; i >= 0; i--) {
B[--count[A[i]]] = A[i];
}
for (i = 0; i < n; i++) {
A[i] = B[i];
}
}
int main(){
int A[] = {1, 4, 6, 2, 3, 2, 3, 2, 7};
int n = 9;
printArray(A, n); // Printing the array before sorting
countSort(A, n); // Function to sort the array
printArray(A, n); // Printing the array before sorting
return 0;
}
This code uses the wrong limit:
for(i=0;i<max+1;i++) {
count[A[i]]++;
}
It effectively iterates through the elements of A, which has n elements, not max+1.
this is the program I made ,if I input [13,11,10,17,18] i get the output [12,13,17,11,10]. I do not understand what mistake I am making. somebody please help me understand.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n,j,i,num,v;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
scanf("%d",&v);
ptr[i] = v;
}
i=0;
j=0;
while(i<5){
j++;
if (ptr[j]%2==0 && i%2==0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
}
if (ptr[j]%2!=0 && i%2 !=0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
}
if (j==4){
i++;
j=0;
}
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
Ok, I tried to tell you how you should have written you program, but you didn't listen:
Make a https://stackoverflow.com/help/minimal-reproducible-example
A MCVE needs all the includes
No interactive stuff. You need to run and run and run your program in a debugger. You don't want to put data in manually every single time.
You want many tests, and you want to repeat them, so that when you fix one, you don't break another.
Make a function which does the job.
Free your memory!
Now to the solution: your idea of a solution was fine apart from the stuff about indexes. It's pretty similar to the one you will find down here. The only difference is that I put the odd numbers al the end to avoid checking elements multiple times.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
void evenodd(int *v, size_t n)
{
for (size_t i = 0; i < n; ++i) {
while (i < n && v[i] % 2 == 0) {
++i;
}
--n;
while (i < n && v[n] % 2) {
--n;
}
if (i < n) {
int tmp = v[i];
v[i] = v[n];
v[n] = tmp;
}
}
}
bool is_evenodd(int *v, size_t n)
{
size_t i = 0;
while (i < n && v[i] % 2 == 0) {
++i;
}
while (i < n && v[i] % 2 != 0) {
++i;
}
return i == n;
}
void main_test(const int *v, size_t n)
{
int *v1 = memcpy(malloc(n * sizeof(int)), v, n * sizeof(int));
evenodd(v1, n);
if (is_evenodd(v1, n)) {
printf("Ok!\n");
}
else {
printf("Fail!\n");
}
free(v1);
}
int main(void)
{
main_test((int[]) { 1 }, 0);
main_test((int[]) { 1 }, 1);
main_test((int[]) { 2 }, 1);
main_test((int[]) { 1, 2 }, 2);
main_test((int[]) { 1, 3 }, 2);
main_test((int[]) { 2, 1 }, 2);
main_test((int[]) { 2, 4 }, 2);
main_test((int[]) { 1, 3, 2 }, 3);
main_test((int[]) { 1, 4, 2 }, 3);
size_t n = 1000;
int *a = malloc(n * sizeof *a);
for (size_t i = 0; i < n; ++i) {
a[i] = rand();
}
main_test(a, n);
free(a);
return 0;
}
You can try the following code :
int even_index = 0; //start index
int odd_index = 4; //end index
for(int i=0;i<5;i++){
if(ptr[i] % 2 == 0){
int temp = ptr[even_index];
ptr[even_index++] = ptr[i]; //swapping values and incrementing even_index
ptr[i] = temp;
}else{
int temp = ptr[odd_index];
ptr[odd_index--] = ptr[i];
ptr[i] = temp;
}
}
or you can also count the number of even numbers in the digits during input and assign odd_value = even_num // number of even digits
ok so I solved it....
see the even numbers always end up in even indexes so we need to set a pointer on those even index(current index) and search for any even number after the current index.
if we find any(even number) we swap the current index value with the even number.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n,j,i,num,v;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
scanf("%d", &v);
ptr[i] = v;
}
i=0;
j=0;
while(i<n && j<n){
if (ptr[j]%2==0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
i+=2;
j=i;
}
j++;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
If this problem is to sort an array in order (descending) and then further place all even values before odd values I would recommend:
Sort the array
Swap and shift any odd numbers with the even numbers
Here's a naive implementation:
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (arr[i] < arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
int lastEven = 0;
for (int i = 0; i < len - 1; i++) {
if (arr[i] % 2 && (arr[i + 1] % 2 == 0)) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
lastEven = i;
} else if (arr[i] % 2 == 0 && lastEven-i > 1) {
for (int j = i; j > lastEven; j--) {
tmp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = tmp;
}
lastEven++;
}
}
Given the input [13,11,10,17,18] this will first sort the array ([18,17,13,11,10]) then separate the evens and odds ([18,10,17,13,11])
#include <stdio.h>
#include <stdlib.h>
void printingArr(int** arr, int rows);
void sortingEachOneOfThem(int** pArr, int rows);
void sortingTheWholeArray(int** pArr, int rows);
void bubbleSort(int* arr);
void freeArray(int **a, int m);
int main(void)
{
int** pArr = 0;
int numOfRows = 0;
int sizes = 0;
printf("Enter number of rows: ");
scanf("%d", &numOfRows);
pArr = (int**) malloc(sizeof(int*) * numOfRows);
if (pArr == NULL)
{
printf("Unsuccessful malloc!\n");
return 1;
}
for (int i = 0; i < numOfRows; i++)
{
printf("Enter array length for row %d: ",i);
scanf("%d", &sizes);
pArr[i] = (int*) malloc(sizeof(int) * sizes + 1);
if (pArr[i] == NULL)
{
printf("Unsuccessful malloc!\n");
return 1;
}
pArr[i][0] = sizes;
for (int k = 1; k < sizes + 1; k++)
{
printf("Enter value for array: ");
scanf("%d", &pArr[i][k]);
}
}
printingArr(pArr, numOfRows);
sortingEachOneOfThem(pArr, numOfRows);
printingArr(pArr, numOfRows);
sortingTheWholeArray(pArr, numOfRows);
printingArr(pArr, numOfRows);
for (int i = 0; i < numOfRows; i++)
{
if (pArr[i] != NULL)
{
free(*(pArr + i));
}
}
//free(pArr);
system("pause");
return 0;
}
/*
this amazing, wonderfull piece of program prints the array given
input: int** arr, int rows
output: none
*/
void printingArr(int** arr, int rows)
{
int i = 0;
int k = 0;
for (i = 0; i < rows; i++)
{
for (k = 0; k <= arr[i][0]; k++)
{
printf("%d ", arr[i][k]);
}
printf("\n");
}
printf("\n");
}
/*
This beautiful function sorts the whole array, but its length of rows like a pyramid
input: int** arr, int rows
output: none
*/
void sortingTheWholeArray(int** pArr, int rows)
{
int* temp = 0;
int i = 0, k = 0;
for (i = 0; i < rows - 1; i++)
{
for (k = 0; k < rows - 1; k++)
{
if (pArr[k][0] > pArr[k + 1][0])
{
temp = pArr[k];
pArr[k] = pArr[k + 1];
pArr[k + 1] = temp;
}
}
}
}
/*
This little small function sorts every row of the array of arrays given to it
input: int** arr, int rows
output: none
*/
void sortingEachOneOfThem(int** pArr, int rows)
{
int i = 0;
for (i = 0; i < rows; i++)
{
bubbleSort(pArr[i]);
}
}
/*
This little piece of a code is a bubble sort, sorts the array given to it :)
input: int* arr, int rows
output: none
*/
void bubbleSort(int* arr)
{
int i = 1, k = 0;
for (i = 1; i < arr[0] - 1; i++)
{
for (k = 1; k <= arr[0] - i; k++)
{
if (arr[k] > arr[k + 1])
{
arr[k] += arr[k + 1];
arr[k + 1] = arr[k] - arr[k + 1];
arr[k] -= arr[k + 1];
}
}
}
}
the free at the end crashes my code, showing this error:
https://i.stack.imgur.com/nqxBG.png
the same usage of the function free() on another code worked good, but not here. I have tried running through it in step by step mode, it crashes at the first free. Dr. memory shows this: https://i.stack.imgur.com/rSZJr.png
another link: https:// i.stack. imgur.com/ZX2Ne.png (paste it without the spaces in the middle, Can't post more than 2 links)
what can I do?
This:
pArr[i] = (int*) malloc(sizeof(int) * sizes + 1);
under-allocates. Adding a single byte to the size of an array of int makes little sense. You probably meant:
pArr[i] = malloc((sizes + 1) * sizeof *pArri[i]);
Don't cast the return value of malloc(), and use sizeof on the left-hand side.
I'm using Linux to implement this sorting. If I have a array arr[] ={1, 1, 1, 2, 2, 3, 3}, how to sort it by this:
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 1
arr[4] = 2
arr[5] = 3
arr[6] = 1
I Tried to do something like this:
for (int i = 0; i < size; i++)
{
if (arr[i] < arr[i+1])
{
}
}
Please give me some suggestions, thank you so much!
a hint
first you have to sort the array, then starting from 1 to (end-1) if active item equals to the last item move it to the end.
#include <stdio.h>
#include <stdlib.h>
/*__________________________________________________
*/
static int __cdecl sortCallback(int *i1,int *i2){
return (*i1<*i2)?-1:(*i1>*i2)?1:0;
}
/*__________________________________________________
*/
void printArr(char* Title,int *arr,int n){
int i;
if(Title)
printf("%s:\n\t",Title);
for (i=0;i<n;i++)
printf("%d ",arr[i]);
printf("\n");
return;
}
/*__________________________________________________
*/
void arrange(int *arr,int n){
int i=1,j;
int a;
while(i<(n-1)){
if(arr[i]==arr[i-1]){
a=arr[i];
for(j=i;j<(n+1);j++){
arr[j]=arr[j+1];
}
arr[n-1]=a;
}else
i++;
}
}
/*__________________________________________________
*/
int main(void){
int arr[7];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 1;
arr[4] = 2;
arr[5] = 3;
arr[6] = 1;
printArr("Initial",arr,7);
qsort(arr,7,sizeof(int),sortCallback);
printArr("Sorted",arr,7);
arrange(arr,7);
printArr("Rearranged",arr,7);
return 0;
}
#include <stdio.h>
void cnv(int n, int arr[n]){//arr is sorted
struct {
int value;
int occurs;
} tmp[n];
//make distinct array
int k = 0;
tmp[k].value = arr[0];
tmp[k].occurs = 1;
for(int i = 1; i < n; ++i){
if(arr[i] != arr[i-1]){
tmp[++k].value = arr[i];
tmp[k].occurs = 1;
} else {
++tmp[k].occurs;
}
}
//Written back
for(int i = 0, j = 0; i < n; ++i){
while(tmp[j].occurs == 0){
j = (j == k) ? 0 : j + 1;
}
arr[i] = tmp[j].value;
--tmp[j].occurs;
j = (j == k) ? 0 : j + 1;
}
}
int main(void){
int arr[] ={1, 1, 1, 2, 2, 3, 3};
int n = sizeof(arr)/sizeof(*arr);
cnv(n, arr);
for(int i = 0; i < n; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}