Fill a nxn matrix in spiral order from 1 to n² - c

I was supposed to fill an nxn matrix in spiral order from 1 to n² using functions and then print its result but I don't know why my code doesn't function can anyone help please?
The principle was to create different functions, each filling the matrix at different time intervals then calling those functions in the main program which prints them in a spiral matrix.
#include <stdio.h>
#include <stdlib.h>
/* initializing the array and variables for the whole program*/
int A[5][5],top,bottom,left,right;
int FillRowForward(int A[5][5],int top,int left,int right,int z)
/*function that fills the top of the matrix from left to right*/
{ left = 0;
for(top=left,right=0;right<=4;right++)
{
A[top][right]=z;
z++;
}
return A[top][right];
}
int FillRowBackwards(int A[5][5],int bottom,int left,int right,int z)
/*fills the lower part from right to left*/
{ bottom =4;
for(left=bottom,right=4;right>=0;right--)
{
A[left][right-1]=A[left][right]+z;
}
return A[left][right-1];
}
int FillColumnDownward(int A[5][5],int top,int bottom,int left,int z)
/*fills the last column from top to bottom*/
{
left=0;
for(top=left,bottom=4;top<=4;top++)
{
A[top+1][bottom]= A[top][bottom]+z;
}
return A[top][bottom];
}
int FillColumnUpward(int A[5][5],int top,int bottom,int left, int z)
/*fills the first column from bottop to top*/
{
left =0;
for(bottom=left,top=0;bottom>=1;bottom--)
{
A[bottom-1][top]=A[bottom][top]+z
}
return A[bottom][top];
}
int main()
{
int i,j,k=1;
while(k<5*5){
int FillRowForward(int A[5][5],int top,int left,int right,int k);
top++;
int FillColumnDownward(int A[5][5],int top,int bottom,int right,int k);
right--;
int FillRowBackwards(int A[5][5],int bottom,int left,int right,int k);
bottom--;
int FillColumnUpward(int A[5][5],int top,int bottom,int left,int k);
}
//prints the matrix
for(i=0;i<=4;i++)
for(j=0;j<=4;j++)
printf("%d",A[i][j]);
return 0;
}

You have a number of problems like:
int FillRowForward(int A[5][5],int top,int left,int right,int k);
not being a function call and that you you never change k, i.e. you have an endless loop.
This solution uses a variable direction to track the current direction of filling the matrix.
#include <stdio.h>
#define ARRSIZE 10
int main()
{
int A[ARRSIZE][ARRSIZE] = { 0 };
int i=0, j=0;
int direction = 0;
for(int k = 1; k <= (ARRSIZE*ARRSIZE); ++k)
{
A[i][j] = k;
switch (direction)
{
case 0 : // Go rigth
if (((j + 1) == ARRSIZE) || (A[i][j+1] != 0))
{
// Switch direction
direction = 1;
++i;
}
else
{
++j;
}
break;
case 1 : // Go down
if (((i + 1) == ARRSIZE) || (A[i+1][j] != 0))
{
// Switch direction
direction = 2;
--j;
}
else
{
++i;
}
break;
case 2 : // Go left
if (((j - 1) == -1) || (A[i][j-1] != 0))
{
// Switch direction
direction = 3;
--i;
}
else
{
--j;
}
break;
case 3 : // Go up
if (((i - 1) == -1) || (A[i-1][j] != 0))
{
// Switch direction
direction = 0;
++j;
}
else
{
--i;
}
break;
}
}
for(i=0; i<ARRSIZE; i++)
{
for(j=0; j<ARRSIZE; j++)
printf("%4d",A[i][j]);
printf("\n");
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19

You have a couple of problems here:
I suppose there is no need for global variables, so you can define everything in the main() function
As already pointed out "In main() you are only providing declarations of the functions, not calling them. "
You have an infinite loop in main() function because you never increased var k
Try to avoid using numbers in your function, use variables or symbolic constants instead. No difference on such small projects, but in bigger projects, you can easily confuse them, also if you want to change, you must change every value, etc.
Your functions are not doing what they are supposed to do. You can write something like this (I found my old program and modified it a bit):
#include <stdio.h>
void print_mat(int mat[][5], int m, int n)
{
int i,j;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
printf("%d\t", mat[i][j]);
}
printf("\n\n");
}
printf("\n");
}
void spiral(int mat[][5], int m, int n)
{
int i, k = 0, l = 0;
int counter = 1;
while(k < m && l < n)
{
for(i = l; i < n; i++)
{
mat[k][i] = counter++;
}
k++;
for(i = k; i < m; i++)
{
mat[i][n-1] = counter++;
}
n--;
if(k < m)
{
for(i = n-1; i >= l; i--)
{
mat[m-1][i] = counter++;
}
m--;
}
if(l < n)
{
for(i = m-1; i >= k; i--)
{
mat[i][l] = counter++;
}
l++;
}
}
}
int main()
{
int mat[5][5];
int n = 5;
spiral(mat,n,n);
print_mat(mat,n,n);
return 0;
}
Since you need to create different functions, you can try to divide this spiral() function into several smaller functions, it can be a good exercise.

