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 4 years ago.
Improve this question
void function(int first[], int second[], int third[]) {
int i;
for(i=0;i<64;i++) {
third[i] = first[i] - second[i];
}
}
I want to subtract the second array from the first one. The first one contains 32 numbers and the second one has 13 numbers. It works fine for the first 13 numbers. Once the second array "runs out" of elements, I want to use the numbers from the beginning of the second array. So I want to subtract the second array's first element from the 14th element of the first one, and so on... How could I achieve it?
you can use % to get the remainder of the index from length of the array, this way, you can iterate through the second array in a circular way!
I changed your code to do as you asked for
// get the length of array before you pass it to the function like this:
// int second_len = sizeof(second) / sizeof(second[0]);
void function(int first[], int second[], int third[], int second_len) {
int i;
for(i=0;i<64;i++) {
third[i] = first[i] - second[i % second_len];
}
}
The elements of the first and second array are sequences of positive
numbers and they are both closed with -1
You could just do as below.
Maintain two indexes i and j.
Where i will index larger array and j will index smaller array and once smaller array reaches -1 reset the j to 0 and once larger array reaches -1 break the loop.
void function(int first[], int second[], int third[]) {
int i =0,j=0;
for(i=0; i<64 ; i++;j++) {
if(second[j] == -1)
{
j =0; //Reset the j=0 to start from beginning
}
if (first[i] == -1)
{
third[i] = -1; //Terminate third with -1
break; //Break the loop
}
third[i] = first[i] - second[j];
}
}
One option is to add an additional looping variable:
void function(int first[], int second[], int third[],
int first_size, int second_size)
{
int i=0, k=0;
for(i=0; i<first_size; i++) {
third[i] = first[i] - second[k];
k++;
if (k==second_size)
k = 0;
}
}
i tracks the size of the first array and the output like in your program, and k follows the size of the second array and resets whenever the size is reached. Instead of hardcoded array sizes the function now takes two additional arguments: sizes of the first and second arrays.
For future reference, the rest of this code could look like this:
#include <stdio.h>
void print_array(int arr[], int);
void function(int arr_1[], int arr_2[], int arr_3[], int, int);
int main()
{
int arr_1[] = {1,2,3,4,5};
int arr_2[] = {1,2};
int n_1 = sizeof(arr_1)/sizeof(arr_1[0]);
int n_2 = sizeof(arr_2)/sizeof(arr_2[0]);
int arr_out[n_1];
function(arr_1, arr_2, arr_out, n_1, n_2);
print_array(arr_1, n_1);
print_array(arr_2, n_2);
print_array(arr_out, n_1);
return 0;
}
void print_array(int arr[], int n_elem)
{
int i = 0;
for (i=0; i<n_elem; i++)
printf("%d ", arr[i]);
printf("\n");
}
With print_array as a function to avoid repeating the same lines of code for each print.
For the example input, the output will be 0 0 2 2 4.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
A function that moves the sorted at the beginning followed by the sorted odd numbers in descending order of an array. (Store it in an array, this array can be accessible at the main program)
Example:
Input: 2 3 4 5 2 1 3
Output: 2 2 4 5 3 3 1
Input: 5 -3 4 2 -11 -4 6
Output: -4 2 4 5 -3 -11
Here is my code:
#include <stdio.h>
#include<conio.h>
int sorted_even(int[], int);
int main()
{
int i,n;
printf("Enter how many elements:");
scanf("%d",&n);
int arr[n];
printf("Enter %d elements:\n", n);
for(i=0;i<n;i++)
{
scanf("\n%d",&arr[i]);
}
sorted_even(arr,n);
}
int sorted_even(int arr[], int n)
{
int arr1[n], j, k, c=0, temp, b;
int i;
for(i=0;i<n;i++)
{
if (arr[i]%2==1)
c++;
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
k=0;
j=n-c;
for(i=0;i<n;i++)
{
if(arr[i]%2==0)
{
if(k<n-c)
arr1[k++]=arr[i];
}
else
{
if(j<n)
arr1[j++]=arr[i];
}
}
printf("\nresults:");
for(i=0;i<n;i++)
{
arr[i]=arr1[i];
printf("\n%d", arr[i]);
}
}
But I have some problems when it comes to sorting the Odd numbers in descending order. :'<
Unless you are doing this as part of some algorithm theory class, you probably shouldn't be inventing your own sorting algorithms. Notably you are using "bubble sort" which is the least efficient one.
If we instead write the code so that we separate the element comparison logic from the sorting algorithm, everything turns much more modular and maintainable. That's how standard C qsort works. It could be implemented as a "quick sort" algorithm, or a merge sort, we don't have to know or care how. We just provide the element comparison as a callback function passed to qsort, which will then call our function over and over during sorting.
As required by the qsort specification, our comparison function should return a number less than 0, equal to zero or larger than zero, depending on if the first object is smaller, equal or larger than the second object.
In your case, it goes like this:
#include <stdlib.h>
#include <stdio.h>
int even_asc_odd_desc (const void* p1, const void* p2)
{
const int* i1 = p1;
const int* i2 = p2;
if(*i1 & 1)
if(*i2 & 1) // both odd
return *i1 < *i2;
else // first odd, second even
return 1;
else
if(*i2 & 1) // first even, second odd
return -1;
else // both even
return *i2 < *i1;
}
int main(void)
{
int arr1[] = {2, 3, 4, 5, 2, 1, 3}; // Output: 2 2 4 5 3 3 1
int arr2[] = {5, -3, 4, 2, -11, -4, 6}; // Output: -4 2 4 6 5 -3 -11
qsort(arr1, sizeof arr1/sizeof *arr1, sizeof *arr1, even_asc_odd_desc);
qsort(arr2, sizeof arr2/sizeof *arr2, sizeof *arr2, even_asc_odd_desc);
for(size_t i=0; i<sizeof arr1/sizeof *arr1; i++)
printf("%d ", arr1[i]);
printf("\n");
for(size_t i=0; i<sizeof arr2/sizeof *arr2; i++)
printf("%d ", arr2[i]);
printf("\n");
return 0;
}
Now even if you want to write your own sorting algorithm, you can still use a comparison function like above, to separate the sorting from the comparison logic.
Just for reference, this is how you'd implement it with the same generic function template as standard C qsort:
void bubble_sort (void* base,
size_t nmemb,
size_t size,
int (*compar)(const void*, const void*))
{
for(size_t i=0; i<nmemb-1; i++)
{
for(size_t j=0; j<nmemb-i-1; j++)
{
// we can't do pointer arithmetic on void*, convert to integer type:
uintptr_t o1 = (uintptr_t)base + j*size;
uintptr_t o2 = (uintptr_t)base + (j+1)*size;
// then convert back to pointer types:
void* p1 = (void*)o1;
void* p2 = (void*)o2;
if( compar(p1, p2) > 0 ) // if *p1 > *p2
{
// swap items
unsigned char tmp[size];
memcpy(tmp, p1, size);
memcpy(p1, p2, size);
memcpy(p2, tmp, size);
}
}
}
}
Now you can replace qsort with bubble_sort in the first example and get the same result - and now we've invented a crappier generic sorting algorithm than the fast standard one already provided to us.
as i understand, you want to sort all the array in arr and then reorder them by odd and even in arr1, so you have to set the odd numbers with reverse order, start with n and then back, k and j will meet at the middle becase you count the number of odd numbers first.
this code will do the trick:
k=0;
j=n-1;
for(i=0;i<n;i++)
{
if(arr[i]%2==0)
{
arr1[k++]=arr[i];
}
else
{
arr1[j--]=arr[i];
}
}
This works as required. I initialized the variable j to 0 and inserting the odd elements in the sorted array arr to the back of the new array arr1.
k=0;
j=0;
for(i=0;i<n;i++){
if(arr[i]%2==0)
{
if(k<n-c){
arr1[k]=arr[i];
k++;
}
}
else
{
if(j<n){
arr1[n-j-1]=arr[i];
j++;
}
}
}
printf("\nresults:\n");
for(i=0;i<n;i++)
{
//arr[i]=arr1[i];
printf("%d\n", arr1[i]);
}
I am trying to solve two different C problems and would like some help and advice in order to better understand how C works and if I'm on the right track with these.
First problem is: To write a function that counts the number of times the value (x) appears among the first (n) elements of an array and returns that count as the frequency of x in theArray. So, an example would be if the array being passed contained the values {5, 7, 23, 8, 23, 67, 23}. And n was 7 and x was 23, then it would return a value of 3 since 23 occurs 3 times within the first 7 elements of the array.
Here is what I have so far:
#include <stdio.h>
#define SIZE 20 /* just for example - function should work with array of any size */
int frequency (int theArray[], int n, int x)
{
int i;
int count = 0;
for (i = 0; i < n; i++)
{
if (theArray[i] == x)
{
count = count++;
}
}
return (count);
}
int main(void)
{
/* hard code n and x just as examples */
int n = 12; /* look through first 12 items of array */
int x = 5; /* value to find */
int numberFrequency;
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
numberFrequency = frequency (theArray[SIZE], n, x);
printf ("%i", numberFrequency);
return 0;
}
Currently I'm getting a run time error message and believe it has something to do with the for loop function.
Second problem is: Write a function that raises an integer to a positive integer power. Have the function return a long int, which represents the results of calculating x to the nth power. Do not use the C pow library function and do not use recursion!
My code so far:
#include <stdio.h>
int x_to_the_n (int x, int n)
{
int i;
long int result = 1;
if (n == 0)
{
return(result);
}
else
{
for (i = 0; i < n ; ++i)
{
/* equation here - How can I make (x*x*x*x*x*x,etc...? */
result = x*(n*x);
}
}
return (result);
}
int main(void)
{
int x =4;
int n =5;
long int result;
result = x_to_the_n (x, n);
printf ("%i", result);
return 0;
}
I can't use recursion so that is out of the question. So, I thought the next best thing would be a for loop. But I'm a little stuck in how I would go about making a for loop do (xxx*x....) based on value of (n). Any help and advice would be appreciated!
In the first problem you give an element after the array as a parameter to your function.
You define a long int array, and pass it into a function expecting an int array.
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
should be
int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
Instead of this:
numberFrequency = frequency (theArray[SIZE], n, x);
try this:
numberFrequency = frequency (theArray, n, x);
And replace:
count = count++;
with:
count++;
I have to write a C program to do the following:
Write a function that takes three arguments: a pointer to the first
element of a range in an array, a pointer to the element following
the end of a range in an array, and an int value. Have the function
set each element of the array to the int value.
My code is not working. Here is what I have so far. Any help is appreciated.
#include <stdio.h>
#include <iostream>
int listNumbers[3]{ 1,2,3 };
void Sorter(int *first, int * last, int *value);
int * first = &listNumbers[0];
int * last = &listNumbers[2];
int value;
int main() {
printf("your list numbers are:\n");
int i;
for (int i = 0; i < 3; ++i) {
printf("%d", listNumbers[i]);
}
printf("\n");
printf("enter an integer:\n");
scanf_s("%d", &value);
Sorter( first, last, &value);
printf("your new list numbers are:\n");
int j;
for (int j = 0; j < 3; ++j) {
printf("%d", listNumbers[j]);
}
printf("\n");
system("PAUSE");
return 0;
}
void Sorter(int *first, int * last, int *value) {
int i=0;
printf("value = %d\n", &value);
*first = value;
while (i <= *last) {
*(first + i) = value;
i++;
}
}
First, work out the different between the 2 pointers.
int count = last - first + 1;
The compiler will automatically divide by the size of an integer. We add 1 to make the range inclusive. Now just iterate through each element:
for (int i = 0; i < count; i++) {
first[i] = value;
}
Also, why are you passing the value as a pointer? This should just be a value.
void Sorter(int *first, int *last, int value) {
And when you call it...
Sorter(first, last, value);
Your Sorter function does not satisfy the problem criteria. The parameters are supposed to be two pointers into an array, and an int. Your function instead accepts three pointers.
You could nevertheless have made it implement at least the apparent spirit of the exercise, by using the value to which the third argument points as the fill value, but you don't do that. Instead you assign the pointer itself to each array element. That ought to at least elicit a warning from your compiler, and you ought not to be ignoring its warnings, especially when your code it not doing what you think it should.
Furthermore, the last pointer is expected to point to just past the last element to set, but you use it as if it points to an integer offset from the start pointer. This is almost the opposite of the previous problem: here, you need to use the pointer value itself, not the int to which it points.
I am here to get some advice on how to continue my program. It is a homework assignment and the idea is to have another method called int is_sorted(int array[], int length);
With these pre and post conditions.
Precondition: array will be an array of integers of length length.
Postcondition: returns true if the array is in sorted(nondecreasing) order, or false otherwise.
So far I have been able to put together the user input array and how long it should be.
#include <stdio.h>
#include <math.h>
int is_sorted(int array[], int lenght);
int is_sorted(int array[], int lenght)
{
int swap;
int smallest;
int index = 0;
scanf("%d", &lenght);
int list[lenght];
int i;
for (i = 0; i < lenght; i++)
{
scanf("%d", &list[i]);
}
return 0;
}
int main()
{
}
How would I go about asking for a user input to swap two elements at a time within the given array?
The final product should look similar to this:
Sample Run: User input in bold
4 <- The length that the array should be.
1 1 1 2 <- user input these 4 numbers.
WHAT IS THE NEXT SWAP? 2 3
EVAN HAS UNSORTED THE ARRAY.
WHAT IS THE NEXT SWAP? 2 0
WHAT IS THE NEXT SWAP? 0 3
EVAN HAS SORTED THE ARRAY.
WHAT IS THE NEXT SWAP? -1 -1
STEVE WAS RIGHT!
-1 -1 end the swapping process and check if the array is sorted.
while(i != -1 && j != -1){
scanf("%d %d", &i, &j);
swap(&array[i], &array[j]);
}
and swap() looks like this:
void swap(int* a, int* b){
int c = *a;
*a = *b;
*b = c;
}
There's probably a nifty trick for swaping two variables doing some bitwise xor-ing that I don't remember about.
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 8 years ago.
Improve this question
So I have the following code so far:
#include <stdio.h>
int foo (int *pointer, int row, int col);
int main() {
int array[3][3] ={ {1,2,3},{4,5,6},{7,8,9}};
int *pointer= array[0];
int row = 2;
int col = 2;
int answer = foo (pointer, row, col);
printf("%d", answer); //prints 5 (which is wrong)
printf("%d", array[2][2]); //prints 9
}
int foo (int *pointer, int row, int col){ //I don't want to use any square brackets here, unless I really have to.
int value;
value = *((int *)(pointer+row)+col);
return value;
}
So my main issue is with passing a 2D pointer, please explain in detail as I am still new at coding. I don't want to really change what I am passing (as in I want to use the pointer in foo(pointer, row, col) and not foo (array, row, col).
passing a 2D pointer
From how you (ab)used the terminology, it's quite clear that you're under the wrong impression that pointers and arrays are the same. They aren't.
If you want to access a multidimensional array using pointers, you must specify all its dimensions (except the first, innermost one) and use pointer arithmetic correctly, possibly using pointers-to-array, since multidimensional arrays are contiguous in memory:
const size_t h = 2;
const size_t w = 3;
int arr[h][w] = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
int *p = &arr[1][2];
int *q = arr[1];
int (*t)[3] = &arr[1];
printf("arr[1][2] == %d == %d == %d\n", *p, q[2], (*t)[2]);
return 0;
int *pointer= array[0];
Instead of use this
int *pointer= &array[0];
Or
int *pointer= array;