Mario problem set - why won't the hashes print? - c

I am currently trying to print a pyramid of hashes for the Mario problem set (less comfortable), and they won't print. Would someone be able to look at my code and pinpoint where I am going wrong? Thank you so much in advance.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
int hashes;
int space;
do
{
int height = get_int("height: ");
}
while (height < 0 || height > 5);
{
for (int i = 0; i < height; i++)
{
int hashes = i;
for (hashes = (i + 1); hashes >= height; hashes++)
{
printf("#");
}
}
}
}

Assume you are using CS50 Lab and make to compile. This program will not compile because of shadow variables (as mentioned in the comments by #Weather Vane), and other errors. Therefore, I assume the executable that's running (i.e. ./mario) was the last good compile of an older version of the source that did not print results.
The for loop in this code is an infinite loop. If you correct the compile errors, you will see nothing but #.
Recommend you delete the "old" compiled version (rm mario in the terminal) and then modify the code so 1) it compiles and 2) does not create an infinite loop.
Remember, you declare a variable including the type, as here: int height;. But when you use the variable (as here int height = get_int("height: ");) you do not use the type declaration.

try this code, hope it helps
#include<stdio.h>
#include<cs50.h>
int main(void){
int height ;
do
{printf("height: ");
height = get_int();
}
while(height<0 || height>23);
for(int i=1;i<height+1;i++)
{
for(int j=0;j<height-i;j++)
{
printf("%s"," ");
}
for(int l=0;l<1;l++)
{
printf("#");
}
for(int k=0;k<i;k++)
{
printf("#");
}
printf("\n");
}
}

Related

Implementing a staircase within a C program [duplicate]

This question already has answers here:
How do I check out a remote Git branch?
(42 answers)
Closed 1 year ago.
I just started with C programming and have some difficulty implementing a program which is giving a staircase with 'Height' amount of steps.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
height = get_int("Height: ");
}
while(height > 8 || height == 0 || height < 0);
int width = 0;
int length = height;
while(width < height)
{
printf(" ");
printf("#");
for(width = 0; width < height; width++)
{
printf("\n");
}
}
}
The first lines with the Height are working, but I have difficulties with actually writing a staircase. I wanted something like this or similar to this.
Height: 3
#
#
#
I just want to learn how to implement something like this if I face a problem like this in the future. If somebody could help me further I would really appreciate it!
This works:
#include <stdio.h>
int main() {
// gets height input - replace with your get_int method
int height;
printf("Height: ");
scanf("%i",&height);
// loop over all the steps: 0 - height
for (int i = 0; i < height; i++) {
// add a space i number of times (where i is our current step number and so equal to width)
// notice that if we take top left as (0,0), we go 1 down and 1 right each time = current step
for (int j = 0; j < i; j++) {
printf(" ");
}
// finally, after the spaces add the character and newline
printf("#\n");
}
return 0;
}
I see three issues here:
You're printing newlines (\n) instead of spaces ( ).
Why print the single space character?
You're printing the "#" before (what should be) the spaces.
Print a newline after the spaces and the #.
Also... the staircase's width is always equal to its height; it's just the line you're printing that's advancing... that's a bit confusing.
#include <stdio.h>
int main(void)
{
int height = 5;
for(int i=0; i<height; printf("%*s\n", ++i, "#"));
}
Output:
Success #stdin #stdout 0s 5572KB
#
#
#
#
#

Error in C program (for loops)

