I want to create a spiral matrix consisted of numbers. Number 1 should be in the last row at the right side and other numbers should just follow the spiral path. The output of my code is different from the wanted result, and it also doesn't separate rows. I hope that you could help me solve these problems.
\\ Expected result: Output of my code: 1 2 3 4 5 10 15 20 25 24 23 22 21
16 11 6 7 8 9 14 19 18 17 12 13
9 10 11 12 13
8 21 22 23 14
7 20 25 24 15
6 19 18 17 16
5 4 3 2 1
#include <stdio.h>
void spiral(int n,int m,int arr[][m])
{
int top = 0,
right = m - 1,
bottom = n - 1,
left = 0,
k;
while( top <= bottom && left <= right )
{
//print top row
for ( k = left; k <= right; k++ )
{
printf("%d ",arr[top][k]);
}
++top;
//print right column
for( k = top; k <= bottom; k++ )
{
printf("%d ",arr[k][right]);
}
--right;
//print bottom row
for( k = right; k >= left; k-- )
{
printf("%d ",arr[bottom][k]);
}
--bottom;
//print left column
for( k = bottom; k >= top; k-- )
{
printf("%d ",arr[k][left]);
}
++left;
}
}
int main(void) {
int rows = 5, cols = 5;
int board[rows][cols];
printf("\nSpiral printing:\n");
spiral(rows,cols,board);
return 0;
}
Related
I have created a program to search for prime numbers. It works without problems until the entered number is smaller than 52, when it is bigger output prints out some blank (0) numbers and I don't know why. Also other numbers have blank output.
My code is:
#include <stdio.h> //Prime numbers
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
int c[100], n, a[50], d, e, b = 1;
void sort() {
for (int i = 1; i < n; i++) {
if (c[i] > 1) {
a[b] = c[i];
printf("%d %d %d\n", a[1], b, i);
b++;
e = 2;
d = 0;
while (d <= n) {
d = c[i] * e;
c[d - 1] = 0;
e++;
}
}
}
}
int main() {
printf("Enter number as an limit:\n");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
c[i] = i + 1;
}
sort();
printf("Prime numbers between 1 and %d are:\n", n);
for (int i = 1; i < b; i++) {
printf("%d ", a[i]);
}
return 0;
}
Here is output for 25:
Enter number as an limit:
25
2 1 1
2 2 2
2 3 4
2 4 6
2 5 10
2 6 12
2 7 16
2 8 18
2 9 22
Prime numbers between 1 and 25 are:
2 3 5 7 11 13 17 19 23
But for 83 is:
Enter number as an limit:
83
2 1 1
2 2 2
2 3 4
2 4 6
2 5 10
2 6 12
2 7 16
2 8 18
2 9 22
2 10 28
2 11 30
2 12 36
2 13 40
2 14 42
2 15 46
2 16 52
0 17 58
0 18 60
0 19 66
0 20 70
0 21 72
0 22 78
0 23 82
Prime numbers between 1 and 83 are:
0 3 5 7 11 0 17 19 23 29 31 37 0 43 47 53 0 61 67 71 73 79 83
Blank spots always spots after 17th prime number. And always the blank numbers are the same. Can you help me please what is the problem?
The loop setting entries in c for multiples of c[i] runs too far: you should compute the next d before comparing against n:
for (d = c[i] * 2; d <= n; d += c[i]) {
c[d - 1] = 0;
}
As a matter of fact you could start at d = c[i] * c[i] because all lower multiples have already been seen during the previous iterations of the outer loop.
Also note that it is confusing to store i + 1 into c[i]: the code would be simpler with an array of booleans holding 1 for prime numbers and 0 for composite.
Here is a modified version:
#include <stdio.h>
int main() {
unsigned char c[101];
int a[50];
int n, b = 0;
printf("Enter number as a limit:\n");
if (scanf("%d", &n) != 1 || n < 0 || n > 100) {
printf("invalid input\n");
return 1;
}
for (int i = 0; i < n; i++) {
c[i] = 1;
}
for (int i = 2; i < n; i++) {
if (c[i] != 0) {
a[b] = i;
//printf("%d %d %d\n", a[0], b, i);
b++;
for (int d = i * i; d <= n; d += i) {
c[d] = 0;
}
}
}
printf("Prime numbers between 1 and %d are:\n", n);
for (int i = 0; i < b; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
Output:
chqrlie$ ./sieve4780
Enter number as a limit:
25
Prime numbers between 1 and 25 are:
2 3 5 7 11 13 17 19 23
chqrlie$ ./sieve4780
Enter number as a limit:
83
Prime numbers between 1 and 83 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79
Your problem seems to be caused by the fact that you have declared an array with size 50, but in fact it goes further than that: imagine you want to use Eratosthenes' procedure to find the first 10,000 prime numbers. Does this mean that you need to declare an array of size 10,000 first (or even bigger), risking to blow up your memory?
No: best thing to do is to work with collections where you don't need to set the maximum size at declaration time, like a linked list, a vector, ..., like that you can make your list grow as much as you like during runtime.
please help me to solve the below problem in java to rotate the outer ring of matrix in anticlockwise by k element and inner ring in clockwise by k element in java and the middle element remains constant. The sample input is
m=5,n=6,k=1 where m is no of rows,n is no of column and k is the number of required shift and the input matrix is
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
and the expected output is
2 3 4 5 6 12
1 14 8 9 10 18
7 20 15 16 11 24
13 21 22 23 17 30
19 25 26 27 28 29
Can someone tell how to proceed for this problem as we need to do clockwise and anticlockwise both.
My solution copies one ring of matrix cells at a time. The rings are traversed step by step. For every step a case number is calculated by checking row and columns against the borders of the ring:
package ak.matrixTurn;
public class Main {
public static void main(String[] args) {
int rows = 5;
int cols = 6;
int delta = 1;
int[][] matrix = new int[rows][cols];
int[][] turned = new int[rows][cols];
// fill matrix
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
matrix[r][c] = r * cols + c + 1;
}
}
// copy 1:1 (not turned yet)
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
turned[r][c] = matrix[r][c];
}
}
ringTurn(matrix, turned, 0, delta);
ringTurn(matrix, turned, 1, -delta);
ShowMatrix(matrix);
ShowMatrix(turned);
System.out.println("Ciao!");
}
// helper class represents a row/col pair
static class RowCol {
int row;
int col;
int left;
int top;
int right;
int bottom;
RowCol(int ring, int rows, int cols) {
row = ring;
col = ring;
left = ring;
top = ring;
right = ring + cols - 1;
bottom = ring + rows - 1;
}
// one step anti-clockwise along our ring
void Advance() {
switch(GetCase())
{
case LEFT: // left col
case TOP+LEFT: // top-left corner
row++; break;
case RIGHT: // right col
case BOTTOM+RIGHT: // bottom-right corner
row--; break;
case BOTTOM: // bottom row
case BOTTOM+LEFT: // bottom-left corner
col++; break;
case TOP: // top row
case TOP+RIGHT: // top-right corner
col--; break;
}
}
// cryptic but shorter version of Advance()
void Advance2() {
row += PlusMinus("+- - + ");
col += PlusMinus(" ++ - -");
}
// return -1 for "-", +1 for "+"
// at 1-based string position r
int PlusMinus(String s) {
int r = GetCase();
char c = s.charAt(r - 1);
return "- +".indexOf(c) - 1;
}
// one step back on our ring
void Retract() {
switch(GetCase())
{
case LEFT: // left col
case BOTTOM+LEFT: // bottom-left corner
row--; break;
case RIGHT: // right col
case TOP+RIGHT: // top-right corner
row++; break;
case BOTTOM: // bottom row
case BOTTOM+RIGHT: // bottom-right corner
col--; break;
case TOP: // top row
case TOP+LEFT: // top-left corner
col++; break;
}
}
// cryptic but shorter version of Retract()
void Retract2() {
row += PlusMinus("-+ - +");
col += PlusMinus(" - - ++ ");
}
private int b2x(boolean b, int x) {
return b ? x : 0;
}
static final int LEFT = (1 << 0);
static final int RIGHT = (1 << 1);
static final int BOTTOM = (1 << 2);
static final int TOP = (1 << 3);
// determine where we are on the ring
int GetCase() {
int r = b2x(col == left, LEFT)
+ b2x(col == right, RIGHT)
+ b2x(row == bottom, BOTTOM)
+ b2x(row == top, TOP);
// we have to stay on our ring
assert r != 0;
return r;
}
} // end of class RowCol
// copy all cells in ring from src to dest
// apply delta offset (> 0 if anti-clockwise)
static void ringTurn(int[][] src, int[][] dest, int ring, int delta) {
int cols = src[0].length - 2 * ring;
int rows = src.length - 2 * ring;
// in-place turns are forbidden
assert dest != src;
// matrices have to match in their size
assert dest[0].length == src[0].length;
assert dest.length == src.length;
if ((rows > 1) && (cols > 1)) {
RowCol srcRC = new RowCol(ring, rows, cols);
RowCol destRC = new RowCol(ring, rows, cols);
// position the destination location
for (int i = 0; i < Math.abs(delta); i++) {
if (delta > 0) {
destRC.Advance2();
} else {
destRC.Retract2();
}
}
// perform the copy operation
// by moving both locations along the ring
int steps = 2 * (rows + cols - 2);
for (int step = 0; step < steps; step++) {
dest[destRC.row][destRC.col] = src[srcRC.row][srcRC.col];
destRC.Advance2();
srcRC.Advance2();
}
}
}
static void ShowMatrix(int[][] matrix) {
int cols = matrix[0].length;
System.out.println();
for (int[] ints : matrix) {
StringBuilder s = new StringBuilder();
for (int col = 0; col < cols; col++) {
s.append(String.format("%3d", ints[col]));
}
System.out.println(s);
}
}
}
Output:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
2 3 4 5 6 12
1 14 8 9 10 18
7 20 15 16 11 24
13 21 22 23 17 30
19 25 26 27 28 29
I can't fix the logical error because I don't know what is wrong in this code. Every input, it shows "element not found". I would really appreciate it if someone can help me in this. Also in this code, I have assumed we'll be taking the size of the array as an odd number, what to do if we decide to take an even number as size?
#include<stdio.h>
int main(){
int size;
printf("Enter the number of elemets(odd number) : ");
scanf("%d",&size);
int arr[size];
printf("Enter the elements in ascending order : ");
for(int i=0;i<size;i++){
scanf("%d",&arr[i]);
}
int element;
int flag=0;
printf("Enter element to be found : ");
scanf("%d",&element);
int low=0;
int high=size-1;
while(low<high){
int mid=(low+high)/2;
if(element<arr[mid]){
high=mid-1;
}
else if(element>arr[mid]){
low=mid+1;
}
else if(element==arr[mid]){
printf("Element %d found at pos %d ",element,mid);
flag=1;
break;
}
}
if(flag==0){
printf("Element not found");
}
return 0;
}
The problem is your while test. You have:
while(low<high) {
...
}
This will fail when low == high if the desired value is at that position. It is easily fixed by changing the test to:
while(low <= high) {
...
}
This is all that's needed to fix it. You don't need to add any special cases to "fix it up". Just make sure your array is in ascending order and it should work.
EDIT: Refer to the better answer by #TomKarzes
My old answer is:
You missed a boundary case of high==low
#include<stdio.h>
int main(){
int size;
printf("Enter the number of elements(odd number) : ");
scanf("%d",&size);
int arr[size];
printf("Enter the elements in ascending order : ");
for(int i=0;i<size;i++){
scanf("%d",&arr[i]);
}
int element;
int flag=0;
printf("Enter element to be found : ");
scanf("%d",&element);
int low=0;
int high=size-1;
while(low<high){
int mid=(low+high)/2;
if(element<arr[mid]){
high=mid-1;
}
else if(element>arr[mid]){
low=mid+1;
}
else if(element==arr[mid]){
printf("Element %d found at pos %d ",element,mid);
flag=1;
break;
}
}
if(low==high && arr[low]==element) //Added 1 extra condition check that you missed
{
printf("Element %d found at pos %d ",element,low);
flag=1;
}
if(flag==0){
printf("Element not found");
}
return 0;
}
For starters for the number of elements of the array you shell use the type size_t. An object of the type int can be small to accommodate the number of elements in an array.
This condition of the loop
int high=size-1;
while(low<high){
//...
is incorrect. For example let's assume that the array has only one element. In this case high will be equal to 0 and hence equal to left due to its initialization
int high=size-1;
So the the loop will not iterate and you will get that the entered number is not found in the array though the first and single element fo the array actually will be equal to the number.
You need change the condition like
while ( !( high < low ) )
//...
This if statement within the else statement
else if(element==arr[mid]){
is redundant. You could just write
else // if(element==arr[mid]){
It would be better if the code that performs the binary search will be placed in a separate function.
Here is a demonstrative program that shows how such a function can be written.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int binary_search( const int a[], size_t n, int value )
{
size_t left = 0, right = n;
int found = 0;
while ( !found && left != right )
{
size_t middle = left + ( right - left ) / 2;
if ( value < a[middle] )
{
right = middle;
}
else if ( a[middle] < value )
{
left = middle + 1;
}
else
{
found = 1;
}
}
return found;
}
int cmp( const void *a, const void *b )
{
int left = *( const int * )a;
int right = *( const int * )b;
return ( right < left ) - ( left < right );
}
int main(void)
{
const size_t N = 15;
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < N; i++ )
{
size_t n = rand() % N + 1;
int a[n];
for ( size_t j = 0; j < n; j++ ) a[j] = rand() % N;
qsort( a, n, sizeof( int ), cmp );
for ( size_t j = 0; j < n; j++ )
{
printf( "%d ", a[j] );
}
putchar( '\n' );
int value = rand() % N;
printf( "The value %d is %sfound in the array\n",
value, binary_search( a, n, value ) == 1 ? "" : "not " );
}
return 0;
}
Its output might look for example the following way
0 2 2 3 4 5 7 7 8 9 10 12 13 13
The value 5 is found in the array
4 8 12
The value 10 is not found in the array
1 2 6 8 8 8 9 9 9 12 12 13
The value 10 is not found in the array
2 3 5 5 7 7 7 9 10 14
The value 11 is not found in the array
0 1 1 5 6 10 11 13 13 13
The value 7 is not found in the array
0 3 3 3 4 8 8 10 11 12 14 14 14 14
The value 3 is found in the array
0 5 5 10 11 11 12 13 13 14 14
The value 12 is found in the array
3 4 5 7 10 13 14 14 14
The value 14 is found in the array
0 3 3 7
The value 2 is not found in the array
1 6 9
The value 10 is not found in the array
2 2 3 3 4 4 4 5 5 6 8 8 9 13 13
The value 11 is not found in the array
11 11 13
The value 11 is found in the array
0 0 0 1 2 5 5 5 7 7 8 9 12 12 14
The value 6 is not found in the array
8 8 13
The value 1 is not found in the array
2 2 4 4 5 9 9 10 12 12 13 13 14 14
The value 14 is found in the array
I am working on a pattern that prints the following code using for loop
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
code is as follows, which results in slightly wrong output.
main(){
int i,j,k,n,num;
printf("\n Enter no of rows: ");
scanf("%d",&num);
for(i=1;i<=num;i++,k=num){
for(j=1,n=i;j<=i;j++,n+=k){
printf("%d ",n);
}
printf("\n");
}
}
And the code gives me this .
which is wrong from the output i wanted
1
2 6
3 7 11
4 8 12 16
5 9 13 17 21
The key to this is how you update n in the inner loop. You need it to take into account not just num but also i as you descend through each iteration. I've fixed num at 5 here and placed the assignment to k at the start of the outer loop as this will always be constant:
#include <stdio.h>
int main(void) {
int i, j, k, n, num;
num = 5;
for(i = 1, k = num; i <= num; i++){
for(j = 1, n = i; j <= i; n += k - j, j++){
printf("%d ", n);
}
printf("\n");
}
}
Gives:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
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 6 years ago.
Improve this question
This code is designed by someone to change array [a1 a2...am b1 b2..bn ] to the array [b1 b2 ..bn a1 a2..am], but it involves the greatest common divisor which I can't get the point.
void Exchange(int a[],int m,int n,int s){
int p=m,temp=m+n;int k=s%p;
while(k!=0){temp=p;p=k;k=temp%p;}
for(k=0 ; k<p ;k++){ //below is where i cant't understand
temp=a[k];i=k;j=(i+m)%(m+n);
while(j!=k)
{a[i]=a[j];i=j;j=(j+m)%(m+n);}
a[i]=temp;
}
};
EDIT: "Properly" indented:
void Exchange(int a[], int m, int n, int s) {
int p = m, temp = m + n, k = s % p;
while (k != 0) {
temp = p;
p = k;
k = temp % p;
}
for (k = 0 ; k < p; k ++) { // below is where i cant't understand
temp = a[k];
i = k;
j = (i + m) % (m + n);
while (j != k) {
a[i] = a[j];
i = j;
j = (j + m) % (m + n);
}
a[i] = temp;
}
};
The code is using a single value of overhead to implement array rotation. If the lengths are mutually prime, a single pass suffices. If not, you have to repeat the shift cycle by the GCD of the lengths
I said earlier that there are other questions on SO that cover this. A look found SO 3333-3814 which deals with a single rotation. I did some messing with code to support that a while ago, demonstrating the need for GCD, but I didn't previously post it.
Here's the code — it uses C99 VLAs — variable length arrays.
#include <stdio.h>
static int gcd(int x, int y)
{
int r;
if (x <= 0 || y <= 0)
return(0);
while ((r = x % y) != 0)
{
x = y;
y = r;
}
return(y);
}
static void dump_matrix(int m, int n, int source[m][n])
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
printf("%4d", source[i][j]);
putchar('\n');
}
}
static void init_matrix(int m, int n, int source[m][n])
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
source[i][j] = (i + 1) * (j + 2);
}
}
static void rotate_1col(int n, int vector[n], int z)
{
z %= n;
if (z != 0)
{
int c = gcd(n, z);
int s = n / c;
for (int r = 0; r < c; r++)
{
int x = r;
int t = vector[x];
for (int i = 0; i < s; i++)
{
int j = (x + z) % n;
int v = vector[j];
vector[j] = t;
x = j;
t = v;
}
}
}
}
static void rotate_cols(int m, int n, int source[m][n], int z)
{
for (int i = 0; i < m; i++)
rotate_1col(n, source[i], z);
}
int main(void)
{
int m = 3;
for (int n = 2; n < 9; n++)
{
int source[m][n];
for (int z = 0; z <= n; z++)
{
init_matrix(m, n, source);
printf("Initial:\n");
dump_matrix(m, n, source);
rotate_cols(m, n, source, z);
printf("Post-rotate %d:\n", z);
dump_matrix(m, n, source);
putchar('\n');
}
}
return 0;
}
The code demonstrates different sizes of rotation on different sizes of array. Example sections of the output:
…
Initial:
2 3 4
4 6 8
6 9 12
Post-rotate 1:
4 2 3
8 4 6
12 6 9
…
Initial:
2 3 4 5
4 6 8 10
6 9 12 15
Post-rotate 3:
3 4 5 2
6 8 10 4
9 12 15 6
…
Initial:
2 3 4 5 6 7
4 6 8 10 12 14
6 9 12 15 18 21
Post-rotate 1:
7 2 3 4 5 6
14 4 6 8 10 12
21 6 9 12 15 18
Initial:
2 3 4 5 6 7
4 6 8 10 12 14
6 9 12 15 18 21
Post-rotate 2:
6 7 2 3 4 5
12 14 4 6 8 10
18 21 6 9 12 15
Initial:
2 3 4 5 6 7
4 6 8 10 12 14
6 9 12 15 18 21
Post-rotate 3:
5 6 7 2 3 4
10 12 14 4 6 8
15 18 21 6 9 12
…
Initial:
2 3 4 5 6 7 8 9
4 6 8 10 12 14 16 18
6 9 12 15 18 21 24 27
Post-rotate 4:
6 7 8 9 2 3 4 5
12 14 16 18 4 6 8 10
18 21 24 27 6 9 12 15
Initial:
2 3 4 5 6 7 8 9
4 6 8 10 12 14 16 18
6 9 12 15 18 21 24 27
Post-rotate 5:
5 6 7 8 9 2 3 4
10 12 14 16 18 4 6 8
15 18 21 24 27 6 9 12
Initial:
2 3 4 5 6 7 8 9
4 6 8 10 12 14 16 18
6 9 12 15 18 21 24 27
Post-rotate 6:
4 5 6 7 8 9 2 3
8 10 12 14 16 18 4 6
12 15 18 21 24 27 6 9
…
First of all, to get the result you said you expected, I have set m and n to be half the array size. I also assumed that s would be initialised to zero, in which case, the first while loop does not iterate. Also, there are several declarations missing in your code so my explanation makes some assumptions.
The variable p holds the number of array elements to swap;
// This is to keep the value to be overwritten by the swap
temp=a[k];
// This is the array index of the bottom half element to write the top half element to
i=k;
// this is to get the current index of the top half;
j=(i+m)%(m+n);
// This assignes the bottom index value with the top half value
while(j!=k)
{
// Write top half element to corresponding bottom half element
a[i]=a[j];
// We can now overwrite top half element; this assignes the index at wich to copy the bottom half element
i=j;
// This is to get out of the loop
j=(j+m)%(m+n);
}
// The bottom half element held at the beginning is now written to the top half at the corresponding index
a[i]=temp;
Hope this is the answer you were looking for. I arrived at this result by using a debugger and by stepping in the code line by line. I don't know if you know how to use a debugger but if not, then I highly recommend your lean how to use one; it it time well spent and it returns an awesome dividend :-)