I have written a first version of hangman. The game will be completed later, when this part of code will work.
The code:
#include <stdio.h>
#include <conio.h>
int main()
{
char word[]={"name"};
char word0[]={"----"};
char lett;
int i;
int c;
int e=0;
while(e<12)
{
gotoxy(2,2);
printf("\n%s\n",word0);
scanf("%c",&lett);
for(i=0,c=0;i<4;i++)
{
if(lett==word[i])
{
word0[i]=word[i];
c++;
}
}
printf("%d",c);
if(c==0)
{
e++;
printf("%d",e);
}
}
printf("You lose");
getchar();
}
The program ends before I make 12 errors and prints two values per cycle (not 1, which it should do) which don't coincide with the actual number of errors. Why?
The second 'cycle', as you call it, is reading the newline character. Try changing your scanf to this:
scanf("%c\n",&lett);
The second entry you get is the new line when you press, says, "a", then "Enter". The "Enter" is a new char which is then processed by your program.
Instead of using scanf("%c",&lett);, use scanf(" %c",&lett); (with a space before the '%' => this will ignore any spaces, new lines, etc.
Some minor changes make the code work.
Note that I had to change the I/O a bit (don't have gotoxy() function, and no interactive input since I was running this on codepad.org). See where the logic of your code is different and you should have your solution.
I added intermediate printf statements so you can follow the flow more clearly - usually a good idea when you are debugging.
Note - you might want to use case insensitive string comparison...
#include <stdio.h>
#include <string.h>
int main()
{
char word[]="name";
char word0[]="----";
char guess[]="bnexacdfm";
char lett;
int i;
int c;
int e=0;
int gi = 0;
while(e<12 && gi < strlen(guess))
{
// gotoxy(2,2);
printf("\n%s\n",word0);
lett = guess[gi++];
printf("you guessed: %c\n", lett);
// scanf("%c",&lett);
for(i=0,c=0;i<4;i++)
{
if(lett==word[i]) // really want case insensitive comparison here
{
word0[i]=word[i];
printf("found %c at position %d\n", lett, i);
c++;
}
}
printf("Number correct in this guess: %d\n",c);
if(c==0)
{
e++;
printf("Total number of incorrect guesses: %d\n",e);
}
}
if(strcmp(word, word0)==0) {
printf("well done! you win\n");
}
else {
printf("Sorry - you lose\n");
}
return 0;
// getchar();
}
Output:
----
you guessed: b
Number correct in this guess: 0
Total number of incorrect guesses: 1
----
you guessed: n
found n at position 0
Number correct in this guess: 1
n---
you guessed: e
found e at position 3
Number correct in this guess: 1
n--e
you guessed: x
Number correct in this guess: 0
Total number of incorrect guesses: 2
n--e
you guessed: a
found a at position 1
Number correct in this guess: 1
na-e
you guessed: c
Number correct in this guess: 0
Total number of incorrect guesses: 3
na-e
you guessed: d
Number correct in this guess: 0
Total number of incorrect guesses: 4
na-e
you guessed: f
Number correct in this guess: 0
Total number of incorrect guesses: 5
na-e
you guessed: m
found m at position 2
Number correct in this guess: 1
well done! you win
Link to code sample: http://codepad.org/56dC0stD
Related
I study in school c programming and I have this assignment to find 3 bugs in this code. I just can't find any! It all seems to work just fine...
maybe I should also mention that I have been studying for about only 2 months.
This is the code:
#include <stdio.h>
#include <stdlib.h>
#define LOWER 0
#define UPPER 172486
/*
Bug Report:
1.
2.
3.
*/
void welcome(void);
void useage(void);
void getNumber(void);
void printTwice(int number);
int main(void)
{
welcome();
return 0;
}
/*
This function prints "welcome".
input: none
output: none
*/
void welcome(void)
{
printf("Welcome to my cool program!\n");
useage();
}
/*
This function prints what the program is for.
input: none
output: none
*/
void useage(void)
{
printf("My program gets a number from you - and prints it twice in a row!\n");
getNumber();
}
/*
The function gets a number.
input: none
output: none
*/
void getNumber(void)
{
printf("Please enter a number between 0 - 172,486: \n");
int number = 0;
scanf("%d", &number);
while(number < LOWER || number > UPPER)
{
printf("Invalid choice!\n");
scanf("%d", &number);
}
printTwice(number);
}
/*
Prints the number twice.
input: the number we got from the user.
output: none
*/
void printTwice(int number)
{
printf("The number twice in a row: %d%d", number, number);
}
Issues:
1.
No warning for entering strings instead of numbers. 00 will be printed.
2.
printf("The number twice in a row: %d%d", number, number);
No space between numbers, no line termination
Proposed change:
printf("The number twice in a row: %d %d\n", number, number);
you enter a number and the program will find if the number is prime or not
so when I enter the number 7 for the first time it will show you 'the number is prime'
then I enter 8 and it will show you 'the number is not prime'
after that I re_enter the number 7 and it will show you 'the number is not prime'
I don't know where is the problem
please help me
an example photo from here
and my code is :
#include <stdio.h>
#include <stdlib.h>
int main (void){
int n;
int t;
int isPrime=0;
char var;
while(var!='q'){
printf("q=quit p=prime :");
fflush(stdin);
scanf("%c",&var);
if(var=='p'){
printf("plz put the number value :");
scanf(" %d",&n);
for(t=2;t<=n/2;t++){
if (n%t==0){
isPrime=1;
break;
}
}
if(isPrime==0){
printf("%d is a prime number\n",n);
}
else{
printf("%d is not a prime number\n",n);
}
}
else if(var=='q'){
printf("thank you bye\n");
break;
}
else{
printf("a wrong letter\n");
}
}
return 0;
}
You need to set isPrime to 0 each time the user enters a number. Otherwise, it still holds the value from the previous number.
Move the variable declaration
int isPrime = 0;
inside the while loop.
BTW, isn't that variable name backwards? You set it to 1 (i.e. true) when you discover that there's a number that divides it equally. But that's when the number is not prime.
You forgot to reset isPrime back to zero inside the "while" loop.
By they way, looks like you are doing this as a learning exercise. That's good, there's no better way to learn than to try things out.
Here's a tip in C, any non-zero value is treated as "true", and zero is treated as "false". So instead of this:
if (myFlag==1) { ... do something }
Just write this:
if (myFlag) { ... do something }
I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}
Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.
EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.
EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
1. You never initialized i (it has indeterminate value - local variable).
2. You never call function is_prime.
And using a loop will be good idea .Comparing to what you have right now.
I just modified your function a little. Here is the code
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
Explanation-
In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don't want to check anymore. So, it will exit the loop.
In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).
If you have any doubts, let me hear them.
I suggest you start with trial division. What is the minimal set of numbers you need to divide by to decide whether a is prime? When can you prove that, if a has a factor q, it must have a smaller factor p? (Hint: it has a prime decomposition.)
Some errors your program had in your prime finding algorithm:
You start the loop with number 1 - this will make all numbers you test to be not prime, because when you test if the modulo of a division by 1 is zero, it's true (all numbers are divisible by 1).
You go through the loop until a, which modulo will also be zero (all number are divisible by themselves).
The condition for a number to be prime is that it must be divisible by 1 and itself. That's it. So you must not test that in that loop.
On main, the error you're getting (control reaches end of non-void function) is because you declare main to return an int.
int main(void)
And to solve that, you should put a return 0; statement on the end of your main function. Bellow, a working code.
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b;
for (b = 2; b < a; b++) {
if (a % b == 0)
return (0);
}
return 1;
}
int main(void)
{
int c, answer;
printf
("Please enter the number you would like to find is prime or not= ");
scanf("%d", &c);
answer = prime(c);
if (answer == 1) {
printf("%d is a prime number \n", c);
} else {
printf("%d is not a prime number\n", c);
}
return 0;
}
On a side note, don't use the CAPSLOCK to write full sentences. Seems like you're yelling.
Mathematically the maximum divisor of a number can be as a large as the square of it, so we just need to loop until sqrt(number).
A valid function would be:
//Function that returns 1 if number is prime and 0 if it's not
int prime(number) {
int i;
for (i = 2; i < sqrt(number); i++) {
if (a % i == 0)
return (0);
}
return 1;
}
#include<stdio.h>
int main()
{
int n , a, c = 0;
printf ("enter the value of number you want to check");
scanf ("%d", &n);
//Stopping user to enter 1 as an input.
if(n==1)
{
printf("%d cannot be entered as an input",n);
}
for(a = 2;a < n; a++)
{
if(n%a==0)
{
c=1;
break;
}
}
if(c==0 && n!=1)
{
printf("%d is a prime number \n",n);
}
else
{
if(c!=0 && n!=1)
{
printf("%d is not a prime number \n",n);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i;
printf("enter the number : ");
scanf("%d",&x);
for ( i=2; i<x;i++){
if ( x % i == 0){
printf("%d",x);
printf(" is not prime number ");
printf("it can be divided by : ");
printf("%d",i);
break;
}[this is best solution ][1]
}
if( i>=x) {
printf("%d",x);
printf(" is prime number");
}
}
I wanted to print the divisors of given range of numbers. It works alright. But when I try to modify it to put **** at the end of the prime number's divisors it acts like bizarre.
#include <stdio.h>
int main()
{
int a,start,rounds,b,c,k=0;
printf("Please enter a number to start :");
scanf("%d",&start);
printf("Please enter how many numbers you want to print from that number :");
fflush(stdin);
scanf("%d",&rounds);
for(a=start;a<=start+rounds;a++)
{
printf("\n\nThe divisors of number :%d are \n",a);
for(b=1;b<=a;b++)
{
c=a%b;
if(!c)
{
k++;
printf("%d\n",b);
}
}
//printf("%d",k);
if((k==2)||(k==1))
printf("***\n");
}
getchar();
return 0;
}
PS:- The trick I used to find a prime number is counting how many printf statement has been executed before loop ends. Is there any wrong with it? When I remove // from printf statement it prints like below.
start=========>k
1 =========>1
2 =========>3
3 =========>5
4 =========>8
5 =========>10
Why is that?
if((k==2)&&(k==1))
There is no way in todays computers that k can be 2 and 1 at the same time. Maybe you meant to say if k is 2 OR k is 1 ?
You need to reset k back to 0 in your outer loop
printf("\n\nThe divisors of number :%d are \n",a);
k = 0;
(And, as others have pointed out, you need an || operator rather than && for the final test)