How can i print the pattern given below (rhombus shape) in C? - c

Expected output:
I have already printed the rhombus shape but I cant get it to print this number pattern (1 232 34543...)
Here is my code.
If anyone can help me I would appreciate it very much.
Thanks in advance.
int main()
{
int i, j, rows;
int stars, spaces;
printf("Enter rows to print : ");
scanf("%d", &rows);
int a;
stars = 1;
spaces = rows - 1;
/* Iterate through rows */
for(i=1; i<rows*2; i++)
{
/* Print spaces */
for(j=1; j<=spaces; j++)
printf(" ");
/* Print stars */
for(j=1; j<stars*2; j++){
printf("*");
}
/* Move to next line */
printf("\n");
if(i<rows)
{
spaces--;
stars++;
}
else
{
spaces++;
stars--;
}
}
getch();
return 0;
}

I did not put my answer to let you figure it out, but since there is already one I show how I did it too. It seems to work. (Only the changed part).
for(j=1; j<stars*2; j++){
if (j < stars)
if (i < rows) // upper left triangle
printf("%c", '0' + ((j + i - 1) % 10));
else // lower left triangle
printf("%c", '0' + ((j + rows * 2 - i - 1) % 10));
else
if (i < rows) // upper right triangle
printf("%c", '0' + (2 * stars - j + i - 1) % 10);
else // lower right triangle
printf("%c", '0' + (2 * stars - j + rows * 2 - i - 1) % 10);
}
Making a bit more compact and getting rid of the "character mentallity" in the printf.
for(char c, j = 1; j < stars * 2; j++) {
if (j < stars)
c = i < rows ? (j + i - 1) : (j + rows * 2 - i - 1);
else
c = i < rows ? (2 * stars - j + i - 1) : (2 * stars - j + rows * 2 - i - 1);
printf("%d", c % 10);
}

Actually there are only two parts that need to be changed. (Since other people have posted answers)
Note: the following solution requires some knowledge on the absolute value function.
First, before the forloop, you declare another variable which stores the value of rows
int totalRows = rows;
then, inside the forloop, change your printf("*"); to the following:
printf("%d",(stars - abs(j-stars) -1 + totalRows - abs(totalRows - i)) %10);
Let me break it down into two sections: row wise and column wise.
Row wise:
When we look at each row, we can see that the number is increasing starting at index 0 until it reaches the center (at index stars), then it starts to decrease. This is the shape of an inverted absolute value function shifted upward. The -1 is to account for starting at index 0 instead of index 1.
stars - abs(j-stars) -1
prints a shape of
This accounts for the increments and decrements in the rows
Column wise:
When we look at each column, we see a similar pattern: the number increases starting at index 1 until center, then it starts to decrease. Another shape of inverted absolute function shifted upward.
row - abs(row - i)
This accounts for the increments and decrements in the columns
When you combine the two together, and take mod 10 (which only keeps the last digit). You get the desired output
printf("%d",(stars - abs(j-stars) -1 + totalRows - abs(totalRows - i)) %10);
//totalRows has the initial value of rows

I found one solution to your problem as below...
#include <stdio.h>
int main()
{
int i, j, k, x, rows, half_row=1;
int stars, spaces;
printf("Enter rows to print : ");
scanf("%d", &rows);
int a;
stars = 1;
spaces = rows - 1;
/* Iterate through rows */
for(i=1; i<rows*2; i++)
{
/* Print spaces */
for(j=1; j<=spaces; j++)
printf(" ");
/* Print numbers */
if(rows >= i){ /* Print First Half */
x = i;
for(k=0;k<i;k++){
if(x>=10){
x=x%10;
}
printf("%d", x);
x++;
}
x--;
for(k=1;k<i;k++){
x--;
printf("%d", x);
if(x==0){
x=10;
}
}
}
else{ /* Print Second Half */
x--;
for(k=1;k<=i-(2*half_row);k++){
if(x==10){
x=0;
}
printf("%d", x);
x++;
}
x--;
for(k=1;k<=i-(2*half_row)-1;k++){
x--;
printf("%d", x);
if(x==0){
x=10;
}
}
half_row++;
}
/* Move to next line */
printf("\n");
if(i<rows)
{
spaces--;
stars++;
}
else
{
spaces++;
stars--;
}
}
getch();
return 0;
}

Related

How do I print a cross to the console in C?

