Fill 2d array in spiral order in c - c

I'm doing program where I enter the number from keyboard. Then 2d array is created, and it's filled in spiral order till this number. All elements after the number will be equal to 0; The function fills the array in spiral order (to right -> down -> left -> up).
Code is:
#include <stdio.h>
#include <time.h>
void spiral(int array[100][100], int m, int n, int s)
{
int size, b, x = 0, y = 1, num = 1;
size = m*n;
for (num=1;num<=size+1;num++)
{
for (b = x; b < n; b++)
{
if (num <=s) {
array[x][b] = num;
num++;
}
else array[x][b] = 0;
}
if (num == size + 1)
{
break;
}
for (b = y; b < m; b++)
{
if (num <=s) {
array[b][n - 1] = num;
num++;
}
else array[b][n - 1] = 0;
}
if (num == size + 1)
{
break;
}
y++;
n--;
for (b = n - 1; b > x; b--)
{
if (num <= s) {
array[m - 1][b] = num;
num++;
}
else array[m - 1][b] = 0;
}
if (num == size + 1)
{
break;
}
for (b = m - 1; b > x; b--)
{
if (num <= s) {
array[b][x] = num;
num++;
}
else array[b][x] = 0;
}
x++;
m--;
}
}
int main()
{
int m, n, s, array[100][100];
srand(time(NULL));
//m=3;
// n=4;
m = 2 + rand() % 5;
n = 2 + rand() % 5;
//memset(array, 0, sizeof(array[0][0]) * 10 * 10);
printf("enter the number \n");
scanf("%i", &s);
spiral(array, m, n, s);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf("%i\t", array[i][j]);
}
printf("\n");
}
return (0); }
However it doesn't work always correctly.
For example when i enter 15 and the program generates 4*3 array the output is`
1 2 3
10 12 4
9 -858993460 5
8 7 6`
However expected output is
1 2 3
10 11 4
9 12 5
8 7 6
Or when i enter 15 and the program generates 4*5 array the output is
1 2 3 4 5
14 0 0 0 6
13 0 0 0 7
12 11 10 9 8
And the expected output is
1 2 3 4 5
14 15 0 0 6
13 0 0 0 7
12 11 10 9 8
I can't find whats wrong with this code.

Try this:
void printArray(int array[10][10], int m, int n) {
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf("%i\t", array[i][j]);
}
printf("\n");
}
printf("\n");
}
void spiral(int array[10][10], int m, int n, int s)
{
int size, b, x = 0, y = 1, num = 1;
size = m*n;
while ( num <= s )
{
for (b = x; b < n; b++)
{
if (num <= s) {
array[x][b] = num;
num++;
} else array[x][b] = 0;
}
if (num == size + 1)
{
break;
}
for (b = y; b < m; b++)
{
if (num <= s) {
array[b][n - 1] = num;
num++;
} else array[b][n - 1] = 0;
}
if (num == size + 1)
{
break;
}
y++;
n--;
for (b = n - 1; b > x; b--)
{
if (num <= s) {
array[m - 1][b] = num;
num++;
} else array[m - 1][b] = 0;
}
if (num == size + 1)
{
break;
}
for (b = m - 1; b > x; b--)
{
if (num <= s) {
array[b][x] = num;
num++;
} else array[b][x] = 0;
}
x++;
m--;
}
}
int main()
{
int m, n, s, array[10][10];
srand(time(NULL));
m = 2 + rand() % 5;
n = 2 + rand() % 5;
memset(array, 0, sizeof(array[0][0]) * 10* 10);
printf("enter the number \n");
scanf("%i", &s);
spiral(array, m, n, s);
printArray(array, m, n);
return (0);
}
Before you had some weird for loop on top of your spiral function. The num++ in it interfered with the fact that you already increased num by one and made it skip the number the next time it would write in the uppermost line.
I changed it to a while loop that runs until num>s and it seems to work for me now.
Note that I just added printArray for easier debugging.

Related

Print Prime Numbers and Reversed Number

