What have you tried to solve this problem?
Adak 419 Nearly a Posting Virtuoso
Adak 419 Nearly a Posting Virtuoso
Adak 419 Nearly a Posting Virtuoso
Adak 419 Nearly a Posting Virtuoso
What have you tried to solve this problem?
Lots of problems with this code:
1) The logic is poor - an endless loop, then a break here, a break there, another break someplace else...
Is this logic for a program, or a Chinese fire drill? ;)
One break, maybe two, OK. Three? No. This is WAY too simple a loop for three breaks.
2) "%2d" is a good format specifier for printf(), but not for scanf(). Delete the 2 from it.
3) After each scanf() lines, add a getchar() to remove the newline char (caused by hitting the enter key), from the keyboard buffer.
That will stop your endless looping (along with #2).
Do while() loops work well for user input:
do {
day = -1;
printf("\n Enter Your Day's Number: ");
scanf("%d", &day);
getchar();
}while(day < 0);
Your for loop has a bad test to end the loop. x will always be greater or equal to zero, so the loop quickly is working outside the array.
for(x=0;x<strlen(title);x++)
should work.
It is more efficient to first, before the for loop, get the length of the string assigned to an int variable, then just use:
len=strlen(title);
for(x=0;x<len;x++)
//rest of code here
because that saves the program from having to measure the length of the string, every time through the loop.
Try to not use <31 or any other inflexible numbers in your code, if possible. Make it so it works with a char array of any length, see?
In the second program, you have this bit of code:
char *a,*b;
FILE *fp,*fp1;
fp=fopen("int.txt","r");
fp1=fopen("obj.txt","w");
getsym_op();
while(1)
{
fscanf(fp,"%s",a);
Looks to me like you're assigning a string to a, but a is a pointer (not an array as you've used before with the same name), and a has been given no valid address yet.
I would NEVER have a char array and a char pointer, in the same program, using the same name - for heaven's sake. :(
Also, you use feof(), which doesn't work as you'd expect. Better to use the return you get from fscanf() to know when to break. Better yet, if you're just getting one string per row, use fgets():
while((fgets(buffer, sizeof(buffer), filePointer)) != NULL) {
}
Print out some of these examples, and see if it begins to gel for you. Work with it, a bit. We learn best by doing.
You're welcome. Carry on! ;)
What is your question or problem with this code?
That's not the code I posted for you. If you want to use code that doesn't work, then I can't help you.
That code works fine. Did you paste it in, or just type it?
Did you get the change from <= to just < in the for loop?
Any other problem, you'll have to post your whole updated program, because I tested the above, and it works with your previous code.
Are you getting an error about:
"function should return a value in main()" ?
void main() is not permitted in standard C. Only int main() with a return 0 (if normal), at the end of the function.
So if corect=0 (false), then what does !(false) evaluate to?
Hint: not false, ;)
int width = 7;
Then replace your blank printing loop with:
for(k=width;k>(i*2);k--)
{
printf(" ");
}
Note that the loop above prints just ONE space char, at a time, instead of two space chars, as the current loop you have, does.
if() and while() and for() statements all have a test. The answer to that test will be either zero or non-zero.
A zero answer means the test result evaluated to false. A non-zero answer means the test result evaluated to true.
if(0 < 1) {
printf("\n Zero is less than one"); //statement was true
else
printf("\n Funky arithmetic going on here!"); statement was false
}
With while() statements, the test is right at the top of the loop - which means the loop may never loop at all, if the test evaluates to false.
while(1 < 0) //a false statement
printf("This is impossible!"); //will never get printed
The ! char is the NOT operator (aka negation). Which "flips" the evaluation around.
Take the above, and make sure you understand why they do what they do, in your compiler. Then add the ! in front of them, and see if you understand why it's doing things differently.
Keep in mind that !(true) equals false, and a negative number as the final result, is just as true as a positive number. Only zero evaluates to false.
Other way around, Daredevil. ++*ptr will increment the value that *ptr points to, not the pointer, itself.
And *ptr++ is an increment to the ptr address.
so *ptr++ is *(ptr++) incrementing the ptr address
and ++*ptr means ++(*ptr) and increments the value that *ptr points to.
How does that compare to what you're getting?
That's good. My compiler liked the program, (no errors or warnings), but also ran out of memory.
Empty lines can be detected by:
if(strlen(buffer)< 2)
//line is one char - undoubtedly a newline char: '\n'
break; //or continue; are common
That looks very good!
This is one of the finest examples of Quicksort I've seen. Tested fast, clear, and easy to optimize further, if you wish.
//Quicksort w/o a separate compare or swap function :)
void quicksort(int A[], int lo, int hi) {
int i, j, pivot, temp;
if(lo == hi) return;
i=lo;
j=hi;
pivot= A[(lo+hi)/2]; //change to (lo +(hi-lo)}/2 and re-test
/* Split the array into two parts */
do {
while (A[i] < pivot) i++;
while (A[j] > pivot) j--;
if (i<=j) {
//swap(A, i, j); //this line works fine.
/* Oddly, on large N, using swap() gives the same time, as
using the swap code below */
temp= A[i];
A[i]= A[j];
A[j]=temp;
i++;
j--;
}
} while (i<=j);
if (lo < j) quicksort(A, lo, j);
if (i < hi) quicksort(A, i, hi);
}
Enjoy!
If the compiler's error or warning says the function should return a value, then I'd try and have the function return a value. ;)
Prototype your functions, and make sure the actual function return types, match the return types of your prototypes.
I surely don't like it.
I can see having two returns in a function. One is preferred, but two is OK. Four returns in one function, is not OK.
mid should be set in ONE line of code, outside of the if else statements instead of being inside, in two different places.
if(n < a[mid]) should set max to mid-1, instead of mid. n is, after all *less than*, a[mid].
if(length <2) is unnecessary.
Take a peek at one of the good binary search functions, and compare it, with yours. This forum has some good examples.
His question referred to ++*ptr, not *++ptr.
I can't tell you, but I can tell you how to troubleshoot it:
1) Copy down the EXACT error message, for reference
2) comment out the calls to functions, one by one, until you find out which function is causing the error.
3) going into that function - comment out various lines, one by one, until you figure out exactly what line of code is giving you the error.
4) Check that out as thoroughly as you can
5) Still stuck, post THAT info back here, and we'll be able to help you more.
The troubleshooting described above is a basic programming skill, which you will have to learn - and learn well - if you're going to program.
"one by one" doesn't literally mean just one function or line of code at a time. You might do several at a time, and keep cutting the amount you're commenting out, down by half, each time you re-try.
Similar to a binary search algorithm. Same goal though - find the faulty line of code.
No, I can't tell you, because on my compiler, if:
int n=3;
int *ptr;
ptr = &n;
++*ptr;
printf("\n%d", *ptr);
prints out: 4
So ++*ptr is the same as ++(*ptr).
*ptr++, on the other hand, is the same as *(++ptr) - meaning it does increment the pointer address on my compiler, so the output is usually 0, but conceptually, could be any integer.
When you have an expression to be evaluated, and you're not sure of the precedence for it, explicitly set it up with the right parenthesis's.
Use while((fgets(bufferName, sizeof(bufferName), filePointerName)) != NULL) {
instead.
Testing for the end of the file has become quite unpopular (and deservedly so), for just this reason (among others). Don't use it.
I refuse to answer, on the grounds that you should be enthusiastically TESTING this yourself. ;)
Put down your latte, take 30 seconds, and test it, FCOLoud!
The indentation is (sadly) missing, but I also liked this pseudo code, a lot:
http://www.daniweb.com/forums/post22184.html#post22184
Without indentation to show dominant and subordinate lines of code, I think it fails, but otherwise, it's great.
continue statement is designed for loops (for or while, or do while). Wouldn't make sense to try and use it in an if/else statement.
You can have a "do nothing" in an if statement, however:
if(numberOfApples > 1)
; //nothing gets done
else
printf("\nNo apples here yet!");
Good pseudo code is just structured English or language:
for each apple in the bowl {
if the apple is ripe
remove the core
remove the skin
slice it into 8th's
roll it in cinnamon and sugar
put it into the pie
else
if the apple is green
return it to the bowl
else
throw it out
}
Mine is generally a toss up between BASIC, C and Python. The key thing is that the logic has to be understandable. I'm no pseudocode guru, however. ;) I'm sure your teacher will have a preferred way that he/she wants it done. THAT's the way to do it, as least for now. :D
Sorry Libathos, that sounds a little too virus-like/malware type programming, for me.
"Beware the Dark Side of the Force", Libathos.
This is another of those "your assignment is to eat, but you can't touch the food with anything", kind of an exercise. ;)
Which means the lecturer will have given you hints (maybe subtle, maybe not), about how he/she wants you to proceed with this.
Review your class notes, and remember what those clues were, for a first step.
Second step, is to post up your try at this problem. Be specific about what the problem is that has you, or your program, stumped. "Won't work", on a post from you, won't work with us.
Surprised to still be up, but RL is odd that way.
I don't like the 12 and 6 printing - you can't easily move them to another column on the screen.
If you want your numbers to line up, you should use %2d, instead of %d, with ALL the numbers being printed. Right now, your picture shows the 11 overlapping the 0 in the 10, and 11 is also too far away from the 12. The one is too far away from the 12, also.
The two and the three are in the same column, so move the 3 to the right.
The six is too far away from the seven, and also from the five. You can space it out right without the %2d format, but it is MUCH more difficult.
Make that change and see what it looks like. Run my version, and you should be able to see the differences in spaces (if any exist then), very quickly.
@Rje7, I'm getting beat up by the sandman, so I have to hit the sack. I couldn't work with your program because you have your variables declared all over the function - my compiler won't accept that.
By printing two numbers wide, I meant in a field 2 digits wide, like so:
printf("%2d", 8);
where 8 could be any single or double digit number. That's a neat trick to know for all kinds of formatting output, btw - even works for files.
I'll check back tomorrow. Hit me up if you have any questions.
You defined your struct, and made a pointer to it, but I don't see an actual struct being declared.
Also, scanf() needs a getchar() after each instance, if you want to keep getting char's from it. Need to pull the newline char, off the keyboard buffer.
After working on this problem, I like your code much better than I did before. ;)
Seriously.
I did mine with two while loops, but in my haste, the logic is not as elegant as it could be. For a clock face, I can accept it, though. :D Everything lines up.
#include <stdio.h>
int main() {
int i, j, median, offset, rows, n;
n = 12;
median = 15;
offset = 3;
rows = 7;
printf("\n\n");
i=0;
while(i<4) { //handles the top half of the clock face
for(j=0;j<median-offset;j++) {
putchar(' '); //prints left margin spaces
}
printf("%2d", n); //then the number
if(i==0) {
putchar('\n');
--n; //get ready adjustments
++i;
offset+=3;
continue;
}
for(j=0;j<2*(offset-4);j++) {
putchar(' '); //prints center spaces on clock face
}
printf("%2d\n", i); //and the second number of the row
offset+=3; //get ready for the next loop
--n;
++i;
}//end of while
offset -=rows-1;
while(i<rows) { //handles the lower half
for(j=0;j<median-offset;j++) {
putchar(' '); //first the spaces on the left
}
printf("%2d", n); //then the number
if(i==rows-1)
break;
for(j=0;j<2*(offset-4);j++) {
putchar(' '); //then center spaces
}
printf("%2d\n", i); //and the second number of the row
offset-=3; //and adjust for the next loop
++i;
--n;
}
printf("\n\n\t\t\t press enter when ready");
i = getchar();
return 0;
}
For a square clock (on edge), just keep everything lined up, and allow for ALL the numbers, to have 2 digits, even if they only have one:
As far as a squared off clock face goes I prefer this one:
12
11 1
10 2
9 3
8 4
7 5
6
over the original. The gap between the 6 and 7 is more uniform.
12
11 1
10 2
9 3
8 4
7 5
6
A graphics console is a graphics console, whether in Turbo C or not. The problem becomes the resolution of that graphics console - in Turbo C, the resolution will be rather low, at best, because the graphics drivers available for TC, were all much lower than what we have today.
Still, it's much better than we can do in a text console! ;)
But this looks like it was meant to be done in a text console, and it's a an exercise in using logic, not graphics commands.
So, I'll look at your code, and see what's up with it. Back in an hour, real life stuff to attend to right now.
I have noticed your code uses very little logic, and lots of "magic numbers". Those are numbers just added into code that seem to have come from the sky or by magic. Let's use variables, and logic, and as few magic numbers as possible.
You opened the file for writing. I'm guessing it should be closed before you call CopyFile.
Adding code tags (click on the [code] icon at the top of your editing window), improves your code's readability, greatly.
Obvious errors.
If you want a nice round clock face, you need to work with a graphic mode console, not a text one, and then use math.h to calculate the number of degree's or radians needed between numbers.
If you want a square one like the red one at the top of your post, you can make that, using the text based console, if you work it out right.
What is the problem with getting the output to look like the squared off red numbered one? Is that what you want, or do you want a round (normal) clock face?
You wind up comparing a char, to a string in words - that won't work.
In your call to findchar(), I'd just pass the one word that you will be checking, rather than the array. You seem to be confused about that, so:
words[random_word][] should do.
ARRSIZE sounds wrong, also. You have ROWS and COLS in a 2D array, and the ROWS * COLS equals your array size.
Then you need to step through the word, checking words[random_number]== guess, one char at a time. (incrementing i)
And welcome to the forum! ;)
You read my post, but not really studied it.
Study my previous post, and and this one, and think of your arithmetic. What times what is negative? What times what is positive? How could that be used in your case, as mentioned previously?
I am NOT going to tell you this answer - you would hate that, surely.
if(hint, hint), EITHER the multiplicater, OR the multiplicand, (but not both!) are negative, what will you have to put at the very end of your function, to make the logic correct?
C'mon! ;)
fgets() DOES limit the amount of chars you can put into your buffer, but you never made your collection of chars in your buffer, into a legitimate string - it has no end of string marker.
#include <stdio.h>
int main() {
int i;
char buff[25];
buff[sizeof(buff)-1]='\0'; //setting the end of string marker
fgets(buff, sizeof(buff)-1, stdin);
printf("\n\n%s", buff);
printf("\n\n\t\t\t press enter when ready");
i = getchar();
return 0;
}
When you print a collection of char's that aren't terminated with an end of string marker, you can get a lot more char's than what are actually in your buffer. Tricky, eh? ;)
Welcome to the forum, and PLEASE surround your code with CODE tags (click on the [CODE] icon in the editing window, to get a pair).
Sorry.
char *array[]= {"Lara","Lin","Nitin","Krishna","Sophia"};
Add the asterisk! ;)
You pretty much have it:
char array[]= {"Lara","Lin","Nitin","Krishna","Sophia"};
If you want the names on their own row, then add another dimension to the array:
char array[5][] = { {"Lara"}, {"Lin"}, etc.
Add
#include <string.h>
to the above. My compiler does it automatically, so I forget to add it sometimes.
I wouldn't go that way with your logic. Don't use ascii numbers for your letters, unless you really need to. Use char's for letters, and stick with 'A', 'B', etc., instead - much easier to read and intuitively understand.
A couple things to get figured out:
1) You need to find the largest char to set as your remove char, in case the instructor (or you), wants to do this with a larger string that goes up to 'G' or beyond.
2) You'll need to print up strlen(c)/2+1 rows. So there's an outer for loop.
3) Your inner for loop
#include <stdio.h>
int main() {
int i, j, len;
char c[15] = { "ABCDEFGFEDCBA" };
char remove = 'A';
printf("\n\n%s", c);
len = strlen(c);
for(i=0;i<len;i++) { //find the greatest char
if(c[i] > remove)
remove = c[i]; //set it as the remove char
}
for(i=0;i<len/2+1;i++) { //for each row to be printed
for(j=0;j<len;j++) { //check each char in c[]
if(c[j] == remove) //and if it's the remove char
c[j]=' '; //replace it with a space
}
--remove; //decrement the remove char
printf("\n%s", c);
}
printf("\n\n\t\t\t press enter when ready");
i = getchar(); ++i;
return 0;
}
;)
No nested for loop is needed for figure 1-4. There is a way to do this with nested for loops, but why use more loops, if it doesn't help make the code simpler, faster, or more intuitive?
You need 1 for loop, which counts from 0 up to the largest number of *'s in any of your rows. That's number 3) in my post, above. (This is true for figures 1,2,3 and 4, but not 5 or 6).
Inside that loop, you need an if statement to tell your program whether it should print a space or a *, on this time through the loop.
And that's all you need for figure 1,2,3, and 4. For figure 5 and 6, you need to:
1) print half of the spaces you calculate should be printed for that row
2) print the *'s
3) print a newline - you don't actually have to print the other half of the spaces
Let's look at figure 3:
*
**
***
****
*****
And let's say we have no left side margin, so the * that's closest to the left side, is actually all the way to to the left side.
How would you make this by hand? Probably, you'd say "I've got to have a maximum of 5 *'s, so what I'll do for the first row is press the space bar 4 times, and then print one *.
So mathematically you're saying:
NumberOfSpaces = (Greatest number of *'s in any row - number of *'s in this row.)
Which in this case, (5 *'s), means:
spaces = 5 - 1
for the first row, and:
spaces = 5 - 5
for the last row in figure 3.
That's how I do this by hand, and probably you do about the same. So have your program do it the same way. You have just three variables to consider:
1) spaces before the first *
2) the number of *'s to print on the line.
3) the largest number of *'s to print on any line
That's how you figure out the *'s to print for figure 3 and 4. Do that, and see what you can do with figure 5 and 6 (the Christmas tree shape figures).
Your functions are not really functions, since you put a semi-colon on the end of their first line, in your program.
I've fixed that for you, and made some important notes in this code, for you. The function main() should not be called, inside your program, as noted. Also, all your fig() functions are now drawing the same tree shape.
#include<stdio.h>
#include<conio.h>
//without the void's, your compiler may assume
//that an int is a parameter to the function
//Turbo C does that, among others.
void fig1(void);
void fig2(void);
void fig3(void);
void fig4(void);
void fig5(void);
void fig6(void);
//void exit(); exit is a C word, don't use
//it for the name of a function.
int main()
{
int cho, i;
do {
printf("[1] Figure 1\n");
printf("[2] Figure 2\n");
printf("[3] Figure 3\n");
printf("[4] Figure 4\n");
printf("[5] Figure 5\n");
printf("[6] Figure 6\n");
printf("[7] Exit\n\n");
printf("Enter your choice:");
scanf("%d",&cho);
/* The next line isn't needed, here, if the user is careful
Why do you want it?
Without it, if the user enters a letter, instead of a
number, the program enters an endless loop.
*/
i = getchar(); //"pulls" the newline off the keyboard buffer
if(cho==1)
{
fig1();
}
else if(cho==2)
{
fig2();
}
else if(cho==3)
{
fig3();
}
else if(cho==4)
{
fig4();
}
else if(cho==5)
{
fig5();
}
else if(cho==6)
{
fig6();
}
// else if(cho==7) { //handled by the do while loop
}while(cho != 7);
printf("\n\n\t\t\t press enter when ready");
i = getchar();
++i;
return 0;
}
void fig1(void) //No semi-colon …
TIME is not a variable, TIME is being replaced by the pre-processor, by the digit 5. So the compiler never see's TIME, and knows nothing about it.
You see the results of this 1) because the program is correct and 2) because the program will compile.
The obvious trouble shooting step seems to be to try the sample code from MSDN, just as it is, and then substitute various values for the speed.
For each value, find out if it's working correctly. Record all the values that you test - good or bad. Then use the good values only, as possible speeds for your program to set.
That's the next step for the software portion, but I'm not satisfied with your lack of info from the CD manufacturer. CD drives haven't changed much over the years, so even though your CD drive is old, the manufacturer should be able to tell you what speeds are possible, and how to set them for that speed, in your program.
If you want the answers to this, you're going to have to be aggressive in seeking it out. This isn't the kind of info that a software forum is likely to be able to provide, unless they have someone familiar with low level drivers.
What is the upper range of USHORT on your system? (check limits.h, etc.) Could you be overflowing the upper limit of it, or of the CD drive?
The Cascade feature was the most noticeable feature of Minesweeper. You clicked on one square, and suddenly 5 or 10 or 20 squares were uncovered in front of your eyes, as if by magic.
Since it never uncovers a square with a mine, it added a lot of zip to the game - the game went by faster, especially when playing with a larger number of squares. The pseudo code in green, gave about the clearest description of the logic for the Cascade. I used it to describe the Cascade function, right in my program. Took me two tries to get the logic right, though.
If you have already turned in your program, I believe we can definitely mark this thread as "solved". ;)
I have not yet written the code to mark a mine. That's next.
Good luck with your studies!
I couldn't find my old minesweeper game, so I started a new one. I found this description of the Cascade algorithm helpful, so I used it to help with that logic. I have only tested this function a few times, so I can't say it's OK, just yet.
/*
"
Another interesting detail is the iterative nature of the cascade algorithm.
It is clear that the queue data-structure can be replaced with any container
data-structure. A stack is an obvious choice. Which begs the question: why
the implementors did not use recursion to implement the algorithm?
The use of recursion in this case would have considerably simplified the
algorithm as it would obviate the need for the queue data-structure. The
recursive algorithm would work as follows:
1. If current square is a mine gameover, otherwise uncover square
2. Count mines adjacent to current square
3. If adjacent mine count is zero, uncover all adjacent covered squares
and make a recursive call for every one of them (steps 2-3)
"
*/
void cascade(int row, int col) {
int i, mines, r=row, c=col;
if(grid[row][col].n || grid[row][col].mines)
return;
else {
if(grid[r-1][c].n==9) grid[r][c].mines++; //12 o'clock
if(grid[r-1][c+1].n==9) grid[r][c].mines++; //1:30 o'clock
if(grid[r][c+1].n==9) grid[r][c].mines++; //3 o'clock
if(grid[r+1][c+1].n==9) grid[r][c].mines++; //4:30 o'clock
if(grid[r+1][c].n==9) grid[r][c].mines++; //6 o'clock
if(grid[r+1][c-1].n==9) grid[r][c].mines++; //7:30 o'clock
if(grid[r][c-1].n==9) grid[r][c].mines++; //9 o'clock
if(grid[r-1][c-1].n==9) grid[r][c].mines++; //10:30 o'clock
if(grid[r][c].mines==0) {
grid[r][c].n=1; //open this square
//recursive call for all adjacent squares
cascade(r-1, c); //12 o'clock
cascade(r-1, c+1); //1:30 o'clock
cascade(r, c+1); //3 o'clock
cascade(r+1, c+1); //4:30 o'clock
cascade(r+1, c); …
Check out "floodfill" and "Minesweeper" (the game),on Wikipedia. One of them should have an example of how it works.
A bomb detection game with no bombs being represented?? Say it ain't so! ;)
I will test it. I'm also looking around for my old minesweeper program, but it may have been lost some years in the past.
You always need to have the user be able to quit the game - MAYBE even save the current game; but definitely to quit it.