I've just started studying information technologies and I am currently stuck on a programming assignment.
I have to write a code in C which displays a cross to the console, the size of the cross being determined by an initial input.
So the console output should look like this:
size?: 5(user input)
xooox
oxoxo
ooxoo
oxoxo
xooox
(replace the os with blank space)
I've now come as far as this:
#include <stdio.h>
int main(void)
{
int n;
printf("size?: ");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if( (i==j) )
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
But this only displays one diagonal of the cross, I'm thinking that the opposite diagonal can be created by another condition after the if however I am lost as to what that condition might be.
You're definitely on the right track! Don't give up.
The way to think about this is to think about the loop counters. You've figured out one half of it. If the row and column are the same, you need to output a *. So what's the other condition? Well, think about counting backwards. If the row is the same as the column counted backwards, we also want a *.
I don't want to do your homework for you, so I'll hold off on writing the code, but hopefully that gives you a hint as to what you need to do.
Replace if( (i==j) ) with if( (i==j)||(i+j)==n+1 ), That is,:
#include <stdio.h>
int main(void)
{
int n;
printf("size?: ");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if( (i==j)||(i+j)==n+1 )
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
Should you need some help, you have to check the column from the other side as well:
#include <stdio.h>
int n;
int main(void) {
printf("size?: ");
scanf("%d",&n);
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if (i == j || i == n - j + 1) printf("*");
else printf(" ");
}
printf("\n");
}
return 0;
}
Edit: There are suggestions to do i + j == n + 1, but I believe i == n - j + 1 makes more sense, since:
i is your current row
j is your current column
n is the size of your square (max row / max column)
i == n - j + 1 means draw * at max - current + 1 column
First thing's first, C compilers don't like
for (int i = 0; i < n; i++)
They like
int i = 0;
for (i = 0; i < n; i++)
But if you're using a C++ compiler, you probably won't get that problem.
Now; back to solving the problem at hand!
On the line:
if( (i==j) )
With this conditional, you're plotting points at (1, 1), (2, 2), (3, 3) ...
You want to also plot points at (1, n), (2, n - 1), (3, n - 2) ...
So you need to add a second conditional to this if statement:
if ( (i==j) || (i == (n - j) + 1 ) )
Then you can simplify this up a bit if you want...
if ( (i==j) || (i == n - j + 1 ) )
And there you go! It now prints a cross, like you described in your question.

Printing a Diamond of Numbers in C

