Write a program to continue to read in positive integers
till a prime is encountered. Assume at least one number will be entered.
Eg.
Please enter #: 8
Please enter #: 9
Please enter #: 10
Please enter #: 11
Thanks you entered a prime, bye.
The main problem that I am having is the continuation until the prime occurs. The code I have to test if the number is prime is here:
// PRIME NUMBER TEST
#include <stdio.h>
int main () {
int number, n, is_prime = 0;
printf("Enter number: ");
scanf("%d", &number);
for (n=2; n<=number/2; n++) {
if (number%n==0)
is_prime = 1;
while(is_prime == 1) {
printf("Enter #: ");
scanf("%d", &number);
}
}
if (is_prime == 0)
printf("%d is a prime number.\n", number);
system("PAUSE");
return 0;
}
I know that it would be a for loop to keep it going and just initializing a counter until the prime occurs, but for whatever reason I just can't get it right. Thanks for the help.
You need to walk though your code and check your invariant for each loop, that is what I mean by my comment of that your for-while loops are inside out....
// PRIME NUMBER TEST
#include <stdio.h>
int main () {
bool is_prime = false;
while(is_prime == false) {
int number, n;
printf("Enter #: ");
scanf("%d", &number); // scanf is not recommended, but use it here anyway
is_prime = true; // we assume so for now, also test for numbers < 2
for (n=2; n<=number/2; n++) // this can be optimized, but leave as is anyway
if (number%n==0)
is_prime = false; // sorry it was not prime
}
printf("%d is a prime number.\n", number);
return 0;
}
Related
I am trying to write a code to accept only odd number. If the number is even, it will ask for another number until an odd number is entered.
If the number is odd, it will continue to run the remaining of the program using that odd value.
I am not sure how to write the syntax for the for loop in this program.
Here is part of the odd number validator code:
#include <stdio.h>
int main()
{
int num;
printf("Enter odd value for n: ");
scanf("%d", &num);
for(num; num % 2 == 0; num)
{
printf("%d is even. TRY AGAIN!: ");
scanf("%d",&num);
}
}
`#include <stdio.h>
int main()
{
int num;
odd: //used label
printf("Enter odd value for n: ");
scanf("%d", &num);
if(num%2==0)
{
printf("%d is even. TRY AGAIN!: \n",num);
goto odd;
}
printf("%d is Odd ",num);
}
I have a program which asks user to enter elements that will be assigned into an array. But i want to check the entered number is whether positive or negative. If there is a negative number program should warn to user and asks user to enter positive numbers again. I wrote my code but it goes into a infinite loop.
How can make it correct?
here is my code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main()
{
int A[MAX] = {};
int n,jj;
printf("How many numbers do you want to enter?\n");
scanf("%d",&n);
for (jj=0; jj<n; jj++)
{
printf(" enter the %d. number\n", (jj+1));
scanf("%d",&A[jj]);
while(A[jj]<=0){
printf("Please enter only positive numbers");
}
}
return 0;
}
For starters this initialization using an empty braced list
int A[MAX] = {};
is incorrect in C. You have to write
int A[MAX] = { 0 };
It is evident that this loop
while(A[jj]<=0){
printf("Please enter only positive numbers");
}
is an infinite loop when A[jj] is not positive. So what you do is what you get.
Instead you could write for example
for (jj=0; jj<n; jj++)
{
printf(" enter the %d. number\n", (jj+1));
do
{
scanf("%d",&A[jj]);
if ( A[jj]<=0 )
{
printf("Please enter only positive numbers");
}
} while ( A[jj] <= 0 );
}
The cause of the infinite loop is due to the use of while(A[jj]<=0)
The problem can be solved in these 2 steps:
read user input into a temporary variable.
Assign the temporary variable to array element, only if the value is positive.
Here is the working code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main() {
int A[MAX] = {};
int n, jj, temp = 0;
printf("How many numbers do you want to enter?\n");
scanf("%d",&n);
for (jj = 0; jj < n; jj++) {
printf("Enter the # %d number : ", (jj+1));
scanf("%d",&temp);
if (temp < 0) {
printf("Negative number will not be accepted. Please try again\n");
--jj;
continue;
}
A[jj] = temp;
}
return 0;
}
Output:
How many numbers do you want to enter?
3
Enter the # 1 number : 1
Enter the # 2 number : -2
Negative number will not be accepted. Please try again
Enter the # 2 number : 2
Enter the # 3 number : 3
i want to take number from user then print if it prime or not but i can't find what is error where result always not prime so what is problem??
#include <stdio.h>
int main(void)
{
int number;
char flag = 0;
printf("Please enter the number:");
scanf("%d",&number);
for (int i = 1; i <= number; i++) {
if (number %i == 0) {
flag = 1;
break;
}
}
if (number==1)
printf("%d neither prime nor not prime", number);
if (flag==1)
printf("%d is not prime",number);
else
printf("%d is prime",number);
return 0;
}
Take a look at the loop condition here:
for(int i=1;i<=number;i++)
With <=, i goes up to number. So the last check will be if(number%number==0), which is always true: your program says that 5 is not a prime number because 5 divided by 5 has remainder 0. The same applies to dividing the number by 1 (which also results in no remainder), so this check should start at 2. This line should be:
for(int i=2;i<number;i++)
Typically i only has to go up to sqrt(number) because no two numbers bigger than the root of number multiplied will result in number.
Also, if the number entered is 1, you get two of the three possible outputs instead of just the first one. To fix this, put an else before the if (flag == 1).
edit to work successfully
#include <stdio.h>
int main(void)
{
int number ;
char flag=0;
printf("please enter the number:");
scanf("%d",&number);
for(int i=2;i<number;i++)
{
if(number%i==0)
{
flag=1;
break;
}
}
if (number==1)
{ printf("%d neither prime nor not prime", number);}
else if (flag==1)
{ printf("%d is not prime",number);}
else
{ printf("%d is prime",number);}
return 0;
}
Just check reminder either it is 0 or 1, if you divide any number in the end it will give you either 0 or 1 in reminder.If reminder is 1 so number is prime or 0 number is not prime.
#include <stdio.h>
int main(void)
{
int number ;
char flag=0;
printf("please enter the number:");
scanf("%d",&number);
if((number>2)&&(number%2==0))
{
flag=1;
}
if (number==1)
{ printf("%d neither prime nor not prime", number);}
if (flag==1)
{ printf("%d is not prime",number);}
else
{ printf("%d is prime",number);}
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");
}
}
a program to get the user to guess the number that the program has picked as the lucky number. It uses one for loop and plenty of if statements. The problem is that my code stops after 2 tries, but suppose to give user 3 tries. Here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int iSecret, iGuess;
srand(time(NULL));
iSecret = rand() % 20 + 1;
int tries = 0;
printf("\nWelcome to the number guessing game!\nFor each game, you have at most 3 chances to guess a secret number from 1 to 20.\n");
for (tries = 0; tries < 3 || iSecret == iGuess; tries++)
{
printf("Please, enter a number between 1 and 20! ");
scanf("%d", &iGuess);
if (iGuess == iSecret)
{
printf("\nCongratulations! You won!");
return 0;
}
else if (iGuess > iSecret)
{
tries++;
printf("\nYour guess was too high.\n");
}
else if (iGuess < iSecret)
{
tries++;
printf("\nYour guess was too low.\n");
}
if (tries == 3)
break;
}
printf("\nYou have reached your third trials. The correct number is %d.\n",
iSecret);
return 0;
}
You are incrementing tries twice: once in the for definition, and also later in the body of the loop.
Remove the extra tries++ statements.
You increment tries inside the code, as well as in the for statement. Strip out the tries++ statements in the if-blocks.
You're incrementing the variable tries multiple times during loop execution,
once every turn and everytime you didn't guess your secret right
for loop already increments tries .. you don't need to do tries++ inside if statements
you don't need the || condition in for loop as you are already doing the check in if statements
here is the fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int iSecret, iGuess;
srand ( time(NULL) );
iSecret = rand() % 20 + 1;
int tries = 0;
printf("\nWelcome to the number guessing game!\nFor each game, you have at most 3 chances to guess a secret number from 1 to 20.\n");
for (tries = 0; tries < 3 ; tries++) {
printf ("Please, enter a number between 1 and 20! ");
scanf ("%d", &iGuess);
if(iGuess == iSecret){
printf ("\nCongratulations! You won!");
return 0;
}
else if (iGuess > iSecret){
printf ("\nYour guess was too high.\n");
}
else if (iGuess < iSecret){
printf ("\nYour guess was too low.\n");
}
}
printf ("\nYou have reached your third trials. The correct number is %d.\n", iSecret);
return 0;
}
Output:
$ ./test
Welcome to the number guessing game!
For each game, you have at most 3 chances to guess a secret number from 1 to 20.
Please, enter a number between 1 and 20! 2
Your guess was too low.
Please, enter a number between 1 and 20! 3
Your guess was too low.
Please, enter a number between 1 and 20! 4
Your guess was too low.
You have reached your third trials. The correct number is 10.
in addition to incrementing tries too many times, the code is overly complicated, you can simplify the logic like
int main ()
{
int iSecret, iGuess;
srand ( time(NULL) );
iSecret = rand() % 20 + 1;
int tries = 0;
printf("\nWelcome to the number guessing game!\nFor each game, you have at most 3 chances to guess a secret number from 1 to 20.\n");
for (tries = 0; tries < 3; tries++) {
printf ("Please, enter a number between 1 and 20! ");
scanf ("%d", &iGuess);
if(iGuess == iSecret) {
printf ("\nCongratulations! You won!");
return 0;
}
printf ( "\nYour guess was too %s.\n", iGuess>iSecret?"high":"low");
}
printf ("\nYou have reached your third trials. The correct number is %d.\n", iSecret);
return 0;
}