I am trying to make a function that cleans out my duplicates of number in my array, but it seems that i cant figure out what i am missing to just remove the duplicate.
Just to make it more clear:
The function should not become void.
[1,2,3,3,4] -> [1,2,3,4]
[4,2,5,1]->[4,2,5,1]
[32,21,2,5,2,1,21,4]->[32,21,2,5,1,4]
It should not be empty spaces in my array, and the function should return
the unique elements in the cleaned array, where cleaned is defined as "non-duplication of integer numbers"
#include <stdio.h>
int generateUniqeList(int *list, int length);
int main()
{
int list[6] = { 5, 5, 4, 3, 2, 1 };
int duplicate = generateUniqeList(list, 6);
for (int i = 0; i < 6; i++)
{
printf("%d\n", list[i] - 1); //Here i am able to change the value of the duplicates with the - 1
}
getchar();
return 0;
}
int generateUniqeList(int *list, int length)
{
int duplicate = 0;
for (int i = 0; i < length; i++)
{
if (list[i] == list[i])
duplicate = list[i];
}
return duplicate;
}
#include <stdio.h>
#include<string.h>
void generateUniqeList(int *list, int length);
int main()
{
int list[6] = { 5, 5, 4, 3, 2, 1 };
generateUniqeList(list, 6);
for (int i = 0; i < 6; i++)
{
printf("%d", list[i]);
//Here i am able to change the value of the duplicates with the - 1
}
putchar('\n');
return 0;
}
void generateUniqeList(int *list, int length){
int i ,j,k;
for (i = 0; i < length; i++) {
for (j = i + 1; j < length;) {
if (list[j] == list[i]) {
for (k = j; k < length; k++) {
list[k] = list[k + 1];
}
length--;
} else
j++;
}
}
}
What you are doing is subtracting every int in your list by 1. This will not remove the duplicates. To remove an element from an array, check out:
How to remove an element from an array in C?
The function does not make a sense. For example the condition in this if statement
if (list[i] == list[i])
duplicate = list[i];
is always true because each object is equal to itself.
And the function does not modify the array.
You can not resize the array but you can gather all unique elements in the beginning of the array and return the number of the unique elements.
Here is a demonstrative program.
#include <stdio.h>
size_t generateUniqeList( int *a, size_t n )
{
size_t m = 0;
for ( size_t i = 0; i < n; i++ )
{
size_t j = 0;
while ( j < m && a[j] != a[i] ) j++;
if ( j == m )
{
if ( m != i ) a[m] = a[i];
++m;
}
}
return m;
}
int main(void)
{
int list[] = { 5, 5, 4, 3, 2, 1 };
const size_t N = sizeof( list ) / sizeof( *list );
for ( size_t i = 0; i < N; i++ ) printf( "%d ", list[i] );
putchar( '\n' );
size_t m = generateUniqeList( list, N );
for ( size_t i = 0; i < m; i++ ) printf( "%d ", list[i] );
putchar( '\n' );
return 0;
}
Its output is
5 5 4 3 2 1
5 4 3 2 1
Related
the first for loop will start at the end and swap its value to the max value in the array a[0-->its own index]
int selection_sort(int *a, int size) {
int i, j, swap;
for (i = size - 1; i <= 0; i--) {
/*this will find the max between o index to i th index*/
for (j = 0; j <= i; j++) {
if (a[i] < a[j]) {
swap = a[i];
a[i] = a[j];
a[j] = a[i];
}
}
}
}
output is the same array with no change in order
For starters the function has the return type int but returns nothing. Also the second parameter should have the unsigned integer type size_t instead of the signed integer type int.
Also you should declare variables in minimum scopes where they are used.
The main problem with your code is that the body of this for loop
for (i = size - 1; i <= 0; i--) {
will never get the control provided that size is not less than 2.
Also there is a typo
a[j] = a[i];
You have to write
a[j] = swap;
Apart from this there are redundant swaps.
The function can look the following way
void selection_sort( int *a, size_t n )
{
for ( size_t i = n; i-- != 0; )
{
size_t max = i;
for ( size_t j = 0; j < i; j++ )
{
if ( a[max] < a[j] ) max = j;
}
if ( max != i )
{
int swap = a[max];
a[max] = a[i];
a[i] = swap;
}
}
}
Here is a demonstration program.
#include <stdio.h>
void selection_sort( int *a, size_t n )
{
for ( size_t i = n; i-- != 0; )
{
size_t max = i;
for ( size_t j = 0; j < i; j++ )
{
if ( a[max] < a[j] ) max = j;
}
if ( max != i )
{
int swap = a[max];
a[max] = a[i];
a[i] = swap;
}
}
}
int main( void )
{
int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
const size_t N = sizeof( a ) /sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
selection_sort( a, N );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
Its output is
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
Your for loop is wrong for (i = size - 1; i <= 0; i--). The comparison should be >=0.
Also, the value swapping is incorrect
if (a[i] < a[j]) {
swap = a[i];
a[i] = a[j];
a[j] = a[i];
}
should be
if (a[i] < a[j]) {
swap = a[i];
a[i] = a[j];
a[j] = swap;
}
I am trying to sort an array of integers for finding the median of the same array. The code I am using sorts only the first two elements of the 10 element array. I have cross checked the swapping of variables in the loops, but everything seems okay.
void sort(int *arr) {
//get the size of this array
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
Application
#include <stdlib.h>
#include <stdio.h>
int main() {
int numbers[10];
numbers[0] = 10;
numbers[1] = 9;
numbers[2] = 8;
numbers[3] = 7;
numbers[4] = 6;
numbers[5] = 5;
numbers[6] = 4;
numbers[7] = 3;
numbers[8] = 2;
numbers[9] = 1;
sort(numbers);
//code sorts the element in the first and second index, the rest are unsorted please help
return 0;
}
What am I doing wrong?
The function parameter has a pointer type
void sort(int* arr){
Even if you will rewrite the function declaration like
void sort( int arr[10] ){
nevertheless the compiler will adjust the function parameter having the array type to pointer to the element type as it is written in your original function declaration
void sort(int* arr){
And in this call of the function
sort(numbers);
the array designator is implicitly converted to a pointer to its first element. That is the call above in fact is the same as
sort( &numbers[0] );
So using the operator sizeof with a pointer expression yields the size of a pointer. That is this line
//get the size of this array
int size=sizeof(arr)/sizeof(arr[0]);
is equivalent to
//get the size of this array
int size=sizeof( int * )/sizeof( int );
and yields either 2 or 1 depending on the used system.
You need to declare the function like
void sort( int *arr, size_t n );
and pass to the function the number of elements in the array explicitly.
Bear in mind that in general the user can use the function for a dynamically allocated array.
Pay attention to that the used by you algorithm is not the insertion sort algorithm. It is the selection sort algorithm with redundant swaps.
A function that implements the insertion sort algorithm can look for example the following way as it is shown in the demonstration program below.
#include <stdio.h>
void insertion_sort( int a[], size_t n )
{
for ( size_t i = 1; i < n; i++ )
{
int current = a[i];
size_t j = i;
for ( ; j != 0 && current < a[j - 1]; j-- )
{
a[j] = a[j - 1];
}
if ( j != i ) a[j] = current;
}
}
int main()
{
int a[] = { 9,8, 7, 6, 5, 4, 3, 2, 1, 0 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
insertion_sort( a, N );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
The program output is
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
As for the function that implements the selection sort algorithm then without redundant swaps it can look the following way as it is shown in the next demonstration program.
#include <stdio.h>
void selection_sort( int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
size_t min = i;
for ( size_t j = i + 1; j < n; j++ )
{
if (a[j] < a[min]) min = j;
}
if ( min != i )
{
int tmp = a[i];
a[i] = a[min];
a[min] = tmp;
}
}
}
int main()
{
int a[] = { 9,8, 7, 6, 5, 4, 3, 2, 1, 0 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
selection_sort( a, N );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
The program output is the same as shown above
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
This is because int size = sizeof(arr) / sizeof(arr[0]); will return 2, because sizeof(arr) will give the sizeof a pointer to int, which in your case is 8 bytes and then sizeof(arr[0]) will give a sizeof int which in your case is 4 bytes.
So,
8 / 4 = 2
Fix:
Add another parameter for the length of the array.
type-cast numbers to (int *) for sort() function
Your sort() function does not implement insertion sort algorithm, instead it is selection sort algorithm. READ MORE
There's no need of stdlib.h header file in your code
Like this: TRY IT ONLINE
#include <stdio.h>
void sort(int *arr, size_t len)
{
for (int i = 0; i < len; i++)
{
for (int j = i + 1; j < len; j++)
{
if (arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
// using `const` keyword, because `arr` isn't modifying inside `print()` function
void print(const int *arr, size_t len){
for (size_t i = 0; i < len; i++)
{
printf("%d\n", arr[i]);
}
}
int main(void)
{
int numbers[10];
numbers[0] = 10;
numbers[1] = 9;
numbers[2] = 8;
numbers[3] = 7;
numbers[4] = 6;
numbers[5] = 5;
numbers[6] = 4;
numbers[7] = 3;
numbers[8] = 2;
numbers[9] = 1;
size_t len = sizeof(numbers) / sizeof(numbers[0]);
sort((int *)numbers, len);
print(numbers, len);
return 0;
}
Any suggestion on how to hide even numbers from user input and only printing odd numbers in ascending order? Like this output describes:
5
3
2
8
7
OUTPUT:
3
5
7
Press any key to continue . . .
I've been trying to figure it out in few hours but was unable to figure the solution :( .
#include <stdio.h>
#include <time.h>
void sort(int number[], int count)
{
int temp, i, j, k;
for (j = 0; j < count; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (number[j] > number[k])
{
temp = number[j];
number[j] = number[k];
number[k] = temp;
}
}
}
printf("OUTPUT:\n");
for (i = 0; i < count; ++i)
printf("%d\n", number[i]);
}
void main()
{
int i, number[1000];
int count = 5;
printf("\nType your number:");
for (i = 0; i < count; ++i)
scanf("%d", &number[i]);
sort(number, count);
}
Just add 'if(number[i]%2==0)' in your program.
#include <stdio.h>
#include <time.h>
void sort(int number[], int count)
{
int temp, i, j, k;
for (j = 0; j < count; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (number[j] > number[k])
{
temp = number[j];
number[j] = number[k];
number[k] = temp;
}
}
}
printf("OUTPUT:\n");
for (i = 0; i < count; ++i)
if(number[i]%2!=0)
printf("%d\n", number[i]);
}
void main()
{
int i, number[1000];
int count = 5;
printf("\nType your number:");
for (i = 0; i < count; ++i)
scanf("%d", &number[i]);
sort(number, count);
}
try to use the following code will solve your problem :
#include <stdio.h>
#include <time.h>
void sort(int number[], int count)
{
int temp, i, j, k;
int numbs[100];
int counter = 0;
for(int h=0; h<count; ++h){
if(number[h] % 2 != 0){
numbs[counter] = number[h];
counter++;
}
}
for (j = 0; j < counter; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (numbs[j] > numbs[k])
{
temp = numbs[j];
numbs[j] = numbs[k];
numbs[k] = temp;
}
}
}
printf("OUTPUT:\n");
for (i = 0; i < counter; ++i)
printf("%d\n", numbs[I]);
}
void main()
{
int i, number[1000];
int count = 5;
printf("\nType your number:");
for (i = 0; i < count; ++i)
scanf("%d", &number[i]);
sort(number, count);
}
There are many ways to accomplish the task, the following might be an overkill.
Consider the interface and usage of qsort to sort an array of int in ascending order.
#include <stdlib.h>
// It needs a function that compares the values
int cmp_int(void const *lhs, void const *rhs)
{
int const a = *(int *)lhs;
int const b = *(int *)rhs;
return (b < a) - (a < b);
}
int main(void)
{
int a[] = {42, 17, -3, 0, 8, -2, 33};
size_t const a_size = (sizeof a) / (sizeof a[0]);
qsort(a, a_size, // The source array and the number of its elements.
sizeof(a[0]), // The size of each element.
cmp_int); // The pointer to the comparator function.
// ...
}
You can adapt the same concepts and write a function that prints only the odd elements.
#include <stdbool.h>
#include <stdio.h>
bool is_odd(int x)
{
return (x % 2) != 0;
}
void print_if(char const *fmt,
size_t n, int const *a,
bool (*predicate)(int))
{
for (size_t i = 0; i < n; ++i)
{
if ( predicate(a[i]) )
printf(fmt, a[i]);
}
putchar('\n');
}
int main(void)
{
int a[] = //...
size_t const a_size = //...
// ...
// Sort 'a', hopefully using qsort.
print_if("%d ", a_size, a, is_odd);
// ...
}
As an alternative, you could copy only the odd elements into another (suitably sized) array, sort it and print it all.
size_t copy_if(size_t n, int const *src,
int *dst,
bool (*predicate)(int))
{
size_t j = 0;
for ( size_t i = 0; i < n; ++i )
{
if ( predicate( src[i] ) )
{
dst[j] = src[i];
++j;
}
}
return j; // Note that the number of elements copied is returned. Use it!
}
Live example #Compiler Explorer.
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
As the declared array has 1000 elements then it means that the user may enter any number of values no greater than 1000. Otherwise there is no sense to declare an array with 1000 elements to enter only 5 numbers. That is you should ask the user how many integers he is going to enter.
Your sort function does not distinguish odd and even numbers. It tries to sort all elements of the array though it seems you need to sort only elements with odd values.
To sort only elements with odd values of an array you could use for example the bubble sort algorithm.
Also you should split sorting and outputting elements with odd values in two separate functions.
Here is a demonstration program that shows how the task can be performed.
#include <stdio.h>
void sort_odds( int a[], size_t n )
{
size_t i = 0;
while ( i != n && a[i] % 2 == 0 ) i++;
if ( i != n )
{
a += i;
n -= i;
for ( size_t last = 0; !( n < 2 ); n = last )
{
last = 0;
size_t previous = 0;
for ( size_t j = 0; j < n; j++ )
{
if ( a[j] % 2 == 1 )
{
if ( a[j] < a[previous] )
{
int tmp = a[j];
a[j] = a[previous];
a[previous] = tmp;
last = j;
}
previous = j;
}
}
}
}
}
void display_odds( const int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
if ( a[i] % 2 == 1 ) printf( "%d ", a[i] );
}
putchar( '\n' );
}
int main(void)
{
enum { N = 1000 };
int number[N];
size_t count = 0;
printf( "Enter the number of integers you want to input (no more than %d): ", N );
scanf( "%zu", &count );
if ( count != 0 )
{
if ( N < count ) count = N;
printf( "Enter your integers: " );
int num;
size_t i = 0;
for ( ; scanf( "%d", &num ) == 1 && i < count; i++ )
{
number[i] = num;
}
sort_odds( number, i );
display_odds( number, i );
}
}
The program output might look like
Enter the number of integers you want to input (no more than 1000): 10
Enter your integers: 9 8 7 6 5 4 3 2 1 0
1 3 5 7 9
My task is to find the most repeating element in an array without sorting or hash-tables.
This is my pseudo-code:
#include <stdio.h>
int most_frequent(int *a, int n)
{
int i, j, max_element, count;
int maxcount = 0;
for(i = 0; i<n; i++)
{
count = 1;
for(j = i+1; j<n; j++)
{
if(a[j] == a[i])
{
count ++;
if(count > maxcount)
{
max_element = a[j];
}
}
}
}
return max_element;
}
The problem is, that it doesn’t always work correctly, e.g. with the array [1 1 2 2 3 3 3 4 4 4 4 5 5 7] the result will be 5.
In this if statement
if(count > maxcount)
{
max_element = a[j];
}
you forgot to change the variable maxcount
if(count > maxcount)
{
maxcount = count;
max_element = a[j];
}
Moreover the if statement should be moved below the inner for loop.
for(i = 0; i<n; i++)
{
count = 1;
for(j = i+1; j<n; j++)
{
if(a[j] == a[i])
{
count ++;
}
}
if(count > maxcount)
{
maxcount = count;
max_element = a[i];
}
}
Pay attention to that if the user will pass to the function the value for the parameter n equal to 0 then the function will return an indeterminate value because the variable max_element is not initialized.
It will be much better to define the function such a way when it returns the index of the element with the most frequent occurrence something like shown in the demonstration program below
#include <stdio.h>
size_t most_frequent( const int *a, size_t n )
{
size_t pos = 0;
size_t max_count = 0;
for ( size_t i = 0; i < n - max_count; i++ )
{
size_t count = 1;
for ( size_t j = i + 1; j < n; j++ )
{
if ( a[j] == a[i] ) ++count;
}
if ( max_count < count )
{
max_count = count;
pos = i;
}
}
return pos;
}
int main( void )
{
int a[] = { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 7 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t pos = most_frequent( a, N );
printf( "The most frequent number is %d found at position %zu\n",
a[pos], pos );
return 0;
}
The program output is
The most frequent number is 4 found at position 7
I'm having some trouble with my sort function which also uses the swap function to work. I have been trying to find my mistake but cant find it. the rest of the code works perfectly, only the sort function doesn't work (it doesn't sort anything.)
I will leave the code here if anybody has any ideas of how to solve my problem please reply.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void sort(int *values, int n);
void swap(int arr[], int i);
void populate(int arr[]);
const int arraysize = 10;
int main()
{
srand((long int) time(NULL));
int ela[10] = {0};
populate(ela); // populates with random values
printf("before func\n");
for(int i = 0; i < arraysize; i++)
{
printf("%i\n", ela[i]);
}
sort(ela, arraysize); // this is the function that is not working
printf("\n\nafter func\n");
for(int i = 0; i < arraysize; i++)
{
printf("%i\n", ela[i]);
}
return 0;
}
void sort(int *values, int n)
{
int count = 1;
while(count != 0)
{
count = 0;
for (int i = 0; i < n; i++) {
if(values[i] > values[(i + 1)] && values[(i + 1)] != '\0')
{
swap(values, i);
count++;
}
if (count == 0) break;
}
}
}
void swap(int arr[], int i)
{
int save = arr[i];
arr[i] = arr[i+1];
arr[i + 1] = save;
return;
}
void populate(int arr[])
{
for(int i = 0; i < arraysize; i++)
{
arr[i] = (rand() % 15);
}
}
void sort(int *values, int n)
{
int count = 1;
while(count != 0)
{
count = 0;
for (int i = 0; i < n-1; i++) {
if(values[i] > values[(i + 1)] )
{
swap(values, i);
count++;
}
//if (count == 0) break;
}
}
}
I doubt this would never be true values[(i + 1)] != '\0' as the values are integers..So running the for loop until the condition i<n-1 would work fine as you are swapping i+1 element with i.
And also if (count == 0) break; inside your for loop should be removed as the loop would break if there is some input like 2 3 2 1 and so wouldn't sort .
Working Ideone: http://ideone.com/k1LJau
Here is an updated version of your sort() function:
void sort(int *values, int n)
{
int count = 1;
while(count != 0)
{
count = 0;
for (int i = 0; i < n; i++) {
if(values[i] > values[(i + 1)] && values[(i + 1)] != '\0')
{
swap(values, i);
count++;
}
}
}
}
Your if(count==0) break; statement would exit your for loop even when you would check initial values of the array. So for instance [5 6 9 8] would exit because count was 0 when it checked the first two items.
If you want to use sort() function, you have to add algorithm header file. But it will not work for c. If you add using namespace std;
Then it will work. And then you have to call like that.
sort(ela, ela+arraysize);
You can edit your sort function like below. Above answers are also nice.
void Sort(int *values, int n)
{
int cnt=0;
while(1)
{
cnt++;
if(cnt==n-1)
break;
for (int i = 0; i < n-cnt; i++)
{
if(values[i] > values[(i + 1)] && values[(i + 1)] != '\0')
{
swap(values, i);
}
}
}
}
Your bubble sort function is wrong.
Here is a demonstrative program that shows how the function can be written
#include <stdio.h>
void swap( int a[], size_t i )
{
int tmp = a[i];
a[i] = a[i+1];
a[i+1] = tmp;
}
void bubble_sort( int a[], size_t n )
{
for ( _Bool sorted = 0; n-- != 0 && !sorted; )
{
sorted = 1;
for ( size_t i = 0; i < n; i++ )
{
if ( a[i+1] < a[i] )
{
sorted = 0;
swap( a, i );
}
}
}
}
int main(void)
{
int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
printf( "\n" );
bubble_sort( a, N );
for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
printf( "\n" );
return 0;
}
The output is
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9