int print_pattern(){
int x;
int y;
int i;
//for loop for the bottom and the top, 0 is the top and 1 is the bottom while it stops at anything above 2.
for (i = 0; i<2;i++){
//loop to the current number
for (x=1;x<=input;x+=2){
// top or bottom, this is the top because i had made the top of the diamond the 0
// therefore this makes my diamond print the top of the function.
if ( i == 0){
//starts for the top of the diamond. and counts the spaces.
for (y=1; y<=input-x; y++){
printf(" ");
}
//starts the printing of the diamond.
for (y=1; y<2*x;y++){
printf("%d ", y);
}
}
//bottom of the diamond, which is from the 1. For this spot it take in the one from the for loop to
// this if statement.
if (i==1){
//counting spaces again
for(y = 1; y<=x; y++){
printf(" ");
}
//printing again but this is the bottom of the pyramid. #really need to comment more
for(y = 1; y<(input-x)*2;y++){
printf("%d ", y);
}
}
//next line starts when printing out the numbers in the output.
printf("\n");
}
}
}
The output is supposed to look like a diamond of the numbers ending with the odd numberat each row. but it is going +2 number past the input and then also not printing the last line. Which should have a single one.
1 1
1 2 3 1 2 3 4 5
1 2 3 4 5 1 2 3 4 5 6 7 8 9
1 2 3 1 2 3 4 5 6 7
1 1 2 3
The left is what is expected and the right is what I currently am getting when inputting 5.
Because you already increment x by 2 in the upper part, you don't need to let the print loop run to y<2*x. It should probably just run to x.
The print loop in the lower part suffers from the fact that y<(input-x)*2 should probably be y<input-x*2 (you want to print 2 less each time).
Generally I'd try to name variables in a more speaking way, like printStartPosition, maxNumToPrint, stuff like that. That makes it easier by a surprising margin to understand a program.
As an enhancement, the two code blocks depending on the i value inside the x loop are structurally very similar. One could try to exploit that and collapse both of them into a function which gets a boolean parameter like "ascending", which increments y when true and decrements it when false. Whether that improves or hinders readability would have to be seen.
Also, keep your variables local if possible.
Peter Schneider has already raised some valid points in his answer.
Think about what you have to do when you print a diamond of height 5:
print 1 centered;
print 1 2 3 centered;
print 1 2 3 4 5 centered;
print 1 2 3 centered;
print 1 centered.
Sou you could write a function that prints the numbers from 1 to n centered in a line and call it with n = 1, 3, 5, 3, 1. This can be achieved with two independent loops, one incrementing n by 2, the other decrementing it.
Another approach is to recurse: print the lines as you go deeper, incrementing n by 2 until you reach the target width, at which point you don't recurse, but return and print lines with the same parameters again as you go up. This will print each line twice except the middle one.
Here's a recursive solution:
#include <stdlib.h>
#include <stdio.h>
void print_line(int i, int n)
{
int j;
for (j = i; j < n; j++) putchar(' ');
for (j = 0; j < i; j++) printf("%d ", (j + 1) % 10);
putchar('\n');
}
void print_pattern_r(int i, int n)
{
print_line(i, n); // print top as you go deeper
if (i < n) {
print_pattern_r(i + 2, n); // go deeper
print_line(i, n); // print bottom as you return
}
}
void print_pattern(int n)
{
if (n % 2 == 0) n++; // enforce odd number
print_pattern_r(1, n); // call recursive corefunction
}
int main(int argc, char **argv)
{
int n = 0;
if (argc > 1) n = atoi(argv[1]); // read height from args, if any
if (n <= 0) n = 5; // default: 5
print_pattern(n);
return 0;
}
A JAVA STAR PATTERN PROGRAM FOR DIAMOND SHAPE converted to C Program. Code comment will explain the changes and flow.
#include <stdio.h>
#include <string.h>
void myprintf(const char* a) {
static int iCount = 0;
if (strcmp(a, "\n") == 0) {
iCount = 0; //if it is new line than reset the iCount
printf("\n"); //And print new line
} else
printf(" %d", ++iCount); //Print the value
}
void main() {
int i, j, m;
int num = 5; //Enter odd number
for (i = 1; i <= num; i += 2) { //+=2 to skip even row generation
for (j = num; j >= i; j--)
printf(" ");
for (m = 1; m <= i; m++)
myprintf(" *"); //display of star converted to number
myprintf("\n");
}
num -= 2; //Skip to generate the middle row twice
for (i = 1; i <= num; i += 2) { //+=2 to skip even row generation
printf(" ");
for (j = 1; j <= i; j++)
printf(" ");
for (m = num; m >= i; m--)
myprintf(" *"); //display of star converted to number
myprintf("\n");
}
}
Output:
1
1 2 3
1 2 3 4 5
1 2 3
1
Here's the short code for such a diamond.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int w = 9;
int l;
for(l=0; l < w; ++l)
{
printf("%*.*s\n", abs(w/2 - l)+abs((2*l+1)-(2*l+1>w)*2*w), abs((2*l+1)-(2*l+1>w)*2*w), "123456789");
}
return 0;
}

(C Program) User made magic square fails on 11x11 array but works on every size up to 11x11?

Alright so I thought my code was working and it seems to do so, it allows the user to choose the size of a magic square where the number one is the start point and starts in the center of the first row. The pattern goes along this line....go up one and over one, if you go up above the first row.....move back to the last row or if you run off the end of the right side of the column than go back to the start of the column...in a magic square if your not familiar with it, all sides are equal when the numbers on that side or diagonal are counted.
An odd number must be entered for this to be written out as a magic square (example: 3x3, 5x5, 7x7, etc..) the problem is it works until I enter 11x11....when done, it comes back around and when the program runs into a slot that has already been filled it is supposed to enter the next number below the last one that was entered into the array...but when 11x11 is entered it overwrites the 1 with a 13 which breaks the cycle and ruins the pattern....I would appreciate it if someone helped me with this, I think maybe the problem has to do with the equation I use to choose the starting point. This works all the way up to 11x11, every odd number entered after that seems to overwrite the starting point.
// Chapter 8 Programming Project #17
#include <stdio.h>
#define N_squared (N * N)
#define MOVE (--row, ++column)
#define RW_SIZE ((int) (sizeof(magic_square) / sizeof(magic_square[0])))
void create_magic_square(int N, int magic_square[N][N], int ROW_SIZE);
void print_magic_square(int N, int magic_square[N][N], int ROW_SIZE);
int main(void)
{
int N, row, column;
printf("This program creates a magic square of a specified size\n");
printf("The size must be an odd number between 1 and 99.\n");
printf("Enter size of magic square: ");
scanf("%d", &N);
int magic_square[N][N];
for (row = 0; row < N; row++) {
for (column = 0; column < N; column++) {
magic_square[row][column] = 0;
}
}
// Create magic square
create_magic_square(N, magic_square, RW_SIZE);
// Print magic square
print_magic_square(N, magic_square, RW_SIZE);
return 0;
}
void create_magic_square(int N, int magic_square[N][N], int ROW_SIZE)
{
printf("Size of N*N = %d\nSize of ROW_SIZE = %d\n", N_squared, ROW_SIZE);
// Here I iterate through the numbers, rows, and columns
int i = 1, row = 0;
int column = (((ROW_SIZE + 1) / 2) - 1);
while (i != N_squared + 1){
// if new position is empty place next number
if (magic_square[row][column] == 0) {
magic_square[row][column] = i;
i++;
// If new position is filled then move back and down
} else if (row + 2 < ROW_SIZE &&
column - 1 >= 0) {
row += 2;
column -= 1;
} else if (row + 2 > ROW_SIZE - 1 &&
column - 1 < 0) {
row = 1;
column = ROW_SIZE - 1;
}
// If current position has been set then move
if (magic_square[row][column] != 0)
MOVE;
// If row runs off the board reset
if (row < 0)
row = ROW_SIZE - 1;
// if column runs off the board reset
if (column > ROW_SIZE - 1)
column = 0;
}
}
void print_magic_square(int N, int magic_square[N][N], int ROW_SIZE)
{
int row, column;
printf("\n");
for (row = 0; row < ROW_SIZE; row++) {
for (column = 0; column < ROW_SIZE; column++) {
if (N > 9)
printf(" %3d ", magic_square[row][column]);
else
printf(" %2d ", magic_square[row][column]);
}
printf("\n\n");
}
}

