How to shift an array elements by n places in C - c

If we have an array, for example, Arr[] = {1,2,3,4,5} and I want to shift the elements by 2, how can I do that?
the the array should be: {3,4,5,1,2}.
I tried to slove this way:
#include <stdio.h>
int main(void) {
int broj,pom,i,niza1[10],niza2[10],raz,tem=0,rest=0;
scanf("%d%d",&broj,&pom);//broj= number of elements and pom=shifting
for (int i=0;i<broj;i++){
scanf ("%d",&niza1[i]);
}
raz=broj-pom;//difrence between thenumber of elements and shifting
for (int i=raz;i<=broj;i++){
niza2[tem]=niza1[i-1];
tem++;
}
for (int i=0;i<broj;i++){
printf("%d",niza2[i]);
}
return 0;
}
input: 5 2
1 2 3 4 5
resault: 3 4 5 0 0
How can I add the last two numbers inside the array?

You are only copying broz - raz elements into new array.
raz=broj-pom;//difrence between thenumber of elements and shifting
for (int i=raz;i<=broj;i++){
niza2[tem]=niza1[i-1];
tem++;
}
should be
I removed unnecessary tem variable.
(i+raz)%broj you need % to wrap the copying.
raz=broj-pom;//difrence between thenumber of elements and shifting
for (int i=0;i<broj;i++){
niza2[i]=niza1[(i+raz)%broj];
}

Related

Array prints an unwanted number for no reason

/*This is a c program that inputs an array of 9 numbers, reverses it and prints it*/
#include <stdio.h>
int main()
{
int a[9];
printf("Enter 9 numbers \n");
int i;
for(i=0;i<9;i++)
{
scanf("%d",&a[i]);
}
int n=10;
int t;
for(i=0;i<9/2;i++)
{
t=a[i];
a[i]=a[8-i];
a[8-i]=t;
}
for(i=0;i<10;i++)
{
printf("%d\t",a[i]);
}
}
This is the output:
Enter 9 numbers 1 2 3 4 5 6 7 8
9
9 8 7 6 5 4 3 2 1
32765
I want to understand where the 32765 is coming from and how to fix it.
The last weird number you see there is the value of the next (10st) address from the cell after your array. "a" has been declared with 9 values, and you should remember that arrays in C start from 0. While printing you are trying to access 10 numbers (from 0 to 9)
As other answers point out, you are using a wrong array length at the last loop.
To avoid these kind of mistakes, use macros or const variables to store the fixed length of the array. For example:
#define ARRAYLEN 9
// ...
int a[ARRAYLEN];
// ...
for (int i = 0; i < ARRAYLEN; i++) {
// ...
}

Stuck on code about arrays and moving digits in it

There are two arrays:
s: 7 3 6 2 8
c: 0 12 5 23 14
new array: 8 3 7 6 2
Basically, you look at array c and if it has an even number, you print the one from the array s. For example, 14 is even so you print 8. You need to print them in that order, from right to left.
So I read the first two arrays, but I don't know how to put the rest of the code. If you put:
array s: 1 2 3
array c: 4 4 4
you will get: 3 2 1, which we need, but if I put 1 odd number, I will get some error number. I don't know how to put the rest of array s, after I put the even numbers.
for(d=0; d<ns; d++)
{
scanf("%d", &s[d]); //here we have the first array
}
for(d=0; d<nc; d++)
{
scanf("%d", &c[d]); //second array
}
for(d=0; d<ns; d++)
{
if(c[d]%2==0) //I check here if the nb. from second array are even
{
r[d]=s[d]; //I try to put the numbers from the first array
}
}
for(d=ns-1; d>-1; d--)
{
printf("%d ", r[d]); //I print the new array
}
}
Your problem description is not very clear, but you want to do this:
You have two arrays s and c of the same size N.
First, walk through the array backwards. If the value in c is even, add the corresponding value from s to the result array.
Finally, add the remaining elements of s to the array. The result array will now have N elements, too.
The first thing to notice is that if you look at c[4] and decide to add element s[4] to the result array, the index for that array is 0, because you add elements from the front. In general, if you want to append to an array, you do:
int array[5]; // space for 5 ints
int n = 0; // current length; start with empty array
array[n++] = 5; // array == [5]; n == 1
array[n++] = 8; // array == [5, 8]; n == 2
array[n++] = 15; // array == [5, 8, 15]; n == 3
Your backwards loop works, but it is a bit clumsy, in my opinion. In C (and other languages), ranges are described by the inclusive lower bound and an exclusive upper bound. In the range [0, N), the value N is just out of bound.
Forwad loops initialize to the lower bound, break on the upper bound and increment after each cycle. Because of this asymetry, backwards loops are simpler when you start with the upper bound, break on the lower bound, but decrement at the start of the loop:
for (i = N; i-- > 0; ) ...
The empty update section looks strange, but in this loop, the index never leaves the valid range and therefore also works with unsigned integers.
Create your arrays:
int s[N] = {7, 3, 6, 2, 8}; // value array
int c[N] = {0, 12, 5, 23, 14}; // control array
int r[N]; // result array
int k = 0; // length of r
Now walk the arrays backwards and pick the items you want:
for (i = N; i-- > 0; ) {
if (c[i] % 2 == 0) {
r[k++] = s[i];
}
}
Walk the array forwards and pick the items you didn't pick in the first pass:
for (i = 0; i < N; i++) {
if (c[i] % 2) {
r[k++] = s[i];
}
}
VoilĂ .

