How to move one element to the left of a fixed array - c

int array[10] = {1,2,3,4,5}
from my understanding, the rest of the indexes that haven't been assign a value will be 0. If I want to move every element to the left (I am wanting to remove the first value i.e. index 0). How do I do this without causing duplicate values for the last index with a integer assigned?
For example:
current array
output: 1234500000
+1 to the left:
output: 2345500000
I tried the following code:
void order_array(int size, int array[])
{
for (int i = 0; i < size-1; i++)
{
if (array[i] == 0)
{
array[i-1] = 0;
}
array[i] = array[i+1];
}
}
expected output after method execution:
output: 2345000000
Also before someone says this is a duplicate, I have looked around and no thread explains with fixed arrays, i.e. with 0's as default values.
Appreciate your response.

if (array[i] == 0)
{
array[i-1] = 0;
}
I don't understand why this block is there. It's not possible to get inside the if statement.
With your expected output and given this is an array of ints, I suspect the solution is to only output four values in your print statement, but if the last element of the array should be zero, you can just do this after your for loop:
array[size-1] = 0;

If you don't want rotation then:
int arr[]; //initialize it
int siz=sizeof(arr)/sizeof(arr[0]);
int index=0;
while(index<siz-1)
{
arr[index]=arr[index+1];
index++;
}
arr[index]=0; //0 default value at the end of the array
This will work fine

You just need to manually set the last value to zero at the end. I'd also consider using the built-in memmove function which is designed for moving around data where the source and destination overlap.
void order_array(int size, int array[]){
memmove(array, array+1, (size-1) * sizeof(array[0]));
array[size-1] = 0;
}

#include <stdio.h>
#define ARRAY_SIZE 10
void order_array(int size, int* array) {
for (int i = 0; i < size; i++) {
if (!array[i]) {
continue;
}
if (i + 1 < size)
array[i] = array[i + 1];
}
}
int main() {
int array[ARRAY_SIZE] = {1, 2, 3, 4, 5};
printf("intput: ");
for (int i = 0; i < ARRAY_SIZE; i++) {
printf("%d", array[i]);
}
printf("\n");
order_array(ARRAY_SIZE, array);
printf("output: ");
for (int i = 0; i < ARRAY_SIZE; i++) {
printf("%d", array[i]);
}
printf("\n");
return 0;
}
Maybe you should consider the last value that not equal to default value 0.
Execute in shell:
gcc -o a.out a.c && ./a.out
intput: 1234500000
output: 2345000000

Related

printing 2 characters and keeping them through dynamically allocated 2d array