void checker(int width,int height){
int horizontal;
int repeat;
int i;
int j;
for(j=1; j<=height; j++){
while(horizontal<=width){
repeat = width/10;
if(horizontal%2){
for(i = 1; i <=repeat; i++)
printf("1");
}
else{
for(i = 1; i <=repeat; i++)
printf("0");
}
horizontal++;
}
printf("\n");
}
}
int main(){
checker(20,10);
return 0;
}
So I'm creating a pattern through C. As you can tell from my code, I'm barely getting the hang of C. As I compile and test this the pattern doesn't print out in 0's and 1's, rather it only prints the \n.
I was wondering why, I might be having a brain fart.
Thank you for the time, it's very appreciated from new comers like me!
Horizontal is not properly initialized. Right now you are using garbage value left in memory. Give horizontal a proper value before trying to use it.
horizontal has not been initialized. unlike some languages, C will not default a non static local variable to 0. It will be just whatever value happens to be in memory.
Change/add line(s):
int horizontal;//not guaranteed to be zero
to
int horizontal = 0;//guaranteed to be zero
Otherwise, this statement may never enter the brackets
while(horizontal<=width){ ...
Also (not required, but maybe nice to have) add this line just after int j;...
...
int j;
if((width < 0) || (height < 0)) return; //prevent negative input values

Trying to write a function to shuffle a deck in C

So all I'm trying to do is take an input from the user of how many cards to use and then randomly assign each card to a different index in an array. I'm having extensive issues getting the rand function to work properly. I've done enough reading to find multiple different ways of shuffling elements in an array to find this one to be the easiest in regards to avoiding duplicates. I'm using GCC and after I input the amount of cards I never get the values from the array back and if I do they're all obscenely large numbers. Any help would be appreciated.
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
void main(){
srand(time(NULL));
int d, c, i, z, l, r;
printf("Enter the deck length: ");
scanf("%d\n ", &c);
int deck[c];
int swap[c];
z = c;
for(l=0; l<c; l++){
swap[l] = l;
}
for(i=z; i=0; i--){
r = rand() / i
deck[i] = swap[r];
for(r; r=(c-1); r++){
swap[r] = swap[(r+1)];
}
}
for(d = 0; d < c; d++){
printf("%d ", deck[d]);
}
return;
}
I can spot one major problem here:
for(i=z; i=0; i--)
^^^
This loop will never execute since you are using assignment(=) and setting i to 0 therefore the condition will always be false, although using equality(==) will still be false in this case, you probably want:
for(i=z; i!=0; i--)
This means you will be using deck unitialized which is undefined behavior. Once you fix that you have a similar problems here:
for(r; r=(c-1); r++){
main has to return int and your return at the end needs to provide a value.
Turning on warning should have allowed you to find most of these issues, for example using -Wall with gcc gives me the following warning for both for loops:
warning: suggest parentheses around assignment used as truth value [-Wparentheses]
Note, see How can I get random integers in a certain range? for guidelines on how to use rand properly.
You basically need to be able to generate 52 numbers pseudo-randomly, without repeating. Here is a way to do that...
First, loop a random number generator 52 times, with a method to ensure none of the random numbers repeat. Two functions in addition to the main() will help to do this:
#include <ansi_c.h>
int NotUsedRecently (int number);
int randomGenerator(int min, int max);
int main(void)
{
int i;
for(i=0;i<52;i++)
{
printf("Card %d :%d\n",i+1, randomGenerator(1, 52));
}
getchar();
return 0;
}
int randomGenerator(int min, int max)
{
int random=0, trying=0;
trying = 1;
while(trying)
{
srand(clock());
random = (rand()/32767.0)*(max+1);
((random >= min)&&(NotUsedRecently(random))) ? (trying = 0) : (trying = 1);
}
return random;
}
int NotUsedRecently (int number)
{
static int recent[1000];//make sure this index is at least > the number of values in array you are trying to fill
int i,j;
int notUsed = 1;
for(i=0;i<(sizeof(recent)/sizeof(recent[0]));i++) (number != recent[i]) ? (notUsed==notUsed) : (notUsed=0, i=(sizeof(recent)/sizeof(recent[0])));
if(notUsed)
{
for(j=(sizeof(recent)/sizeof(recent[0]));j>1;j--)
{
recent[j-1] = recent[j-2];
}
recent[j-1] = number;
}
return notUsed;
}

How to solve error: expected identifier or '('

I've got a problem with something I'm programming.
I get this error over and over;
jharvard#appliance (~/Dropbox/pset1): make mario
clang -ggdb3 -O0 -std=c99 -Wall -Werror mario.c -lcs50 -lm -o mario
mario.c:23:5: error: expected identifier or '('
do
^
mario.c:32:1: error: expected identifier or '('
do
^
2 errors generated.
I searched all over the internet but couldn't find the problem..
removing the ; after int main(void) didn't help
This is my code:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void);
//Ask User for Height, and check
int a, b, rows, height;
int a = 0;
int b = 0;
int rows = 1;
do
{
printf ("Height: ");
height = GetInt();
}
while (height <=0 || height > 23);
//build half pyramid
do
{
do
{
printf("r");
a++;
}
while (a < height - rows);
do
{
printf("#");
b++;
}
while (b < rows + 1);
printf("\n");
rows++;
while (rows <= height);
}
I've been trying to solve this problem for a few days, but i just can't figure it out!
Thank you so much in advance!
int main(void);
You have just declared the main. You need to define it and add the code inside that definition.
int main()
{
.....
}
You got nested loop with do/while. Make sure that each start with do end with while.
Look like at the end of file, the "while" is not correct.
printf("\n");
rows++;
while (rows <= height);
}
That could be you missing the close '}' before 'while (rows <= height);'
Correct code could be:
int main(void)
{
//Ask User for Height, and check
int a, b, rows, height;
a = 0; // <- removed int
b = 0; // <- removed int
rows = 1; // <- removed int
do
{
printf ("Height: ");
height = GetInt();
}
while (height <=0 || height > 23);
//build half pyramid
do
{
do
{
printf("r");
a++;
}
while (a < height - rows);
do
{
printf("#");
b++;
}
while (b < rows + 1);
printf("\n");
rows++;
} // <- add }
while (rows <= height);
}
Main post is edited, so clear answer.
All your code is outside of a function because you're doing int main(); you're declaring a function. Use {} brackets instead.
int main() {
//Code here.
}
int a, b, rows, height;
int a = 0;
int b = 0;
Here in your above statements a and b are re-declared more than once causing compilation error.
Take the last while outside of the do scope:
while (rows <= height);
If you don't indent your code, which you (by all means) should do, at least write the starting and the ending curly brackets at once when you write the loop statement, before putting any code into that loop's body (which goes between the curly brackets). It will save you from troubles like these in the future.
In case of react native project .... its a simple issue.
You can go to you project target in ios and check Build, version and build identifier... they might have extra space on the end which should be removed
Hope it helps. Worked for me