Accessing specific elements in a multi-dimensional array of pointers in C

How do I access elements 0-K in a 2D array of pointers with i rows and j columns?
I was unable to see how using nested for loops to index out the desired element would work, because it is unknown if K is smaller or larger than either i or j.
So, I was thinking that it was necessary to provide for different conditions:
if (K < j) {
//index through the first row
}
while (K > j) {
//do some manipulations to determine how many rows to index through
}
But this just seems unnecessarily complex. Is there a way with using pointers and derefencers to get the value of element K out of a 2D array of pointers?
Say, for example, I want to get the value 7 out of this array:
(Note: This image does not accurately reflect how a 2D array of pointers looks...I know that is, in essence, an array of 1D arrays.)
If I have understood you correctly then you need the following.
First of all you can reinterpret a two-dimensional array as a one-dimensional array. And you can split sequential indexes into rows and columns.
In the demonstrative program below there are shown the both approaches.
#include <stdio.h>
#define M 3
#define N 4
int main(void)
{
int a[M][N];
int *p = ( int * )a;
for ( size_t i = 0; i < M * N; i++ )
{
p[i] = i;
}
for ( size_t i = 0; i < M * N; i++ )
{
printf( "%2d ", a[ i / N ][ i % N ] );
if ( ( i + 1 ) % N == 0 ) putchar( '\n' );
}
return 0;
}
The program output is
0 1 2 3
4 5 6 7
8 9 10 11

Reordering the rows in a matrix in a specific order