Related

Printing 2D array elements within a function is causing a segmentation fault

I created an 2D array, each line receiving 6 random different values between 1-60.
#define QTE 50
#define NUM 6
void mostrar();
int main(void)
{
int sorteios[QTE][NUM], repeticao[61] = {};
srand(time(NULL));
for (int i = 1; i < QTE; i++)
{
for (int j = 0; j < 6; j++)
{
int gerado = rand() % 60 + 1;
for (int k = j; k > 0; k--)
{
if (j == 0)
{
break;
}
while (gerado == sorteios[i][k])
{
gerado = rand() % 60 + 1;
}
}
sorteios[i][j] = gerado;
int aleatorio = sorteios[i][j];
repeticao[aleatorio] += 1;
}
printf("Sequência %04d:\t %02d\t%02d\t%02d\t%02d\t%02d\t%02d\n", i, sorteios[i][0], sorteios[i][1], sorteios[i][2], sorteios[i][3], sorteios[i][4], sorteios[i][5]);
}
mostrar(sorteios[QTE][NUM]);
}
This code itself is working if there's a for loop inside the main function but using the function to execute causes segmentation fault(core dumped).
void mostrar(int *array[QTE][NUM])
{
printf("Mostrando..\n");
for (int p = 0; p < QTE; p++)
{
printf("Sequência %04d:\t %02d\t%02d\t%02d\t%02d\t%02d\t%02d\n", p, *array[p][0], *array[p][1], *array[p][2], *array[p][3], *array[p][4], *array[p][5]);
}
}
A piece of the console result..
...
Sequência 0043: 35 59 08 31 16 40
Sequência 0044: 26 47 27 52 32 08
Sequência 0045: 35 34 26 35 31 14
Sequência 0046: 07 44 13 22 35 46
Sequência 0047: 50 17 16 53 49 29
Sequência 0048: 27 39 37 50 10 44
Sequência 0049: 29 35 30 55 18 53
Mostrando..
Segmentation fault (core dumped)
Aside from the way you pass the array to the function, already discussed in the comments, there are some other issues in your code, here is a corrected version with comments where fixes are needed:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define QTE 50
#define NUM 6
// if you want the access the array, jut use that as an argument, no pointer needed
void mostrar(int array[][NUM])
{
printf("Mostrando..\n");
for (int p = 0; p < QTE; p++)
{
// correcting the dereference to match the argument...
printf("Sequência %04d:\t %02d\t%02d\t%02d\t%02d\t%02d\t%02d\n", p, array[p][0], array[p][1], array[p][2], array[p][3], array[p][4], array[p][5]);
}
}
int main(void)
{
int sorteios[QTE][NUM], repeticao[61] = {0};
srand(time(NULL));
// beginning at index 1 would leave the first index empty, also messing up the
// indexing in the function, so start at index 0
for (int i = 0; i < QTE; i++)
{
for (int j = 0; j < 6; j++)
{
int gerado = rand() % 60 + 1;
for (int k = j; k > 0; k--)
{
if (j == 0)
{
break;
}
while (gerado == sorteios[i][k])
{
gerado = rand() % 60 + 1;
}
}
sorteios[i][j] = gerado;
int aleatorio = sorteios[i][j];
repeticao[aleatorio] += 1;
}
}
// pass only the array, if you include indexes you are just passing an element
// of the array, and sorteios[QTE][NUM] would be outside of the bounds of the array
// and wouldn't match the original function argument either
mostrar(sorteios);
}
Live demo

Error in implementing bubble sorting in a merge sort program in C

