Get first col in matrix - c

I have simple program that gets the sum of main and anti diagonals of a matrix. And then it get the sum of first and last column of a matrix.For example:
1 2 3
4 5 6 --> The matrix
7 8 9
md = 1 + 5 + 9 = 15
ad = 7 + 5 + 3 = 15
lastCol = 3 + 6 + 9 = 18
firstCol = 1 + 4 + 7 = 12
How can i get the sum of the firstCol of a square matrix ? Here is my code:
int main(){
int n;
scanf("%d",&n);
int i,j,a[n][n],firstCol=0,lastCol=0,md=0,ad=0;
for(i = 0;i <n;i++){
for(j=0;j<n;j++){
scanf("%d",&a[i][j]);
}
}
for(i = 0;i <n;i++){
for(j=0;j<n;j++){
if(i==j){
md+=a[i][j];
}
if(i+j==n-1){
ad+=a[i][j];
}
}
}
for(i=0;i<n;i++){
lastCol+=a[i][n-1];
}
}

for (i = 0; i < n; i ++) {
firstCol += a[i][0];
}

Use functions. Try to make them a bit more universal. This one will return sum of the first column of any size array.
long long int sumFirstCol(size_t rows, size_t cols, int (*array)[cols])
{
long long int result = 0;
if(array && rows && cols)
{
for(size_t row = 0; row < rows; row++)
{
result += array[row][0];
}
}
return result;
}
int main(void)
{
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},};
printf("%lld\n", sumFirstCol(3, 3, matrix));
}

Related

how to print a matrix with a negated row more efficiently

