hi I am trying to print a 4 x 4 matrix in clockwise direction,
Input:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Expected output is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
My code is:
int MAXR=3,MAXC=3,MINR=0,MINC=0;
while(MINR < MAXR && MINC < MAXC)
{
for(i=MINC;i<=MAXC;i++)
{
printf("%d ",arr[MINR][i]);
}
for(j=MINR+1;j<=MAXR;j++)
{
printf("%d ",arr[j][MAXC]);
}
for(i=MAXC-1;i>=MINC;i--)
{
printf("%d ",arr[MAXR][i]);
}
MINR++;
if((MINR%2)==0)
{
MINC=MINC+2;
}
//MAXR--;
//MAXC--;
//printf("\nMAXR=%d MINR=%d\n",MAXR,MINR);
for(j=MAXR-1;j>MINR;j--)
{
printf("%d ",arr[j][MINC]);
}
MAXR--;
MAXC--;
}
But output is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 11
Please help me to fix the bug!
Thanks!
output is:
I hope you have fixed your defect by now. But it was a fun spec, so here is my version:
gcc (GCC) 4.7.3: gcc -Wall -Wextra -std=c99 spiral.c
#include <stdio.h>
int main() {
int matrix[4][4] = {
{ 1, 2, 3, 4 },
{ 12, 13, 14, 5 },
{ 11, 16, 15, 6 },
{ 10, 9, 8, 7 } };
int edge = sizeof(matrix[0]) / sizeof(int) - 1;
int i = 0;
int j = 0;
printf("%d ", matrix[i][j]);
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[i][++j]); }
while (0 < edge) {
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[++i][j]); }
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[i][--j]); }
--edge;
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[--i][j]); }
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[i][++j]); }
--edge;
}
return 0;
}
My approach was to write out the sequence of required changes to i and j and find the pattern. What I found was that the pattern appeared after the first line, so I did that as a separate initial step.
The following code will help you to print of a matrix of any size (rows/cols) clockwisely.
void printMatrixClockwisely(int** numbers, int rows, int columns)
{
if(numbers == NULL || columns <= 0 || rows <= 0)
return;
int start = 0;
while(columns > start * 2 && rows > start * 2)
{
PrintMatrixInCircle(numbers, columns, rows, start);
++start;
}
}
void printNumber(int number)
{
printf("%d\t", number);
}
void PrintMatrixInCircle(int** numbers, int columns, int rows, int start)
{
int endX = columns - 1 - start;
int endY = rows - 1 - start;
// print a row from left to right
for(int i = start; i <= endX; ++i)
{
int number = numbers[start][i];
printNumber(number);
}
// print a col from up to down
if(start < endY)
{
for(int i = start + 1; i <= endY; ++i)
{
int number = numbers[i][endX];
printNumber(number);
}
}
// print a row from right to left
if(start < endX && start < endY)
{
for(int i = endX - 1; i >= start; --i)
{
int number = numbers[endY][i];
printNumber(number);
}
}
// print a col from down to up
if(start < endX && start < endY - 1)
{
for(int i = endY - 1; i >= start + 1; --i)
{
int number = numbers[i][start];
printNumber(number);
}
}
}
Related
I have a problem in my C program. I need to write a histogram of numbers. If the number on the input will be outside the interval [1, 9], consider such a number as the value 1. I don't understand why it doesn't work.
#include <stdio.h>
#include <stdlib.h>
void printHistogram_vertical(int *hist, int n);
int main()
{
int i, j;
int inputValue;
scanf("%d", &inputValue);
int hist[inputValue];
for (i = 0; i < inputValue; ++i)
{
scanf("%d", &hist[i]);
}
int results[10] = {0};
for (i = 0; i < 10; ++i)
{
for (j = 0; j < inputValue; ++j)
{
if (hist[j] >= 10 && hist[j] < 1)
{
results[j] == 1;
}
if (hist[j] == i)
{
results[i]++;
}
}
}
return 0;
}
void printHistogram_vertical(int *hist, int n)
{
int i, j;
for (i = 1; i < n; i++)
{
printf(" %d ", i);
for (j = 0; j < hist[i]; ++j)
{
printf("#");
}
printf("\n");
}
}
Input:
9
3 3 2 3 7 1 1 4 10
My Output:
1 ##
2 #
3 ###
4 #
5
6
7 #
8
9
The correct output:
1 ###
2 #
3 ###
4 #
5
6
7 #
8
9
If the number is bigger than 10 and smaller than 1 it should count this number as 1. I write this function:
for (i = 0; i < 10; ++i)
{
for (j = 0; j < inputValue; ++j)
{
if (hist[j] >= 10 && hist[j] < 1)
{
results[j] == 1;
}
if (hist[j] == i)
{
results[i]++;
}
}
}
There are 2 problems with following condition:
if (hist[j] >= 10 && hist[j] < 1)
{
results[j] == 1;
}
The comparison is broken. Value cannot be above 9 AND below 1 at the same time. It should be OR instead.
What should be increment of index 1, is actually comparison == of wrong index.
Replacement:
if (hist[j] >= 10 || hist[j] < 1)
{
results[1]++;
}
But double for loop construction is more complicated than it needs to be. It could be replaced with single for loop:
for (j = 0; j < inputValue; ++j) {
int value = hist[j];
if(value >= 1 && value <= 9) {
results[value]++;
}
else {
results[1]++;
}
}
I have to make a Floyd Triangle that prints in this order:
7 8 9 10
4 5 6
2 3
1
But currently my code print like this:
1
2 3
4 5 6
7 8 9 10
CODE:
#include <stdio.h>
int main()
{
int n, i, c, a = 1;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (c = 1; c <= i; c++)
{
printf("%d ", a);
a++;
}
printf("\n");
}
return 0;
}
Can someone help me?
Here you are.
#include <stdio.h>
int main(void)
{
while ( 1 )
{
printf( "Enter a non-negative number (0 - exit): " );
unsigned int n;
if ( scanf( "%u", &n ) != 1 || n == 0 ) break;
int width = 0;
for ( unsigned int tmp = n * ( n + 1 ) / 2; tmp != 0; tmp /= 10 )
{
++width;
}
putchar( '\n' );
for ( unsigned int i = 0; i < n; i++ )
{
unsigned int value = ( n - i ) * ( n - i + 1 ) / 2 - ( n - i - 1 );
for ( unsigned int j = 0; j < n - i; j++ )
{
printf( "%*u ", -width, value++ );
}
putchar( '\n' );
}
putchar( '\n' );
}
return 0;
}
The program output might look like
Enter a non-negative number (0 - exit): 10
46 47 48 49 50 51 52 53 54 55
37 38 39 40 41 42 43 44 45
29 30 31 32 33 34 35 36
22 23 24 25 26 27 28
16 17 18 19 20 21
11 12 13 14 15
7 8 9 10
4 5 6
2 3
1
Enter a non-negative number (0 - exit): 4
7 8 9 10
4 5 6
2 3
1
Enter a non-negative number (0 - exit): 0
I solved it by hacking (i.e. trying different things and adjusting the code based on the output):
I started by moving the generation code to a separate function. I then cut and pasted the function, giving it a different name. I then started modifying the for loops.
I went through four versions until I hit the correct one:
#include <stdio.h>
#include <stdlib.h>
void
fwd(int n)
{
int i, c;
int a = 1;
for (i = 1; i <= n; i++) {
for (c = 1; c <= i; c++) {
printf("%d ", a);
a++;
}
printf("\n");
}
}
void
rev1(int n)
{
int i, c;
int a = 1;
for (i = n; i >= 1; i--) {
for (c = 1; c <= i; c++) {
printf("%d ", a);
a++;
}
printf("\n");
}
}
void
rev2(int n)
{
int i, c;
int a = 0;
for (i = 1; i <= n; i++)
a += i;
for (i = n; i >= 1; i--) {
for (c = i; c >= 1; c--) {
printf("%d ", a);
a--;
}
printf("\n");
}
}
void
rev3(int n)
{
int i, c;
int a = 0;
for (i = 1; i <= n; i++)
a += i;
for (i = n; i >= 1; i--) {
for (c = i; c >= 1; c--) {
printf("%d ", (c - i) + a);
a--;
}
printf("\n");
}
}
void
rev4(int n)
{
int i, c;
int a = 0;
for (i = 1; i <= n; i++)
a += i;
for (i = n; i >= 1; i--) {
for (c = 1; c <= i; c++) {
printf("%d ", (c - i) + a);
}
a -= i;
printf("\n");
}
}
int
main(int argc,char **argv)
{
int n;
--argc;
++argv;
if (argc > 0)
n = atoi(*argv);
else
scanf("%d", &n);
printf("fwd:\n");
fwd(n);
printf("\nrev1:\n");
rev1(n);
printf("\nrev2:\n");
rev2(n);
printf("\nrev3:\n");
rev3(n);
printf("\nrev4:\n");
rev4(n);
return 0;
}
Here's the program output:
fwd:
1
2 3
4 5 6
7 8 9 10
rev1:
1 2 3 4
5 6 7
8 9
10
rev2:
10 9 8 7
6 5 4
3 2
1
rev3:
10 8 6 4
6 4 2
3 1
1
rev4:
7 8 9 10
4 5 6
2 3
1
The other answers are great, but no one posted a recursive function so I thought I'd add one.
#include <stdio.h>
void recursive(int n, int i);
void straight(int n);
// one way of doing it with a recursive function
void recursive(int n, int i) {
if(n <= 0)
return;
if(i <= n) {
printf( "%-3d", (((n * (n + 1) / 2) - n) + i) );
recursive(n, i + 1);
} else {
printf("\n");
recursive(n - 1, 1);
}
}
// straightforward nested loop way
void straight(int n) {
int i, j, row_sum;
for(i = n; i > 0; --i) {
// the sum: i + (i-1) + (i-2) + ... + 2 + 1 = (i * (i+1)) / 2
row_sum = (i * (i + 1)) / 2;
for(j = i; j > 0; --j) {
printf("%-3d", row_sum - j + 1);
}
printf("\n");
}
}
// entry point
int main(int argc, char **argv) {
int n = 0;
scanf("%d", &n);
printf("Recursive Output for n=%d\n", n);
recursive(n, 1);
printf("\nStraight Output for n=%d\n", n);
straight(n);
return 0;
}
Output:
Recursive Output for n=5
11 12 13 14 15
7 8 9 10
4 5 6
2 3
1
Straight Output for n=5
11 12 13 14 15
7 8 9 10
4 5 6
2 3
1
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");
}
}
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
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;
}