I am learning data structure and algorithms. The program takes a set number of inputs in an array and sorts them out using merge sort. The condition is whenever the size of a sub-array is equal to or smaller than 10, it should sort the elements out using bubble sort and then merge them together. My problem is with getting the program to bubble sort. So far I have been unable to find out the mistake in my program. I am still learning everyday. I would really appreciate it if someone could help me find the error and fix it please. Thank you very much and have a g'day.
Here's the code:
#include<stdio.h>
#include<stdlib.h>
#define arrsize 10
void merge_sort(int, int);
void merge_array(int, int, int, int);
int arr_sort[arrsize];
void bubblesort(int a[],int size);
void main()
{
int a[50],n,i;
printf("\nEnter %d Elements for Sorting\n", arrsize);
for (i = 0; i < arrsize; i++)
scanf("%d", &arr_sort[i]);
printf("\nYour Data :");
for (i = 0; i < arrsize; i++) {
printf("\t%d", arr_sort[i]);
}
merge_sort(0, arrsize - 1);
printf("\n\nSorted Data :");
for (i = 0; i < arrsize; i++) {
printf("\t%d", arr_sort[i]);
}
}
void bubblesort(int arr_sort[],int size)
{
int temp,i,j;
for(i=0;i<size;i++)
{
for(j=0;j<size-1;j++)
{
if(arr_sort[j]>arr_sort[j+1])
{
temp=arr_sort[j];
arr_sort[j]=arr_sort[j+1];
arr_sort[j+1]=temp;
}
}
}
}
void merge_sort(int i, int j) {
int m;
if (i < j) {
m = (i + j) / 2;
if(m<=5)
{
for(i=0;i<=m;i++){
for(j=i+1;j<=m;j++){
bubblesort(arr_sort[i],m);
bubblesort(arr_sort[j],m);}}
merge_array(i,m,m+1,j);
}
else
merge_sort(i, m);
merge_sort(m + 1, j);
merge_array(i, m, m + 1, j);
}
}
void merge_array(int a, int b, int c, int d) {
int t[50];
int i = a, j = c, k = 0;
while (i <= b && j <= d) {
if (arr_sort[i] < arr_sort[j])
t[k++] = arr_sort[i++];
else
t[k++] = arr_sort[j++];
}
while (i <= b)
t[k++] = arr_sort[i++];
while (j <= d)
t[k++] = arr_sort[j++];
for (i = a, j = 0; i <= d; i++, j++)
arr_sort[i] = t[j];
}
Among the issues in your code:
From merge_sort, you should be calling bubble_sort for a given floor magnitude, hard-fixed in your merge_sort, specified globally, or as an argument to your functions. The former of these is easiest to achieve.
Your bubble_sort invocation from merge_sort is wrong from inception, as you're passing int values where int* should be present.
Your functions should all take the array to sort as an argument, and at least the length as well. This makes the functions more robust, and thanks to pointer arithmetic, easier to implement than you may think.
Fixing this requires major surgery.
Updated merge_array
First some surgery for the merge_array function. This assumes you support variable length arrays (VLAs). Notice the function accepts the array base address, the mid point, and the overall length.
void merge_array(int a[], int mid, int len)
{
// change to int tmp[arrsize], or use dynamic allocation, if your
// platform doesn't support VLAs
int tmp[len];
int i = 0, j = mid, k = 0;
while (i < mid && j < len)
tmp[k++] = ((a[i] < a[j]) ? a[i++] : a[j++]);
while (i < mid)
tmp[k++] = a[i++];
for (i = 0; i < k; ++i)
a[i] = tmp[i];
}
Updated merge_sort
Now the merge_sort function as described in the problem analysis. Like the above, it should take an array base address and a length, but that's all it needs. Pointer arithmetic will let us partition on recursed calls.
void merge_sort(int a[], int len)
{
if (len < 5)
{
// bubblesort short partitions (less than length:5)
bubble_sort(a, len);
}
else
{
int mid = len / 2;
merge_sort(a, mid);
merge_sort(a + mid, len - mid); // note pointer arithmetic here
merge_array(a, mid, len);
}
}
Updated bubble_sort
This simple bubble sort uses forward swap detection to leave early on already-sorted detection. Like the prior functions, we have the base address of some array and a specified length.
void bubble_sort(int a[], int size)
{
int swapped = 1;
while (swapped && size-- > 0)
{
swapped = 0;
for (int i = 0; i < size; ++i)
{
if (a[i + 1] < a[i])
{
int tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
swapped = 1;
}
}
}
}
Putting It All Together
Below is the complete program, which includes a print helper to dump an array to the console, and a random-generator to avoid lengthy keyboard input. The provided main() creates a random-filled array, prints it, sorts it, then prints the result. Obviously the output will vary with each run, but you hopefully get the idea of how the above functions are called.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define arrsize 40
void merge_sort(int a[], int len);
void merge_array(int a[], int mid, int len);
void bubble_sort(int a[], int size);
void merge_array(int a[], int mid, int len)
{
// change to int tmp[arrsize], or use dynamic allocation, if your
// platform doesn't support VLAs
int tmp[len];
int i = 0, j = mid, k = 0;
while (i < mid && j < len)
tmp[k++] = ((a[i] < a[j]) ? a[i++] : a[j++]);
while (i < mid)
tmp[k++] = a[i++];
for (i = 0; i < k; ++i)
a[i] = tmp[i];
}
void merge_sort(int a[], int len)
{
if (len < 5)
{
// bubblesort short partitions (less than length:5)
bubble_sort(a, len);
}
else
{
int mid = len / 2;
merge_sort(a, mid);
merge_sort(a + mid, len - mid); // note pointer arithmetic here
merge_array(a, mid, len);
}
}
void bubble_sort(int a[], int size)
{
int swapped = 1;
while (swapped && size-- > 0)
{
swapped = 0;
for (int i = 0; i < size; ++i)
{
if (a[i + 1] < a[i])
{
int tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
swapped = 1;
}
}
}
}
void print_arr(int const arr[], int len)
{
while (len-- > 0)
printf("%d ", *arr++);
fputc('\n', stdout);
}
int main()
{
srand((unsigned)time(NULL));
int arr_sort[arrsize];
// generate random array
for (int i = 0; i < arrsize; ++i)
arr_sort[i] = 1 + rand() % 99;
print_arr(arr_sort, arrsize);
// sort the array
merge_sort(arr_sort, arrsize);
print_arr(arr_sort, arrsize);
}
Sample Output
16 81 73 86 87 66 14 93 19 13 62 32 70 56 29 88 20 21 7 27 70 46 72 42 95 83 24 2 5 43 67 79 8 18 82 39 81 56 56 45
2 5 7 8 13 14 16 18 19 20 21 24 27 29 32 39 42 43 45 46 56 56 56 62 66 67 70 70 72 73 79 81 81 82 83 86 87 88 93 95
Hope it helps.

