My function writePrime has to write all prime numbers from array using pointer arithmetic. I cannot use any other function except main and writePrime.
#include <stdio.h>
void writePrime(int arr[], int n) {
int *q = arr, *qq = arr, i, prime;
while (q < arr + n) {
while (qq < arr + n) {
i = 1;
if (*qq % i != 0)
continue;
else
prime = 1;
i++;
qq++;
}
if (prime == 1)
printf("%d ", *q);
q++;
}
}
int main() {
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 92, 93, 94, 95, 96};
int n = sizeof(arr) / sizeof(*arr);
writePrime(arr, n);
return 0;
}
This code just prints the same unchanged array. How could I modify this to work?
The variable n should be declared as having the type size_t
size_t n = sizeof(arr) / sizeof(*arr);
because it is the type of an expression with the sizeof operator.
So the function should be declared like
void writePrime( const int arr[], size_t n );
Using two loops with two pointers within the function does not make a sense.
Each variable is divisible by 1. So this code snippet
i = 1;
if (*qq % i != 0)
continue;
else
prime = 1;
also does not make any sense.
And you are using initially uninitialized variable prime that must be reset before processing each element of the array.
The function can be defined the following way
void writePrime( const int arr[], size_t n )
{
for ( const int *p = arr; p != arr + n; ++p )
{
int prime = *p % 2 == 0 ? *p == 2 : *p != 1;
for ( int i = 3; prime && i <= *p / i; i += 2 )
{
if ( *p % i == 0 ) prime = 0;
}
if ( prime ) printf( "%d ", *p );
}
putchar( '\n' );
}
Related
I want to print the number of unique elements instead of show the elements For example show 4. Means we have 4 unique elements
#include<stdio.h>
#define max 100
int ifexists(int z[], int u, int v)
{
int i;
for (i=0; i<u;i++)
if (z[i]==v) return (1);
return (0);
}
void main()
{
int p[max], q[max];
int m;
int i,k;
k=0;
printf("Enter length of the array:");
scanf("%d",&m);
printf("Enter %d elements of the array\n",m);
for(i=0;i<m;i++ )
scanf("%d",&p[i]);
q[0]=p[0];
k=1;
for (i=1;i<m;i++)
{
if(!ifexists(q,k,p[i]))
{
q[k]=p[i];
k++;
}
}
printf("\nThe unique elements in the array are:\n");
for(i = 0;i<k;i++)
printf("%d\n",q[i]);
}
https://onlinegdb.com/Bk3tvQMpw
Sort the array then iterate through the elements and print out if the current element is different than the last:
int cmpint(const void *a, const void *b) {
return *(int *) a) < *(int *) b :
-1 ?
(
*(int *) b) < *(int *) a ?
1 :
0
);
}
int main() {
/* ... */
qsort(p, m, sizeof(*p), cmpint);
int n = 0;
for(int i = 0; i < m; i++) {
if(!i || p[i-1] != p[i]) n++;
}
printf("Number of unique elements: %d\n", n);
}
where p is your now sorted array and length is m as per example code. As qsort is expected O(m *log(m)) so will this aglorithm. If you don't sort the array it will be O(m^2) due to m linear searches.
If I have understood the question correctly what you need is to count unique elements in an array using a function and without defining an auxiliary array. That is there is no need to output the unique elements themselves.
In this case the corresponding function can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
int is_unique( const int a[], size_t n, int value )
{
while ( n != 0 && a[ n - 1 ] != value ) --n;
return n == 0;
}
int main(void)
{
int a[] = { 1, 2, 3, 3, 2, 1 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t count = 0;
for ( size_t i = 0; i < N; i++ )
{
count += is_unique( a, count, a[i] );
}
printf( "There are %zu unique elements in the array.\n", count );
return 0;
}
The program output is
There are 3 unique elements in the array.
If you do not want to define one more function to count unique elements in an array then just move the loop in the function shown in the above demonstrative program inside main.
Here you are.
#include <stdio.h>
int main(void)
{
int a[] = { 1, 2, 3, 3, 2, 1 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t count = 0;
for ( size_t i = 0; i < N; i++ )
{
size_t j = i;
while ( j != 0 && a[j - 1] != a[i] ) --j;
count += j == 0;
}
printf( "There are %zu unique elements in the array.\n", count );
return 0;
}
The program output is the same as shown above that is
There are 3 unique elements in the array.
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
instead of
void main()
I am trying to write a sorting algorithm using a function that finds the adress of the minimum element in the array:
#include <stdio.h>
int * findMin(int * start,int * end) ///function to return the adress of the smallest array element
{
int *min = start;
int x;
int size = (end - start);
for(x=0; x<size; x++)
{
if (*(start+x)<*min)
min = (start+x);
}
return min;
}
But here in my sort algorithm, since the last element has nothing more to compare itself with, is mistakenly left as it is
void sort(int * start, int * end) ///funtion to sort the array in ascending order
{
int x,temp;
int size = (end - start);
for (x = 0; x <size; x++)
{
if ( *(start+x) > *findMin(start,end))
{
temp = *findMin(start+x,end);
*findMin(start+x,end) = *(start+x);
*(start+x) = temp;
}
}
}
int main()
{
int arr[10]={5,11,3,12,17,25,1,9,14,2};
sort(arr,&arr[9]);
for(int i=0;i<10;i++)
printf("%d ",arr[i]);
printf("\n");
}
How can I correct this?
The expression in this declaration
int size = (end - start);
does not give the exact size of the array. At least you should write
int size = end - start + 1;
However it is not a good idea to pass the pointer to the last element of the array instead of the pointer to the memory after the last element of the array. In this case you can specify an empty range as start is equal to end.
Also if the function accepts two pointers then there is no need to introduce intermediate variables used as indices in loops.
And this code snippet
temp = *findMin(start+x,end);
*findMin(start+x,end) = *(start+x);
*(start+x) = temp;
is very inefficient.
Here is a demonstrative program that shows how the functions can be implemented.
#include <stdio.h>
int * findMin( const int * start, const int * end ) ///function to return the adress of the smallest array element
{
const int *min = start;
if ( start != end )
{
while ( ++start != end )
{
if ( *start < *min ) min = start;
}
}
return ( int * )min;
}
void selection_sort( int *start, int *end ) ///funtion to sort the array in ascending order
{
for ( ; start != end; ++start )
{
int *min = findMin( start, end );
if ( min != start )
{
int tmp = *start;
*start = *min;
*min = tmp;
}
}
}
int main(void)
{
int arr[] = { 5, 11, 3, 12, 17, 25, 1, 9, 14, 2 };
const size_t N = sizeof( arr ) / sizeof( *arr );
for ( const int *p = arr; p != arr + N; ++p )
{
printf( "%d ", *p );
}
putchar( '\n' );
selection_sort( arr, arr + N );
for ( const int *p = arr; p != arr + N; ++p )
{
printf( "%d ", *p );
}
putchar( '\n' );
return 0;
}
The program output is
5 11 3 12 17 25 1 9 14 2
1 2 3 5 9 11 12 14 17 25
But here in my sort algorithm, since the last element has nothing more to compare itself with, is mistakenly left as it is
No, that's at best a misleading characterization. Your findMin() does not specifically compare array elements to their immediate successors, so the fact that *end has no successor is irrelevant. The problem is (in part) simply that you have an off-by-one error, resulting in never comparing *end with *min. That mistake would be harder to make and easier to recognize if you relied more directly on pointer arithmetic and comparisons:
int *findMin(int *start, int *end) {
int *min = start;
// The original code is equivalent to this variant:
// for (int *x = start; x < end; x++) {
// but this is what you need for an inclusive upper bound:
// for (int *x = start; x <= end; x++) {
// or, since initially min == start, this would be even better:
for (int *x = start + 1; x <= end; x++) {
if (*x < *min) {
min = x;
}
}
return min;
}
I've prepared a code that should found the longer series of elements in growing order .for example ,in arrays exists following elements : 1 2 3 4 5 2 7 6 7 9,output will 5 (the series from 1 to 5) ,function will return integer tempcount that include numbers of element and print it.but get an error ,the function
isn't working:
#include "stdafx.h"
#include <stdio.h>
int find_maximum(int[], int);
int main() {
int c, array[100], size, location, maximum,found;
scanf_s("%d", &size);
for (c = 0; c < size; c++)
scanf_s("%d", &array[c]);
location = find_maximum(array, size);
maximum = found;
printf("Maximum elements = %d ", maximum);
return 0;
}
int find_maximum(int a[], int n) {
int c, index = 0,count =1,tempCount=1;
for (c = 1; c < n; c++)
if (a[c] > a[index])
count +=1;
else
{
if (count > tempCount)
{
tempCount=count;
}
}
return tempCount;
}
The variables maximum and found are not initialized and are used nowhere except this statement that does not make sense
maximum = found;
You are storing the length of the maximum subsequence in the variable location
location = find_maximum(array, size);
It is the variable value which you need to output.
The function find_maximum also does not make sense. For example you are comparing elements of the array with the same element at position 0.
int c, index = 0,count =1,tempCount=1;
^^^^^^^^^
for (c = 1; c < n; c++)
if (a[c] > a[index])
count +=1;
//…
The function can be declared and implemented as it is shown in the demonstrative program below.
#include <stdio.h>
size_t max_ascending_seq( const int a[], size_t n )
{
size_t max_n = 0;
for ( size_t i = 0; i < n; )
{
size_t current_n = 1;
while ( ++i < n && a[i-1] < a[i] ) ++current_n;
if ( max_n < current_n ) max_n = current_n;
}
return max_n;
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 2, 7, 6, 7, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t max_n = max_ascending_seq( a, N );
printf( "%zu\n", max_n );
return 0;
}
The program output is
5
A more generic function can be written the following way.
#include <stdio.h>
size_t max_ascending_seq( const int a[], size_t n, int predicate( int, int ) )
{
size_t max_n = 0;
for ( size_t i = 0; i < n; )
{
size_t current_n = 1;
while ( ++i < n && predicate( a[i-1], a[i] ) ) ++current_n;
if ( max_n < current_n ) max_n = current_n;
}
return max_n;
}
int less_than( int x, int y )
{
return x < y;
}
int greater_than( int x, int y )
{
return y < x;
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 2, 7, 6, 7, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t max_n = max_ascending_seq( a, N, less_than );
printf( "%zu\n", max_n );
max_n = max_ascending_seq( a, N, greater_than );
printf( "%zu\n", max_n );
return 0;
}
The program output is
5
2
I want to find the number within a range in an array and must be in a recursive way. The function variables couldn't be modified.
Let's say in the range of 2 and 3
The input is : int a[] = {4, 1, 3, 1, 3, 2};
and the output will be = {3,3,2} , 3 found
Not sure how to code the recursive function in this case. The below I have tried not working.
int within(int a[], int N, int lower, int upper, int result[])
{
if(N == 1 && N <= upper && N>= lower)
return a[0];
return within(&a[1], N-1, lower, upper, result);
}
int main()
{
int a[] = {4, 1, 3, 1, 3, 2};
int result[6] = {0};
int i, nResult;
nResult = within(a, 6, 2, 3, result);
printf("%d data passed the bounds\n", nResult);
for (i = 0; i < nResult; i++){
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
I want to find the number within a range in an array
Let's say in the range of 2 and 3
Normally a for loop or similar would be so much easier here
If it has to be recursive....
// need to have another number - r - number in range
// r starts at zero
//
// normally lower case for variable and capitals for things you #define
// N starts at the number of elements of a less one
//
int within(int a[], int N, int lower, int upper, int r, int result[])
{
if(a[0] <= upper && a[0]>= lower) {
result[r]= a[0];
r++;
}
if(N==0) {
return r;
} else {
r = within(&a[1], N-1, lower, upper, r, result);
return r;
}
}
the function will give a return value of the number of values found within the range.
The code above is recursive, but so much more complicated and fragile than a simple loop... such as the fragment below
for (i=0;i<N;i++) {
if(a[i] <= upper && a[i]>= lower) {
result[r]= a[i];
r++;
}
}
If it has to be recursive wihtout r...
// need to have another number - result[0] - number in range
// result[0] starts at zero
//
// normally lower case for variable and capitals for things you #define
// N starts at the number of elements of a less one
//
int within(int a[], int N, int lower, int upper, int result[])
{
if(a[0] <= upper && a[0]>= lower) {
result[0]++;
result[result[0]]= a[0];
}
if(N==0) {
return result[0];
} else {
result[0] = within(&a[1], N-1, lower, upper, result);
return result[0];
}
}
now result conatins
{number in range, first number in range, second number in range....}
Something like this. If you want to implement a recursive function, try to do it in the way that the recursive call happens at the end.
#include <stdio.h>
int find_in_range(int* out, int const *in, int length, int from, int to)
{
if (length == 0)
{
return 0;
}
int addon;
if (*in >= from && *in <= to)
{
*out = *in;
++out;
addon = 1;
}
else
{
addon = 0;
}
return find_in_range(out, in + 1, length - 1, from, to) + addon;
}
#define N 6
int main()
{
int in[N] = {4, 1, 3, 1, 3, 2};
int out[N] = {0};
int num_found = find_in_range(out, in, N, 2, 3);
for (int i = 0; i < num_found; ++i)
{
printf("%d ", out[i]);
}
printf("\n");
return 0;
}
You can modify the following code as per your requirements. This is just a proof of concept code:
#include <stdio.h>
#include <stdlib.h>
static int result[4];
static int ctr1 = 0;
static int ctr2 = 0;
void recFind(int* arr, int* key){
if(ctr2 == 8)
return;
if(*arr >= key[0] && *arr <= key[1])
result[ctr1++] = *arr;
arr++;
ctr2++;
recFind(arr, key);
}
int main(){
int arr[] = {1,3,3,6,4,6,7,8};
int key[] = {1,4};
recFind(arr, key);
printf(" { ");
for(int i = 0; i < 4; i++){
printf("%d ", result[i]);
}
printf("}\n");
}
As it follows from the description of the assignment the function should provide two values: the number of elements that satisfy the condition and an array that contains the elements themselves.
It is evident that the array should be allocated dynamically. And it is logically consistent when the function itself returns the number of elements while the pointer to the generated array is passed by reference as an argument.
The recursive function can look the following way
#include <stdio.h>
#include <stdlib.h>
size_t get_range( const int a[], size_t n, int lower, int upper, int **out )
{
size_t m;
if ( n )
{
m = get_range( a, n - 1, lower, upper, out );
if ( lower <= a[n-1] && a[n-1] <= upper )
{
int *tmp = realloc( *out, ( m + 1 ) * sizeof( int ) );
if ( tmp )
{
tmp[m] = a[n-1];
*out = tmp;
++m;
}
}
}
else
{
*out = NULL;
m = 0;
}
return m;
}
int main(void)
{
int a[] = { 1, 2, 3, 4, 5, 4, 3, 2, 1 };
const size_t N = sizeof( a ) / sizeof( *a );
int lower = 2, high = 3;
int *out;
size_t n = get_range( a, N, lower, high, &out );
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", out[i] );
}
putchar( '\n' );
free( out );
return 0;
}
The program output is
2 3 3 2
Below codes will work for you in recursive way. If you don't want to print the numbers just comment out printf statement inside function printfRange. Hope you can understand the logic :-
int within(int *a, int rngH, int rngL, int length)
{
int len = length;
static int i = 0;
static int found = 0;
if(len <=0 )
{
return i;
}
if (*a == rngH)
{
printf("%d,",*a);
i++;
found = 1;
within(++a,rngH, rngL,--len);
}
else if(*a == rngL && found > 0)
{
printf("%d,",*a);
i++;
within(++a,rngH, rngL,--len);
}
else
{
within(++a,rngH, rngL,--len);
}
return i;
}
int main() {
int a[] = {4, 1, 3, 1, 3, 2};
int total = within(a,3,2,6);
printf("\n");
printf("Total :%d\n",total);
return 0;
}
I'm trying to write a sorting function with just recursion. I keep getting the error:
lvalue required as unary '&' operand
This are the functions I'm using:
void sorter_rec (int a[], int n) {
if (n ==1 ) return;
else {
swap( &(maximumrec(a,n)), &a[n-1]);
sorter_rec(a,n-1);
return;
};
}
The error is in sorter_rec.
void swap(int *px, int *py)
{ int z = *px;
*px = *py;
*py = z;
return;
}
int maximumrec(int ar[], int n)
{
if (n == 1) {
return ar[0];
} else {
int max = maximumrec(ar, n-1);
return ar[n-1] > max ? ar[n-1] : max;
}
}
How can I solve this?
You may not apply the operator & to the temporary object returned by the function maximumrec.
Also if you are using the selection sort starting from the end of array then the maximum element should be also searched starting from the end of array. In this case the sorting algorithm will be more stable.
Here is a demonstrative program that uses your approach but instead of the searching maximum element it searches minimum element. You can rewrite it such a way that it would search the maximum element if you want.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define N 20
int * min_element( int a[], size_t n )
{
int *min = a;
if ( !( n < 2 ) )
{
min = min_element( a + 1, n - 1 );
min = *min < *a ? min : a;
}
return min;
}
void swap( int *a, int *b )
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void sort( int a[], size_t n )
{
if ( !( n < 2 ) )
{
int *min = min_element( a, n );
if ( min != a ) swap( a, min );
sort( a + 1, n - 1 );
}
}
int main(void)
{
int a[N];
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < N; i++ ) a[i] = rand() % N;
for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
printf( "\n" );
sort( a, N );
for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
printf( "\n" );
return 0;
}
The program output might look like
17 9 12 15 1 17 19 17 6 2 14 19 2 8 5 19 0 12 16 8
0 1 2 2 5 6 8 8 9 12 12 14 15 16 17 17 17 19 19 19
Your basic algorithm works. All I had to do was fix up the way you passed pointers around, and it worked the first time! Hope this helps. I changed some names to fit my own style a bit, and added some convenience things (macro and logging method), and main() so I could test it.
Note that the name of an array is the same as &array[0]
#include <stdio.h>
#define INT_COUNT(n) (sizeof(n) / sizeof(int))
void dumpIntArray(int *array, int n) {
printf("{ ");
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf(" }\n");
}
void swap(int *px, int *py) {
int z = *px;
*px = *py;
*py = z;
return;
}
int *ptrToMax(int *sortable, int n) {
if (n == 1) {
return sortable;
} else {
int *maximum = ptrToMax(sortable, n - 1);
return sortable[n - 1] > *maximum ? &sortable[n - 1] : maximum;
}
}
void quicksort(int *sortable, int n) {
if (n == 1 ) {
return;
} else {
swap(ptrToMax(sortable, n), &sortable[n - 1]);
quicksort(sortable, n - 1);
return;
}
}
int main(int argc, char **argv) {
int foo[] = { 1, 5, 3, 2, 4, 9, 10, 8, 7 };
printf("Before:\n");
dumpIntArray(foo, INT_COUNT(foo));
quicksort(foo, INT_COUNT(foo));
printf("After:\n");
dumpIntArray(foo, INT_COUNT(foo));
}