Copying elements from an array to another one and counting the number of a character in C - c

I'm new to C, so I apologize for asking silly questions.
I need to copy certain elements from an array to another one, but I can't make it work and get random numbers instead. In this case I need all the elements after the smallest one from the first array to be copied to the second one.
The other thing I can't figure out is a function that counts how many times a certain symbol is used. I need to find the number of times I've used the biggest odd digit in an array.
Here's the code, I've made so far. I hope you understand most of it:
#include <stdio.h>
#define DIM 100
int enter (int x[]);
int min (int x[], int y[], int n);
int sort (int x[], int n);
void print (int x[], int n);
//=============================================
int main () {
int a[DIM], b[DIM], n, i;
n = enter (a);
printf("The smallest element in the first array: %d.\n The smallest element in the second array: %d.\n", min (a, b, n));
printf("%d\n", sort (b, n));
for (i = 0; i < n; i++)
printf ("%d ", b[i]);
printf ("\n");
system("pause");
return 0;
}
//===========================================================
int enter (int x[]) {
int i, n;
do {
printf ("Enter number of elements in array: ");
scanf ("%d", &n);
}
while (n < 1 || n > DIM);
printf ("Enter %d elements:\n", n);
for (i = 0; i < n; i++)
scanf ("%d", &x[i]);
return x[i], n;
}
int min (int x[], int y[], int n) {
int minimum, i, j=0, p;
minimum = x[0];
for ( i = 1 ; i < n ; i++ ) {
if ( x[i] < minimum ) {
minimum = x[i];
p = i+1;
}
}
for (i = p+1; i<n; i++ && j++) {
x[i] = y[j];
}
return minimum;
}
int sort (int x[], int n) {
int i, j, a;
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j) {
if (x[i] > x[j]){
a = x[i];
x[i] = x[j];
x[j] = a;
}
}
}
printf("Elements from array in ascending order: \n");
for (i = 0; i < n; ++i)
printf("%d\n", x[i]);
return x[i];
}

I need to find the number of times I've used the biggest odd digit in
an array.
Fist sort your array start at the end and find the biggest odd number. You can find a odd number by number%2==1. Finally count equal numbers:
// sort the array
sort(b, n); // sort function from your questions code
// find the biggest odd number
int i = n-1;
while ( i >= 0 && b[i]%2 == 0 )
{
i --;
}
// count the biggest odd number
count = 0;
int j = i;
while ( j >= 0 && b[i]==b[j] ) // note first time i==j !
{
count ++;
j --;
}
If you don't want to sort your array use this:
// find the biggest odd number
int oddInx = -1;
for ( int i = 0; i < n; i++ )
{
if ( b[i]%2 == 1 && ( oddInx < 0 || b[i] > b[oddInx] ) )
oddInx = i;
}
// count the biggest odd number
count = 0;
if ( oddInx >= 0 )
{
for ( int i = 0; i < n; i++ )
{
if ( b[i] == b[oddInx] )
count ++;
}
}

Related

Program to find prime numbers from the set of numbers of Fibonacci series in C