To find and assign primes to an array

Hi I have made a simple program to print primes between 1 and 100 but I cannot figure a way to assign these values to an array of size 25 as we all know there are 25 primes between 1 and 100:
#include <stdio.h>
int main() {
int i, k;
for (i = 3; i < 100; i = i + 2) {
for (k = 2; k < i; k++) {
if (i % k == 0)
break;
}
if (i == k)
printf("%d\n", i);
}
}
Just create an array at the top, write to it, and then read out of it after you've found all your primes. Note that this could definitely be done more efficiently, but given the number of calculations you're doing, that's beside the point.
Code
#include<stdio.h>
int main() {
int primes[25];
int i, k;
int j = 0;
// find primes
for(i = 2; i < 100; i++) {
for (k = 2; k < i; k++) {
if (i % k == 0) {
break;
}
}
if (i == k) {
primes[j] = i;
j++;
}
}
// print primes
for (j = 0; j < 25; j++) {
printf("%d\n", primes[j]);
}
return 0;
}
Also note that 2 is prime, so you'll want to make sure that that's included in your output.
Output
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Make an array before you begin, then create a variable that increments while each prime is found. It might look something like this:
#include <stdio.h>
int main() {
int primes[25];
primes[0] = 2;
int count = 1;
for (int i = 3; i < 100; i += 2) {
int k;
for (k = 2; k < i; k++) {
if (i % k == 0) break;
}
if(i == k) {
primes[count] = i;
count++;
}
}
}
Warning: this is a humorous answer, not to be taken seriously.
Just like we all know there are 25 primes between 1 and 100, we might as well know the magic value to avoid using an array at all:
#include <stdio.h>
int main() {
long long magic = 150964650272183;
printf("2");
for (int i = 3; magic; magic >>= 1, i += 2)
magic & 1 && printf(" %d", i);
printf("\n");
return 0;
}
Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Algorithm to determine whether a permutation can be generated by 2 parallel stacks

