I need to make a program that prints this:
.......#
......##
.....###
....####
...#####
..######
.#######
########
Basically, if the n is 8. it will print 7 dots and 1 hash***. then in the next row it will print 7 dots and 2 hashes, then 6 dots and 3 hashes until there are 0 dots and 8 hashes.
So far my code looks like this:
int main(void)
{
int G = 1;
int n = 8;
int m = 0;
int k = 0;
int Z = 1;
for (m = n; m > 0; m --)
{
for (k = n - 1; k >= Z; k --)
{
printf(".");
}
printf("\n");
Z = Z + 1;
}
for (int i = 0; i < n; i ++)
{
for (int j = 0; j < G; j++)
{
printf("#");
}
printf("\n");
G = G + 1;
}
}
But the result of this comes out as this:
.......
......
.....
....
...
..
.
#
##
###
####
#####
######
#######
########
Since this is obviously homework or some self studies, I'll write how you need to think here.
The first problem is to be able to print ONE row given total number of rows and current row.
So let's start with total number or rows. I will use more descriptive variable names, which you also should.
int total = 8;
Now we need to print one row, given the current row. Let's assume that the first row has number 1. Let's start with the dots.
for(int i=0; i<(total-row); i++)
printf(".");
Then we continue with the hashes:
for(int i=0; i<row; i++)
printf("#");
And now we just need to do this total times and add a newline after each:
for(int row=1; row<total; row++) {
for(int i=0; i<(total-row); i++)
printf(".");
for(int i=0; i<row; i++)
printf("#");
printf("\n");
}
Please note that it is very common with obo (off by one) errors when doing things like this. We could let 0 be the first row instead of one, but then we need to change a few other things. You said you wanted 1 hash and 7 dots on first line and 8 hash and 0 dots on last line, which seems a bit odd, but just change row<total to row<total+1 and you get that.
You'll rather want something that does the printing from within the same loop. Here's some pseudo code of a simple way to write this algorithm:
for(int dots=n-1; dots>DOTS_MIN; dots--)
{
for(int i=0; i < dots; i++)
print dot
for(int i=dots; i < n; i++)
print hash
printf("\n");
}
First, start from naming, it's a challenging task to find out what Z stands for.
So we have
int totalRows = 4;
int totalColumns = 8;
and we should print out totalRows of rows:
for (int row = 1; row <= totalRows; ++row) {
}
from 2nd row on we should add a new line:
for (int row = 1; row <= totalRows; ++row) {
/* Start a new line from the 2nd row on */
if (row > 1)
printf("\n");
}
Time to print dots, we have totalColumns - row of them:
for (int i = 1; i <= totalColumns - row; ++i)
printf(".");
Followed by row # symbols:
for (int i = 1; i <= row; ++i)
printf("#");
Combining these chunks all together:
int main() {
int totalRows = 4;
int totalColumns = 8;
for (int row = 1; row <= totalRows; ++row) {
/* Start a new line from the 2nd row on */
if (row > 1)
printf("\n");
/* Printing dots */
for (int i = 1; i <= totalColumns - row; ++i)
printf(".");
/* Printing # */
for (int i = 1; i <= row; ++i)
printf("#");
}
return 0;
}
Related
When creating a 2D array and setting the value of some element, other elements get set too, what could be the reason behind such anomaly?
Following is the code example.
#include <stdio.h>
#define MAX_X 240
#define MAX_Y 2
char grid[MAX_X][MAX_Y];
int main()
{
int i,j,row,col;
col = MAX_X;
row = MAX_Y;
// Init 2D array
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
grid[i][j] = '.';
}
}
grid[0][121] = 'X'; // << [ISSUE HERE] `X` is written into 2 elements instead of 1
// Display 2D array
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%c", grid[i][j]);
}
printf("\n");
}
}
Note:
Issue showed up on g++, and was reproduced using this snippet on online gdb's compiler
You define grid as grid[240][2] which means 240 rows x 2 columns, and as #wildplasser mention you swap the col and row assignment. It should be:
row = MAX_X;
col = MAX_Y;
I want to output Yay if the matrix doesn't contain the same number on the same row or column otherwise output Nay
this is for my college homework. I already tried to check the column and row in the same loop but the output still not right
#include <stdio.h>
int main()
{
int size;
int flag;
scanf("%d",&size);
char matrix[size][size];
for (int i = 0; i < size; i++)
{
for (int l = 0; l < size; l++)
{
scanf("%s",&matrix[i]);
}
}
for (int j = 0; j < size; j++){
for (int k = 0; k < size; k++){
if(matrix[j] == matrix[j+1] || matrix[j][k]==matrix[j][k+1])
{
flag = 1;
}
else
{
flag = 0;
}
}
}
if (flag == 1)
{
printf("Nay\n");
}
else
{
printf("Yay\n");
}
return 0;
}
I expect to output "Nay" when I input
3
1 2 3
1 2 3
2 1 3
and "Yay" when i input
3
1 2 3
2 3 1
3 1 2
Your matrix is a 2D array and you are referencing it using only a single subscript matrix[index] at several places which returns the address of the row. Index it using both the row and column indices. Try the code below:
{
int size;
int flag;
scanf("%d",&size);
char matrix[size][size];
for (int i = 0; i < size; i++)
{
for (int l = 0; l < size; l++)
{
scanf("%s",&matrix[i][l]);
}
}
for(int j = 0; j < size; j++){
for (int k = 0; j < size; j++){
if(matrix[j][0]== matrix[j][k] || matrix[k][0]==matrix[k][j])
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
}
if (flag == 1)
{
printf("Nay\n");
}
else
{
printf("Yay\n");
}
return 0;
}
Your have a logic problem. Your flag is reset on every element in the matrix and thus only reflects the result of the last check.
In addition, you need a break; in your nested loop. The logic is, if your flag becomes 1, you are sure to say Nay, and you don't want the flag to be reset to 0.
int flag = 0;
for (int i = 0; i != size && !flag; ++i) {
for (int j = 0; j != size; ++j) {
if ( /* detection */ ) {
flag = 1;
break;
}
}
}
if (flag)
printf("Nay\n");
else
printf("Yay\n");
Note: The commented /* detection */ part requires more work. Since it's your homework, you may try it first. You could use a hash table for memorization. Or brutal force to make the program simply work. It seems that your detection only checks for neighboring elements, which is not sufficient to assert that an element is unique in its row or column. Consider
1 2 1
3 4 5
6 7 8
I can't do your homework for you. The following is the brutal-force way you may consider.
The if ( /* detection */ ) part could be if (has_same_element(matrix, i, j)), with a function (pseudo code)
int has_same_element(matrix, row, col)
{
for each element a in matrix's row except matrix[row][col] itself
if (a == matrix[row][col])
return 1
for each element b in matrix's col except matrix[row][col] itself
if (b == matrix[row][col])
return 1
return 0
}
Of course there are smarter ways, like using a hash table, in which case you don't even need the nested loop. For the time being, work out a feasible solution, instead of the best solution.
I am new to C, and I am trying to print diamond shapes according to the rows(2~10), columns(2~10) and the length(3, 5, 7, 9) of the diamond input from the user.
Using the code below I can print diamond and number of diamonds correctly, but I just can't get the correct distance between them.
void printDiamondWith(int diamondlength, int numberOfDiamonds) {
int i, j, k;
int star, space;
star = 1;
space = diamondlength;
for (i = 1; i < diamondlength * 2 - 1; i++) {
for (k = 0; k < numberOfDiamonds; k++) {
for (j = 0; j < space; j++) {
printf(" "); // Print the distance for the previous star
}
for (j = 1; j < star * 2; j++) {
printf("*");
}
for (j = 0; j < space; j++) {
printf(" "); // Print the distance for the next star
}
}
printf("\n");
// Check if length is equal 3, else length -1 to get the correct rows of second half of the diamond
if (diamondlength == 3) {
// Loops until the first half of the diamond is finished, then reverse the process to print the second half
if(i < (diamondlength - diamondlength / 3)) {
space--;
star++;
} else {
space++;
star--;
}
} else if (diamondlength >= 3) {
if (i < (diamondlength - 1 - diamondlength / 3)) {
space--;
star++;
} else {
space++;
star--;
}
}
}
}
Actual running result:
Expected result:
Your formulas for calculating the space is off. It works for me when I change this
space = diamondlength;
to this
space = diamondlength/2+1;
And this
for (k = 0; k < numberOfDiamonds; k++) {
for (j = 0; j < space; j++) {
to this:
for (k = 0; k < numberOfDiamonds; k++) {
for (j = 0; j < space-1; j++) {
In such situations I recommend hardcoding the variable for different parameters and write down what the variable has to be for what parameter so you can try to find a function that maps the parameter to the value. For instance I saw that as diamondlength increased, the space error also increased, so the relation between parameter and variable can't be one to one.
I'm trying to solve the 8 queens puzzle problem in C. I'm having problems with the recursive search. The program is supposed to start at a given column:
execute(tabuleiro,8,0);
Where the 8 is the number of columns in the board, and 0 is the start column.
This works when I start at column 0. When I send any other column number to the recursive search, the program just counts to the last column. For example, if I choose to start the search from the number 5 column, the code search from the column 5 to 7, after this it should search from 0 to 4, but it doesn't do that.
If I do this:
execute(tabuleiro,8,3);
It fills in only the last 5 colummns, and does not return to column 0 to finish the solution:
Also, how can I select the initial position for the queen in this code? Like I said before, the column is assigned in the code, but I'm not sure how to pick the correct column.
The code has 3 functions: one is to display the board, a second to check if the move is legal (so one queen doesn't attack the other), and the last one to place one queen and recur for the remainder of the board.
#include <stdlib.h>
#include <windows.h>
int sol = 0;
void viewtab(int tab[][8], int N)
{
int i,j;
for( i = 0; i < N; i++)
{
for( j = 0; j < N; j++)
{
if(tab[i][j] == 1)
printf("R\t");
else
printf("-\t");
}
printf("\n\n");
}
printf("\n\n");
system("pause");
printf("\n");
}
int secury(int tab[][8], int N, int lin, int col)
{
// this function is to check if the move is secury
int i, j;
// attack in line
for(i = 0; i < N; i++)
{
if(tab[lin][i] == 1)
return 0;
}
//attack in colune
for(i = 0; i < N; i++)
{
if(tab[i][col] == 1)
return 0;
}
// attack in main diagonal
//
for(i = lin, j = col; i >= 0 && j >= 0; i--, j--)
{
if(tab[i][j] == 1)
return 0;
}
for(i = lin, j = col; i < N && j < N; i++, j++)
{
if(tab[i][j] == 1)
return 0;
}
// attack in main secondary
for(i = lin, j = col; i >= 0 && j < N; i--, j++)
{
if(tab[i][j] == 1)
return 0;
}
for(i = lin, j = col; i < N && j >= 0; i++, j--)
{
if(tab[i][j] == 1)
return 0;
}
// if arrive here the move is secury and return true
return 1;
}
void execute(int tab[][8], int N, int col)
{
int i;
if(col == N)
{
printf("Solution %d ::\n\n", sol + 1);
viewtab(tab, N);
sol++;
return;
}
for( i = 0; i < N; i++)
{
// check if is secury to put the queen at that colune
if(secury(tab, N, i, col))
{
// insert the queen (with 1)
tab[i][col] = 1;
// call recursive
execute(tab, N, col + 1);
// remove queen (backtracking)
tab[i][col] = 0;
}
}
}
int main()
{
int i, j, tabuleiro[8][8];
for (i = 0; i < 8; i = i + 1)
for (j = 0; j < 8; j = j + 1) tabuleiro[i][j] = 0;
execute(tabuleiro,8,0);
return 0;
}
The search always stops in the rightmost column because you specifically tell it to stop there:
void execute(int tab[][8], int N, int col)
{
int i;
if(col == N)
{
printf("Solution %d ::\n\n", sol + 1);
viewtab(tab, N);
sol++;
return;
}
Look at your termination condition: you check the current column against the highest column number, and stop there.
If you want to go back to column 0, you have to change your loop logic. For instance, let col reach N, at which point you reset it to 0, and let it continue until you hit the original value. Another way is to continue until the count of placed queens is N.
You choose the initial point in the same way: you pick the first one and make your recursive call. If that eventually results in a solution, you print it. If not, your top-most call continues to the next row (line) of the board and puts the first queen there.
This is already in your main logic. Just make sure that secury will return true when the board is empty, rather than false or throwing an error.
A. You can place the first Queen at (0,0).
B. And begin the search also from (0,0).
C. I do not see any need to start looking for some other index.
Successfully!!
I am trying to display the elements of an array in the number of columns that the user specifies. They decide how large the array is and how many columns it will be displayed in. Right now, I am printing the elements of the array in columns but, I have extra rows and columns with numbers that are not in the array. Thus if I select array size and column number as 5 3, I would hope to see:
1 3 5
2 4
Instead, I get something like:
1 3 5
2 4 107863456
128976543 58764 896543221
5643217 90876543456 8976543
I am getting 3 columns with 4 rows. I do not know why this is happening. Here is the portion of my code that deals with creating columns, let me know if more code is needed (x is variable that holds array size, y holds number of columns):
void colDisplay(int *aPtr, int x, int y) {
int i, j;
srand(time(NULL));
for(i = 0; i < x; i++) {
aPtr[i] = rand()%5+1;
}
/*Trying to format display for number of columns used*/
printf("Unsorted columns\n");
for(i = 0; i < x; i++) {
for(j = 0; j < y; j++) {
//printf("%d = %d ", (i*y)+j, aPtr[(i*y)+j]);
printf("%d ", aPtr[(i*y)+j]);
}
printf("\n");
}
}
The inner loop is counting the columns correctly, but the outer loop is using x as a row count, instead of an item count. To fix the problem you can use a single loop that counts items, and outputs newlines at the correct times.
j = 0;
for ( i = 0; i < x; i++ )
{
printf("%d ", aPtr[i] );
j++;
if ( j == y || i == x-1 )
{
printf( "\n" );
j = 0;
}
}
I agree with the solution by #user3386109.
Also, the following change will help:
Original 'for' loop with j:
for(j = 0; j < y; j++)
Modified code:
for (j = 0; (j < y) && (i*y+j < x); j++)
Reason: index = i*y+j may exceed x if (x % y != 0) i.e. if x (array size) is not integral multiple of y (display column size).
Because of arrays index out of bound.
You should do the following:
for(i = 0; i >= 0; i++) {
boolean isContinue = true;
for(j = 0; j < y; j++) {
int index = i*y+j;
if(index==x){
isContinue = false;
break;
}
printf("%d ", aPtr[(i*y)+j]);
}
if(!isContinue){
break;
}
printf("\n");
}