I want to find prime numbers from the Fibonacci series after printing them. First, I implemented the code for Fibonacci then added each element into an array. Then passed the array to a method to check for prime. Wanted to try it with an array. Displaying the series but not the prime numbers from the following code.
#include <stdio.h>
int fib()
{
int a=0,b=1, arr[20];
arr[0] = a;
arr[1] = b;
printf("%d, %d,",a, b );
int c=0;
for(int i=2; i<=20; i++)
{
c=a+b;
arr[i] = c;
printf("%d,",c);
a=b;
b=c;
}
checkPrime(arr);
}
void checkPrime(int a[])
{
int i, count;
for(i=0; i<sizeof(a); i++)
{
count=0;
for(int j=2; j<=a[i]/2 ; j++)
{
if(a[i]%2==0)
count++;
}
if(count>1)
printf("%d is a Prime", a[i]);
}
}
int main()
{
fib();
}
Output of the code
0, 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,
8 is a Prime
You have certain bugs in your implementation.
In fib function you iterate until i <= 20 but your arr have length 20 therefore your loop will go out of bounds of array. You should iterate until i < 20 or increase length of your array.
In checkPrime function you iterate until i < sizeof(a). But sizeof function doesn't return size of your array. It returns size of type of variable that you pass to it therefore it will return sizeof(int*) which = 8 (in case you 64 bit machine but I guess you have). To fix this bug you should pass length of your array in checkPrime function and use it.
You don't reset the count variable after j loop.
checkPrime function doesn't check if the number is prime. You have wrong expression in your nested loop. To check if number N is prime you should check if there any divisor of N that at least less than sqrt(N). Your expression is wrong.
Considering the adjustments above I suggest the next solution:
void checkPrime(int a[], size_t a_len) {
int i, count;
for (i = 1; i < a_len; i++) {
count = 0;
for (int j = 2; j <= sqrt((double)a[i]); j++) {
if (a[i] % j == 0) {
count++;
break;
}
}
if (count == 0) {
printf("%d is a Prime\n", a[i]);
} else {
count = 0;
}
}
}
int fib() {
size_t arr_size = 21;
int a = 0, b = 1, arr[arr_size];
arr[0] = a;
arr[1] = b;
printf("%d, %d, ", a, b);
int c = 0;
for (int i = 2; i < arr_size; i++) {
c = a + b;
arr[i] = c;
if (i == arr_size - 1)
printf("%d ", c);
else
printf("%d, ", c);
a = b;
b = c;
}
printf("\n");
checkPrime(arr, arr_size);
}

Sorting an array with duplicate values without modifying the elements, without using secondary array or without using any inbuilt function

