I have an array of numbers that has been sorted in before, so there's no need to sort it, I need to insert an given value, named it val, at a valid position in my array.
My program works for a given value that is smaller than the last one, but for the case where the value is bigger than the last one, my program just doesn't want to insert the value.
For example, for the array {1, 2, 3, 4, 6} and the value 5, the array should be {1, 2, 3, 4, 5, 6}, but for the value 7 my array is looking like {1, 2, 7, 4, 6, 0}.
#include <stdio.h>
void insert(int val, int *n, int v[])
{
int index;
index = n - 1;
if (n == 0)
{
v[0] = val; // check if array is empty
n = n + 1; // v[0] becomes the given value
} // increase size of array
if (val > v[index])
{
v[index+1] = val; // given value is bigger than the last value in array
n = n + 1; // increase size
}
else
{
while (index >= 0 && v[index] > val)
{
v[index+1] = v[index]; //shift items to the right
index--;
}
v[index + 1] = val; //after moving elements to the right
n = n + 1; // i set the value to the valid position
}
}
void display(int n, int v[])
{
int i;
for (i = 0;i < n; i++)
printf("%d ", v[i]);
}
int main(void)
{
int v[10] = { 12, 23, 34, 41, 69, 71, 81, 91, 100 };
int n;
n = 9; // size of array
insert(101,n,v); // 101 is given value to insert
display(n,v);
return 0;
}
You have a couple of mistakes:
You are passing int instead of int * so you're not able to update array size
You are not correctly placing value in the array
This is how your code should look like:
#include <stdio.h>
void insert(int val, int *nPtr, int v[]);
void display(int n, int v[]);
int main(void) {
int v[10] = {12, 23, 34, 41, 69, 71, 81, 91, 100};
int n;
n = 9;
insert(101, &n, v);
display(n, v);
return 0;
}
void insert(int val, int *nPtr, int v[]) {
int n = *nPtr;
int i, j;
int k = 0;
for (i = 0; i < n + 1; i++)
if (!k) {
if (v[i] > val || i == n) {
for (j = n - 1; j >= i; j--) {
v[j + 1] = v[j];
}
v[i] = val;
n++;
k = 1;
}
}
*nPtr = n;
}
void display(int n, int v[]) {
int i;
for (i = 0; i < n; i++)
printf("%d ", v[i]);
printf("\n");
}
You can also try to insert number on the beginning, for example 0 and it will still work.
Related
In the code below, the output ends up being 70, with a count of 4. However, the test_score 95 has a count of 5 and it should be the one that comes out on the output, but doesn't. It would seem that there is a skipping of elements in the array tes_scores[]. I can't see where I'm going wrong with the body of the function int mode( int arr[], int n ).
#include<stdio.h>
#define MAX_SCORE 100
int mode(int arr[], int n);
int main()
{
int test_scores[] = { 90,85,100,50,50,85,60,70,55,55,80,95,70,60,95,80,100,75,70,95,90,90,70,95,50,65,85,95,100,65 };
int n = sizeof(test_scores) / sizeof(int);
printf("Mode of the test_scores is %d\n", mode(test_scores, n));
}
int mode(int arr[], int n)
{
int i, j, modes;
int count[11] = {};
int scores[11] = {100, 95, 90, 85, 80, 75, 70, 65, 60, 55, 50};
modes = 0;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(scores[j] == arr[i])
{
count[j] += 1;
}
}
}
for(i = 0; i < 11; i++)
{
if(count[i] > count[i + 1])
modes = scores[i];
}
return modes;
}
its not possible to litteraly make a for each in C, nevertheless you can use special value that specify the end of your array, for example if your score could'nt be negatives you can put a '-1' at the end to specify end of the array like a '\0' or if you make a 'type' **arr, put the last index of your array to NULL to indicate the end of it.
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;
}
So, I have this so far. I'm trying to find the two largest numbers in an array and return them. I looked up a lot of resources online, and most of them say "call by reference" is the way to go. But I've no idea how to make it work with my program. For example, I saw this example online:
void Calculate(int x, int y, int* prod, int* quot)
{
*prod = x*y;
*quot = x/y;
}
int x = 10,y = 2, prod, quot;
Calculate(x, y, &prod, ")
How does the above program actually "return"? How do I print the return values to the console?
#include "stdio.h"
void largest_two( int numbers[], int len, int *largest, int *next_largest){
int i, temp;
*largest = numbers[0];
*next_largest = numbers[1];
if(*largest < *next_largest){
temp = *next_largest;
*largest = *next_largest;
*next_largest = temp;
}
for (i=0; i<sizeof(numbers); i++) {
if(numbers[i]>= *largest){
*largest = numbers[i];
*next_largest = *largest;
}
else if ( numbers[i] > *next_largest){
*next_largest = numbers[i];
}
}
}
int main() {
int numbers[] = {3, 1, 2, 3, 6, 2, 8, 0, 0, 0};
int len = 3;
int largest, next_largest;
//==>??? printf("%d %d", largest_two(numbers, len, &largest, &next_largest));
}
Sides' from the pointer issues (you should read a tutorial / book on them), your main problem is that you're attempting to print the single return value of a function with return type void which means it won't return at all.
Your code:
int main() {
int numbers[] = {3, 1, 2, 3, 6, 2, 8, 0, 0, 0};
int len = 10; // sizeof(numbers)
int largest, next_largest;
largest_two(numbers, len, &largest, &next_largest);
printf("%d %d", largest, next_largest);
}
Keep in mind this is still not entirely correct, but it does adress your problem of printing the numbers.
Also, passing len means you shouldn't do this for (i=0; i<sizeof(numbers); i++) but this instead for (i=0; i<len; i++)
Firstly, this line:
for (i=0; i<sizeof(numbers); i++)
is not correct. You want this to be instead:
for (i=0; i<len; i++)
which should be passed to largest_two() as sizeof numbers/sizeof numbers[0], which is the actual length of the array.
I also suggest setting largest and next_largest to INT_MIN from <limits.h>, and then finding these values from their. It seems you are also having trouble with pointers, and it would be best to use them only when needed.
Here is an example which simplifies your approach, which finds the largest and second largest element in one loop of the array. It also only uses pointers when needed.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define ARRAYSIZE(x) (sizeof x/sizeof x[0])
void largest_two(int numbers[], size_t len, int *largest, int *next_largest);
int main(void) {
int numbers[] = {3, 1, 2, 3, 6, 2, 8, 0, 0, 0};
int largest, next_largest;
largest_two(numbers, ARRAYSIZE(numbers), &largest, &next_largest);
printf("largest = %d\nnext_largest = %d\n", largest, next_largest);
}
void largest_two(int numbers[], size_t len, int *largest, int *next_largest) {
int max, smax;
max = smax = INT_MIN;
for (size_t i = 0; i < len; i++) {
if (numbers[i] > max) {
smax = max;
max = numbers[i];
} else if (numbers[i] > smax && numbers[i] < max) {
smax = numbers[i];
}
}
*largest = max;
*next_largest = smax;
}
Output:
largest = 8
next_largest = 6
Second dataset:
int numbers[] = {3, 1, 6, 3, 6, 2, 8, 0, 8, 7};
Output:
largest = 8
next_largest = 7
I have the following code: value represents an array of numbers. I want to arrange all numbers while also keeping track of the max and min.
if (value > stats_max)
stats_max = value;
if (value < stats_min)
stats_min = value;
can I do:
if ((value > stats_min) && (value < stats_max))
stats_mid = value;
just to print one value.
what should I do to write all those "values" in an array?
For example, like this
#include <stdio.h>
int main(void){
int values[] = { 9, 5, 1, 7, 3, 8, 2, 6, 4, 0};
size_t size = sizeof(values)/sizeof(*values);
int *value = values;
int stats_max, stats_min;
size_t i;
stats_max = stats_min = *value;
for(i = 0; i < size; ++i, ++value){
if (*value > stats_max)
stats_max = *value;
if (*value < stats_min)
stats_min = *value;
}
printf("max = %d, min = %d\n", stats_max, stats_min);
return 0;
}
Okay so I've tried to print and Array and then reverse is using another array But I'm trying to create a For Loop that will take an array and reverse all of the elements in place without me having to go through the process of creating an entirely new array.
My for loop is running into some problems and I'm not sure where to go from here...i'm using i to take the element at the end and move it to the front and then j is being used as a counter to keep track of the elements...if there is an easier way to do this Any suggestions would be appreciated.
I'm New to this programming language so any extra info is greatly appreciated.
#include <stdlib.h>
#include <time.h>
int Random(int Max) {
return ( rand() % Max)+ 1;
}
void main() {
const int len = 8;
int a[len];
int i;
int j = 0;
Randomize() ;
srand(time(0));
//Fill the Array
for (i = 0; i < len; ++i) {
a[i] = rand() % 100;
}
//Print the array after filled
for (i = 0; i < len; ++i) {
printf("%d ", a[i]);
}
printf("\n");
getchar();
//Reversing the array in place.
for (i = a[len] -1; i >= 0, --i;) {
a[i] = a[j];
printf("%d ", a[j]);
j++;
}
}
A while loop may be easier to conceptualize. Think of it as starting from both ends and swapping the two elements until you hit the middle.
i = len - 1;
j = 0;
while(i > j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i--;
j++;
}
//Output contents of now-reversed array.
for(i = 0; i < len; i++)
printf("%d ", a[i])
void reverse_range(int* buffer, int left, int right)
{
while (left < right)
{
int temp = buffer[left];
buffer[left++] = buffer[right];
buffer[right--] = temp;
}
}
call it to reverse array
int a[3] = {1, 2, 3};
reverse_range(a, 0, 2);
You are on the right track but need to think about that last for loop a little more and the assignment operation inside. The loop initialization is off, since i = a[len] - 1 will copy the value of the last entry to i. Since that value is a random number, your index will probably start out of bounds.
Next, you're copying half of the array to the other half and then back. That loop does the following:
a[7] = a[0]
a[6] = a[1]
a[5] = a[2]
a[4] = a[3] ...
At this point you've lost all of the initial values in a[4] through a[7].
Try this:
for( i = 0; i < len / 2; i++ ){
int temp = a[i];
a[i] = a[len - i];
a[len - i] = temp;
}
Use a debugger and step through the loop watching the value of i, temp, and each element in the array
Just my 2 cents...
#include <stdlib.h>
#include <stdio.h>
int main() {
int arry[] = {0, 1, 2, 3, 4, 5};
int* s = arry;
int* e = arry + (sizeof(arry) / sizeof(arry[0])) - 1;
while (s < e) {
*e ^= *s;
*s ^= *e;
*e ^= *s;
s++;
e--;
}
for (size_t i = 0; i < (sizeof(arry) / sizeof(arry[0])); i++) {
fprintf(stderr, "%d, ", arry[i]);
}
fprintf(stderr, "\n");
}
For starters, instead of this:
for (i = a[len] -1; i >= 0, --i;) {
you want this:
for (i = len-1; i >= 0, --i;) {
but you also only want to go half-way through the array, so it would be
for (i = len-1; i > j, --i;) {
Try this;
#include <stdlib.h>
#include <time.h>
int Random(int Max) {
return ( rand() % Max)+ 1;
}
void main() {
const int len = 8;
int a[len];
int i,end;
int j = 0;
Randomize() ;
srand(time(0));
//Fill the Array
for (i = 0; i < len; ++i) {
a[i] = rand() % 100;
}
//Print the array after filled
for (i = 0; i < len; ++i) {
printf("%d ", a[i]);
}
printf("\n");
getchar();
for (i = 0; i < n/2; i++) {
t = a[i];
a[i] = a[end];
a[end] = t;
end--;
}
}
Hope this helps... :)
Just for suggestion. Try to use meaningful variable name instead of just i,a.... That will help you while writing a bigger code. :)
You can reverse an array in place you don't need an auxiliary array for that, Here is my C code to do that
#include <stdio.h>
int main(void)
{
int arr[5]={1,2,3,4,5};
int size=sizeof(arr)/sizeof(int);
int success= reverse(arr,size);
if(success==1)
printf("Array reversed properly");
else
printf("Array reversing failed");
return 0;
}
int reverse(int arr[], int size)
{
int temp=0;
int i=0;
if(size==0)
return 0;
if(size==1)
return 1;
int size1=size-1;
for( i=0;i<(size/2);i++)
{
temp=arr[i];
arr[i]=arr[size1-i];
arr[size1-i]=temp;
}
printf("Numbers after reversal are ");
for(i=0;i<size;i++)
{
printf("%d ",arr[i]);
}
return 1;
}
Here's an easy and clean function for flipping arrays of all sizes. Change the parameters according to your type of array:
void flipArray(int *a, int asize){
int b[asize];
int *b_p = b;
for(int i=0; i<asize; i++){
//backwardsOrientation = (arraySize-1)-increment
b_p[asize-1-i] = a[i];
}
for(int i=0; i<asize; i++){
a[i] = b_p[i];
}
}
If you are not interested in writing functions for any numeric type, try macros for this task. This code same working with any built-in numeric type: int, float, double.
It has not a support for strings, since any string is ending on the character the NULL character \0. More a controlled version my similar answer is here https://stackoverflow.com/a/42063309/6003870 and contains solution for reverse a string.
A full code
#include <stdio.h>
// print items of an array by a format
#define PRINT_ARRAY(array, length, format) \
{ \
putchar('['); \
for (size_t i = 0; i < length; ++i) { \
printf(format, array[i]); \
if (i < length - 1) printf(", "); \
} \
puts("]"); \
}
// reverse an array in place
#define REVERSE_ARRAY(array, length, status) \
if (length > 0) { \
for (int i = 0; i < length / 2; ++i) { \
double temp; \
temp = array[i]; \
array[i] = array[length - i - 1]; \
array[length - i - 1] = temp; \
} \
*status = 0; \
} \
else if (length < 0) *status = -1; \
else *status = 1;
#define SUCCESS_REVERSE_ARRAY_MSG "An array succefully reversed"
#define FAILED_REVERSE_ARRAY_MSG "Failed reverse for an array"
#define NO_CHANGED_REVERSE_ARRAY_MSG "An array no changed"
/*
Print message about status reverse an array
*/
static void
print_msg_reverse_array_status(const int status)
{
if (status == 0) printf("Status: %s\n", SUCCESS_REVERSE_ARRAY_MSG);
else if (status == -1) printf("Status: %s\n", FAILED_REVERSE_ARRAY_MSG);
else if (status == 1) printf("Status: %s\n", NO_CHANGED_REVERSE_ARRAY_MSG);
}
int
main (const int argc, const char *argv[])
{
// keep value of status
int status;
puts("\tExample reverse of an integer array");
int arr_int[5] = {1, 2, 3, 4, 5};
status = 0;
PRINT_ARRAY(arr_int, 5, "%d");
REVERSE_ARRAY(arr_int, -1, &status);
// will be an error, since a length is less 0, and the array is not changed
print_msg_reverse_array_status(status);
PRINT_ARRAY(arr_int, 5, "%d");
status = 0;
REVERSE_ARRAY(arr_int, 0, &status);
// a length is equal to 0, so an array is not changed
print_msg_reverse_array_status(status);
PRINT_ARRAY(arr_int, 5, "%d");
status = 0;
REVERSE_ARRAY(arr_int, 5, &status);
print_msg_reverse_array_status(status);
PRINT_ARRAY(arr_int, 5, "%d");
puts("\n\tExample reverse of an float array");
float arr_float[5] = {0.78, 2.1, -3.1, 4, 5.012};
status = 0;
PRINT_ARRAY(arr_float, 5, "%5.3f");
REVERSE_ARRAY(arr_float, 5, &status);
print_msg_reverse_array_status(status);
PRINT_ARRAY(arr_float, 5, "%5.3f");
puts("\n\tExample reverse of an double array");
double arr_double[5] = {0.00001, 20000.002, -3, 4, 5.29999999};
status = 0;
PRINT_ARRAY(arr_double, 5, "%8.5f");
REVERSE_ARRAY(arr_double, 5, &status);
print_msg_reverse_array_status(status);
PRINT_ARRAY(arr_double, 5, "%8.5f");
return 0;
}
I am used the GCC for compilation and your result must be as next
Example reverse of an integer array
[1, 2, 3, 4, 5]
Status: Failed reverse for an array
[1, 2, 3, 4, 5]
Status: An array no changed
[1, 2, 3, 4, 5]
Status: An array succefully reversed
[5, 4, 3, 2, 1]
Example reverse of an float array
[0.780, 2.100, -3.100, 4.000, 5.012]
Status: An array succefully reversed
[5.012, 4.000, -3.100, 2.100, 0.780]
Example reverse of an double array
[ 0.00001, 20000.00200, -3.00000, 4.00000, 5.30000]
Status: An array succefully reversed
[ 5.30000, 4.00000, -3.00000, 20000.00000, 0.00000]
Testing environment
$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 8.6 (jessie)
Release: 8.6
Codename: jessie
$ uname -a
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux
$ gcc --version
gcc (Debian 4.9.2-10) 4.9.2
public static void ReverseArrayInPlace()
{
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
int end = arr.Length - 1;
foreach (var item in arr)
{
Console.WriteLine(item);
}
for (int i = 0; i < arr.Length/2; i++)
{
var temp = arr[i];
arr[i] = arr[end];
arr[end] = temp;
end--;
}
Console.WriteLine("--------------------------");
foreach (var item in arr)
{
Console.WriteLine(item);
}
}
Here is how I did it in Java
It will be exactly same in C or C++ too
class Solution {
private void reverseHelper(char s[],int i, int j){
if(i >= j) return;
char temp = s[i];
s[i] = s[j];
s[j] = temp;
reverseHelper(s,i+1,j-1);
}
public void reverseString(char[] s) {
reverseHelper(s,0,s.length-1);
}
}
The space complexity here is O(1)
#include<Stdio.h>
#include<string.h>
#define max 25
int main()
{
char arr[max]="0123456789";
strrev(arr);
atoi(arr);
return 0;
}
//you can also use built in functions such as strrev(); string reverse atoi just
//changes string into integer