I'm in my first programming course ever and have a few questions about an assignment that we've been given.
I'm trying to print the following pattern to the screen:
*
***
*****
*******
The pattern is supposed to contain 5 rows and each subsequent row has 2 additional asterisks from the row above making roughly a pyramid shape.
I've been working on creating code to do this using for loops (this was part of the instructions) and here's what I have so far:
int main ()
{
int row;
int col;
for (row = 1; row <= 5; row++) //rows
{
for (col = 1; col <= row; col++) //columns
{
printf_s("*");
}
printf_s("\n");
}
return 0;
}
The problem with my code is that I am not accounting for the required empty spaces to get the alignment correct. With the above current code here's what the output looks like:
*
**
***
****
*****
I'm hoping someone can point me in the right direction as to how to re-write my code to get the correct alignment and the correct number of leading spaces.
Thank you in advance.
You have a loop to print the asterisks but you are not printing out any spaces before that.
And the number of asterisks you print are not correct. For example your output has only 2 *s in second line when there should've been 3.
You could do
printf("%*s", NUM, "");
to print NUM spaces instead of using a separate loop.
Something like
for (row = 0; row < ROWS ; row++) //rows
{
printf("%*s", ROWS-1-row, "");
for (col = 0; col < row*2+1; col++) //columns
{
printf("*");
}
printf("\n");
}
The number of asterisks in each row is one more than double the row number if the row numbering starts from 0.
ROWS represent the number of rows to be printed.
The outer loop is for each row and the inner loop prints a number of asterisks in the row. YOu have omitted to preceded the row with a suitable number of spaces.
If you change the outer loop to the more conventional:
for (row = 0; row < 5; row++)
It makes the character count arithmetic simpler.
The inner loop should be preceded by another loop to print 4 - row spaces.
The asterisk loop needs to print row * 2 + 1 asterisks.
Try this:
r - count of rows
s - increment
i - rows index
j - columns index
start - starting count of *
#include <stdio.h>
int main(void)
{
int i,j,r=4,s,start;
start = 1;
s = start*2;
for (i=0;i<r*s;i+=s)
{
for (j=0;j<r*s/2-(i/2)-start;j++) printf(" ");
for (j=0;j<i+start;j++) printf("*");
printf("\n");
}
return 0;
}
Related
This code is for printing the inverse half pyramid:
* * *
* *
*
#include<stdio.h>
int main() {
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (i=rows; i>=1; --i)
{
for (j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Let's say if I enter rows = 5, then "i" will initialize its value as 5, check if it's greater than 1,
then we go to the 2nd for loop, where j has the initial value of 1, and then check if it's less than the value of "i= 5", which it IS, then after that, how will the second loop run?
The first for loop is to decrement from 5 (rows variable) to 1 (since it is inverted half pyramid).
The second/inner for loop (loop j) is to print the * character i times (i is set in outer for loop).
Once the inner for loop exits, a new line is printed (\n) and i is decremented and the inner loop runs again for the new value of i.
* * * *
* * *
* *
*
The above pattern contains N rows and each row contains N-i + 1 columns (where i is the current row number). Considering this let us write a step by step descriptive logic to print inverted right triangle star pattern.
Input number of rows to print from user. Store it in a variable say rows.
To iterate through rows run an outer loop from 1 to rows. The loop structure should look like for(i=1; i<=rows; i++).
To iterate through columns run an inner loop from i to rows. The loop structure should look like for(j=i; j<=rows; j++). Inside this loop print star.
Note: Instead of iterating from i to rows you can also iterate from 1 to rows - i + 1.
After printing all columns of a row, move to next line i.e. print new line.
Good explanation taken from https://codeforwin.org/2015/07/inverted-right-triangle-star-pattern-program-in-c.html
/**
* Reverse right triangle star pattern program in C
*/
#include <stdio.h>
int main()
{
int i, j, rows;
/* Input number of rows from user */
printf("Enter number of rows : ");
scanf("%d", &rows);
/* Iterate through rows */
for(i=1; i<=rows; i++)
{
/* Iterate through columns */
for(j=i; j<=rows; j++)
{
printf("* ");
}
/* Move to the next line */
printf("\n");
}
return 0;
}
I want to know how I can print a certain row, certain column and the anti diagonal in an NxN matrix. So far I know how to print the matrix itself and the main diagonal. As you can see in the code I'm printing the main diagonal.
#include <stdio.h>
int main() {
int r1, c1;
printf("\n Enter number of rows for M1");
scanf("%d", &r1);
printf("\n Enter number of columns for M1");
scanf("%d", &c1);
int m1[r1][c1];
// int m2[][];
int i, j;
printf("\n Enter first Matrix: \n");
for(i = 0; i < r1; i++){
for(j = 0; j < c1; j++){
scanf("%d", &m1[i][j]);
}
}
for(i = 0; i < r1; i++){
for(j = 0; j < c1; j++){
if(i == j){
printf("%d", m1[i][j]);
}
}
printf("\n");
}
return 0;
}
This exercise is supposed to teach you how to translate a task into the correct loop.
In order to understand how to do that, I'd suggest this way:
Take a specific example (matrix), and write down the expected result. Then try to reverse-engineer it to the right loop code by understanding the indices pattern:
Let's take this matrix:
1 6 4 3
9 3 5 2
3 3 8 0
1 5 4 4
Example 1 - Main diagonal
Expected result would be 1384
which is practically cells (0,0) (1,1) (2,2) (3,3). Now, look at this list of indices and figure out the pattern - it's one index that increments in every iteration ==> one index (one loop) is enough:
for(i = 0; i < r1; i++) {
printf("%d", m1[i][i]);
}
Example 2 - Anti diagonal
Expected result would be 3531 which is practically cells (0,3) (1,2) (2,1) (3,0). Again, look at this list of indices and figure out the pattern - it's one index that increments in every iteration and the other one decrements. But if you think about it, the second index is a function of the first one. That means that also this one can be done with one index only:
for(i = 0; i < r1; i++) {
printf("%d", m1[i][r1 - i + 1]);
}
Because second-index = r1 - first-index + 1, always.
I tried to explain here how you should go about thinking and writing the correct loop given a task. Now try to use this method for the rest of your tasks - a certain row and a certain column (it's even easier than the diagonals).
For row 2 the indices will be (2,0) (2,1) (2,2) (2,3) - so what's the pattern?
Good luck.
I'm currently developing a simple naval battle game for my first exam at my college but i'm getting a strange output on my gameboard...
It should be iterating my "j" variable, but instead I get that strange character...
Here's my code:
//CREATES COORDENATES OF THE GAMEBOARD
//ATTRIBUTE ONE LETTER TO EACH TRAY LINE
for (i=0;i<11;i++){
tabuleiro[i][0] = letra[i-1];
}
//ATTRIBUTE ONE NUMBER TO EACH TRAY COLUMN
for (j=1;j<11;j++){
tabuleiro[0][j] = j;
}
//CREATES THE "SEA"
for (i=1;i<11;i++){
for (j=1;j<11;j++){
tabuleiro[i][j] = '~';
}
}
I've tryied to change my tabuleiro[0][j] = j; to tabuleiro[0][j] = (j+'0'); but then it only iterates until 9 and give me strange characters again...
If I'm not wrong I think this has something to do with the ASCII code (please correct me if I'm wrong) but I've no clue how to fix this.
Could you explain me how can I solve this please.
to have precise control of the character i suggest
tabuleiro[0][j] = "123456789T"[j];
This will pick the jth character from that string
BTW the reason you got ':' is becasue ':' is the next ascii character after '9' - see http://www.asciitable.com/
The issue is the char code for 10 + '0' = 58 which is the char code for ':'. You might consider removing the column and row names out of the game array. They are just labels and not part of the game (I assume).
#define board_size 10
And
// Create game board and initialize grid to '~', in main() possibly
// Game is 10x10 grid
char tabuleiro[board_size][board_size];
for (int row = 0; row < board_size; row++) {
for (int col = 0; col < board_size; col++) {
tabuleiro[row][col] = '~';
}
}
Have a function that draws the game board:
void drawBoard(char tabuleiro[board_size][board_size]) {
// Print top line
printf(" ");
for (int col = 0; col < board_size; col++) {
printf(" %-2d", col+1);
}
printf("\n");
// Print grid
for (int row = 0; row < board_size; row++) {
// Print letter
printf("%c ", 'A' + row);
// Print board
for (int col = 0; col < board_size; col++) {
printf(" %c ", tabuleiro[row][col]);
}
printf("\n");
}
}
I have just started making my Sudoku game and I have made this function grid for creating a 6x6 Sudoku grid. I have used the rand() function for different numbers in each cell (currently it will only check rows for repetition of numbers). rand() is also used for random numbers of empty cells in each grid.
The problem is that sometimes the grid is perfect 6x6 and without any number repeating (in rows only), however, sometimes in some cells there are garbage values generated and sometimes the number of columns is increased. I don't understand what is causing the problem?
The Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void grid(void) {
int cell[6][6], row, col, s, i, j;
char in = 'A';
srand(time(NULL));
for (row = 0; row <= 5; row++) {
printf("\t\t\t[ |");
for (col = 0; col <= 5; col++) {
s = rand() % 6 + 1;
if (s % 2 == 0)
{
cell[row][col] = rand() % 6 + 1;
for (j = 0; j<col; j++) {
if (cell[row][j] == cell[row][col]) {
col--;
continue;
}
}
}
else { printf(" | ", in++); continue; }
printf(" %d | ", cell[row][col]);
}
printf("]\n\n");
}
}
int main()
{
grid();
}
They are too many syntax errors in the code you post, and the format is quite horrible. Try editing it so we can help you !
col--;
Maybe this is your problem, because if you col--; in your for (col = 0; col < 6; col++) loop, you will do more than 6 iterations.
I know this question is old, but a commenter here did say to wait at least 1 hour...
To answer your question directly:
You get garbage values because you do not set values for cell when !(s % 2 == 0).
You get more than 6 entries per row because your c-- statement causes the col loop to execute more than 6 times (and you printf each time).
If you want to maintain the general structure of your logic, then do this in two passes - fill cell completely and then print the whole thing. However, there are other problems. You probably want to remove the s % 2 == 0 check completely, and the first continue could be a break (or a goto if you really want to make people angry).
I'm having a little bit of trouble on an assignment and am looking for some advice. I'm supposed to create a "game" that is similar to Candy Crush or Bejeweled. The assignment takes in a .txt file that contains a matrix of values from 1-5 and then assigns each value to a spot in a [10][10] array. Then an Escape Code function prints out colored pixels in place of the number values for each spot, creating a "game board" looking output. Finally, the program is supposed to look for any matches of 3 same-colored pixels and replace them with a white pixel and "XX". Then the program prints the corrected game board with the matches X'd out.
I have it mostly coded, but I've encountered a couple of issues...
1.) I am supposed to label the columns and rows 0-9, and while I have no problem coding the labels for the columns using printf( ), when I try to print the row labels I get a random string of numbers.
2.) I replaced the matches with white pixels by reassigning the value in the array to 7, for which the ANSI Escape Code is white. However, I'm unsure about how to print the "XX" in the same spot.
I wish I could post some pictures as an example but I don't have enough "reputation" on this site as a new account. I've included my code so far below.
#include <stdio.h>
void printEscapeCode(int c);
int main(void)
{
/* Declare an image array to be gameboard */
int gameboard[10][10];
/* Declare variables and load in how many rows and columns */
int Nrows;
int Ncols;
scanf("%d %d",&Nrows, &Ncols);
/* Load in candy values for each row */
int row, col;
for(row = 0; row < Nrows; row++)
{
/* Load in candy values for each column */
for(col = 0; col < Ncols; col++)
{
/* Declare variable to hold value */
int x;
scanf("%d",&x);
/* Tell where to store candy value */
gameboard[row][col] = x;
}
}
/* Calls function to print candy colors for each row */
printf(" 0 1 2 3 4 5 6 7 8 9\n");
for(row = 0; row < Nrows; row++)
{
printf("0 ");
/* Calls function to print candy colors for each column */
for(col = 0; col < Ncols; col++)
{
/* If statement to look for three matching candies */
if(gameboard[row][col] == gameboard[row+1][col] && gameboard[row+1][col] == gameboard[row+2][col])
{
/* Sets matching candies to display white */
gameboard[row][col] = 7;
gameboard[row+1][col] = 7;
gameboard[row+2][col] = 7;
}
if(gameboard[row][col] == gameboard[row][col+1] && gameboard[row][col+1] == gameboard[row][col+2])
{
gameboard[row][col] = 7;
gameboard[row][col+1] = 7;
gameboard[row][col+2] = 7;
}
printEscapeCode(gameboard[row][col]);
}
printEscapeCode(7);
printf("\n");
}
return 0;
}
/* Function that prints candy colors */
void printEscapeCode(int c){
printf("\x1b[4%dm ",c);
}