So as the question says i am just trying to sort an array with duplicate values.
The array is sorted properly but problem arises when a duplicate value is given to the array
O/P:without duplicate
Enter the size of the array : 5
Enter the 5 elements
7 3 4 8 1
After sorting: 1 3 4 7 8
Original array value 7 3 4 8 1
O/P: with duplicates
5 3 1 1 4
After sorting: 1 3 4 1 3
Original array value 5 3 1 1 4
#include <stdio.h>
void print_sort(int *arr, int size) //function definition
{
int i, j, k, temp, largest = arr[0], smallest = arr[0];
for( i = 1 ; i < size ; i++ )
{
if(arr[i] > largest)
{
largest = arr[i];
}
if(arr[i] < smallest)
{
smallest = arr[i];
}
}
printf("After sorting: ");
for(i = 0; i < size; i++)
{
temp = largest;
printf("%d ", smallest);
for(k = i + 1; k < size; k++)
{
if(arr[i] == arr[k])
{
smallest = arr[i];
break;
}
for(j = 0; j < size; j++)
{
if(arr[j] > smallest && arr[j] < temp)
{
temp = arr[j];
}
}
smallest = temp;
}
}
printf("\n");
printf("Original array value ");
for( i = 0 ; i < size ; i++ )
{
printf("%d ", arr[i]);
}
}
int main()
{
int size, i;
printf("Enter the size of the array : ");
scanf("%d", &size);
int arr[size];
printf("Enter the %d elements\n",size);
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
print_sort(arr, size);
}
I understand that it is a specific exercise (homework ?), with no possibility to modify the array not to use an additional array.
This implies that classical sorting algorithms cannot work.
Iteratively searching for the minimum is a possible solution, even if not efficient O(n^2).
To cope with duplicates, it it necessary not only to memorize the current minimum, but also its position.
This is a possible implementation.
#include <stdio.h>
#include <stdlib.h>
void print_sort(int *arr, int size) //function definition
{
int i, j, k, largest = arr[0], smallest = arr[0];
int i_smallest = 0;
for (i = 1; i < size; i++ ) {
if (arr[i] > largest) {
largest = arr[i];
}
if(arr[i] < smallest) {
smallest = arr[i];
i_smallest = i;
}
}
printf("After sorting: ");
for (i = 0; i < size; i++) {
int temp = largest + 1;
int i_temp = -1;
printf("%d ", smallest);
if (i == size-1) break;
for (k = 0; k < size; k++) {
if (arr[k] < smallest) continue;
if (arr[k] == smallest) {
if (k <= i_smallest) continue;
i_temp = k;
temp = smallest;
break;
}
if (arr[k] < temp) {
temp = arr[k];
i_temp = k;
}
}
smallest = temp;
i_smallest = i_temp;
}
printf("\n");
printf("Original array value ");
for( i = 0 ; i < size ; i++ )
{
printf("%d ",arr[i]);
}
}
int main(void) {
int size, i;
printf("Enter the size of the array : ");
if (scanf("%d", &size) != 1) exit(1);
int arr[size];
printf("Enter the %d elements\n",size);
for (i = 0; i < size; i++) {
if (scanf("%d", &arr[i]) != 1) exit(1);
}
print_sort(arr, size);
return 0;
}
Maybe it is easier to insert each read value directly into the sorted Array. So you don't have to sort the array afterwards.
If you want to do it this way, geeksforgeeks.org has nice examples also for C which I already used (https://www.geeksforgeeks.org/search-insert-and-delete-in-a-sorted-array/).
// C program to implement insert operation in
// an sorted array.
#include <stdio.h>
// Inserts a key in arr[] of given capacity. n is current
// size of arr[]. This function returns n+1 if insertion
// is successful, else n.
int insertSorted(int arr[], int n, int key, int capacity)
{
// Cannot insert more elements if n is already
// more than or equal to capacity
if (n >= capacity)
return n;
int i;
for (i = n - 1; (i >= 0 && arr[i] > key); i--)
arr[i + 1] = arr[i];
arr[i + 1] = key;
return (n + 1);
}
/* Driver program to test above function */
int main()
{
int arr[20] = { 12, 16, 20, 40, 50, 70 };
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 26;
printf("\nBefore Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
// Inserting key
n = insertSorted(arr, n, key, capacity);
printf("\nAfter Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

Why is my code producing a segmentation fault?

So im working on this program that is supposed to take the pointer to an array and the array’s size (number of elements in the array)
as arguments, finds the place the index of the outlier, fixes the array in place (that is puts the outlier to a
place it is supposed to be), and returns the old index where the outlier was found. i finished my code but for some reason, somewhere in my main function its telling me there is a segmentation fault, i know its in my main function because it compiled and ran fine when it was just the original code. heres the code;
#include <stdio.h>
long long int fix_sorted_array(double* arr, unsigned long n)
{
double temp;
int i, j;
for ( i = 0; i < n - 1; i ++)
{
if (arr[i] > arr[i + 1])
{
for ( j = i + 1; j > 0; j --)
{
if (arr[j] < arr[j-1])
{
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
return i + 1;
}
}
return -1;
}
int main()
{
int n;
int j;//declared variables
double arr[n];
printf("Enter elements of array : \n");
for ( int i = 0; i < n; i ++)
{
scanf("%lf", &arr[i]);
}
printf("Return index : %lld\n",fix_sorted_array (&arr[n], n));
printf("Array after : \n");
for ( j = 0; j < n; j ++)
{
printf("%.2lf", arr[j]);
}
}
You're passing an address outside the array to the function in this line:
printf("Return index : %lld\n",fix_sorted_array (&arr[n], n));
You want to pass the address of the start of the array, not the end, so it should be:
printf("Return index : %lld\n",fix_sorted_array (arr, n));
You also need to initialize n before you declare the array.
printf("How many numbers? ");
scanf("%d", &n);
double arr[n];
You have never accepted the value of n. Below code might help.
#include <stdio.h>
long long int fix_sorted_array(double* arr, unsigned long n)
{
double temp;
int i, j;
for ( i = 0; i < n - 1; i ++)
{
if (arr[i] > arr[i + 1])
{
for ( j = i + 1; j > 0; j --)
{
if (arr[j] < arr[j-1])
{
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
return i + 1;
}
}
return -1;
}
int main()
{
int n;
int j;//declared variables
printf("Enter the number of elements in arrays");
scanf("%d",&n); // initialize the values of n
double arr[n];
printf("Enter elements of array : \n");
for ( int i = 0; i < n; i ++)
{
scanf("%lf", &arr[i]);
}
printf("Return index : %lld\n",fix_sorted_array (&arr[0], n)); // Also pass the value of starting index in array i.e. `arr[0]`
printf("Array after : \n");
for ( j = 0; j < n; j ++)
{
printf("%.2lf", arr[j]);
}
}

Recursive C program for sorting giving unexpected output

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;
}

Swapping largest and smallest numbers in C

I want to write a program that reads 10 int values from the user and swaps the largest and smallest numbers on the first and second values, then the rest of the numbers should be in the order.
Please check the code and help me what the wrong is.
For instance:
1
9
4
5
6
7
8
2
4
5
New order should be 9 1 4 5 6 7 8 2 4 5
#include <stdio.h>
int main() {
int a[10],i,min,max=0,pos=0;
printf("Please enter 10 int values :\n");
do{
scanf("%d", &a[pos++]);
} while (pos<10);
for (i=0; i<10;i++) {
printf("%i\n",a[i]);
if (max<a[i])
{
max=a[i];
}
if (min>a[i])
{
min=a[i];
}
for (i=0;i<10;i++) {
if (a[i]==max)
a[i]=max;
if (a[i] == min) a[i] = min;
}
printf("The new order is : %d %d %d ", max, min, ...);
return 0;
}
EDIT:
It is the new form
#include <stdio.h>
int main() {
int a[10],i,pos,temp,min = 0,max = 0;
printf("Please enter 10 int values :\n");
do {
scanf("%d", &a[pos++]);
} while (pos < 10);
for ( =1; i<10;i++) {
if (a[i]>a[max])
{
max=i;
}
if (a[i]<a[min])
{
min=i;
}
}
temp=a[max];
a[max]=a[min];
a[min]=temp;
printf("%d %d",a[max],a[min]);
for (i=0;i<10;i++){
if ((i != min) && (i != max)) {
printf("%d ", a[i]);
}
}
printf("\n");
return 0;
}
As others have noted, your code does not properly identify the maximum and minimum values in the array because you are writing min and max back into the array instead of the other way around.
Since you want to swap these values, what you actually want are the indices of the min and max values of the array, and swap those.
It is best to break this code into functions instead of having everything in main. Here is a solution that will do what you want:
#include <stdio.h>
int indexofmax(int *data, int len)
{
int max = 0;
int i;
for(i = 0; i < len; i++)
{
if(data[i]>data[max]) max = i;
}
return max;
}
int indexofmin(int *data, int len)
{
int min = 0;
int i;
for(i = 0; i < len; i++)
{
if(data[i]<data[min]) min = i;
}
return min;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
// user enters in 10 ints...
int max = indexofmax(a, 10);
int min = indexofmin(a, 10);
int i;
swap(&a[min], &a[max]);
for(i = 0; i < 10; i++)
{
printf("%d ", a[i]);
}
return 0;
}
This initialization min=0,max=0 is not right.
Instead have min = INT_MAX and max = INT_MIN.
By setting min=0, you would never get the lowest number in the array if it is greater than 0.
Similarly by setting max=0, you would never get the greatest number in the array if it is lower than 0.
You are gaining nothing by this code:
for(i=0;i<10;i++)
{ if(a[i]==max) a[i]=max;
if(a[i]==min) a[i]=min; }
It is evident that this loop
for(i=0;i<10;i++)
{ if(a[i]==max) a[i]=max;
if(a[i]==min) a[i]=min; }
does not make sense.
Moreover variable min is not initialized while variable max is initialized incorrectly.
int a[10],i,min,max=0,pos=0;
For example the array can contain all negative elements. In this case you will get incorrect value of the maximum equal to 0.
And I do not see where the elements are moved to the right to place the maximum and the minimum to the first two positions of the array.
If I have understood correctly then what you need is something like the following. To move the elements you could use standard function memmove declared in header <string.h>. However it seems you are learning loops.
#include <stdio.h>
#define N 10
int main( void )
{
int a[N] = { 4, 5, 9, 6, 7, 1, 8, 2, 4, 5 };
for (size_t i = 0; i < N; i++) printf("%d ", a[i]);
printf("\n");
size_t min = 0;
size_t max = 0;
for (size_t i = 1; i < N; i++)
{
if (a[max] < a[i])
{
max = i;
}
else if (a[i] < a[min])
{
min = i;
}
}
if (max != min)
{
int min_value = a[min];
int max_value = a[max];
size_t j = N;
for (size_t i = N; i != 0; --i)
{
if (i - 1 != min && i - 1 != max)
{
if (i != j)
{
a[j - 1] = a[i - 1];
}
--j;
}
}
a[--j] = min_value;
a[--j] = max_value;
}
for (size_t i = 0; i < N; i++) printf("%d ", a[i]);
printf("\n");
}
The program output is
4 5 9 6 7 1 8 2 4 5
9 1 4 5 6 7 8 2 4 5
You're not actually altering the array.
In the second loop, you say "if the current element is the max, set it to the max". In other words, set it to its current value. Similarly for the min.
What you want is to swap those assignments.
if(a[i]==max) a[i]=min;
if(a[i]==min) a[i]=max;
Also, your initial values for min and max are no good. min is unitialized, so its initial value is undefined. You should initialize min to a very large value, and similarly max should be initialized to a very small (i.e. large negative) value.
A better way to do this would be to keep track of the index of the largest and smallest values. These you can initialize to 0. Then you can check a[i] > a[max] and a[i] < a[min]. Then you print the values at indexes min and max, then loop through the list and print the others.
int i, temp, min=0, max=0;
for (i=1; i<10; i++) {
if (a[i] > a[max]) max = i;
if (a[i] < a[min]) min = i;
}
printf("%d %d ", a[max], a[min]);
for (i=0; i<10; i++) {
if ((i != min) && (i != max)) {
printf("%d ", a[i]);
}
}
printf("\n");
Just keep it nice and simple, like this:
#include <stdio.h>
#include <stdlib.h>
#define MAXNUM 10
int find_biggest(int A[], size_t n);
int find_smallest(int A[], size_t n);
void print_array(int A[], size_t n);
void int_swap(int *a, int *b);
int
main(void) {
int array[MAXNUM], i, smallest, biggest;
printf("Please enter 10 int values:\n");
for (i = 0; i < MAXNUM; i++) {
if (scanf("%d", &array[i]) != 1) {
printf("invalid input\n");
exit(EXIT_FAILURE);
}
}
printf("Before: ");
print_array(array, MAXNUM);
smallest = find_smallest(array, MAXNUM);
biggest = find_biggest(array, MAXNUM);
int_swap(&array[smallest], &array[biggest]);
printf("After: ");
print_array(array, MAXNUM);
return 0;
}
int
find_biggest(int A[], size_t n) {
int biggest, i, idx_loc;
biggest = A[0];
idx_loc = 0;
for (i = 1; i < n; i++) {
if (A[i] > biggest) {
biggest = A[i];
idx_loc = i;
}
}
return idx_loc;
}
int
find_smallest(int A[], size_t n) {
int smallest, i, idx_loc;
smallest = A[0];
idx_loc = 0;
for (i = 1; i < n; i++) {
if (A[i] < smallest) {
smallest = A[i];
idx_loc = i;
}
}
return idx_loc;
}
void
print_array(int A[], size_t n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", A[i]);
}
printf("\n");
}
void
int_swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Resources