program that tells if a number is prime - c

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 }

Related

Guessing Game in C programming

I built a guessing game in C programming using while loop, and I am having a problem with it during execution. So, when I print a number less than the guess number or greater than the guess number, I get the correct answer. But when the user enters the right answer, the screen shows the statement for the greater number "The number you entered is greater than the Secret Number." and then it shows the right statement below this "This is the secret Number." I think the problem could be because else statement does not define the condition for greater number but I am not sure how to solve this. Can somebody help me?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Guessing game
const int SecretNum = 4;
int guess;
while (guess != SecretNum){
printf("Enter a number: ");
scanf("%d", &guess);
if (guess < SecretNum){
printf("The number you entered is less than the Secret Number. \n");
} else printf("The number you entered is greater than the Secret Number.\n");
}
printf("This is the secret number.\n");
return 0;
}
You think the problem could be because else statement does not define the condition for greater number, so you should add that.
Also you have to initialize guess before using its value.
Formatting your code using indent properly is another important portion.
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Guessing game
const int SecretNum = 4;
int guess = !SecretNum; /* initialize guess : guess will be different value from SecretNum using this */
while (guess != SecretNum){
printf("Enter a number: ");
scanf("%d", &guess);
if (guess < SecretNum){
printf("The number you entered is less than the Secret Number. \n");
} else if (guess > SecretNum) /* add condition */
printf("The number you entered is greater than the Secret Number.\n");
}
printf("This is the secret number.\n");
return 0;
}

Loop does not run more than once

The output should print the statement "Case #(N): I will become a good boy." a certain number of times depending on user input. It should only print prime numbers of N. This is the latest attempt.
#include<stdio.h>
int main(){
int primeNum;
int primeCount;
int primeCheck;
int caseCount=1;
int caseCheck;
scanf("%d", &caseCheck);//gets number of cases
do {
scanf("%d", &primeNum);
primeCheck = 0;
if (primeNum<=1)
{
caseCount++;
}
for (primeCount=2 ; primeCount<=primeNum/2 ; primeCount++)//checks if number is prime
{
if ((primeNum%primeCount) == 0)//checks if number is not prime
{
primeCheck=1;
}
}
if (primeCheck==0)
printf("Case #%d: I will become a good boy.\n", caseCount);//prints if number is prime
} while (caseCount=caseCheck);//while case counter does not exceed number of cases
return(0);}`
The result of this piece of code when the output is 2 [enter] 4 [enter] 2 is "Case #2: I will become a good boy." Why does it not print more than one time and start from number 2?
Just change while (caseCount=caseCheck); to while (caseCount==caseCheck);
The problem with your code is you're not checking the condition. You're just reassigning a value to a variable.

C Program to find prime number

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

Bug in a simplified (and incomplete) version of hangman game

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

Finding prime numbers is giving me errors

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)

Resources