I have started the CS50x problem set 1; however my programme seems to stop after I have input the the number for height.
I.e. the programme will ask for a number between 8 and 23 (repetitively until it gets a correct input) and once I do so the code stops.
What have I done wrong here?
Below is the code I have written. All help would be greatly appreciated as I have looked at various questions on here S.E. but none addressing this problem.
include stdio.h
include cs50.h
int main (void)
{
printf("ok lets make a pyramid :)\n");
// height = x
int x;
// spaces = z
int z;
// hashes = a
int a;
// Get correct number for height
do
{
printf("Give me a positive number between 8 and 23 for the height of the pyramid\n");
x = GetInt();
}
while (x < 8 || x > 23);
// Build the phantom pyramid
for (int q = 0; q == x; q++)
{
// Spaces
for (z = x - 1; z == 0 ; z--)
{
printf(" ");
}
// Hashtags
for (a = 1; a == q; a++)
{
printf("#\n");
}
}}
Aside from that your #include syntax is wrong (#include <stdio.h>), your fundamental problem here, and the reason that your program exits without printing anything, is that the main for loop is never entered. C for loops are executed while the controlling expression is true, not until is is true. You have:
for (int q = 0; q == x; q++){ ... }
Since q == x evaluates to 0 (false), because q is 0 and x is between 8 and 23, this loop never executes, and the program exits. Each of your loops has this problem. You can fix it:
for (int q = 0; q < x; q++)
{
// Spaces
for (z = x - 1; z > 0 ; z--)
{
printf(" ");
}
// Hashtags
for (a = 0; a <= q; a++)
{
printf("#");
}
printf("\n");
}
Here, note that in the first pass through the loop, q is 0, so a must start at 0 to print a single hash on the first line. Also, the newline character is not printed until the loop is finished printing the line. These changes give this output for a height of 8:
#
##
###
####
#####
######
#######
########
I am not sure if this is the output that you want. The spacing on the left is tied to the height of the pyramid. If you want the pyramid steps on the left, you can change the associated for statement:
for (z = x - 1; z > q ; z--)
But I was under the impression that the Mario Pyramid had the steps on the left, and two hashes in the top line. You could modify your loop to do this, but here is a different loop. You don't need the variable a, and rather than thinking of z as "spaces", think of it as representing the line-position:
for (int q = x; q > 0; q--) {
// print spaces at beginning of line
for (z = 1; z < q; z++) {
printf(" ");
}
// print hashes at end of line
for ( ; z < x + 2; z++) {
printf("#");
}
// print newline when finished printing line
printf("\n");
}
The new loop gives this output for a height of 8:
##
###
####
#####
######
#######
########
#########
Related
I was written this code to rotate the matrix elements one by one.
I wanted to do this on my own but I am stuck in this position someone please find what is the problem in my code and suggest me there is any easy implementation other than this.
#include<iostream>
using namespace std;
void rotate(int a[][10],int r,int c)
{
int b[10][10];
// Copying the input matrix 2d array to temp array
for (int x = 0; x < r; x++)
{
for (int y = 0; y < c; y++)
{
b[x][y] = a[x][y];
}
}
//Rotation process
int i = 0;
int j = 0;
int flag = 0;
while (flag == 0)
{
if (i == 0 && j < c-1)
{
b[i][j+1] = a[i][j];
j++;
}
else if (j == c-1 && i < r-1)
{
b[i+1][j] = a[i][j];
i++;
}
else if (i == r-1 && j <= c-1 && j > 0)
{
b[i][j-1]=a[i][j];
j--;
}
else if (j == 0 && i <= r-1)
{
if (i==0 && j==0)
{
//to break the loop
flag = 1;
}
b[i-1][j] = a[i][j];
i--;
}
}
for (int k = 0; k < r; k++)
{
for (int l = 0; l < c; l++)
{
cout<<"\t"<<b[k][l];
}
cout<<endl;
}
}
int main()
{
int a[10][10],row,col;
cout<<"Enter no of rows : ";
cin>>row;
cout<<"Enter no of columns : ";
cin>>col;
// Getting array elements
cout<<"Enter "<<row<<"X"<<col<<" matrix elements : ";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin>>a[i][j];
}
}
rotate(a,row,col);
cout<<endl;
system("pause");
return 0;
}
This code is not working. Someone help me to find what wrong with this code or suggest me another way.
Thank you.
If I were solving this, I might use 4 independent loops and a single variable to hold the value to carry forward (can be read from the original or matrix copy). While perhaps more repetitive than some approaches, it also removes needing to track 'which direction' state or delta movement variables.
In pseudo-code, it might look like this:
carry = m[0][0]
x, y = 1, 0 # start at (1,0) so we end on (0,0)
# go right from (1,0) to (cols-1,0)
while x < cols:
temp = m[x][y] # hold value of this cell
m[x][y] = carry # replace it with the carried-over value
carry = temp # and forward the previous value as the next carry
x += 1 # update position
# reset back to valid index (avoid additional check in loop)
x -= 1
# do same for other directions around
# the movement is thus:
# (1,0) -> (cols-1,0) NW -> NE
# (cols-1,0) -> (cols-1,rows-1) NE -> SE
# (cols-1,rows-1) -> (0,rows-1) SE -> SW
# (0,rows-1) -> (0,0) SW -> NW
A 1xN or Nx1 matrix might need additional consideration depending on expectations.
Another approach is to use delta variables to move. Think of a little turtle that walks straight and turns right when walking into a wall. The terminal condition is once again set as (0,0) which can be checked at the end of the logic - in this case when the turtle attempts to walk North into a wall, we know it was from (0,0) and the path is completed.
This approach feels less repetitive while maintaining simple state transitions.
carry = m[0][0]
x, y = 1, 0 # start at (1,0)
dx, dy = 1, 0 # and facing East
while true:
# could also use prev_x and prev_y instead of a carry
temp = m[x][y]
m[x][y] = carry
carry = temp
# move / walk
x += dx
y += dy
# turn right when running into a wall
# at most one bound can be violated at a time
if x >= cols:
dx, dy = 0, 1 # face South (was facing East)
x = cols - 1
else if y >= rows:
dx, dy = -1, 0 # face West (was facing South)
y = rows - 1
else if x < 0:
dx, dy = 0, -1 # face North (was facing West)
x = 0
else if y < 0:
# at (0,0) walking North - finished!
break
I'm working on Preset 1 for CS50, Mario More Comfortable. I've been trying to compile the below code, but I'm receiving an 'error: expected expression' message. I've checked the spelling, semicolons, brackets, and parentheses, but everything seems in order. Thoughts?
Code:
#include <stdio.h>
#include <cs50.h>
int main(void)
{
// declare h
int h;
// get integer (user input) between 1 and 8, inclusive
do
{
h = get_int("Height: \n");
// if integer is greater than 8 or less than 1, prompt the user again until they enter a valid input
}while(h > 8 || h < 1);
// outer loop uses i to print a row of bricks h times
for (int i = -1; i < h; i++)
{
// inner loop uses j to print a column h times
for (int j = 0; j <= h; j++)
{
// e.g. if 8 + 8 > (8 - 1), print hash; else print blank: right-aligns
if (i + j > (h - 1))
{
printf("#");
}
printf(" ");
// e.g. if 8 + 8 < (8 - 1), print hash; else print blank: left-aligns
else if (i + j < (h - 1))
{
printf("#");
}
}
printf("\n");
}
}
Error message:
error: expected expression
else (i + j < (h - 1))
The expected results of this exercise:
# #
## ##
### ###
#### ####
##### #####
###### ######
####### #######
######## ########
You're having error because of the else if
The if statement is offering to computer to check a condition and proceed with a statement inside the curly braces {}. When you exit from these curly braces and write another statement or expression you basicly leaving behind that condition checking. After that if you want to check a condition, you should use if again. You can use else if right after if statement to check if another conditions is valued.
h = 5;
x = 3;
if (h < x)
printf("h is less than x\n");
x = 10;
if (h < x)
printf("h is less than x\n");
else if (h > x)
printf("h is bigger than x\n);
else
printf("h is equal to x\n");
the program will check the first if condition than evaluate the expression x = 10 then keep reading the next lines and check the second if condition with the new values, then check the else if and later else.
after I've fixed this I've checked your code and it doesn't give the pyramid but square print. If you haven't solved this problem set try to add printf(" "); to print spaces to create pyramid shape. Logic is to decrement the size of spaces while incrementing the size of #'s. If you change your for loop conditions you can achieve the results you want. While you are decrementing the first loop you can increment the nested loop. First loop will print a downward space pyramid while second loop will print a upward # pyramid. Hope make sense.
I have a string like this :
h12pw3Bb4
I want decompressed to :
hhhhhhhhhhhhpwwwBbbbb
for numbers less than 10 i wrote this code but it isn't work for numbers greater than 10
for(int j = 0;j< strlen(txt);j++){
if(isdigit(txt[j])){
int x = txt[j];
x = x - 49;
while(x > 0){
printf("%c" , txt[j-1]);
x--;
}
}else{
printf("%c" , txt[j]);
}
}
See h12 implies print 'h' 12 times right. But you are reading character by character then when '1' is read 1 h will be print and next when 2 is read 2 h's are printed. So based on your code you are not going to achieve what you desire. You need to change it.
So, I think this should help:
int st = 0;
for(int j = 0;j< strlen(txt);) {
int x = 0;
while(j < strlen(txt) && isdigit(txt[j])) {
x = (x * 10) + (txt[j] - '0');
j++;
}
x--;
while(x > 0){
printf("%c" , txt[st]);
x--;
}
if (j < strlen(txt))
printf("%c" , txt[j]);
st = j;
j++;
}
Assumptions :
The first number must be a letter.
Please change them accordingly to your requirements.
Right, with multi-digit numbers you need several iterations of the loop before knowing the value of x.
So personally what I would do is this:
define and initialize two variables int x and char c outside of the loop
in the if block: calculate the value of x (multiplying it by 10 and adding txt[j] - 49 ?)
in the else block: print c x times, reset x to 0, set c to txt[j]
recently i read this topic about generating mazes in c . see here https://www.algosome.com/articles/maze-generation-depth-first.html
and i want to write it in c . here is my code and it's not working right .
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int check[5][5];
int v[5][5];
int border(int x , int y ){
if(x> -1 && x< 6 && y > -1 && y<6)
return 1;
else
return 0 ;
}
int wall[6][6][6][6];
void dfs ( int x , int y){
srand(time(NULL));
int s = 1/*rand() % 4 ;*/ ;
if(s=1 ){
if(border(x ,y-1)&& check[x][y-1]==0){
check[x][y]=1;
wall[x][y][x+1][y]=1;
dfs(x , y-1);
}
else
return ;
}
else if(s=2){
if(border(x+1 ,y)&&check[x+1][y]==0){
check[x][y]=1;
wall[x+1][y][x+1][y+1]=1;
dfs(x+1 , y);
}
else return ;
}
else if(s=3){
if(border(x ,y+1)&&check[x][y+1]==0){
check[x][y]=1;
wall[x][y+1][x+1][y+1]=1;
dfs(x , y+1);
}
else return ;
}
else if(s=0){
if(border(x-1 ,y)&&check[x-1][y]==0){
check[x][y]=1;
wall[x][y][x][y+1]=1;
dfs(x-1 , y);
}
else return ;
}
return ;
}
int main(){
dfs( 4, 4);
for(int i =0 ; i < 6 ; i++)
for (int j =0 ; j < 6 ; j++)
for ( int h =0 ; h <6 ; h++)
for (int k =0 ; k < 6 ; k ++)
printf("%d \n" , wall[i][j][h][k]);
return 0 ;
}
i invert my table to graph , and i want to show me the coordinates of my walls .
what's the problem ?
You have several errors – programming errors and logic errors – in your code:
When you distiguish between the directions the s=1 and so on should be s == 1. You want a comparison, not an assignment. (Your code is legal C, so there is no error.)
You call srand at the beginning of dfs, which you call recursively. This will make your single (commented) rand call always create the same random number. You should seed the pseudo random number generator only once at the beginning of main.
You can store the paths the way you do, but it is wasteful. There are only four possible paths from each cell, so you don't need an array that allows to create a path between (0,0) and (3,4), for example.
Your code would benefit from using constants or enumerated values instead of the hard-coded 5's and 6's. This will allow you to change the dimensions later easily.
But your principal error is in how you implement the algorithm. You pick one of the for directions at random, then test whether that direction leads to a valid unvisited cell. If so, you recurse. If not, you stop. This will create a single unbranched path through the cells. Note that if you start in a corner cell, you have already a 50% chance of stopping the recursion short.
But you want something else: You want a maze with many branches that leads to every cell in the maze. Therefore, when the first recursion returns, you must try to branch to other cells. The algorithm goes like this:
Make a list of all possible exits.
If there are possible exits:
Pick one exit, create a path to that exit and recurse.
Update the list of possible exits.
Note that you cannot re-use the old list of exits, because the recursion may have rendered some possible exits invalid by visiting the destination cells.
Below is code that creates a maze with the described algorithm. I've used two distinct arrays to describe horizontal and vertical paths:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
enum {
W = 36, // width of maze
H = 25 // height of maze
};
enum {
North,
East,
South,
West,
NDir
};
char visited[H][W];
char horz[H][W - 1]; // horizontal E-W paths in the maze
char vert[H - 1][W]; // veritcal N-S paths in the maze
/*
* Fill dir with directions to unvisited cells, return count
*/
int adjacent(int dir[], int x, int y)
{
int ndir = 0;
if (y > 0 && visited[y - 1][x] == 0) dir[ndir++] = North;
if (x < W - 1 && visited[y][x + 1] == 0) dir[ndir++] = East;
if (y < H - 1 && visited[y + 1][x] == 0) dir[ndir++] = South;
if (x > 0 && visited[y][x - 1] == 0) dir[ndir++] = West;
return ndir;
}
/*
* Traverse cells depth first and create paths as you go
*/
void dfs(int x, int y)
{
int dir[NDir];
int ndir;
visited[y][x] = 1;
ndir = adjacent(dir, x, y);
while (ndir) {
int pick = rand() % ndir;
switch (dir[pick]) {
case North: vert[y - 1][x] = 1; dfs(x, y - 1); break;
case East: horz[y][x] = 1; dfs(x + 1, y); break;
case South: vert[y][x] = 1; dfs(x, y + 1); break;
case West: horz[y][x - 1] = 1; dfs(x - 1, y); break;
}
ndir = adjacent(dir, x, y);
}
}
/*
* Print a map of the maze
*/
void map(void)
{
int i, j;
for (i = 0; i < W; i++) {
putchar('_');
putchar('_');
}
putchar('\n');
for (j = 0; j < H; j++) {
putchar('|');
for (i = 0; i < W; i++) {
putchar(j < H - 1 && vert[j][i] ? ' ' : '_');
putchar(i < W - 1 && horz[j][i] ? '_' : '|');
}
putchar('\n');
}
}
int main()
{
srand(time(NULL));
dfs(0, 0);
map();
return 0;
}
You can test it here. If you replace the while in dsf with a simple if, you get more or less what you implemented. Note that this creates only a single, usually short path.
i have an assignment to do a right angle triangle with an odd number (user gives us what number) and to make it to the right
example if user gives us 5:
*****
***
*
i can use only stdio.h
where am i wrong ?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(){
int x,i,y=0;
printf("select odd number:\n");
scanf("%d", &x);
for (i=x ; (i <= x)&&(i>0); i=i-2){
for (y; y > 0; y=y-2){
printf("_");
}
for (x; x >= 0; x-=2){
printf("*");
}
x = x - 2;
printf("\n");
}
return 0;
}
Your outer loop is testing against x but within that you are again using x as a loop variable and when that loop ends you are setting x less than 0 with x = x - 2. So the outer loop condition isn't going to work.