I wrote the following function:
void negate_row(const int n, const int r, int *a)
{
if (r == 0)
{
printf("Matrix with negated row: ");
printf("\n");
for (int y = 0; y < 3; y++)
{
*(a + 3 * r + y) = *(a + 3 * r + y) *(-1);
printf("%d ", *(a + 3 * r + y));
}
printf("\n");
for (int y = 0; y < 3; y++)
{
*(a + 3 * r + y) = *(a + 3 * r + y) *(-1);
printf("%d ", *(a + 3 * (r + 1) + y));
}
printf("\n");
for (int y = 0; y < 3; y++)
{
*(a + 3 * r + y) = *(a + 3 * r + y) *(-1);
printf("%d ", *(a + 3 * (r + 2) + y));
}
printf("\n");
}
So basically what happens here is my function takes in a n X 3 matrix and negates a specific row using pointer arithmetic. I have been able to achieve that, I've also been able to figure out how to print that same matrix with the negated row. It's just the way I'm doing it is not efficient at all. I'd have to write an if statement for each row, ex if r == 0,1,2,3,4 etc... is there any way I can do this more efficiently?
Some clarifications: const int n decides the size of the matrix (n x 3), const int r decides what row is negated (0 <= r < n).
A second loop will help. I generally find pointer code a bit harder to read. Particularly with Matrix manipulation you might be better off using array syntax instead of pointer syntax.
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
{
printf("%d ", *(a + 3 * (r + x) + y));
}
printf("\n");
}
Particular case (3 rows):
int mul = 1, y = 0;
for (int x = 0; x < n; x++) {
mul = x == r ? -1 : 1;
y = (a + 3 * x);
printf("%d ", (*y) * mul);
printf("%d ", (*y + 1) * mul);
printf("%d ", (*y + 2) * mul);
printf("\n");
}
More generic (m rows):
int mul = 1;
for (int x = 0; x < n; x++) {
mul = x == r ? -1 : 1;
for (int y = 0; y < m; y++) {
printf("%d ", ((*(a + m * x + y)) * mul);
}
printf("\n");
}
Note: In new compilers there is also no difference in speed between array or pointer syntax.
You could write a function that accepts a one-dimensional array (a row of your matrix) and then using this function you could in a loop output its all rows or output a selected row.
Here is a demonstrative program.
#include <stdio.h>
void negate_row( const int *a, size_t n, int width )
{
if ( width < 1 ) width = 1;
for ( const int *p = a; p != a + n; ++p )
{
printf( "%*d ", width, -*p );
}
putchar( '\n' );
}
int main(void)
{
enum { M = 3, N = 4 };
int matrix[M][N] =
{
{ 0, 1, 2, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
for ( int ( *p )[N] = matrix; p != matrix + M; ++p )
{
negate_row( *p, N, 3 );
}
return 0;
}
The program output is
0 -1 -2 -4
-5 -6 -7 -8
-9 -10 -11 -12
As you showed a code where you are using pointers tp output elements of an array then in this demonstrative program I am also using pointers everywhere to access elements of an array.
The third parameter of the function specifies the width of the field for an outputted value.
To output the matrix in the reversed order of rows you can use the loop shown in the program blow.
#include <stdio.h>
void negate_row( const int *a, size_t n, int width )
{
if ( width < 1 ) width = 1;
for ( const int *p = a; p != a + n; ++p )
{
printf( "%*d ", width, -*p );
}
putchar( '\n' );
}
int main(void)
{
enum { M = 3, N = 4 };
int matrix[M][N] =
{
{ 0, 1, 2, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
for ( int ( *p )[N] = matrix + M; p != matrix; )
{
negate_row( *--p, N, 3 );
}
return 0;
}
The program output is
-9 -10 -11 -12
-5 -6 -7 -8
0 -1 -2 -4
You can generalize the function easily: as long as the row is within the matrix, your code works for any row. Also note that it is better to use a separate function to print the matrix.
#include <stdio.h>
void negate_row(const int n, const int r, int *a) {
if (r >= 0 && r < n) {
// negate row r
for (int col = 0; col < 3; col++) {
*(a + 3 * r + col) *= -1;
}
}
}
void print_matrix(const int n, int *a, const char *title) {
if (title) {
printf("%s:\n", title);
}
for (int row = 0; row < n; row++) {
for (int col = 0; col < 3; col++) {
printf("%d ", *(a + 3 * row + col));
}
printf("\n");
}
printf("\n");
}
int main() {
int matrix[5 * 3] = {
0, 1, 2,
3, 4, 5,
6, 7, 8,
9, 10, 11,
12, 13, 14,
};
print_matrix(5, matrix, "Matrix");
negate_row(5, 0, matrix);
print_matrix(5, matrix, "Matrix with negated row");
negate_row(5, 3, matrix);
print_matrix(5, matrix, "Matrix with two negated rows");
negate_row(5, 0, matrix);
negate_row(5, 3, matrix);
print_matrix(5, matrix, "Matrix back to origin");
return 0;
}
Output:
Matrix:
0 1 2
3 4 5
6 7 8
9 10 11
12 13 14
Matrix with negated row:
0 -1 -2
3 4 5
6 7 8
9 10 11
12 13 14
Matrix with two negated rows:
0 -1 -2
3 4 5
6 7 8
-9 -10 -11
12 13 14
Matrix back to origin:
0 1 2
3 4 5
6 7 8
9 10 11
12 13 14

Algorithms: To determine whether a given set has two subsets which are disjoint such that sum of elements in both subsets is same?

Here is the code that I have written:-
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int ctr = 0;
void partition(int arr[], int n) {
int i, j, k = 0, r, in = 0, te, flag = 0;
int *sum;
sum = (int*)malloc(sizeof(int) * pow(2, n));
for (i = 0; i < pow(2, n); i++) {
printf("{");
for (j = 0; j < n; j++) {
if (i & (1 << j)) {
printf("%d ", arr[j]);
sum[k] = sum[k] + arr[j];
}
}
k++;
printf("}");
printf("\n");
}
printf("\n \n");
int *temp;
for (k = 0; k < pow(2, n) - 1; k++) {
in = 0;
temp = (int*)malloc(sizeof(int));
for (r = k + 1; r < pow(2, n); r++) {
if (sum[k] == sum[r]) {
printf("\n Printing solution for sum %d", sum[k]);
for (i = 0; i < pow(2, n); i++) {
if (i == k || i == r) {
printf("{");
for (j = 0; j < n; j++) {
if (i & 1 << j) {
for (te = 0; te < in; te++) { //Disjointness
if (temp[te] == arr[j])
flag = 1;
}
if (flag == 1)
break;
temp[in++] = arr[j];
temp = (int*)realloc(temp, sizeof(int));
printf("%d ", arr[j]);
}
}
printf("}");
printf("\n");
}
}
break;
}
}
free(temp);
}
}
void main() {
int *arr, n, i;
printf("\n Enter the number of elements in the set \n");
scanf("%d", &n);
arr = (int*)malloc(sizeof(int) * n);
printf("\n Enter the set elements \n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
partition(arr, n);
}
It works perfectly for the input {1,2,3}. For {1,2,3,4}, it gives the correct output as well.
For {1,2,3,4}, the output is:
Printing solution for sum 3{1 2 }
{3 }
Printing solution for sum 4{1 3 }
{4 }
Printing solution for sum 5{2 3 }
{1 4 }
Printing solution for sum 6{1 2 3 }
{}
Printing solution for sum 7{}
{}
But if the input is {1,5,11,5}, the output is:
Printing solution for sum 5{5 }
{}
Printing solution for sum 6{}
{}
Printing solution for sum 11{}
{}
Printing solution for sum 16{}
{}
Printing solution for sum 17{}
{}
Since {1,5,5} and {11} is a solution, in this case, the expected output should be Printing Solution for sum 11 {1,5,5} and {11} but it's not displaying that.
What is the problem and how can I fix it?
Your algorithm is too complicated. You start on the correct path, computing the sum of all subsets of the set, but you do not correctly compute all possible disjoint subsets to try and find one with the same sum.
Here is a simpler approach:
enumerate all subsets
for each subset, compute the sum and store a structure with the subset signature and its sum into an array.
sort the array by the value of the sum
iterate over the sorted array:
for each element, iterate over the subsequent elements with the same sum, if one of them has a disjoint subset signature, you have a match, print it.
the space complexity is O(2N) and the time complexity is even worse at O(2N+1), which is very bad, but manageable for small sets.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
struct s { int sig, sum; };
int compare(const void *p1, const void *p2) {
int sum1 = ((const struct s*)p1)->sum;
int sum2 = ((const struct s*)p2)->sum;
return (sum1 > sum2) - (sum1 < sum2);
}
void print_set(int arr[], size_t sig) {
printf("{");
while (sig) {
if (sig & 1)
printf(" %d", *arr);
arr++;
sig >>= 1;
}
printf(" } ");
}
void partition(int arr[], int n) {
size_t i, j, count = 1ULL << n;
struct s *array = calloc(sizeof(*array), count);
int b, sum;
if (array != NULL) {
for (i = 1; i < count; i++) {
sum = 0;
for (b = 0; b < n; b++) {
if (i & (1ULL << b))
sum += arr[b];
}
array[i].sig = i;
array[i].sum = sum;
}
qsort(array, count, sizeof(*array), compare);
for (i = 0; i < count; i++) {
for (j = i + 1; j < count && array[i].sum == array[j].sum; j++) {
if ((array[i].sig & array[j].sig) == 0) {
printf("solution with sum=%d: ", array[i].sum);
print_set(arr, array[i].sig);
print_set(arr, array[j].sig);
printf("\n");
}
}
}
free(array);
}
}
int main() {
int *arr, n, i;
printf("Enter the number of elements in the set: ");
if (scanf("%d", &n) == 1) {
arr = (int*)malloc(sizeof(int) * n);
if (arr != NULL) {
printf("Enter the set elements: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &arr[i]) != 1)
return 1;
}
partition(arr, n);
free(arr);
}
}
return 0;
}
Output:
Enter the number of elements in the set: 3
Enter the set elements: 1 2 3
solution with sum=3: { 3 } { 1 2 }
Enter the number of elements in the set: 4
Enter the set elements: 1 2 3 4
solution with sum=3: { 1 2 } { 3 }
solution with sum=4: { 4 } { 1 3 }
solution with sum=5: { 2 3 } { 1 4 }
Enter the number of elements in the set: 4
Enter the set elements: 1 5 11 5
solution with sum=5: { 5 } { 5 }
solution with sum=11: { 11 } { 1 5 5 }
You may find the following to be a place to start. What this sample program does is to take a set of values and then generate as possible disjoint subsets where the sum of the elements of each subset are equal between the two subsets.
I am not sure if this actually answers your question. The requirements specified are quite loose. The source you provide does not compile with Visual Studio and when a few basic compile errors were corrected the resulting program crashed. I also find your example output confusing.
The criteria for disjoint subsets as created by this program are:
values in one subset can not appear in the other
membership is ordered and tracked via an index assigned to each element of the superset
a subset may have duplicate values but not duplicate indexed elements
the empty set is not considered to be a valid disjoint subset since it has no elements
there must be at least two subsets that can be formed from the set
only two subsets are considered and there may be more (e.g. {1, 2, 3, 4, 5} could have {2,3}, {1,4}, {5}).
The source code follows. This is from a single C source code file that is part of a Visual Studio C++ solution with the C++ main() calling the C source code entry point of mymain2(). I did it that way because it was easier for me.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
int *pSet; // array of values. array is malloced when max number is known.
int nSetMax; // max number of array elements, amount malloced.
int nSetCur; // current number of in use array elements.
} SetType;
static void generateSet (int i, int arr[], int n, SetType *temp)
{
int j;
temp->nSetCur = 0;
for (j = 0; j < n; j++)
{
if ( i & (1 << j))
{
int te;
int flag = 0;
for (te = 0; te < temp->nSetCur; te++)
{
// we compute disjoint property by the order of the elements in
// the set using element index in order to allow duplicate values per
// request of the question. Exampe 1, 5, 11, 5 as list of values.
if (temp->pSet[te] == j)
flag = 1;
}
if (flag == 1)
continue;
temp->pSet[temp->nSetCur] = j;
temp->nSetCur++;
}
}
}
static void printItems (int arr[], const SetType temp)
{
if (temp.nSetCur > 0) {
int j;
int sum = 0;
printf(" {");
for (j = 0; j < temp.nSetCur; j++) {
printf("%2d ", arr[temp.pSet[j]]);
sum += arr[temp.pSet[j]];
}
printf("} = %3d\n", sum);
} else
printf (" {}\n");
}
// determine if the two sets are disjoint by comparing the element indexes
// of the elements in each subset. the element index is the position of the
// subset element in the set from which the subset was drawn.
static int checkSetsByIndex (const SetType tempI, const SetType tempR)
{
int i;
for (i = 0; i < tempI.nSetCur; i++) {
int j;
for (j = 0; j < tempR.nSetCur; j++) {
if (tempI.pSet[i] == tempR.pSet[j])
return 0;
}
}
return 1;
}
// determine if the two sets are disjoint by comparing the element values
// of the elements in each subset. the element value is the value of the
// subset element in the set from which the subset was drawn.
// we may have duplicate values but as long as they are not in two different
// subsets then we allow it.
static int checkSetsByValue (int arr[], const SetType tempI, const SetType tempR)
{
int i;
#if 1
// following code does a check that the two sets are disjoint by value
// meaning they do not share any values. however a set may have multiple
// elements with the same value.
// if not needed then you can turn it off with Preprocessor check.
for (i = 0; i < tempI.nSetCur; i++) {
int j;
for (j = 0; j < tempR.nSetCur; j++) {
if (arr[tempI.pSet[i]] == arr[tempR.pSet[j]])
return 0;
}
}
#endif
return 1;
}
static void partition(int arr[], int n)
{
int i;
int iPow2n = pow(2, n);
int *sum = calloc(iPow2n, sizeof(int));
printf ("Generate and list sums\n");
for(i = 0; i < iPow2n; i++)
{
int j;
printf(" {");
for (j = 0; j < n; j++)
{
if (i & (1 << j))
{
printf("%2d ", arr[j]);
sum[i] = sum[i] + arr[j];
}
}
printf("} = %3d\n", sum[i]);
}
printf("\n\nGenerate list of disjoint sets for each sum.\n");
for (i = 0; i < iPow2n - 1; i++)
{
int r;
SetType tempI = {calloc(iPow2n, sizeof(SetType)), iPow2n, 0};
SetType tempR = {calloc(iPow2n, sizeof(SetType)), iPow2n, 0};
for(r = i + 1; r < iPow2n; r++)
{
if(sum[i] == sum[r])
{
generateSet (i, arr, n, &tempI);
generateSet (r, arr, n, &tempR);
// check disjoint subsets by looking at the index of the
// subset elements where the index is the index of the original
// set from which the subset is drawn.
if (checkSetsByIndex (tempI, tempR)) {
// check that the two subsets are disjoint by element values
// as well. this means that while a subset may have duplicate
// values, the elements of each subset must be disjoint can not
// have elements whose values are the same.
// so if we have a set {1, 5, 11, 5} then subsets of
// {5}, {5} is invalid but {1, 5, 5}, {11} is valid.
if (checkSetsByValue (arr, tempI, tempR)) {
printf("\n Printing solution for sum %d\n", sum[i]);
printItems (arr, tempI);
printItems (arr, tempR);
break;
}
}
}
}
free(tempI.pSet);
free(tempR.pSet);
}
}
int mymain2(void)
{
int n;
printf("\n Enter the number of elements in the set \n");
scanf("%d",&n);
if (n > 0) {
int i;
int *arr = malloc(sizeof(int) * n);
printf("\n Enter the set elements \n");
for (i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
partition(arr,n);
free (arr);
}
return 0;
}
For a set of 4 values whose elements are {1, 2, 3, 4} it generates the following output:
Enter the number of elements in the set
4
Enter the set elements
1 2 3 4
Generate and list sums
{} = 0
{ 1 } = 1
{ 2 } = 2
{ 1 2 } = 3
{ 3 } = 3
{ 1 3 } = 4
{ 2 3 } = 5
{ 1 2 3 } = 6
{ 4 } = 4
{ 1 4 } = 5
{ 2 4 } = 6
{ 1 2 4 } = 7
{ 3 4 } = 7
{ 1 3 4 } = 8
{ 2 3 4 } = 9
{ 1 2 3 4 } = 10
Generate list of disjoint sets for each sum.
Printing solution for sum 3
{ 1 2 } = 3
{ 3 } = 3
Printing solution for sum 4
{ 1 3 } = 4
{ 4 } = 4
Printing solution for sum 5
{ 2 3 } = 5
{ 1 4 } = 5
For a set of 4 values {1, 5, 11, 5} it generates the following output:
Enter the number of elements in the set
4
Enter the set elements
1 5 11 5
Generate and list sums
{} = 0
{ 1 } = 1
{ 5 } = 5
{ 1 5 } = 6
{11 } = 11
{ 1 11 } = 12
{ 5 11 } = 16
{ 1 5 11 } = 17
{ 5 } = 5
{ 1 5 } = 6
{ 5 5 } = 10
{ 1 5 5 } = 11
{11 5 } = 16
{ 1 11 5 } = 17
{ 5 11 5 } = 21
{ 1 5 11 5 } = 22
Generate list of disjoint sets for each sum.
Printing solution for sum 11
{11 } = 11
{ 1 5 5 } = 11
For a set of 5 values {1, 2, 3, 4, 5} it generates the following output:
Enter the number of elements in the set
5
Enter the set elements
1 2 3 4 5
Generate and list sums
{} = 0
{ 1 } = 1
{ 2 } = 2
{ 1 2 } = 3
{ 3 } = 3
{ 1 3 } = 4
{ 2 3 } = 5
{ 1 2 3 } = 6
{ 4 } = 4
{ 1 4 } = 5
{ 2 4 } = 6
{ 1 2 4 } = 7
{ 3 4 } = 7
{ 1 3 4 } = 8
{ 2 3 4 } = 9
{ 1 2 3 4 } = 10
{ 5 } = 5
{ 1 5 } = 6
{ 2 5 } = 7
{ 1 2 5 } = 8
{ 3 5 } = 8
{ 1 3 5 } = 9
{ 2 3 5 } = 10
{ 1 2 3 5 } = 11
{ 4 5 } = 9
{ 1 4 5 } = 10
{ 2 4 5 } = 11
{ 1 2 4 5 } = 12
{ 3 4 5 } = 12
{ 1 3 4 5 } = 13
{ 2 3 4 5 } = 14
{ 1 2 3 4 5 } = 15
Generate list of disjoint sets for each sum.
Printing solution for sum 3
{ 1 2 } = 3
{ 3 } = 3
Printing solution for sum 4
{ 1 3 } = 4
{ 4 } = 4
Printing solution for sum 5
{ 2 3 } = 5
{ 1 4 } = 5
Printing solution for sum 5
{ 1 4 } = 5
{ 5 } = 5
Printing solution for sum 6
{ 2 4 } = 6
{ 1 5 } = 6
Printing solution for sum 7
{ 3 4 } = 7
{ 2 5 } = 7

Pattern Printing in C for printing numbers in vertical pattern

I wrote a function to print the below pattern.
For example, if the n value is 4 the pattern is
1
2 7
3 6 8
4 5 9 10
Or if the value of n is 5, then the pattern is
1
2 9
3 8 10
4 7 11 14
5 6 12 13 15
My function gives me the first two block but not the next block. I'm stuck here for long time!
My function is
int printPattern(int n) {
int row, column, fwdCtr = 1, evenCtr = 0, ctr = n;
for(row = 1; row <= n; row++) {
fwdCtr = row;
for(column = 1; column <= row; column++) {
if(column % 2 != 0) {
printf("%d ", fwdCtr++);
} else {
evenCtr = fwdCtr + ctr;
printf("%d ", evenCtr);
ctr = ctr - 2;
}
}
printf("\n");
}
}
What I get is
1
2 7
3 6 4
4 5 5 4
Please give suggestions of changes!
The following code should do it:
#include <stdio.h>
void f(int n)
{
for (int i = 0; i < n; ++i)
{
for (int j=0; j<=i; ++j)
{
// Calculate the numbers used so far by previous columns
int x = 0;
for(int v=0; v<j;++v)
{
x = x + (n-v);
}
if ((j % 2) == 0)
{
// even columns
printf("%d ", x+i-j+1);
}
else
{
// odd columns
printf("%d ", x+n-i);
}
}
printf("\n");
}
}
int main(void)
{
f(5);
return 0;
}
Output:
1
2 9
3 8 10
4 7 11 14
5 6 12 13 15
The easy thing to do is just print the right number based on the row and column and the value of n, like this
int main(void)
{
int n = 20;
for (int row = 0; row < n; row++) {
for (int col = 0; col <= row; col++)
printf("%3d ", 1 + col*n - (col-1)*col/2 + (col%2 ? n-1-row : row-col));
printf("\n");
}
}

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

Print a pattern in C

I wish to print a pattern in C language like this:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
Currently I have this:
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i>=j)
{
printf(" %d ",j+i-1);
}
}
printf("\n");
}
printf("\n");
}
I am not getting the desired result.Please can anybody help
Basically if you analyze the difference between numbers at each row:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
^ ^ ^ ^
diff 4 3 2 1
Then for each column (except the first one which is equal to the row) the formula is:
col_value = val(row, col-1) + (5-col))
For example, the last row:
5 9 12 14 15
9 = 5 + (5-1)
12 = 9 + (5-2)
14 = 12 + (5-3)
15 = 14 + (5-4)
Code:
#include<stdio.h>
int main()
{
int i,j,k;
for(i=1;i<=5;i++)
{
k = i;
for(j=1;j<=i;j++)
{
printf("%d ", k);
k += 5-j;
}
printf("\n");
}
return 0;
}
Check this :
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
int temp = 4;
int sum = 0;
for(j=1;j<=i;j++)
{
if (j == 1)
sum = i;
else{
sum = sum + temp --;
}
printf("%d ",sum);
}
printf("\n");
}
}
int main () {
int k,i, j;
for (i = 1; i <=5; i++) {
k = i;
for (j = 1; j <= i; j++) {
printf ("%d ", k);
k = k + (5-j);
}
printf ("\n");
}
}
The logic is quite straight forward.
1) The number of elements in a row equals the row number. Hence use the inner loop with j = 1 to j <= i
2) If you see the pattern you observe that every row starts with the number equals to the row index, the next number is +4 and then +3 and so on.
3) Hence use k = k + (5-j)
int main()
{
int i,j,temp=0,l;
for(i=1;i<=5;i++)
{
l=4;
temp = i;
for(j=1;j<=i;j++)
{
if(j>1)
{
printf("%d\t",temp+l);
temp = temp+l;
l=l-1;
}
else
printf("%d\t",i);
}
printf("\n");
}
getch();
return 0;
}

Resources