Sudoku: checking 3x3 grids for repeating values

I have worked for a sudoku puzzle in C but I'm stuck in one problem: Checking every 3x3 grid for not having duplicate values.
Here is my code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int v[10][10];
//Matrix start from 1 and end with 9
//So everywhere it should be i=1;i<=9 not from 0 to i<9 !!!
//Display function ( Display the results when it have)
void afisare()
{
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++)
printf("%2d",v[i][j]);
printf("\n");
}
printf("\n");
}
//Function to check the valability of value
int valid(int k, int ii, int jj)
{
int i;
//Check for Row/Column duplicate
for(i = 1; i <= 9; ++i) {
if (i != ii && v[i][jj] == k)
return 0;
if (i != jj && v[ii][i] == k)
return 0;
}
//Returns 0 if duplicate found return 1 if no duplicate found.
return 1;
}
void bt()
{
int i,j,k,ok=0;
//Backtracking function recursive
for(i=1;i<=9;i++){
for(j=1;j<=9;j++)
if(v[i][j]==0)
{
ok=1;
break;
}
if(ok)
break;
}
if(!ok)
{
afisare();
return;
}
for(k=1;k<=9;k++)
if(valid(k,i,j))
{
v[i][j]=k;
bt();
}
v[i][j]=0;
}
int main()
{
//Reading from the file the Matrix blank boxes with 0
int i,j;
freopen("sudoku.in","r",stdin);
for(i=1;i<=9;i++)
for(j=1;j<=9;j++)
scanf("%d",&v[i][j]);
bt();
system("pause");
return 0;
}
I know in function Valid I should have the condition to check every 3x3 grid but I don't figure it out: I found those solution to create some variables start and end
and every variable get something like this:
start = i/3*3;
finnish = j/3*3;
i and j in my case are ii and jj.
For example found something like this:
for (int row = (i / 3) * 3; row < (i / 3) * 3 + 3; row++)
for (int col = (j / 3) * 3; col < (j / 3) * 3 + 3; col++)
if (row != i && col != j && grid[row][col] == grid[i][j])
return false;
I tryed this code and it doesn't work.
I don't understand this: I have the next matrix for sudoku:
1-1 1-2 1-3 1-4 1-5 1-6
2-1 2-2 2-3 2-4 2-5 2-6
3-1 3-2 3-3 3-4 3-5 3-6
If my code put's a value on 3-2 how he check in his grid for duplicate value, that formula may work for 1-1 or 3-3 but for middle values doesn't work, understand ?
If my program get's to 2-5 matrix value It should check if this value is duplicate with 1-4 1-5 1-6 2-4 2-6 ... untill 3-6.
Since you are using index arrays starting with 1 and not zero, you have to correct for that when calculating the sub-grid indexes.
start = (i - 1) / 3 * 3 + 1;
finish = (j - 1) / 3 * 3 + 1;

Finding square made of 1's in a 2D array/matrix