Hello I am trying to print something like this with 2d array.
Note that when user enters the same number, character should be printed above existing char.
EXPECTED RESULTS:
Input 1: 3 //user1 inputs 3
****
****
**x*
Input 2: 1 //user2 inputs 1
****
****
y*x*
Input 3: 1 //user1 inputs 1
****
x***
y*x*
current results:
enter first: 3
3***
***
**x
enter second: 1
1******
******
xx****
enter first: 2
2*********
*********
***xxx***
But keeping printed values on its previous places.
The problem is that they don't get printed in right order. And also it seems that I haven't done the best job with 2d array which is dynamically allocated.
Here is something what I've tried:
#include <stdio.h>
#include <stdlib.h>
int num(int term)
{
int number1;
int number2;
if(term==1)
{
scanf("%d", &number1);
return number1;
}
if (term==2)
{
scanf("%d", &number2);
return number2;
}
return 0;
}
void function(int a, int b, int result[], int size)
{
int i = 0;
int j = 0;
int desired_num = 0;
int count = 0;
int *arr[a];
for (i = 0; i < a; i++)
arr[i] = (int *)malloc(a * sizeof(int));
for (i = 0; i < a; i++)
for (j = 0; j < b; j++)
arr[i][j] = ++count;
for (i = 0; i < a; i++)
{
for (j = 0; j < b; j++)
{
for (int counter = 0; counter < size; counter++)
{
if (arr[i][j] == arr[a - 1][result[counter] - 1])
{
arr[i][j] = desired_num;
}
if (arr[i][j] == desired_num)
{
printf("%s", "x");
}
else
{
printf("*");
}
}
}
printf("\n");
}
}
int main()
{
int counter = 1;
int i = 0;
int given_number;
int array[20];
for (;;)
{
if (counter % 2 != 0)
{
printf("enter first: ");
given_number = num(1);
printf("%d", given_number);
}
else
{
printf("enter second: ");
given_number = num(2);
printf("%d", given_number);
}
array[i] = given_number;
function(3, 3, array, counter);
counter++;
}
return 0;
}
array[i] = given_number;
i is never changed from the value of 0. You are only ever overwriting the first element of array each iteration. The other 19 elements remain in an indeterminate state.
counter and array are passed to function, as size and result respectively:
This means as size is incremented, it is used as a bounds for accessing elements of result; elements that contain indeterminate values.
for (int counter = 0; counter < size; counter++)
{
if (arr[i][j] == arr[a - 1][result[counter] - 1])
This will surely lead to Undefined Behaviour as those indeterminate values are used to index arr, effectively accessing random memory offsets. This fact alone makes it hard to reason about the output you are seeing, as really anything is valid.
While perfectly valid, the variable-length array of dynamic allocations is a somewhat perplexing choice, especially considering you fail to free the memory allocated by malloc when you are done with it.
int *arr[a];
for (i = 0; i < a; i++)
arr[i] = (int *)malloc(a * sizeof(int));
int arr[a][b]; would work, given a and b are not stack-crushingly large values (or non-positive). You are, or would be, bounded by the size of array in main anyway.
The triply nested loop is confused at best. There is only logic for printing the x and * characters, so you obviously will never see a y.
For each element of arr, you iterate through each element of result. If the current element of arr equals the value of the column selected by the current value of result ([result[counter] - 1]) in the last row (arr[a - 1]) you print x, otherwise *.
Again UB from utilizing indeterminate values of result, but you can see you are printing a * b * size characters, plus newlines, each iteration.
This is severely flawed.
Some other things of note:
The two branches of the if .. else statement in the num function do the exact same thing, just with different identifiers.
The two branches of the if .. else statement in main are identical, other than the first printf in each, and the integer value passed to num, which have the same effect.
This means the only thing that needs to branch is the printf argument.
A generic function for getting an integer would work fine
int get_num(void)
{
int n;
if (1 != scanf("%d", &n)) {
fprintf(stderr, "Could not read input.\n");
exit(EXIT_FAILURE);
}
return n;
}
for use inside main
if (counter % 2 == 0)
printf("enter first: ");
else
printf("enter second: ");
given_number = get_num();
A small issue: printf("%d", given_number); is muddling the output slightly.
There is no reason to repeatedly generate the array. Initialize an array in main to serve as the state of the program. Over time, fill it with the users' selections, and simply print the array each iteration.
Make sure to always check the return value of scanf is the expected number of conversions, and ensure the integers provided by the users will not access invalid memory.
Here is a cursory example.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define EMPTY '*'
#define PLAYER_ONE 'X'
#define PLAYER_TWO 'O'
int get_num(void)
{
int n;
if (1 != scanf("%d", &n)) {
fprintf(stderr, "Could not read input.\n");
exit(EXIT_FAILURE);
}
return n;
}
int main(void)
{
const size_t rows = 6;
const size_t cols = 7;
char board[rows][cols + 1];
memset(board, EMPTY, sizeof board);
/* our rows are now strings */
for (size_t i = 0; i < rows; i++) {
board[i][cols] = '\0';
puts(board[i]);
}
unsigned char turn = 1;
while (1) {
printf("Player %s, Enter column #(1-%zu): ",
turn & 1 ? "One" : "Two", rows);
int input = get_num();
if (1 > input || input > cols) {
printf("Invalid column [%d]. Try again...\n", input);
continue;
}
size_t sel = input - 1;
if (board[0][sel] != EMPTY) {
printf("Column [%d] is full! Try again...\n", input);
continue;
}
size_t n = rows;
while (n--) {
if (board[n][sel] == EMPTY) {
board[n][sel] = turn & 1 ? PLAYER_ONE : PLAYER_TWO;
break;
}
}
for (size_t i = 0; i < rows; i++)
puts(board[i]);
turn ^= 1
}
}

Does this code have anything to do with pointers?

Could somebody help me with this piece of code.
I have no idea that what it does.
#include <stdio.h>
int main()
{
int arr[5],i;
int a = 1, n = 5;
for (i=0; i<5;a+= arr[i++]);
int d = a;
printf("%d",d);
}
technically this code has pointers. That is because arrays are pointers to the values that are stored in it(arr[0-5]). Every Element of the array points to a Adress anywhere in the memory.
int main()
{
int arr[10];
unsigned int x;
for(x = 0; x < 9; x++)
{
arr[x] = x;
printf("%d ", *(arr+x));
}
return 0;
}
in this code you can see that you can use an pointer notation to navigate trough an array.
now to your second question. the code that you gave us here is first initializing a array with 5 elements, a int named 'i', a int named 'a' with the value 1, and a int named 'n' that has the value 5.
then you go into a for loop that repeats 5 times. in the for loop you give a the value of the array[i]. but because the array is not filled with numbers it comes a number that is anywhere in the memory.
next you give the variable 'd' the value of 'a'. and at least you print 'd'.
I think that you want it so that you go into a loop and it prints the elements of the array.
int main()
{
int arr[5], i, a = 1, d;
for(i = 0; i < 5; i++)
arr[i] = i;
for(i = 0; i < 5; i++)
{
a = arr[i];
d = a;
printf("%d ", d);
}
return 1;
}
i think that is what you want.
Of note, we've not put anything of interest into arr, however notice the semicolon on the end of this line:
for (i=0; i<5;a+= arr[i++]);
That's a succinct (confusing?) way of saying
for (i=0; i<5; i++)
{
a += arr[i];
}
So a is summing up whatever is in arr.

Print descending array C

I have to create functions for print array, fill array witn descending numbers.
I created functions for printing array and creating descending array.But I faced with a problem.
If I use my own function printArray() it prints something unclear. Where is the problem, what i do wrong?
Please, help.
Here is the code in C. value - is value of array
Function for printing array:
void printArray (int arr[]){
int i;
printf("\n");
for(i = 0; i < value; i ++)
printf("%3d ", arr[i]);
}
Function for creating descending array:
int createDescendingArray(int a[])
{
int i;
printf("\nDescending array is created.\n");
for (i = value; i > 0; i--) {
a[i] = i;
}
printArray(a); // print of created array
}
Main function:
int main(){
int arr1[value]; //create new array
arr1[value] = createDescendingArray (arr1); //fill array with descending numbers
}
However when I don't use my print function in function createDescendingArray() and print it in Main funktion with standart method like this:
{int i;
for(i = 0; i < value; i++)
{
a[i]=i;
printf("%3d", a[i]);
}
}
It shows descending array as ascending (look at the picture)
How it works?
You have been using a variable named value in your function which prints array, without initializing it, hence the garbage value.
you should initialize it in the function or pass its start value as an argument to the function.
#include <stdio.h>
#include <stdlib.h>
void printArray(int *arr, int length)
{
int i;
printf("\n");
for (i = 0; i < length; i++)
{
printf("%3d ", arr[i]);
}
}
int *createDescendingArray(const int length)
{
if (length == 0)
return NULL;
int *a = malloc(length * sizeof(int));
;
printf("\nDescending array is created.\n");
for (int i = length-1; i >= 0; i--)
{
a[i] = i;
}
printArray(a, length); // print of created array
return a;
}
int main()
{
int *a = createDescendingArray(20);
printArray(a, 20);
return 0;
}
these changes should most probably do the trick but again, there is no initialization of value in the function that creates array as well
EDIT: stop creation of array if length is 0
EDIT2: fixed code to consider 0 as an element
EDIT3: Fixed code with suggestion from #CraigEstey in comments, tested and working
EDIT4: fixed for loop and removed cast on mallock
The function
int createDescendingArray(int a[])
{
int i;
printf("\nDescending array is created.\n");
for (i = value; i > 0; i--) {
a[i] = i;
}
printArray(a); // print of created array
}
is wrong.
According to the output in your question, it seems that you have defined value as 4 (you are not showing us the code with the definition). In that case, your code for the mentioned function is equivalent to the following:
int createDescendingArray(int a[])
{
printf("\nDescending array is created.\n");
a[4] = 4;
a[3] = 3;
a[2] = 2;
a[1] = 1;
printArray(a); // print of created array
}
I did nothing else to the code than unroll the loop.
Since the array a has a size of 4 elements, valid indices are from 0 to 3. Therefore, by writing to a[4], you are writing to the array out of bounds, causing undefined behavior.
If you had written
for (i = value - 1; i >= 0; i--)
instead of
for (i = value; i > 0; i--)
then the unrolled loop would be:
a[3] = 3;
a[2] = 2;
a[1] = 1;
a[0] = 0;
This is better, because now we have fixed the undefined behavior; you are no longer writing to the array out of bounds. However, this is still not what you want. If you want descending output, your unrolled loop must look like this instead:
a[0] = 3;
a[1] = 2;
a[2] = 1;
a[3] = 0;
This can be accomplished by changing your function to the following:
int createDescendingArray(int a[])
{
int i;
printf( "\nDescending array is created.\n" );
for ( i = 0; i < value; i++ ) {
a[i] = value - i - 1;
}
printArray(a); // print of created array
}
Here is a small test program:
#include <stdio.h>
//NOTE: It is customary for constants to be written upper-case,
//not lower-case, so the line below should normally not be used.
#define value 4
void printArray (int arr[]) {
int i;
printf( "\n" );
for( i = 0; i < value; i++ )
printf("%3d ", arr[i]);
}
int createDescendingArray(int a[])
{
int i;
printf( "\nDescending array is created.\n" );
for ( i = 0; i < value; i++ ) {
a[i] = value - i - 1;
}
printArray(a); // print of created array
}
int main( void )
{
int array[value];
createDescendingArray( array );
}
The output is:
Descending array is created.
3 2 1 0
In this test program, I took over most of your other code, but I did not take over the function main, because it was also causing undefined behavior:
int main(){
int arr1[value]; //create new array
arr1[value] = createDescendingArray (arr1); //fill array with descending numbers
}
In the line
arr1[value] = createDescendingArray (arr1);
you are assigning the return value of the function to a variable, although the function did not return a value. This causes undefined behavior. You may want to consider changing the return type to void in the function declaration, if it does not return a value.
Also, even if the function did return a value, arr1[value] would be writing to the array out of bounds, as valid indices are from 0 to value - 1.

2 Dimensional Array sorting in c

Here is a segment of my (incomplete) code
int rows(int board[][9]){
int badUnits = 0, i = 0, n = 9, j, z = 0;
int (*temp)[9];
//Sort each row of 2d array
for (z; z < n; z++){
for (i; i < n; i++){
for (j = i; j < n; j++){
if (board[z][i] > board[z][j]){
temp = board[z][i];
board[z][i] = board[z][j];
board[z][j] = temp;
}
}
}
}
printf ("%d\n", temp[1][0]);
printf ("%d\n", temp[1][1]);
return badUnits;
}
The function takes a 9*9 array.
I get a segmentation fault when the print statements are executed.
I believe my sort code is correct because it is similar to what I use for 1d arrays and I think everything else is correctly assigned.
So the culprit would be my temp variable. I have gone through and tried to assign values to it, tried to change the type, and have taken into account that the 2d array decays into a pointer but is not actually a pointer.
The conclusion I am left with is that this is a dynamic allocation issue. Can someone please lend a hand and assist me in fixing this? I have exhausted my knowledge base and am stuck.
To clarify: I decided to print the temp variable because I thought it would lend some information. The main problem was that the swap was not working, and I was still left with an unsorted array when I originally attempted to print out the board[][]. I know that board is what I am SUPPOSED to be printing.
Thank you for any help!
You assign an int value to temp
temp = board[z][i]; // Temp now is a what ever value was at
// That location in the array e.g. 42
You then treat temp as if it was the address in memory of an integer array
temp[1][1] // treat temp as a pointer and find the integer
// 10 integers further along then temp.
Also sometime temp will not have been initialised (never assigned to) in this case your going to get unexpected behaviour depending on what the last value stored where temp is now (Lets call it a random number).
Did you mean to output the values in board?
printf ("%d\n", board[1][0]);
printf ("%d\n", board[1][1]);
One thing to notice is that the variable temp will only get assigned to if a swap occurs, if the sorting algorithm was correct that is still a situation that could occur with a input corresponding to a sorted board.
But more importantly, the variable temp is used as an int during the swap. Later that integer value is interpreted as a pointer in the expressions temp[1][0] and temp[1][1], which in all likelihoods is not a valid address. You may want to change temp to be declared as:
int temp;
And figure out exactly what you would like to print. If it is whatever one of the two swapped values was (for the last swapped pair in the loop), then you would print it as:
printf("%d", temp);
Else, you would have to add logic according to what you really want to do.
Note that a single pass of this algorithm would not perform a complete sort, but I guess that's one of the reason why you said the provided code was not complete.
Something like this?
#include <stdio.h>
#include <stdlib.h>
void printArray(int** arr, int w, int h) {
for (int i = 0; i < w; ++i) {
for (int j = 0; j < h; ++j) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void sortArray(int** arr, int w, int h) {
for (int row = 0; row < h; ++row) {
for (int col = 0; col < w; ++col) {
for (int i = 0; i < w; ++i) {
if (arr[row][i] > arr[row][col]) {
int tmp = arr[row][col];
arr[row][col] = arr[row][i];
arr[row][i] = tmp;
}
}
}
}
}
int main() {
int w = 9, h = 9;
int** arr = (int**)malloc(sizeof(int*) * w);
for (int i = 0; i < w; ++i) {
arr[i] = (int*)malloc(sizeof(int) * h);
for (int j = 0; j < h; ++j) {
arr[i][j] = rand() % 10;
}
}
printf("Unsorted:\n");
printArray(arr, w, h);
sortArray(arr, w, h);
printf("Sorted:\n");
printArray(arr, w, h);
for (int j = 0; j < h; ++j) {
free(arr[j]);
}
free(arr);
return 0;
}

How do I write a function that returns true if every integer in the array is different?

I have to write a function that will return true if every integer in the array is unique (different). So, I've tried correcting my for loops/my if statement and I've tried running the tests that I wrote. But, the test for a string with an integer appearing more than once still fails. I've reviewed my code but I still can't find the problem.
#include "in.h"
int in(int input[], int size)
{
for (int i = 0; i < size - 1; i++)
{
for (int j = i + 1; j < size; j++)
{
if (input[i] == input[j])
{
return 0;
}
}
}
return 1;
}
Here are my test cases:
#include "in.h"
#include "checkit.h"
void in_tests(void)
{
int input[3] = {2, 4, 5};
int answer;
answer = in(input, 3);
checkit_int(answer, 1);
int input1[4] = {1, 3, 4, 1};
int answer1;
answer1 = in(input1, 4);
checkit_int(answer, 0);
}
int main()
{
in_tests();
return 0;
}
without sort, an O(n2):
j begins with i+1.
int IsDiff(int array[], int count)
{
int i,j;
for (i=0; i<count; i++)
{
for (j=i+1;j<count;j++)
{
if (array[i] == array[j])
return 0;
}
}
return 1;
}
If space is not an issue, then we can have a O(n) solution using a hashtable. Start storing each element of the array in a hashtable. While inserting elements, make a check to see if it already present in the hashtable ( which takes O(1) time.) If the element is already present, then return false immediately, else iterate until the end of array and return true.
actually, thats not why your function doesn't work. the main reason is because currently you are checking if any pair DONT match, which would be great if you wanted to see if all the elements matched, but you want to do the opposite, so you want to check the opposite, if any pair DOES match. so first change your if to be
if(input[i] == input[j]) return false;
if one pair is equal then you know that your test has already failed so there is no need to check the remaining pairs, just return false there and then.
the only other thing to do is to sort out your loops so that you only iterate over each pair once and don't compare a value against it's self. to do that change the for loops to be:
for(int i =0; i<size-1; i++)
for(int j=i+1; j<size; j++)
then if you make it to the end of the function, it means no pair as matched, so just return true;
O(n^2) as well.. but I added this function that makes the code more understandable...
int unique(int input[], int value,int size){
int times=0;
for (int i = 0; i < size; i++)
{
if(input[i]==value){
times++;
if(times==2)
return 0;
}
}
return 1;
}
int in(int input[], int size)
{
int x, answer;
for (int i = 0; i < size; i++)
{
if(!unique(input,input[i],size))
return 0;
}
return 1;
}
You are very close, try this:
#include "in.h"
int in(int input[], int size)
{
int answer = 1;
for (int i = 0; i < size-1; i++)
{
for (int j = i+1; j < size; j++) //check everything above your current
//value because you have already checked
//below it.
{
if (input[i] == input[j])
{
answer = 0; //If any are not unique you
break; //should exit immediately to save time
}
}
if (answer == 0)
break
}
return answer;
}
Thinking about the problem
let's say you have an array like this: int array[] = { 3, 1, 4, 8, 2, 6, 7, 7, 9, 6 };
if you start with the first element you need to compare to the rest of the elements in the set ; so 3 needs to be compared to 1, 4, 3... etc.
if 3 is unique you need to now go to 1 and look at the remaining elements, but next time around you don't need to worry about the 3 ; so your value under consideration (let's call that V) needs to be each of, array[0] to array[N-1] where N is the size of array (in our case 10);
But if we imagine ourselves in the middle of the array, we'll notice that we have already compared previous elements to the current element when the previous element was the value under consideration. So we can ignore any elements "behind" us; which means comparison has to start the each time with the INDEX of current value under consideration (let's call that k) and compare it to values starting with the NEXT index and going to the end of the array ; so pseudo-code for our array of 10 it would look like this:
int is_a_set(int array[])
{
for ( k = 0; k < 10-1 ; k++ ) { /* value under consideration */
v = array[k];
for ( m = k+1 ; m < 10; m++ ) { /* compared to the remaining array starting
* starting from the next element */
if ( v == array[m] ) { /* we found a value that matches, no need to
* to continue going, we can return from this function
*/
return true;
}
}
}
return false;
}
now you can use something like:
if ( is_a_set(my_array) ) {
}
You should be able to use this to figure the rest of your code out :-)
NOTE: a collection with unique elements is called a set so I named the function is_a_set
HINTS: convert size of the array (10) into a parameter or a variable of some sort
Here's my attempt at it (very simple and inefficient though):
#include <stdio.h>
int uniq_int(int arr [], int size)
{
int i, j;
for (i = 0; i < size; i++)
for (j = i + 1; j < size; j++)
if (arr[i] == arr[j])
return 0;
return 1;
}
int main()
{
int arr [] = {1, 2, 4, 3, 5};
(uniq_int(arr, 5)) ? printf("Unique!\n") : printf("Not...\n");
/* the above can be written more traditionally like this:
if (uniq_int(arr, 5) != 0)
{
printf("Unique!\n");
}
else
{
printf("Not...\n");
}
*/
return 0;
}
This will compare every member of the array against the rest, starting from the first
and comparing it against the next one and so on until the end of the inner loop.
Then we start the outer loop again but this time we compare the second element of the array against the ones after it.
As soon as a match is found the function will return and there won't be a need to compare the other elements. Otherwise the outer loop will go on until the last element and once that's reached it will exit and return 1, meaning every member is unique.
It has a complexity of O(n^2) as the set is processed twice for each member in the worst case.

Resources