Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
#include <stdio.h>
int main () {
int []={1,2,3,7,8}; // add element after 3 --> 4,5,6 (condition that i don't know position of 3 in array)
for(int i=0,i<10;i++)
{
printf("%d\n",n[i]);
}
return 0;
}
i want output 1,2,3,4,5,6,7,8
but remember in case i don't know the position of 3 or 7 in array
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
// n = len of tab
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
int main()
{
int len = 10;
int top_number_count = 3;
int data[10] = {1, 11, 3, 4, 5, 20, 7, 8, 9, 10};
int temp[10];
// copy the tab for dont change any value
for (int i = 0; i < len; i++) {
temp[i] = data[i];
}
// sort the new tab
bubbleSort(temp, len);
// print the top number
// top_number_count is the count of max number you want
for (int i = len - top_number_count; i < len; i++)
printf(">%d\n", temp[i]);
return 0;
}
As the number of large values to be displayed may vary, sorting the array is the best choice. There are different techniques of sorting. For this program I shall use the "bubble sort"(if you wish to learn other sorting techniques, check this).
Once the array is sorted in descending order(largest to smallest), we can specify the number of large values we need. The program below displays the first 3 largest numbers.
#include <stdio.h>
int main()
{
int data[10] = {0, 12, 90, 8, 1, 2, 7, 9, 11, 10} ;
int MaxElements = 10 ;
int endBoundary = MaxElements - 1 ;
for(int index = 0 ; index <= MaxElements-1 ; index++)
{
for(int counter = 0 ; counter < endBoundary ; counter++)
{
if(data[counter] < data[counter+1]) // then swap the values
{
int temp = data[counter] ;
data[counter] = data[counter+1] ;
data[counter+1] = temp ;
}
}
endBoundary-- ;
}
// displaying the first 3 largest numbers
int numOfValuesSought = 3 ;
for(int count = 0 ; count < numOfValuesSought ; count++)
{
printf("%d\n", data[count]) ;
}
return 0 ;
}
How to separate the even position number of an array from the odd position number in C.
Example
int arr[]= {2,3,4,5,6,7,8,9,1};
int odd[]= {2,4,6,8,1};
int even[] = {3,5,7,9};
Use % to get the remainder. If the remainder is nonzero, then the index is odd, otherwise even. But index starts from 0 and not 1, thus the first element's index is 0 and is even. if you want to sort according to that (seems to be you do), add 1 to index.
#include <stdio.h>
int main() {
int arr[] = {2, 3, 4, 5, 6, 7, 8, 9, 1}; // our array
const size_t max_size = sizeof(arr) / sizeof(arr[0]);
int odd[max_size];
size_t odd_cnt = 0;
int even[max_size];
size_t even_cnt = 0;
for (size_t i = 0; i != max_size; ++i) {
if ((i + 1) % 2) { // if (i + 1) % 2 is nonzero, i + 1 is odd
odd[odd_cnt++] = arr[i];
} else {
even[even_cnt++] = arr[i];
}
}
for (size_t i = 0; i != odd_cnt; ++i) {
printf("%d ", odd[i]);
}
printf("\n");
for (size_t i = 0; i != even_cnt; ++i) {
printf("%d ", even[i]);
}
printf("\n");
return 0;
}
I have an array of values x = {0,0,1,2,3,0,0,7,8} and I want to remove the zero entries using C.
Attempt:
I am attempting to loop through each value in the array and check if the entry is not equal to zero. If this condition is true, then I am attempting to populate a new array with original array value.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int x[] = { 0, 0, 1, 2, 3, 0, 0, 7, 8 };
int i;
int x_upd[100];
for (i = 0; i < 9; i++) {
if (x[i] != 0) {
x_upd[i] = x[i]; // if true, populate new array with value
}
}
for (i = 0; i < 9; i++) {
printf(" Peak updated %d\t", x_upd[i]); //
}
return 0;
}
The output is not giving me the values {1,2,3,7,8} as desired. Instead, I am getting garbage values at the location where the zeros used to be.
Any advice on what I am doing wrong here? Do I need an else statement?
There is already such a function in C++. It is named remove_copy. In C such a function can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
int * remove_copy(const int *in, size_t n, int *out, int value)
{
for (size_t i = 0; i != n; i++)
{
if (in[i] != value) *out++ = in[i];
}
return out;
}
int main( void )
{
int a[] = { 0, 0, 1, 2, 3, 0, 0, 7, 8 };
int b[sizeof(a) / sizeof(*a)];
const size_t N = sizeof(a) / sizeof(*a);
int *last = remove_copy(a, N, b, 0);
for (int *first = b; first != last; ++first)
{
printf("%d ", *first);
}
putchar('\n');
return 0;
}
The program output is
1 2 3 7 8
Or the function can return the number of the copied values
size_t remove_copy(const int *in, size_t n, int *out, int value)
{
size_t m = 0;
for (size_t i = 0; i != n; i++)
{
if (in[i] != value) out[m++] = in[i];
}
return m;
}
As for your code then you need to use an additional variable that will keep the index in the destination array. For example
int m = 0;
for ( i = 0; i < sizeof( x ) / sizeof( *x ); i++ )
{
if ( x[i] != 0 )
{
x_upd[m++] = x[i]; // if true, populate new array with value
}
}
for ( i = 0; i < m; i++ )
{
printf(" Peak updated %d\t", x_upd[i] ); //
}
In fact the first loop corresponds to the second function implementation shown above.
You go through the values 0-9 once, in order, and you skip values that are 0, so you get {garbage, garbage, 1, 2, 3, garbage, garbage, 7, 8}. You'd have to keep a separate counter for the number of values that aren't 0:
int position = 0;
for(i = 0; i < 9; i++)
{
if(x[i] != 0)
{
x_upd[position] = x[i]; // if true, populate new array with value
position++;
}
}
//loop until you get to counter
for(i = 0; i < position; i++)
{
printf(" Peak updated %d\t", x_upd[i]);
}
You should use separate counter variables, otherwise you will "skip" the indexes where the original array contains zeroes when assigning to the new array.
#include <stdio.h>
int main() {
int x[] = { 0, 0, 1, 2, 3, 0, 0, 7, 8 };
int i;
int j = 0;
int x_upd[100];
for (i = 0; i < 9; i++) {
if (x[i] != 0) {
x_upd[j++] = x[i]; // if true, populate new array with value
}
}
for (i = 0; i < j; i++) {
printf(" Peak updated %d\t", x_upd[i]); //
}
return 0;
}
The trick in this situation, is to use a different variable to index into your other array.
So instead of this:
x_upd[i] = x[i];
You could have another variable j that only increments when you assign a value to x_upd
x_upd[j++] = x[i];
No need to create a new array, see the working code with one array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int x[] = { 0, 0, 1, 2, 3, 0, 0, 7, 8 };
int i, n;
for (i = 0, n = 0; i<9; i++)
{
if (x[i] != 0)
{
x[n++] = x[i];
}
}
for (i = 0; i<n; i++)
{
printf("%d,", x[i]);
}
return 0;
}
OUTPUT:
1,2,3,7,8,
This
for(i=0;i<9;i++)
{
if(x[i] != 0)
{
x_upd[i] = x[i]; // if true, populate new array with value
}
}
is skipping places in the x_upd array, since i is still being incremented even when you don't insert values in your new array.
You should do this:
int j = 0;
for(i=0;i<9;i++)
{
if(x[i] != 0)
{
x_upd[j++] = x[i]; // if true, populate new array with value
}
}
Then, here
for(i=0;i<9;i++)
{
printf(" Peak updated %d\t",x_upd[i]); //
}
You should just count till j:
for(i=0;i<j;i++)
{
printf(" Peak updated %d\t",x_upd[i]); //
}
This problem can be solved by using two indexes: one for the source array (x) and another for the destination array (x_upd), which are i and j, respectively, in the code below.
int i, j;
for(i=0,j=0; i<9; i++) {
if (!x[i]) // is x[i] zero?
continue; // then skip this element
// otherwise copy current element and update destination index
x_upd[j++] = x[i];
}
As you can see, the index j is only being updated (i.e.: incremented by one) when an element from x is being copied to x_upd, whereas the index i is being updated in each iteration of the for loop.
The problem lies here:
for(i=0;i<9;i++)
{
if(x[i] != 0)
{
x_upd[i] = x[i]; // if true, populate new array with value
}
}
and
for(i=0;i<9;i++) {
printf(" Peak updated %d\t",x_upd[i]); //
}
You need to maintain separate index for x and x_upd, since they will be of different size(x_upd wont have the '0').
Try this:
int j;
for(i=0,j=0;i<9;i++) {
if(x[i] != 0)
{
x_upd[j] = x[i]; // if true, populate new array with value
j++; // index for values inserted
}
}
and to print, use the correct count, obtained from the above code:
int k;
for(k=0;k<=j;k++) {
printf(" Peak updated %d\t",x_upd[k]); //
}
You should increment x_upd array index separately. Something like:
int y = 0;
for(i=0;i<9;i++)
{
if(x[i] != 0)
{
x_upd[y] = x[i]; // if true, populate new array with value
y++;
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int x[] = {0,0,1,2,3,0,0,7,8};
int i;
int count = 0;
int x_upd[100];
for(i=0;i<9;i++)
{
if(x[i] != 0)
{
x_upd[count] = x[i]; // if true, populate new array with value
count++;
}
}
for(i=0;i<count;i++)
{
printf(" Peak updated %d\t",x_upd[i]); //
}
return 0;
}
Output
Peak updated 1 Peak updated 2 Peak updated 3 Peak updated 7 Peak updated 8
no indexes needed
int populate(int *src, int *dest, int size)
//usage: - src - source table
//src - source table
//dest - destination table
//size of the source table - source table
//Return: -1 if pointers are null, -2 if source table has zero elements, or number of non zero elements copied
{
int result = (src == NULL || dest == NULL) * -1;
// it an equivalen of:
// int result;
// if(src == NULL || dest == NULL)
// result = -1;
// else
// result = 0;
if(size == 0) result = -2;
if (!result)
{
while(size--)
if (*src)
{
*dest++ = *src;
result++;
}
src++;
}
return result;
}
int main()
{
int x[] = { 0,0,1,2,3,0,0,7,8 };
int x_upd[100];
int result = populate(x,x_upd, sizeof(x) / sizeof(x[0]))
for (int i = 0; i<result; i++)
{
printf(" Peak updated %d\t", x_upd[i]); //
}
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I got this problem statement from a programming puzzle book. I am able to find out the horizontal palindromes, but only if the entire row is a palindrome.
How can I fulfill this? Also how can be diagonal palindromes acquired?
A pseudo code is okay too, I just need the basic logic behind this. I will perform the rest.
Thank You.
The trick behind finding the horizontal palindromes is the take an entire row and then split it into various strings. Once that is done, you need to check if that string is a palindrome. For vertical strings, you need to do the same thing for the columns.
Now for the diagonal ones, you need to start from a point at the edge and then move forward diagonally (+[1][1]) for going to the bottom right until you reach the end. Now keep doing for every tactical point of every edge which will help you get all the diagonal strings, the next thing you need to do is to split these strings and check if each of these short strings are a palindrome or not.
This would come under dynamic programming most likely. Although I am confused it might come under greedy approach as well. I'll confirm it once with my professor.
Here is the code I did back when I was trying to solve the same thing -
#define PALLEN 2
#include <stdio.h>
#include <string.h>
int a[10][10];
/*int a[5][5] = {
{ 1, 2, 1, 3, 5 } ,
{ 4, 5, 6, 7, 4 } ,
{ 4, 5, 5, 4, 1 } ,
{ 1, 9, 2, 1, 4 } ,
{ 1, 9, 4, 1, 5 }
};*/
int n=0;
void checkPalindrome(char*);
void diagonalPal();
void stringSpliter(char*);
int main() {
int i, j, k, l, x;
int c = 0;
int jmp;
int ptr = 0;
int diag;
char recycler[20];
char diaglist[25];
char revdiaglist[25];
system("cls");
printf("\nEnter the dimension (n) of this square matrix i.e. (n*n) - ");
scanf("%d", &n);
printf("\nNow enter the elements for this %d*%d matrix - ", n,n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d", &a[i][j]);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("-%d-", a[i][j]);
}
printf("\n");
}
printf("\nHorizontal Palindromes");
for (i = 0; i < n; i++) {
for (j = n-1, k = PALLEN; j > 0; j--, k++) {
while (c < j) {
jmp = c;
memset(recycler, 0, 20);
ptr = 0;
for (l = 0; l < k; l++) {
recycler[ptr] = a[i][jmp]; //0,0 -- 0,1
ptr++;
jmp++;
}
checkPalindrome(recycler);
c++;
}
c = 0;
}
}
printf("\n\nVertical Palindromes");
for (i = 0; i < n; i++) {
for (j = n-1, k = PALLEN; j > 0; j--, k++) {
while (c < j) {
jmp = c;
memset(recycler, 0, 20);
ptr = 0;
for (l = 0; l < k; l++) {
recycler[ptr] = a[jmp][i]; //0,0-- 1,0
ptr++;
jmp++;
}
checkPalindrome(recycler);
c++;
}
c = 0;
}
}
printf("\n\nDiagonal Palindromes");
diagonalPal();
}
void stringSpliter(char *a){
int i,j,k,ptr,jmp,c=0,l;
int len;
len = strlen(a);
char recycler[20];
for (j = len-1, k = PALLEN; j > 0; j--, k++) {
while (c < j) {
jmp = c;
memset(recycler, 0, 20);
ptr = 0;
for (l = 0; l < k; l++) {
recycler[ptr] = a[jmp]; //0,0 -- 0,1
ptr++;
jmp++;
}
checkPalindrome(recycler);
c++;
}
c = 0;
}
}
void diagonalPal(){
int i, x=0, j, k, ptr=0;
char diagrecycler[20];
for(i = 0; i < n; i++){
memset(diagrecycler, 0, 25);
ptr = 0;
for(j = i, k = 0; j < n, k < n; j++, k++){
diagrecycler[ptr++] = a[j][k];
}
stringSpliter(diagrecycler);
}
for(i = 1; i < n; i++){
memset(diagrecycler, 0, 25);
ptr = 0;
for(j = 0, k = i; j < n, k < n ;j++, k++){
diagrecycler[ptr++] = a[j][k];
}
stringSpliter(diagrecycler);
}
}
void checkPalindrome(char *string){
int isPalindrome = 1, i=0;
char rev[20];
strcpy(rev, string);
strrev(rev);
isPalindrome = strcmp(rev, string);
if(isPalindrome == 0){
printf("\n");
while(string[i]!='\0') printf("%d", string[i++]);
}
}
// Output
/*Enter the dimension (n) of this square matrix i.e. (n*n) - 4
Now enter the elements for this 4*4 matrix - 1 2 3 4
5 2 1 6
8 1 1 8
9 5 3 2
-1--2--3--4-
-5--2--1--6-
-8--1--1--8-
-9--5--3--2-
Horizontal Palindromes
11
8118
Vertical Palindromes
22
11
3113
Diagonal Palindromes
121
212
G:\Code snippets\C programmes>*/
I'm trying to write a function which moves all numbers from begining of array to the end of it. order should not change.
for example i have this array:
1, 2, 3, 4, 5, 0, 0, 0, 0
i want to change it to:
0, 0, 0, 0, 1, 2, 3, 4, 5
I already wrote a version of it but it can't keep the order. (array[] is original and a[] is sorted)
#include <stdio.h>
#define SIZE_MAX 20
int main()
{
int array[SIZE_MAX] = {1, 2, 3, 4, 5, 0, 0, 0, 0};
int a[SIZE_MAX];
int i;
int p = 0;
for (i = SIZE_MAX-1; i >= 0; i--, p++)
{
a[i] = array[p];
}
for (i = 0; i < SIZE_MAX; i++)
{
printf("%d", a[i]);
}
}
One option would be to loop through the array twice, first copying over the zeros, then the rest of the values:
#include <stdio.h>
#define SIZE_MAX 10
int main()
{
int array[SIZE_MAX] = {1, 2, 0, 0, 3, 4, 5, 0, 0, 0};
int a[SIZE_MAX];
int i;
int p = 0;
for (i = 0; i < SIZE_MAX; ++i) {
if (array[i] == 0) {
a[p++] = 0;
}
}
for (i = 0; i < SIZE_MAX; ++i) {
if (array[i] != 0) {
a[p++] = array[i];
}
}
for (i = 0; i < SIZE_MAX; i++) {
printf("%d", a[i]);
}
}
I changed SIZE_MAX to 10, so that it matches the number of elements in the array.
The sentence "I'm trying to write a function which moves all numbers from beginning of array to the end of it." sounds like it should be done in place - and it turns out with this problem it is quite easy to do an in-place algorithm. Note that unlike other algorithms here, this just scans the array once, and writes the array once. Here I wrote it into a function:
void relocate_zeroes(size_t length, int *array) {
int *target = array + length - 1;
int *source = target;
for (; source >= array; source--) {
if (*source) {
*target-- = *source;
}
}
while (target >= array) {
*target-- = 0;
}
}
Basically we scan the source array once from end to beginning; and if we meet a non-zero integer, we relocate it just before the previous non-zero integer. When the whole array has been scanned, the area between the base (array) and target is filled with zeroes.
In the beginning both target and source point to the last value of the array; if the *source is not 0, we replace *target with *source; that is, if the last element is non-zero, we replace it by itself and decrease both target and source pointers; if the last element is 0, we don't copy it anywhere, only decrease the source pointer; continuing this way at the end we have copied all non-zero elements, and we can fill the remaining array elements with zeroes.
Given program:
#define SIZE_MAX 9
int main() {
int array[SIZE_MAX] = {1, 0, 2, 3, 0, 4, 0, 0, 5};
int i;
relocate_zeroes(SIZE_MAX, array);
for (i = 0; i < SIZE_MAX; i++) {
printf("%d ", array[i]);
}
}
The output will be
0 0 0 0 1 2 3 4 5
If the 2-array version is required, then this is easy to modify for that too:
void relocate_zeroes(size_t length, int *source_array, int *target_array) {
int *target = target_array + length - 1;
int *source = source_array + length - 1;
for (; source >= source_array; source--) {
if (*source) {
*target-- = *source;
}
}
while (target >= target_array) {
*target-- = 0;
}
}
If you need all the 0 at the beginning and rest of the numbers in same order try this :
#include <stdio.h>
#define SIZE_MAX 9
int main()
{
int array[SIZE_MAX] = {1, 2, 3, 4, 5, 0, 0, 0, 0};
int a[SIZE_MAX];
int i;
int temp[SIZE_MAX];
int ind1=0,ind2=0;
// separating all the 0's and store it at the beginning
for (i = 0; i < SIZE_MAX; i++)
{
if(array[i]==0)
a[ind1++]=0;
else
temp[ind2++]=array[i];
}
// storing rest of the numbers in order
for (i = 0; i < ind2; i++)
{
a[ind1++]=temp[i];
}
for (i = 0; i < SIZE_MAX; i++)
{
printf("%d", a[i]);
}
}
NOTE:
first i stored all the 0's in the result array and in the meantime all the non zero value are being stored in temp array.
later, i just merged the temp array to the result array.
Integer fullArray[] = { 1, 10, 20, 0, 59, 63, 0, 88, 0 };
for (int i = 0; i <= fullArray.length - 1; i++) {
if (fullArray[i] == 0 && i > 0) {
int temp = fullArray[i - 1];
if (temp != 0) {
fullArray[i - 1] = 0;
fullArray[i] = temp;
i = -1;
}
}
}
System.out.println(Arrays.asList(fullArray).toString());
Here is an in-place method using swap()
#include <stdio.h>
#define SIZE_MAX 20
swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
moveZerosLeft(int length, int *array)
{
int i = 0;
int cur = length - 1;
for( i = length - 1; i >= 0; --i)
if(array[i] != 0)
{
swap(&array[i], &array[cur--]);
}
}
int main()
{
int array[SIZE_MAX] = {1, 2, 3, 4, 5, 0, 0, 0, 0};
int i;
int length = 9;
moveZerosLeft(length, array);
// display the result
for(i = 0; i < length; i++)
{
printf("%d ", array[i]);
}
}
We scan from the right of the array to the left. When we see a non-zero value, we swap it with a zero which we saw previously.
This method requires only 1 scan of the array.
public class Demo{
public static void moveZeros() {
int[] num = {1, 0, 0 , 6, 7, 0};
int temp=-1;
for (int i = 0; i < num.length;i++)
{
if(num[i]!=0)
{
++temp;
if(num[temp] ==0){
int val = num[i];
num[i]=num[temp];
num[temp]=val;
}
else
{
num[temp]=num[i];
}
}
}
}
public static void main(String args[])
{
Demo.moveZeros();
}
}