The setting is similar to the stack-sortable permutation problem discussed by Knuth before, but on permutation generation with stack.
I would like to write a program to determine whether a permutation is stack-generatable with 2 stacks instead of only 1.
This is actually a homework problem, which the requirement are as follows:
A permutation of 1 to n is a stack-generated permutation if and only
if it can be generated by pushing 1 to n onto a stack and popping them
o. For example, stack-generated permutation (2, 1, 3) can be
generated by doing operations push 1, push 2, pop, pop, push 3, pop.
In this problem, instead of using only one stack, we use two stacks:
every time you can push an element to either stack, or you can pop
element from either stack as long as it is non-empty. However, once an
element is popped, it cannot be pushed back to either stack again.
Your task is to determine whether a permutation can be generated by
using two stacks.
I know that if a permutation contain the pattern 4123, it cannot be generated. However, doing pattern matching seems very time consuming and likely out of my ability, not to mention that I do not know whether 4123 is the only pattern.
Currently I am trying to actually generate it with 2 stacks in order to determine whether a permutation can be generated, but my algorithm can only determine some of the stack-generatable permutation. Therefore I would like to know what is the correct algorithm for this problem. An working C code would of cause be amazing, but any tips, advise or pseudo code are also good enough. Thank you!
An example permutation to determine:
62 61 58 53 67 66 47 65 69 68 64 45 70 71 63 44 42 60 72 59 41 73 74 57 56 39 55 54 38 37 52 51 50 49 48 76 46 43 75 40 36 35 77 34 31 30 33 29 32 78 22 79 28 27 80 20 26 25 24 23 83 82 81 85 84 87 89 21 19 90 88 92 86 95 94 18 98 96 97 93 17 15 99 91 16 100 14 12 13 9 8 11 6 5 10 7 4 3 2 1
My current implementation(which is very messy and has no comment, so I do not recommend you reading it):
#include <stdio.h>
#define MAXSIZE 1000
typedef struct stack {
int data[MAXSIZE];
int top;
} Stack;
void push(Stack *s, int d);
int pop(Stack *s);
int peek(Stack *s);
int isEmpty(Stack *s);
int getPos(int d[], int size, int a);
void push(Stack *s, int d) {
(*s).top++;
(*s).data[(*s).top] = d;
}
int pop(Stack *s) {
int d = (*s).data[(*s).top];
(*s).top--;
return d;
}
int peek(Stack *s) {
if (!isEmpty(s)) {
return (*s).data[(*s).top];
} else return -1;
}
int isEmpty(Stack *s) {
if ((*s).top < 0) {
return 1;
} else return 0;
}
int getPos(int d[], int size, int a) {
int i = 0, al = -1;
for (i = 0; i < size; i++) {
if (d[i] == a) {
al = i;
}
}
if (al != -1) {
return al;
} else return -1;
}
int main() {
int t = 0;
scanf("%d", &t);
int i = 0;
for (i = 0; i < t; i++) {
int failed = 0;
int n = 0;
scanf("%d", &n);
int target[MAXSIZE];
int j = 0;
for (j = 0; j < n; j++) {
scanf("%d", &target[j]);
}
Stack s1, s2;
s1.top = -1;
s2.top = -1;
Stack *s1_ptr = &s1;
Stack *s2_ptr = &s2;
int output[MAXSIZE];
int oh = 0;
int th = 0;
int k = 1;
for (k = 1; k <= n; k++) {
int f1 = 0, f2 = 0;
int checkAgain = 1, pushed = 0;
while (checkAgain) {
checkAgain = 0;
if (k == target[th]) {
push(s1_ptr, k);
output[oh] = pop(s1_ptr);
oh++;
th++;
pushed = 1;
} else if (!isEmpty(s1_ptr) && peek(s1_ptr) == target[th]) {
output[oh] = pop(s1_ptr);
oh++;
th++;
checkAgain = 1;
} else if (!isEmpty(s2_ptr) && peek(s2_ptr) == target[th]) {
output[oh] = pop(s2_ptr);
oh++;
th++;
checkAgain = 1;
}
}
if (!pushed) {
if (isEmpty(s1_ptr)) {
push(s1_ptr, k);
} else if (isEmpty(s2_ptr)) {
push(s2_ptr, k);
} else {
int s1l = -1, s2l = -1;
if (peek(s1_ptr) >= 0) {
s1l = getPos(target, n, peek(s1_ptr));
}
if (peek(s2_ptr) >= 0) {
s2l = getPos(target, n, peek(s2_ptr));
}
int kl = getPos(target, n, k);
int canPush1 = 0, canPush2 = 0;
if (kl < s1l) {
canPush1 = 1;
}
if (kl < s2l) {
canPush2 = 1;
}
if (canPush1 && canPush2) {
if (s1l < s2l) {
push(s1_ptr, k);
} else {
push(s2_ptr, k);
}
} else if (canPush1 && !canPush2) {
push(s1_ptr, k);
} else if (!canPush1 && canPush2) {
push(s2_ptr, k);
} else {
failed = 1;
break;
}
}
}
}
if (failed) {
printf("No\n");
continue;
}
int m = th;
for (m = th; m < n; m++) {
if (peek(s1_ptr) == target[th]) {
output[oh] = pop(s1_ptr);
oh++;
th++;
} else if (peek(s2_ptr) == target[th]) {
output[oh] = pop(s2_ptr);
oh++;
th++;
} else {
failed = 1;
break;
}
}
if (th == n) {
printf("Yes\n");
} else {
printf("No\n");
}
}
return 0;
}
I solved it with the help from two Chinese sites, as there is actually a similar question in NOIP2008, which deals with permutation sortable by 2 stacks. The solution for generatable permutation is pretty similar. I can write more later if someone is interested about the solution.
The two sites that helped me:
NOIP2008 双栈排序 twostack 题解
NOIP2008提高组复赛题解
My solution:
#include <stdio.h>
#include <string.h>
#define MAXN 1002
int const NEINF = -1;
int targetPermutation[MAXN];
int precalculatedMax[MAXN];
int bipartiteGraph[MAXN];
int adjacencyMatrix[MAXN][MAXN];
int N;
int noSolution = 0;
void reset();
void colouringAndCheckConflict(int i, int c);
void checkAdjacencyAndDye();
void colouringAndCheckConflict(int i, int c) {
bipartiteGraph[i] = c;
int j;
for (j = 1; j <= N; j++) {
if (adjacencyMatrix[i][j]) {
if (bipartiteGraph[j] == c) //conflict : not a bipartite graph
{
noSolution = 1;
return;
}
if (!bipartiteGraph[j]) {
colouringAndCheckConflict(j, 3 - c); // color the opposite color 1<->2
}
}
}
}
void checkAdjacencyAndDye() {
/* 231 for sortable
* i<j<k, S[k]<S[i]<S[J]
* 312 for generatable
* k<i<j, S[i]<S[J]<S[k]
* DONE: Modify the algorithm to make it right for generation instead of sortable
*/
int i, j;
precalculatedMax[0] = NEINF;
for (i = 1; i <= N; i++) {
precalculatedMax[i] = targetPermutation[i];
if (precalculatedMax[i - 1] > precalculatedMax[i])
precalculatedMax[i] = precalculatedMax[i - 1];
}
for (i = 1; i <= N - 1; i++) {
for (j = i + 1; j <= N; j++) {
if (targetPermutation[i] < targetPermutation[j] && precalculatedMax[i - 1] > targetPermutation[j]) {
adjacencyMatrix[i][j] = adjacencyMatrix[j][i] = 1;
}
}
}
for (i = 1; i <= N; i++) {
if (!bipartiteGraph[i] && !noSolution) {
colouringAndCheckConflict(i, 1);
}
}
}
void reset() {
memset(adjacencyMatrix, 0, sizeof(adjacencyMatrix));
memset(bipartiteGraph, 0, sizeof(bipartiteGraph));
memset(targetPermutation, 0, sizeof(targetPermutation));
memset(precalculatedMax, 0, sizeof(precalculatedMax));
N = 0;
noSolution = 0;
}
int main() {
int t;
scanf("%d", &t);
int k;
for (k = 1; k <= t; k++) {
int i;
scanf("%d", &N);
for (i = 1; i <= N; i++) {
scanf("%d", &targetPermutation[i]);
}
checkAdjacencyAndDye();
if (!noSolution) {
printf("Yes\n");
} else {
printf("No\n");
}
reset();
}
return 0;
}