I am successfully storing the calculated subsets in a 2-D array matrix in C language.Now I want to print the subsets in an order desired.
For eg.
2-D array matrix is
10 7 3 2 1
10 7 5 1
7 6 5 3 2
10 6 5 2
10 7 6
Desired Output
10 7 6
10 7 5 1
10 7 3 2 1
10 6 5 2
7 6 5 3 2
How quick sort can be applied to sort/order these rows?
As #chqrlie noted, this can be easily solved with qsort.
Depending on the way the matrix is declared (is it an array of pointers to arrays of ints? do all arrays have the same length? is it a global array of fixed size?) the code will have to do slightly different things.
So, assuming the array is a global variable and all rows have same length (padded with 0s):
MWE:
#include <stdio.h>
#include <stdlib.h>
/*
Compare 2 integers
returns:
-1 if *i1 < *i2
+1 if *i1 > *i2
0 if *i1 == *i2
*/
int intcmp(const int *i1, const int *i2)
{
return (*i2 < *i1) - (*i1 < *i2);
}
#define ROWS 5
#define COLS 5
/*
Assumes rows already sorted in descending order
NOTE: qsort calls the comparison function with pointers to elements
so this function has to be tweaked in case the matrix is an array of
pointers. In that case the function's declaration would be:
int rowcmp(int **pr1, int **pr2)
{
const int *r1 = *pr1;
const int *r2 = *pr2;
// the rest is the same
}
*/
int rowcmp(const int *r1, const int *r2)
{
int i = 0, cmp;
do {
cmp = intcmp(&r1[i], &r2[i]);
i++;
} while (i < COLS && cmp == 0);
return -cmp; /* return -cmp to sort in descending order */
}
int data[5][5] = {
{10,7,3,2,1},
{10,7,5,1,0},
{ 7,6,5,3,2},
{10,6,5,2,0},
{10,7,6,0,0}
};
void printmatrix()
{
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%d ", data[i][j]); /* leaves a trailing space in each row */
}
printf("\n");
}
}
int main()
{
printmatrix();
qsort(data, 5, sizeof(data[0]), (int (*)(const void *, const void *))rowcmp);
printf("\n");
printmatrix();
return 0;
}
For the most flexible solution, I would define
struct row {
size_t len;
int *elems;
};
struct matrix {
struct row *rows;
size_t nrows;
};
and change the code accordingly.
NOTE: code not thoroughly tested, use with caution ;)
First of all, are you sure that the 1 on row 3,col 5 should be there and not on the last line?
Anyway, an efficient way to achieve what you want is:
compute the frequency array
declare a new matrix
go from the highest element (10 in your case) from frequency array and put in your matrix using your desired format.
It is time-efficient because you don't use any sorting algorithm, thus you don't waste time there.
It is NOT space-efficient because you use 2 matrices and 1 array, instead of only 1 matrix as suggested in other posts, but this should not be a problem, unless you use matrices of millions of rows and columns
C code for frequency array:
int freq[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for(int i=0; i<NO_ROWS; i++) {
for(int j=0; j<NO_COLS; j++) {
if(MATRIX[i][j]!=null && MATRIX[i][j]>0 && MATRIX[i][j]<11) {
freq[MATRIX[i][j]]++;
}
}
}
C code for computing the new matrix dimensions
(assuming you want to keep the number of rows)
OUTPUT_MATRIX[100][100] /*I declared it statically, but I would advise to make it dinamically */
/* first, compute the number columns.
To do so, we need the number of elements
(we get them by simply summing up frequency array's elements) */
int s=0;
for(int i=0; i<11; i++) {
s+=frequency[i];
}
int addOne = 0 /* boolean value to check if we will have to add one extra column for safety */
if(s % NO_ROWS) {
addOne = 1; /* division is not even, so we will have to add extra column */
}
NO_COLS = s/NO_ROWS + addOne;
Now, final part, assigning the values from frequency array to the OUTPUT_MATRIX
int k=0;
int currentNumber = 10; /* assigning starts from 10 */
for(int i=0; i<NO_ROWS; i++) {
for(int j=0; j<NO_COLS; j++) {
if(currentNumber>0) {
if(frequency[currentNumber]==0 || k>=frequency[currentNumber]) {
currentNumber--;
k=0;
}
OUTPUT_MATRIX[i][j] = frequency[currentNumber];
k++;
} else {/*here, you can assign the rest of the value with whatever you want
I will just put 0's */
OUTPUTMATRIX[i][j] = 0;
}
}
}
Hope this helps!
This is what I do in C++ to reorder a matrix:
// b is the matrix and p is an array of integer containing the desired order of rows
for(i=0; i<n; i++){
if( p[i]==i )
continue;
b[i].swap(b[p[i]]);
j = p[i]; // New row i position
// Update row i position to new one
for(int k=i+1; k<n; k++){
if( p[k] == i )
p[k] = j;
}
printRow( b[i] );
}
You need to define an array of pointers of the data type you use and then you can reorder your matrix.
for example your matrix is: arr[5][10], and you want to print line 4 before line 3:
int *[5] arr2;
arr2[0] = &arr[0][0];
arr2[1] = &arr[1][0];
arr2[2] = &arr[2][0];
arr2[3] = &arr[4][0];
arr2[4] = &arr[3][0];
in regard to how will the ordering algorithm work, i would suggest placing a header in the start of each array in the matrix which will tell you how many elements it has(basically the first element of each array can be a counter of the total elements) afterwards you can order the strings by comparing the header, and if it is equal comparing the first element and so on. this can be done in a loop that iterates as many times as there are elements in the array, when the elements are not equal, break out of the loop.
hope this helps.

How to read 2D arrays in C?

I'm learning about 2D arrays in C and I'm a bit confused. I have the following program which reads a 2D arrays and adds its values in another array.
#include <stdio.h>
int main() {
int arr[4][5] = {{1,2,3,4,5},
{3,1,1,5,2},
{4,1,4,1,5},
{2,5,3,3,4}};
int many[4];
int i;
for (i=0;i<4;i++) {
many[i] = arr[i][i] + arr[i][i];
printf("%d\n", many[i]);
}
The output of this program is:
2
2
8
6
But I think it should be 3, 3, 9, 7 because the for loop starts at 1 and the first column and row gets 1 and second column and row get 2 because there is already 1 which means 1+1 = 2 and 2 + 1 = 3, for second number it is same idea.
For the third number I got 9 because we get 4 from row 2 column 2. 4 + 4 + 1 = 9 and for last number I got 7 because last row has 3 in row 3 column 3.
The output you get is absolutely right for this loop.
for (i=0;i<4;i++)
{
many[i] = arr[i][i] + arr[i][i];
printf("%d\n", many[i]);
}
You can easily get to know it by tracing.
so let's trace it...
during i=0
arr[0][0] denotes 1st element (as indices start from 0) of 1st array which is 1
many[0] = arr[0][0]+arr[0][0] // 1+1=2
during i=1
arr[1][1] denotes 2nd element of 2nd array which is also 1
many[0] = arr[1][1]+arr[1][1] // 1+1=2
during i=2
arr[2][2] denotes 3rd element of 3rd array which is 4
many[2] = arr[2][2]+arr[2][2] // 4+4=8
during i=3
arr[3][3] denotes 4th element of 4th array which is 3
many[3] = arr[3][3]+arr[3][3] // 3+3=6
Therefore,The output of this program is:
2
2
8
6
Note: arr[m][n] denotes (n+1)th element of (m+1)th array
You need 2 loops to iterate through your 2D array
#include <stdio.h>
int main() {
int arr[4][5] = {{1,2,3,4,5},
{3,1,1,5,2},
{4,1,4,1,5},
{2,5,3,3,4}};
int many[4];
int i;
int j;
for(i=0;i<4;i++)
{
many[i] = 0;
for(j=0;j<5;j++)
{
many[i] += arr[i][j];
}
printf("%d\n", many[i]);
}
}

Resources