A number and a reversed number form a pair. If both numbers are prime numbers, we call it a reversed prime number pair. For instance, 13 and 31 is a 2 digit reversed prime number pair, 107 and 701 is a 3 digit reversed prime number pairs.
Write a program to output all n (2<=n<=5) digit reversed prime number pairs. If the input is less than 2 or greater than 5, output "Wrong input." and terminate the program. While ouputting , every 5 pairs form a new line, and only output the pair in which the first number is smaller than the second number.
Input: 1
Output: Wrong input.
Input: 3
Output:
(107,701)(113,311)(149,941)(157,751)(167,761)
(179,971)(199,991)(337,733)(347,743)(359,953)
(389,983)(709,907)(739,937)(769,967)
There are 14 results.
Can anyone give me hints how to do this?
I know how to determine if a number is a reversed prime number, but i couldn't understand how to complete this challenge from my friend
#include <stdio.h>
int checkPrime(int n) {
int i, isPrime = 1;
if (n == 0 || n == 1) {
isPrime = 0;
}
else {
for(i = 2; i <= n/2; ++i) {
if(n % i == 0) {
isPrime = 0;
break;
}
}
}
return isPrime;
}
int main (void)
{
int a, reverse = 0, remainder, flag=0;
scanf("%d",&a);
int temp = a;
while (temp!=0) {
remainder = temp%10;
reverse = reverse*10 + remainder;
temp/=10;
}
if (checkPrime(a)==1) {
if (checkPrime(reverse)==1){
printf("YES\n");
flag=1;
}
}
if (flag==0)
printf("NO\n");
}
This will be the correct solution:
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <stdlib.h>
#define MAX_N 100000
int *primes;
int num_primes;
void init_primes() {
int sqrt_max_n = sqrt(MAX_N);
primes = (int *) malloc(sqrt_max_n / 2 * sizeof(int));
num_primes = 0;
primes[num_primes] = 2;
num_primes++;
for (int i = 3; i <= sqrt_max_n; i += 2) {
bool is_prime = true;
for (int j = 0; j < num_primes; j++) {
if (i % primes[j] == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primes[num_primes] = i;
num_primes++;
}
}
}
int is_prime(int n) {
for (int i = 0; i < num_primes; i++) {
if (primes[i] == n) {
return 1;
}
if (n % primes[i] == 0) {
return 0;
}
}
return 1;
}
int reverse(int n) {
int reversed_n = 0;
while (n > 0) {
reversed_n = reversed_n * 10 + n % 10;
n /= 10;
}
return reversed_n;
}
int main() {
init_primes();
int n;
printf("Enter n (2 <= n <= 5): ");
scanf("%d", &n);
if (n < 2 || n > 5) {
printf("Wrong input.\n");
return 0;
}
int min = (int) pow(10, n - 1);
int max = (int) pow(10, n) - 1;
int count = 0;
for (int i = min; i <= max; i++) {
if (is_prime(i)) {
int reversed_i = reverse(i);
if (i < reversed_i && is_prime(reversed_i)) {
printf("(%d %d)", i, reversed_i);
count++;
if (count % 5 == 0) {
printf("\n");
} else {
printf(" ");
}
}
}
}
return 0;
}
After testing this code I get the same result what you need:
Enter n (2 <= n <= 5): 3
(107 701) (113 311) (149 941) (157 751) (167 761)
(179 971) (199 991) (337 733) (347 743) (359 953)
(389 983) (709 907) (739 937) (769 967)
The init_primes method caches all the required prime numbers until the sqrt of your limit to a dynamic array.
The is_prime method uses that cache for detecting whether a number is prime or not.

Why does my program only work half the time?

I have an assignment to write a program for a natural number where its inverse is divisible by its number of digits. A natural number n ( n > 9) is entered from the keyboard. To find and print the largest natural number less than n that its inverse is divisible by its number of digits. If the entered number is not valid, print a corresponding message (Brojot ne e validen).
I have tried :
#include <stdio.h>
int main() {
int n,r,s=0,a=0;
int m;
scanf("%d",&n);
int t=n;
if(t<10)
{ printf("Brojot ne e validen");}
else {
for (int i = n - 1; i > 0; i--) {
while (n != 0) {
r = n % 10;
s = (s * 10) + r;
n = n / 10;
a++;
if (s % a == 0) {
m = i;
break;
}
}
}
printf("%d\n", m);
}
return 0;
}
And when my inputs is 50, it gives the correct answer which is 49, but when I try numbers like 100 or 17 it prints 98 instead of 89 and 16 instead of 7 respectively. I have been baffled by this for more than an hour now
check your logic.
you can check each value by
#include <stdio.h>
int main() {
int t,r,s=0,a=0;
int m;
scanf("%d",&t);
if(t<10)
{ printf("Brojot ne e validen");}
else {
for (int i = t - 1; i > 0; i--) {
while (t != 0) {
r = t % 10;
printf("%d \n", r);
s = (s * 10) + r;
printf("%d \n", s);
t = t / 10;
printf("%d \n", t);
a++;
if (s % a == 0) {
m = i;
break;
}
}
}
printf("%d\n", m);
}
return 0;
}

I want to print the following pyramid of number pattern

1
2 4
3 5 7
6 8 10 12
9 11 13 15 17
Following is the code in which I am not able to print the pyramid:-
int main()
{
int i,j;
for(i=1;i<=5;i++){
for(j=1;j<=i;j++){
printf("%d ",i*j);
}
printf("\n");
}
return 0;
}
You need to track both even and odd numbers .
#include <stdio.h>
int main()
{
int even=1,odd=2;
int n=10;
for (int i = 1; i <= n; i++)
{
int a= (i % 2 == 0);
for (int j = 1; j < i; j++)
{
if(a)
{
printf("%d ",even);
}
else
{
printf("%d ",odd);
}
even += a ? 2 : 0;
odd += a ? 0 : 2;
}
printf("\n");
}
return 0;
}
Not very clean and compact algorithm but sth like this would work:
#include <stdio.h>
#include <stdlib.h>
int main() {
char tmp[10];
int n = 0, row = 1, odd = 1, even = 2, c = 0, selectOdd, fin = 0;
printf("maximum number: ");
scanf("%s", tmp);
n = atoi(tmp);
if (n != 0) {
while (fin < 2) {
selectOdd = row % 2;
c = row;
if (selectOdd) {
while (c != 0) {
printf("%3d", odd);
odd += 2;
if (odd > n) {
fin++;
break;
}
c--;
}
}
else {
while (c != 0) {
printf("%3d", even);
even += 2;
if (even > n) {
fin++;
break;
}
c--;
}
}
printf("\n");
row++;
}
}
return 0;
}
it's simple
your algorithm is odd, even, odd,... and so on
so you start with odd number until reach line number
for next line is even and you can find start number with this
you just need find number at start of line and continue print number number
in each step you just need
num += 2;
remember 'lineIndex' start from 1
num = (lineIndex - 1) * 2 + lineIndex % 2;
this is a full code
#include <stdio.h>
int main(){
int numIndex;
int lineIndex;
int num;
for (lineIndex = 1; lineIndex <= 5; lineIndex++) {
num = (lineIndex - 1) * 2 + lineIndex % 2;
for (numIndex = 0; numIndex < lineIndex; numIndex++) {
printf("%2d ", num);
num += 2;
}
printf("\n");
}
}

Breaking a number into the sum of two numbers

I have a problem with a such a task:
Write a program that finds such a pair of numbers x and y that their sum is equal to n. In addition, the pair of numbers should meet the following conditions:
the number x has at least 2 digits,
the number y is one digit less than the number x.
N is from the range <10 ; 10^5>
for number 80, the output should look like this:
79 + 1 = 80
78 + 2 = 80
77 + 3 = 80
76 + 4 = 80
75 + 5 = 80
74 + 6 = 80
73 + 7 = 80
72 + 8 = 80
71 + 9 = 80
I wrote a code that works in most cases but the system rejects the solution when testing the number 100000, because the program does not find such pairs - the test requires 9000 such pairs. I can't understand what's wrong because I think the program is okay. I'd like to ask for some advice.
My code:
#include <stdio.h>
#include <math.h>
int digit_count(int n)
{
int i = 0;
while (n > 0)
{
n /= 10;
i++;
}
return i;
}
int breakdown(int n)
{
long n_digits = digit_count(n), check = 0, count = 1;
long double y_max = pow(10, (n_digits - 1)) - 1, y_min = (pow(10, (n_digits - 2)));
for (int i = (int)y_min; i <= (int)y_max; i++)
{
if (digit_count(n - i) >= 2 && digit_count(i)+1 == digit_count(n - 1))
{
printf("%d + %d = %d %d\n", n - i, i, n, count);
check = 1;
count++;
}
}
if (check == 0)
{
printf("Nothing to show.");
}
return 0;
}
int main(void)
{
unsigned int n = 0;
printf("Podaj N: ");
if (1 != scanf("%u", &n))
{
printf("Incorrect input");
return 1;
}
if (n > 1000000 || n < 10)
{
printf("Incorrect input");
return 1;
}
breakdown(n);
return 0;
}
PS: I forgot to mention that the count variable is here only for debugging
I solved the problem in this way. Now it works for all numbers in the range according to the task.
#include <stdio.h>
#include <math.h>
int digit_count(int n)
{
int i = 0;
while (n > 0)
{
n /= 10;
i++;
}
return i;
}
int breakdown(int n)
{
int n_digits = digit_count(n), check = 0;
double y_max = pow(10, n_digits - 1) - 1;
//int i = 0 instead of i = y_min = (pow(10, (n_digits - 2))
for (int i = 0; i <= (int)y_max; i++)
{
//instead of if (digit_count(n - i) >= 2 && digit_count(i)+1 == digit_count(n - i))
if (digit_count(n - i) >= 2 && digit_count(n - i) == digit_count(i) + 1)
{
printf("%d + %d = %d\n", n - i, i, n);
check = 1;
}
}
if (check == 0)
{
printf("Nothing to show.");
}
return 0;
}
int main(void)
{
unsigned int n = 0;
printf("Podaj N: ");
if (1 != scanf("%u", &n))
{
printf("Incorrect input");
return 1;
}
if (n > 1000000 || n < 10)
{
printf("Incorrect input");
return 1;
}
breakdown(n);
return 0;
}
The posted code checks all the numbers in [10k - 2, 10k - 1 - 1], k beeing the number of digits of n, using the expansive (and wrong) condition
if (digit_count(n - i) >= 2 && digit_count(i)+1 == digit_count(n - 1)) { /* ... */ }
// ^
You can solve the problem avoiding all (or at least most of) those digits counts, by carefully calculating the valid extents of the ranges of the x and y values.
The following is a possible implementation
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
static inline long min_(long a, long b)
{
return b < a ? b : a;
}
static inline long max_(long a, long b)
{
return b < a ? a : b;
}
int digit_count(long n);
// Specilization for integer exponent.
long pow_10_(int exponent);
// A little helper struct
typedef struct range_s
{
long begin, end;
} range_t;
// Shrinks the range of the y values so that all the x = z - y are valid
// (the right nummber of digits and less than z).
range_t find_range(long z, long x_0)
{
range_t y = {max_(1, x_0 / 10), x_0};
range_t x = {x_0, min_(z, x_0 * 10)};
long x_1 = z - y.begin;
if (x_1 < x.begin)
y.end = y.begin;
else if (x_1 >= x.end)
y.begin = min_(z - x.end + 1, y.end);
long x_2 = z - y.end;
if (x_2 > x.end)
y.begin = y.end;
else if (x_2 <= x.begin)
y.end = max_(z - x.begin + 1, y.begin);
return y;
}
long print_sums(long z, range_t y);
long breakdown(long z)
{
int n_digits = digit_count(z); // <- Only once.
long x_0 = pow_10_(n_digits - 1);
// Depending on z, the x values may have the same number of digits of z or
// one less.
long count = 0;
if (n_digits > 2)
{
count += print_sums(z, find_range(z, x_0 / 10));
}
count += print_sums(z, find_range(z, x_0));
return count;
}
int main(void)
{
long n = 0;
if (1 != scanf("%lu", &n))
{
printf("Incorrect input");
return 1;
}
if (n > 1000000 || n < 10)
{
printf("Incorrect input");
return 1;
}
printf("\nCount: %ld\n", breakdown(n));
return 0;
}
int digit_count(long n)
{
int i = 0;
while (n > 0)
{
n /= 10;
i++;
}
return i ? i : 1; // I consider 0 a 1-digit number.
}
long pow_10_(int exponent)
{
if (exponent < 0)
return 0;
long result = 1;
while (exponent-- > 0)
result *= 10;
return result;
}
#define SAMPLES 5
long print_sums(long z, range_t y)
{
for (long i = y.begin; i < y.end; ++i)
#ifndef SHOW_ONLY_SAMPLES
printf("%ld + %ld = %ld\n", z - i, i, z);
#else
if ( i < y.begin + SAMPLES - 1 || i > y.end - SAMPLES )
printf("%ld + %ld = %ld\n", z - i, i, z);
else if ( i == y.begin + SAMPLES )
puts("...");
#endif
return y.end - y.begin;
}
Testable here.

even strings of an array in backwards way

I am trying to print an array in order to the even strings print backwards but the not even string in usual way. What do I do wrong with it?
For example:
1 0 3
9 7 3
5 7 8
and I need it:
1 0 3
3 7 9
5 7 8
But I also have a problem with filling an array in spiral way; how should I take a center of an array? Please, could you give an idea — how should I do this? And the array must be square. For example:
1 2 3
4 5 6
7 8 9
but I need it:
3 2 9
4 1 8
5 6 7
My code so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10][10],n,m,i,j;
printf("Enter m: ");
scanf("%d",&m);
printf("Enter n: ");
scanf("%d",&n);
for(i=0;i<m;i++){
for(j=0;j<m;j++){
printf("a[%d][%d]: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
// in usual order
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(i%2 != 0){
printf("%d ",a[i][j]);
}
else {
printf("%d ",a[n-i+1][j]);
}
}
printf("\n");
}
return 0;
}
example of filling an array in spiral
#include <stdio.h>
#include <string.h>
typedef enum {
N, W, S, E
} Dir;
typedef struct walker {
int row, col;
Dir dir;
int steps;
} Walker;
Walker go_forward(Walker walker){
switch(walker.dir){
case N:
walker.row -= 1;
break;
case W:
walker.col -= 1;
break;
case S:
walker.row += 1;
break;
case E:
walker.col += 1;
break;
}
return walker;
}
Walker proceed_left(Walker walker){
walker.dir = (walker.dir + 1) % 4;//turn left
walker = go_forward(walker);
return walker;
}
int main(void){
int n;
for(;;){
printf("Enter n(0 < n < 10): ");fflush(stdout);
int ret_s = scanf("%d", &n);
if(ret_s == 1){
if(0 < n && n < 10)
break;
} else if(ret_s == 0)
while(getchar() != '\n');//clear input
else //if(ret_s == EOF)
return 0;
}
int a[n][n];
memset(a, 0, sizeof(a));//zero clear
Walker walker = { .row = n / 2, .col = n / 2, .dir = E, .steps = 0 };
for(;;){
walker.steps += 1;
a[walker.row][walker.col] = walker.steps;
if(walker.steps == n * n)//goal
break;
Walker left = proceed_left(walker);
if(a[left.row][left.col] == 0)//left side is vacant
walker = left;
else
walker = go_forward(walker);
}
for(int r = 0; r < n; ++r){
for(int c = 0; c < n; ++c){
if(c)
putchar(' ');
printf("%2d", a[r][c]);
}
puts("");
}
}
Here is a program that includes the function spiral_fill(), which fills a square array with sequential ints, starting from 1 at the center, and proceeding in a counter-clockwise spiral. The function fills the array by first storing a 1 in the center, then filling the L-shaped region above and to the left, then below and to the right, and continuing until the array is filled.
#include <stdio.h>
#define ARR_SZ 3
void spiral_fill(size_t arr_sz, int arr[arr_sz][arr_sz]);
void print_arr(size_t rows, size_t cols, int arr[rows][cols]);
int main(void)
{
int test_arr[ARR_SZ][ARR_SZ];
spiral_fill(ARR_SZ, test_arr);
print_arr(ARR_SZ, ARR_SZ, test_arr);
return 0;
}
void spiral_fill(size_t arr_sz, int arr[arr_sz][arr_sz])
{
int center = arr_sz / 2;
int current = center;
int start_col, stop_col, start_row, stop_row;
size_t layer = 0;
int next_val = 1;
arr[center][center] = next_val++;
++layer;
while (layer < arr_sz) {
if (layer % 2) { // For odd layers, fill upper L
current -= layer;
start_col = center + layer / 2;
stop_col = center - (layer + 1) / 2;
for (int j = start_col; j >= stop_col; j--) {
arr[current][j] = next_val++;
}
start_row = center - layer / 2;
stop_row = center + layer / 2;
for (int i = start_row; i <= stop_row; i++) {
arr[i][current] = next_val++;
}
++layer;
} else { // For even layers, fill lower L
current += layer;
start_col = center - layer / 2;
stop_col = center + layer / 2;
for (int j = start_col; j <= stop_col; j++) {
arr[current][j] = next_val++;
}
start_row = center + (layer - 1) / 2;
stop_row = center - layer / 2;
for (int i = start_row; i >= stop_row ; i--) {
arr[i][current] = next_val++;
}
++layer;
}
}
}
void print_arr(size_t rows, size_t cols, int arr[rows][cols])
{
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
printf("%-5d ", arr[i][j]);
}
putchar('\n');
}
}
Here is a 3X3 array:
3 2 9
4 1 8
5 6 7
Here is a 6X6 array:
31 30 29 28 27 26
32 13 12 11 10 25
33 14 3 2 9 24
34 15 4 1 8 23
35 16 5 6 7 22
36 17 18 19 20 21

Resources