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
Related
The following code takes an array of integers and create an array with the mobile means (i.e. the value in i-th place is the mean of the last n elements in the array before i (if they exists); if i<n, it is the mean of the existing elements before i. Thus as an example: for n=3
1 2 3 4 5 6 -> 1 1.5 2 3 4 5
#include <stdio.h>
#include <stdlib.h>
float *
mobMean (int x[], int n, int nval)
{
int i, j, sum, num;
float *means;
if(means=malloc(sizeof(float) * nval))
{
for(i=0; i<nval; i++)
{
sum=0;
num=0;
for(j=i; j>=0 && i-j>=n; j--)
{
sum+=x[j];
num++;
}
*(means+i)=(float)sum/num;
}
}
else
printf("e");
return means;
}
int
main()
{
int a[10], i;
float *b;
for(i=0; i<10; i++)
scanf("%d", &a[i]);
b=mobMean(a,3,10);
for(i=0; i<10; i++)
printf("%f", *(b+i));
free(b);
return 0;
}
The console (gcc compiler) returns as an output -nan 10 times consecutively. not only my pc, but also the online compiler. google doesn't have a clue of what that is. i would really appreciate your help.
The body of this for loop
for(j=i; j>=0 && i-j>=n; j--)
is never executed due to the condition i-j>=n because initially i - j is equal to 0.
You could write for example
sum = x[i];
num = 1;
for ( j = i; j-- != 0 && num < n; ++num )
{
sum += x[j];
}
Here is a demonstration program.
#include <stdio.h>
#include <stdlib.h>
float * mobMean( const int a[], size_t size, size_t n )
{
float *means = NULL;
if (( means = malloc( sizeof( float ) * size ) ) != NULL)
{
for (size_t i = 0; i < size; i++)
{
float sum = a[i];
size_t num = 1;
for (size_t j = i; j-- != 0 && num < n; ++num)
{
sum += a[j];
}
means[i] = sum / num;
}
}
return means;
}
int main( void )
{
int a[] = { 1, 2, 3, 4, 5, 6 };
const size_t N = sizeof( a ) / sizeof( *a );
float *b = mobMean( a, N, 3 );
if (b != NULL)
{
for (size_t i = 0; i < N; i++)
{
printf( "%.1f ", b[i] );
}
putchar( '\n' );
}
free( b );
}
The program output is
1.0 1.5 2.0 3.0 4.0 5.0
I declared local variables in for loops. You may declare them before loops in beginnings of code blocks if you marked the question with the language tag c89.
I am trying to make a recursive function to sort an array. The idea is to swap two elements whenever the one with smaller index is larger, because we want to sort into ascending order. The following is the program in C that I have written for this
void sort(int a[30], int n)
{
int m = 0,i,temp;
for(i = 0;i<n-1,m==0;i++)
{
printf("The array when i is %d is %d",i,a[0]);
for(i=1;i<n;i++)
printf(",%d",a[i]);
printf("\n");
if(a[i]>a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
m = 1;
}
}
if(m==0)
{
printf("The sorted array is %d",a[0]);
for(i=1;i<n;i++)
printf(",%d",a[i]);
}
else
sort(a,n);
}
int main()
{
int a[30],n;
printf("Enter the number of elements\n");
scanf("%d",&n);
if(n>30||n<1)
printf("The number of elements should be a natural number not exceeding 30");
else
{
int i;
for(i=0;i<n;i++)
{
printf("Enter element number %d\n",i+1);
scanf("%d",&a[i]);
}
sort(a,n);
}
return 0;
}
This program is not giving desired output, it runs into a very long loop (even for n=4), and then suddenly stops.
Can somebody please detect the problem??
In the condition of the if statement
for(i = 0;i<n-1,m==0;i++)
there is used the comma operator. Its value is the value of the right hand operand that is of m==0.
I think you mean
int m = 1;
for (i = 0; m != 0 && i<n-1; i++ )
{
m = 0;
//...
That is if in the inner loop there was not swapping elements of the array that means that the array is already sorted then m will be equal to 0 and the outer loop will stop its iterations.
Also withing the inner loop you have to use another variable for the index not i.
Here is a demonstrative program that shows how the function can be implemented based on the method bubble sort.
#include <stdio.h>
void bubble_sort( int a[], size_t n )
{
if ( !( n < 2 ) )
{
size_t last = 1;
for ( size_t i = last; i < n; i++ )
{
if ( a[i] < a[i-1] )
{
int tmp = a[i];
a[i] = a[i-1];
a[i-1] = tmp;
last = i;
}
}
bubble_sort( a, last );
}
}
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' );
bubble_sort( a, N );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
return 0;
}
The program output is
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
you declare int i once here int m = 0,i,temp; then use it for every loop
look:
for(i = 0;i<n-1,m==0;i++)
{
printf("The array when i is %d is %d",i,a[0]);
//error for(i=1;i<n;i++)//this is your infinitive loop
printf(",%d",a[i]);
printf("\n");
if(a[i]>a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
m = 1;
}
}
every time you you enter this loop
for(i=1;i<n;i++)
printf(",%d",a[i]);
your i become 1 and then after loop , it will be 3 and so this will effect your base loop:(after first time)
for(i = 0;i<n-1,m==0;i++)
your i here will always be 4 so this is an infinitive loop
look at this
void swap(int array[], int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
void sort(int array[], int startpoint, int arraylength) {
if (startpoint == arraylength - 1) return;
int minindex = startpoint;
for (int i = startpoint; i < arraylength; i++) if (array[i] < array[minindex]) minindex = i;
swap(array, startpoint, minindex);
sort(array, startpoint + 1, arraylength);
}
int main()
{
int a[30], n;
printf("Enter the number of elements\n");
scanf("%d", &n);
if (n > 30 || n < 1)
printf("The number of elements should be a natural number not exceeding 30");
else
{
int i;
for (i = 0; i < n; i++)
{
printf("Enter element number %d\n", i + 1);
scanf("%d", &a[i]);
}
sort(a,0, n);
}
return 0;
}
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
What's wrong with my C program? the title is to sort n number from small to large, when i run it, everything goes fine but the number isn't been sorted. I just don't know how to solve that although i have thought for a long time.
Here is the code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void selection(int *a[], int n);
int main()
{
int n;
int i;
scanf("%d", &n);
int *a[n];
int b[n];
srand((int) time(0));
for (i = 0; i < n; i++)
{
b[i] = ((int) (rand() % 100));
a[i] = &b[i];
}
selection(a, n);
return 0;
}
void selection(int *a[], int n)
{
int i;
int j;
int position;
int temp;
for (i = 0; i < n - 1; i++)
{
position = i;
for (j = i + 1; j < n; j++)
{
if (*a[i] > *a[j])
position = j;
}
temp = *a[i];
*a[i] = *a[position];
*a[position] = temp;
}
for (i = 0; i < n - 1; i++)
printf("%d\n", *a[i]);
}
I have found neither the quick sort nor the bubble sort in the presented code.
It seems you are trying to use the selection sort.
I think that the function can look the following way.
void selection_sort( int * a[], int n )
{
int i;
for ( i = 0; i < n; i++ )
{
int position = i;
int j = i + 1;
for ( ; j < n; j++ )
{
if ( *a[j] < *a[position] ) position = j;
}
if ( position != i )
{
int *temp = a[position];
a[position] = a[i];
a[i] = temp;
}
}
for ( i = 0; i < n; i++ ) printf( "%d ", *a[i] );
putchar( '\n' );
}
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