issues trying to make rows in c program

#include <stdio.h>
int prime(int limit,int col);
int main(){
int limit,col,count,i;
printf("Table of Primes\n");
printf("===============\n");
printf("Upper limit: ");
scanf("%d",&limit);
getchar();
printf("# of columns: ");
scanf("%d",&col);
count=prime( limit,col);
return 0;
}
int prime(int limit,int col){
int i,j,w;
for(w=0;w<col;w++){
for(i=2;i<=limit;i++){
for(j=2;j<=i;j++){
if(i%j==0){
break;
}
}
if(i==j){
printf("%d ",i);
}
}
printf("\n");
}
}
The code above is to find the amount of prime numbers between 2 and the user input numbers.
I have that working fine, but my issue is getting the Code to be put into columns (defined by # of columns)
I talked this over with my teacher and she said that I do not have to use a 2D array to accomplish this.
Can anyone please help me out?
Also the output is spouse to look like this:
Table of Primes
===============
Upper limit: 175
# of columns: 5
2 3 5 7 11
13 17 19 23 29
31 37 41 43 47
53 59 61 67 71
73 79 83 89 97
101 103 107 109 113
127 131 137 139 149
151 157 163 167 173
Thank you.
You can easily test the number of columns and print a newline. The function prime() also lacked a return value so I return w as the number of primes found. This is just a slight tweak to your prime() function.
#include <stdio.h>
#include <string.h>
int prime(int limit, int col) {
int i, j, w = 0;
for (i=2; i<=limit; i++) {
for (j=2; j<=i; j++) {
if (i%j == 0) {
break;
}
}
if (i==j) {
if (w++ % col == 0) // test number of columns
printf("\n");
printf("%7d", i); // specify field width
}
}
printf("\n");
return w;
}
int main(void) {
prime (173, 5);
return 0;
}
Program output:
2 3 5 7 11
13 17 19 23 29
31 37 41 43 47
53 59 61 67 71
73 79 83 89 97
101 103 107 109 113
127 131 137 139 149
151 157 163 167 173
I leave you to add the frills.
I suggest you to make separate functions for finding primes and displaying primes, so you will have more control on displaying those primes:
#include <stdio.h>
#include <math.h> // sqrt
int is_prime (int x);
void prime(int limit, int col);
int main ()
{
int limit, col;
printf("Table of Primes\n");
printf("===============\n");
printf("Upper limit: ");
scanf("%d",&limit);
getchar();
printf("# of columns: ");
scanf("%d",&col);
prime(limit, col);
printf("\n");
return 0;
}
int is_prime (int num)
{
int flag;
int i;
double p;
p = sqrt(num);
flag = 1;
if (num == 1)
return 0;
if (num == 2)
return flag;
if ((num % 2) == 0)
return 0;
for (i = 3; i <= p; i += 2)
{
if ((num % i) == 0)
{
flag = false;
return flag;
}
}
return flag;
}
void prime (int limit, int column)
{
int i, j, cnt;;
cnt = 0;
for (i = 0; i < limit; i++) {
if (is_prime(i)) {
printf("%4d ", i);
cnt++;
if ((cnt % column) == 0) {
printf("\n");
}
}
}
}
Of course you can change is_prime to your own function.
You can keep a variable to count how many numbers have been printed, then count % col will be zero every time count is a multiple of col, so this would work
#include <stdio.h>
void prime(int limit, int col);
int readint(const char *const message);
int main()
{
int limit,col;
printf("Table of Primes\n");
printf("===============\n");
limit = readint("Upper limit");
col = readint("# of columns");
prime(limit, col);
return 0;
}
int readint(const char *const message)
{
int value;
printf("%s> ", message);
while (scanf("%d", &value) != 1)
{
int chr;
printf("\tinvalid input\n");
printf("%s> ", message);
do {
chr = getchar();
} while ((chr != EOF) && (chr != '\n'));
}
return value;
}
void prime(int limit, int col)
{
int i, j;
int count;
count = 0;
for (i = 2 ; i <= limit ; i++)
{
for (j = 2 ; j <= i ; j++)
{
if (i % j == 0)
break;
}
if (i == j)
{
count += 1;
printf("%5d", i);
if ((count != 0) && (count % col == 0))
printf("\n");
}
}
}
Note that your code does not handle invalid input, I added that in this code, many people erroneously ignore scanf()'s return value, which is there for a reason.

Resources