Thanks for helping. I really appreciate it. I Have been searching for solution on SO, but nothing is exactly what I need. I need it in C.
My task is to find "largest square" of 1's in an array. The array consists of only 0's and 1's and looks, for example, like this:
4 4
0 1 1 1
0 1 0 1
0 1 1 1
1 0 1 0
Output should print [row][col] of "upper left corner" 1, and [row][col] of "lower right corner", So it should be, for my example, [0][1] and [2][3].
I am using my getcolor() function to get value on [row][col] spot.
Also, I have these functions to get longest horizontal and vertical lines. For some reason they only work with arrays with the same number of columns and rows. When I use, for example, an array with 4 cols and 5 rows, it does not work right. Aan you help me please?
void getHline(Bitmap *arr)
{
int i, j, k;
int line, line_start, line_end, line_max = 0;
// Horizontally
for (k = 0; k < arr->rows; k++)
{
for (i = 0; i < arr->rows; i++)
{
if(!getcolor(arr, k, i))
{
continue;
}
for(j = i; j < arr->cols; j++)
{
if(!getcolor(arr, k, j))
{
break;
}
}
j--;
if(j - i + 1 > line_max)
{
line = k;
line_start = i;
line_end = j;
line_max = line_end-line_start+1;
}
}
}
printf("horizontally\n");
printf("start: [%d][%d]\n", line_start, line);
printf("end: [%d][%d]\n", line_end, line);
}
void getVline(Bitmap *arr)
{
int i, j, k;
int col, col_start, col_end, col_max = 0;
for(k = 0; k < arr->cols; k++)
{
for (i = 0; i < arr->rows; i++)
{
if (!getcolor(arr,i,k)) continue;
for (j = i; j <arr->cols; j++)
{
if (!getcolor(arr,j,k)) break;
}
j--;
if (j - i + 1 >col_max)
{
col = k;
col_start = i;
col_end = j;
col_max = col_end-col_start+1;
}
}
}
printf("\nverticaly\n");
printf("start: [%d][%d]\n", col, col_start);
printf("end: [%d][%d]\n", col, col_end);
}
If you're trying to get the largest square this has noting to do with the longest horizontal and vertical lines, because they could be separated and no square associated with them.
When trying to solve a complex problem, don't try to solve it all at once.
The first thing we have, is that each point of the array is associated with a square (the largest one for each point). So we have to find that square: We take a point of the array, then we move by steps through a continuous horizontal and vertical lines. For each step we check if we get a square and repeat the process until we get the largest square associated with that single point.
Each time we get the largest square associated with a point we check if it's largest than the last largest square associated with some previous point.
After connecting these parts we get our final program.
Explanation of the variables used in the program:
Link to the program http://pastebin.com/Yw05Gbtg or view it here:
EDIT:
#include <stdio.h>
main()
{
int lines=4, cols=4;
int arr[4][4] = {
{0,1,1,1,},
{0,1,0,1,},
{0,1,1,1,},
{1,0,1,0,}
};
int x_start, y_start, x_end, y_end, d_max=0;
int i, j, k, l;
int col_start, line_start, col_end, line_end, checker;
for (y_start=0; y_start<lines; y_start++){
for (x_start=0; x_start<cols; x_start++){
x_end = x_start;
y_end = y_start;
for (i=x_start, j=y_start; i<cols && j<lines; i++, j++){ // moving horizontally and vertically
if (!arr[y_start][i] || !arr[j][x_start]){ // checking if the horizontal or vertical lines are not continuous
break;
}
else {
checker = 1;
for (k=x_start, l=y_start; k<i+1 && l<j+1; k++, l++){ // check if square
if (!arr[j][k] || !arr[l][i]){
checker = 0;
break;
}
}
if (checker){ // if square then
x_end = i;
y_end = j;
}
}
}
if ((x_end-x_start)>d_max){
col_start = x_start;
line_start = y_start;
col_end = x_end;
line_end = y_end;
d_max = col_end-col_start;
}
}
}
printf("The largest square is:\n[%d][%d] x [%d][%d]\n", line_start, col_start, line_end, col_end);
// this is only to check if the program is working properly
for (y_start=line_start; y_start<line_end+1; y_start++){
printf("\n ");
for (x_start=col_start; x_start<col_end+1; x_start++){
printf("%d ", arr[y_start][x_start]);
}
}
printf("\n");
}
There is confusion between rows and cols somewhere in your code. To find it, rename your variables i, j and k to something more meaningful, like row, col_start and col_end.
As for finding maximal square, you might want to use prefix sums.

Resources