C programming - A array and a random number combined question?

this is the part of my code I'm having trouble with. I can't understand why its doing it wrong. I have an array where it stores numbers 0 - 25 which are cases. The numbers are to be randomized and overwritten into the array. Only condition is is that no number can be doulbes, there can only be one of that number. I'm not asking you to do my code but do hint me or point me in the write directions. I am trying to learn :)
The problem lies within the second do loop. I can get the numbers to be randomized, but I get doubles. I have created a loop to check and fix this, but it's not working. The code does run, and doubles do still happen and I can't see why. It looks correct to me. Please look, thank you (:
This is what I have done originally (at the very end is where I am at now):
int check_double = 0;
int i = 0;
int counter = 0;
int array_adder = 0;
int random_number = 0;
int cases[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26
};
float money[] = {
0.01,1,5,10,25,50,75,100,200,300,400,500,750,1000,5000,10000,25000,50000,750000,100000,200000,300000,400000,500000,750000,1000000
};
//Randomize all case number and realine them in the array
srand ( time(NULL) );
do
{
cases[counter]= rand() % 26;
counter += 1;
printf("%d\n", cases[counter]);
}
while (counter <= 25);
//make sure there are no doubles in the array, just 0 - 25 and not a single number repeated twice
do
{
check_double = 0;
for (i = 0; i < counter; i++)
{
if (cases[counter] == cases[i])
{
cases[counter] = rand()% 26;
check_double == 1;
}
}
}
while (check_double != 0);
Currently, what I had achived after that was combing both loops and check for doubles as the array goes. This is what I made, it still has doubles and im not sure why, I only posted the cose with both loops combined:
do
{
cases[counter]= rand() % 26;
if (cases[counter]>=1);
for(i=0;i<=counter;i++)
if (cases[counter]==cases[i])
{
cases[counter]=rand()% 26;
}
printf("%d\n",cases[counter]);
counter+=1;
}
Robsta, you could try the following piece of code, I have run this in Dev-C++, any changes that you require can be made from your side. But, I assure you that this code generates what you intend.
int check_double = 0;
int i = 0;
int counter = 0;
int cases[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26
};
//Randomize all case number and realine them in the array
srand ( time(NULL) );
do
{
cases[counter]= rand() % 26;
for(i=0;i<counter;i++)
if (cases[counter]==cases[i]){
while (cases[counter]==cases[i])
{
cases[counter]=rand()% 26;
}
i=0;
}
printf("%d\t%d\n",counter,cases[counter]);
counter+=1;
}while (counter <= 25);
If you have any clarifications required, I would love to discuss with you.
-Sandip
You're only ever writing over the last value in the array:
for(i=0;i<counter;i++)
if (cases[counter]==cases[i])
You need to loop through as you are, then have an inner loop, where you compare all the other entries to the current one.
Even easier would be to do the loop where you set each random number, so when you set cases[3] for example, loop from 0 to 2 and check to see if your new value for 3 clashes, if so, wash - rinse - repeat!
You have this line of code:
check_double==1;
That doesn't change check_double because it's ==, not =. == compares; it doesn't assign. Change that line to this:
check_double=1;
A helpful compiler (clang in this example) will give you a warning about this:
test.c:5:14: warning: expression result unused [-Wunused-value]
check_double==1;
~~~~~~~~~~~~^ ~
You can't check for duplicates with a single loop. You need to at least compare every possible pair of elements to be able to see if there's a duplicate. I'm guessing you forgot to loop over counter somewhere inside the second do...while?
Note that your method is not guaranteed to terminate. (Very, very likely but not certain.) Why don't you simply shuffle the cases array? Shuffling is simple but tricky; see Fisher-Yates (or Knuth) Shuffle for a simple algorithm.
If you are asking how to randomly sequence the number 1-25 then you could do something like this. This is a very brute-force way of generating the sequence, but it does work and might give you a starting point for something more optimized.
#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#include <conio.h>
const int LastNumber = 25;
bool HasEmpty(int available[LastNumber][2])
{
bool result = false;
for(int i = 0; i < LastNumber; i++)
{
if (available[i][1] == 0)
{
result = true;
break;
}
}
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
int available[LastNumber][2];
int newSequence[LastNumber];
srand((unsigned int)time(NULL));
for(int i = 0; i < LastNumber; i++)
{
available[i][0]=i;
available[i][1]=0;
}
int usedIndex = 0;
while (HasEmpty(available))
{
int temp = rand() % (LastNumber + 1);
if (available[temp][1] == 0)
{
newSequence[usedIndex++] = available[temp][0];
available[temp][1] = 1;
}
}
for(int i = 0; i < LastNumber; i++)
{
printf("%d\n",newSequence[i]);
}
getch();
return 0;
}

Resources