Nested For Loop Problems in C - c

Im trying to understand and figure out how to make a pyramid going left to right.
I have the computer asking for the height, it is only 1-8
Im trying to make that pyryamid look something like this depending on the height
I have a squared being made.
Heres the code
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int getHeight;
do
{
//asks height
getHeight = get_int("Height: ");
}
//If the height is greater then 8 then ask for the Height again
while(getHeight > 8);
//
for(int row = 0; row < getHeight; row++)
{
for(int colums = 0; colums < getHeight; colums++)
{
printf("#");
}
printf("\n");
}
}**

It looks like your inner loop is wrong. It iterates up to getHeight but should only iterate up to (and including) row:
for(int row = 0; row < getHeight; row++)
{
for(int colums = 0; colums <= row; colums++)
{ // ^^^^^^
Each iteration of the outer loop will increase row. The inner loop will make one more iteration over colums every time row increases.
Output if the user enters 8:
# // row 0, columns 0-0
## // row 1, columns 0-1
### // row 2, columns 0-2
#### // row 3, columns 0-3
##### // row 4, columns 0-4
###### // row 5, columns 0-5
####### // row 6, columns 0-6
######## // row 7, columns 0-7

Related

C - Access a certain row or column in a matrix

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.

Printing a pattern to the screen in C

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;
}

Where did I go wrong in my loops in my code?

I was trying to program a Mario half pyramid in C but my code is not doing anything.
I originally messed up with loop breakers with it putting everything upside down and when I fixed it it is simply asking for an input and not doing anything else.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
int space;
int rows;
int hashes;
// The code below decides if the users input meets the guide lines
do
{
printf("Enter the heigth of the pyramid here");
height = GetInt();
}
while (height <= 0 || height > 23);
for(rows = 1 ;rows > height ;rows++)
{
// the code gives the number of spaces per row
for(space = height - 1;space >= 1;space--)
{
printf(" ");
};
//The code below gives the number of hashes that have to be printed
for(hashes = height + 1 - space; hashes> 0; hashes--)
{
printf("#");
};
height = height + 1
printf("\n");
}
};
Your for loop is not going to iterate for a single time if height is not less than 1.
for(rows = 1 ;rows > height ;rows++)
{
//....
I modified your code like the following for height = 5
for (rows = 1; rows <= height; rows++) {// iterate up to height times
for (space = height - rows; space >= 1; space--) { // at first print spaces height -1 times. then spaces will be reduced by 1 from previous.
printf(" ");
};
// at first print hashes 2 times. then hashes will be increased by 1 from previous.
for (hashes = rows + 1; hashes > 0; hashes--) {
printf("#");
};
printf("\n");
}
and get output:
##
###
####
#####
######

Making a Hash Pyramid

Currently doing the CS-50 course and was wondering if anyone could help me with this. I'm supposed to create a program which will ask a user for a height between 1-23 (and continuously prompt the user until a valid answer is given) --- I was able to code that part.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
printf("please give me a height between 1-23: ");
height = GetInt();
}
while (height < 1 || height > 23);
}
The do while loop seems to do what its intended. Now, the program, given the variable "height" now needs to create a pyramid of that height. The bottom of the pyramid is to be aligned with the bottom left hand of the terminal and its last "row" is to finish with 2 hashes as such:
Sample pyramid of height 4:
##
###
####
#####
But the code needs to be generic for any height of pyramid 1-23.
This is where I'm having a hard time (in actually making a code to draw this).
Ive noticed that for each row, the number of hashes needed (if we call the top row "row 1" and the subsequent "row 2" and so on... is
row number+1. As for the amount of spaces that are needed, can be represented by height-row number.
If someone would be able to explain to me how I could write this program using C, it would be much appreciated! :)
Here is a way you can implement this. Basically, you need to build the pyramid from the bottom up. The task is easy once you see the loop structure, its just tricky to get the math down for printing the correct number of spaces and hash symbols:
#include <stdio.h>
int main(void)
{
int height, i, j;
do
{
printf("please give me a height between 1-23: ");
height = GetInt();
}
while (height < 1 || height > 23);
printf("\n");
for (i = 0; i < height; i++) {
for (j = 0; j < height - i - 1; j++)
printf(" ");
for (j = 0; j < i + 2; j++)
printf("#");
printf("\n");
}
}
For more clarification on whats going on, and why each loop is necessary:
Outer for loop: the variable i corresponds to a row in the pyramid. the value of i will remain constant for each of the second two loops
First inner for loop: for any row, there needs to be height - i - 2 spaces. You can figure this out because the total row width will be height, and any row has i + 2 hash symbols, so there needs to be height - (i + 2) = height - i - 1 spaces. So basically, this loop just prints the required spaces. You can track this with the variable j
Second inner for loop: This loop is similar to the first inner loop, but you need to now print the hash marks. At the beginning of the loop you reset j and count up to the required number of hash marks
Here is a version that may offer some insight:
#include <stdio.h>
#include <cs50.h>
int main(void) {
//initialize variables
int height, n, j, k, i;
printf("Height: \n");
// Get user input
height = GetInt();
n = height;
for(i = 0; i < height; i++) {
// create n spaces based off height
for(k = n; k > i; k--)
printf("%c", ' ');
// create hash tags
for(j = 0; j < i+2; j++)
printf("#");
printf("\n");
}
return 0;
}
Result if user entered a height of 5:
Height:
##
###
####
#####
######
The 1st for loop essentially prints the number of rows matching the height entered
The 2nd for loop involves printing the number of spaces based on the height entered
The 3rd for loop involves printing the number of hashes (with respect to the height value) after the amount of spaces on the same line
Cheers

Coursework - Creating a Match-3 "Candy Crush" Game in C

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);
}

Resources