Prime Number Check 1-100 (C) [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
The code below is to read input from the user to check if an int [1-100] is a prime number or not. (If out of range, will print "Done). If non prime, will output that to the console and the number divisible.
Right now this program is running correctly for 1-10 except for 3 and 9... Any suggestions?
#include <stdio.h>
int main()
{
int num, i;
printf("Number [1-100]:? \n");
scanf("%d", &num);
while(num>0 && num <101)
{
if (num==1||num==2)
printf("Prime\n");
for (i=2; i<=num/2; ++i)
{
if (num%i==0)
{
printf("Non-prime,divisible by %d\n",i);
break;
}
else {
printf("Prime\n");
break;
}
}
printf("Number[1-100]:? \n");
scanf("%d",&num);
}
printf("Done\n");
}

First, make sure your code has appropriate whitespace. This will help you realize when things aren't lined up like you think they are.
#include <stdio.h>
int main()
{
int num, i;
printf("Number [1-100]:? \n");
scanf("%d", &num);
while(num>0 && num <101){
if (num==1||num==2)
printf("Prime\n");
for(i=2; i<=num/2; ++i)
{
if (num%i==0)
{
printf("Non-prime,divisible by %d\n",i);
break;
}
else {
printf("Prime\n");
break;
}
}
printf("Number[1-100]:? \n");
scanf("%d",&num);
}
printf("Done\n");
}
Now you should realize that your else statement happens on the first check! So when 3 is not divisible by 2, it prints "prime."
And then it breaks out of the loop.
And this happens for EVERY number. All your program is doing is checking to see if numbers are divisible by 2.
If you wrote "Odd" instead of "Prime" it would at least be correct there.
This is the kind of problem where setting a flag might be useful (there are other ways to do this, but this is one way).
So you could set a flag, say int isPrime = 1;
Now, if you find out that the number is not prime, you simply set isPrime = 0;.
Finally, at the end of the for loop (let me repeat: AFTER the for loop finishes), you need to check that variable.
And you can say,
if (isPrime == 1)
{
printf("Prime\n");
} else
{
printf("Non-prime.");
}
I'll let you figure out how to print the divisor :)
(For reference, correctly using the flag would look like this -- and for clarity I removed the 'feature' in which it continuously looped)
#include <stdio.h>
int main()
{
int num, i;
int isPrime = 1;
printf("Number [1-100]:? \n");
scanf("%d", &num);
for(i=2; i<=num/2; ++i)
{
if (num%i==0)
{
isPrime = 0;
break;
}
}
if (isPrime == 1)
{
printf("Prime\n");
} else
{
printf("Non-prime.");
}
printf("Done\n");
}

The reason why 3 is behaving differently is that the for logic never reaches 3. For "(i=2; i <= num/2; ++i)", if num equals 3, then the i (being 2) is no longer less than 3/2, which is 1 (after rounding off). So, you should add "num==3" check to the "if (num==1||num==2)".

You're not checking the entire range between 2 and num/2. You need a while loop and a prime flag.
Something like this.
while(num>0 && num <101)
{
unsigned char prime = 1; // set prime flag
i = 2;
while( i < (num/2)+1)
{
if(num%i == 0)
prime = 0;
i++;
}
if(num == 1)
prime = 0;
if(prime == 0)
printf("%d is nonprime\n", num);
else
printf("%d is prime\n", num);
prime = 1;
printf("Number[1-100]:? \n");
scanf("%d",&num);
}

Related

a C program that reads a sequence of numbers and display a message [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
The program should have the following guidelines:
The numbers are read from the standard input.
The first number is the length of the sequence (n) followed by n numbers.(ie, if you put '54321' the length of the sequence is 5 numbers)
If n is 0 or negative, the program displays the message “Error_1” followed
by a new line on the standard input.
If the length is shorter than n, it displays “Error_2” followed by a new line and quits.
I'm finding point number 2 difficult
My code is:
#include <stdio.h>
int main() {
int i,j,k;
printf("Enter a Number:\n");
scanf("%d", &i);
if (i <= 0 ) {
printf("Error_1\n");
} else if(){
printF("Error_2\n")
}
}
#include <stdio.h>
int main() {
int i,j,k;
printf("Enter a Number:\n");
scanf("%d", &i);
if (i <= 0 ) {
printf("Error_1\n");
} else{
scanf("%d",&j);
k=0;
while(j>0)
{
k++;
j=j/10;
}
if(k<i)
printf("Error_2\n");
}
}
so what i did was, i found out the length of number entered and if the length does not match with provided length , it prints error2. i found out the length by continously dividing the number by 10 till it becomes 0.
Check this out. You can use log base 10 to compute the length of the sequence. Easier and clener.
To compile the code use -lm flag.See the following command:
gcc sampleFilename.c -lm
#include <stdio.h>
#include<math.h>
int main() {
int i,num, length;
printf("Enter a Number:\n");
scanf("%d", &i);
if (i <= 0 ) {
printf("Error_1\n");
}
else{
printf("Enter the number: ");
scanf("%d",&num);
length=(int) log10(num)+1;// compute the length of the number .. read about log10
if (length < i ) //length of the sequence is less than the number 'i'
printf("Error_2\n");
}
}
there is something you have to understand
your code:
"if (i <= 0 ) {
printf("Error_1\n");
} else if () {/* I'm talking about this*/
printF("Error_2\n")
}"
commend: /* its mean else if (its empty!!) you should write condition in the if, what you need to do its just use if and not else or else if
https://www.programiz.com/c-programming/c-if-else-statement*/
currect code below:
#include <stdio.h>
int main()
{
int num,cnt=0;
printf("Enter length: "\n);
scanf("%d", &num);
while(num > 10) //checking first number
{
cnt++;
num /= 10;
}
if(num <= 0)
{
printf("Error_01\n");
}
if(num == (count + 1)!)
{
printf("Error_02");
}
return 0;
}
Try this below code,
Hope this will work
#include <stdio.h>
int main()
{
int i,j,k;
printf("Enter any number: \n");
scanf("%d", &i);
k = 0;
if(i <= 0)
{
printf("Error_01\n");
}
printf("Enter value number: \n");
scanf("%d", &j);
while(j != 0) // check till first digit
{
k++;
j /= 10;
}
if(k != i)
{
printf("Error_02\n");
}
return 0;
}
by the way this was referred from
https://codeforwin.org/2016/10/c-program-to-count-number-of-digits-in-number.html

Guessing game in C, cannot get the number of tries to work, variable is "counter" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Not too sure how to make the counter variable work to count how many tries it takes to guess the number right. Ive tried putting "counter++;" in each if statement but that doesn't do anything. This is my first code that I've written by myself so don't drag it too hard please <3
int main()
int counter
{
int num , guess;
counter = 0;
srand(time(0));
num = rand() % 200 + 1;
printf ( "Guessing game, guess the number between 1 and 200" );
do {
scanf ( "%d" , &guess);
if ( guess > num ){
printf ( "Too high" );
}
if ( guess < num ){
printf ( "Too low" );
}
if ( guess == num ){
counter++;
printf ( "Your guess is correct!, it took you %d tries" , counter );
}
}while (guess != num);
return 0;
}
You only increment counter when the user guesses correctly. You should instead increment it for every try.
There are syntax errors in your program. Here is a corrected version:
#include <stdio.h>
int main() {
int counter = 0;
int num, guess;
srand(time(0));
num = rand() % 200 + 1;
printf("Guessing game, guess the number between 1 and 200");
while (scanf("%d", &guess) == 1) {
counter++;
if (guess > num) {
printf("Too high\n");
}
if (guess < num) {
printf("Too low\n");
}
if (guess == num) {
printf("Your guess is correct! it took you %d tries\n", counter);
return 0;
}
}
printf("Invalid input\n");
return 1;
}

Optimization with coding [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a program for prime numbers but I need to optimize it. Any hints?
int num, i, count = 0;
printf("Type a non-negative integer:\n");
scanf("%d", &num);
if((num%2 == 0 )&& (num != 2)||(num == 1)){
printf("%d is not a prime number.\n", num);
} else if(num == 2){
printf("%d is a prime number.\n", num);
} else {
for(i = 3; i < num; i += 2){
if(num%i == 0){
count++;
break;
}
}
if(count == 0){
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
}
}
You only need to check up to the square root of num. See testing primes for some more hints.
I think this is one of the basic problems that you might solve it yourself!
I can help you to solve this problem; first start with having a look to the prime numbers definition:
A prime number is a number that is only diviible by 1 and itself.
Assume that we name it N then N is only divisible by 1 and N, and the number 1 is not prime.
So the idea is:
1 - if number is 1 is not prime !
2 - if number is 2 is prime
3 - else ----> we initialize i = 2 , then start calculating the value of N%i; if it is 0 the number is not prime, otherwise we must increment i by 1.
We do step 3 until i<N (or i<=sqrt(N) )
If the number is not divisible by any i, then it is prime!
Here is a simple implementation:
int n ;
printf("enter n:");
scanf("%d",&n);
if(n<=1) printf("is not prime");
else if(n==2) printf("is prime");
else{
bool flag = true;
for(int i = 2 ; i < n ; i++)
if( n%i==0 ){
flag = false;
break;
}
if(flag) printf("is prime");
else printf("is not prime");
}
There is a better algorithm to find a series of prime numbers; I think it's better to learn it:
Sieve of Eratosthenes
I hope this tutorial helps you to find out what is a prime number.

what is wrong with this code? (to check whether a given number is a prime number) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
#include <stdio.h>
#include <conio.h>
void main() {
int a, n, x;
clrscr();
printf("enter a number");
scanf("%d", &a);
n > 1;
a != n && n < a;
if (a / n == x)
printf("a is not a prime no");
else
printf("a is a prime no");
}
If I run this and put a composite number, it still shows it as prime.
your if statement is never true duo to n and x are not initialized. Therefore you only get your else as return. Moreover your expression n>1; and a != n && n < a; return a bool which is not compered to anything. In that case you need to use a for loop.
Here is a link About for loops
int main()
{
int a,n,x = 0;
printf("enter a number: ");
scanf("%d",&a);
for(n=2; n<=a/2; ++n)
{
if(a%n==0)
{
x=1;
break;
}
}
if (x==0)
printf("",n);
else
printf("a is not a prime no");
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();//clearing the screen
int n,x=2,count=0;//Here count is initialised to 0,if it is not prime it remains the same,else it will be equal to 1.You will understand this as you go down
//A number is a prime number if it is not divisible by any other number from 2 and the number before it.
printf("Enter a number : ");
scanf("%d",&n);
while(x<n)//As this checking process should continue till the number just preceding it
{
if(n%x==0)//checking if the number n is divisible by x or not
{
count++;//IF divisible,there is no meaning in continuing,So we are coming out of the loop by incrementing the variable "count"
break;
}
else
x++;
}
if(count==0)
{
printf("%d is a prime number",n);
return 0;//Here if number is prime,There is no need to go further and execute till end,To reduce time complexity ,We will write a return statement to stop executing the code.
}
printf("%d is not a prime number",n);
return 0;
}

C programming about scanf and array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I try to make this program when I enter 3 5 2 5 5 5 0
=>
Enter numbers: 3 5 2 5 5 5 0
The largest number is 5
The occurrence count of the largest number is 4
int main()
{
int a[10];
int i,max, count;
printf("Enter numbers: ");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
max=a[0];
count=1;
for(i=1;i<10;i++)
{
if(max<a[i])
{
count = 1;
max = a[i];
}
else if(max==a[i])
{
count++;
}
}
printf("The largest number is %d\n",max);
printf("The occurrence count of the largest number is %d",count);
return 0;
}
It is my code, but it is totally wrong..
I don't know what should I do
please help me
You've got several errors.
In your first loop, you want to read into a[i], not a[10].
Your code corrently assumes you always type in 10 numbers. It looks like you wanted a value of 0 to end the list. Me, I'd use end-of-file to end the list. To check for 0 you need an extra line if(a[i] == 0) break; in the loop. To check for EOF (or other non-numeric input which will cause problems) you could check to see that scanf returns 1.
In case you enter less than 10 numbers, you'll need a new variable that knows how many variables you actually entered. I set nn = i after the first loop.
Then you just need to change the second loop to run from 1 to nn, not 10.
Putting this all together, we have:
#include <stdio.h>
int main()
{
int a[10];
int i,max, count, nn;
printf("Enter numbers: ");
for(i=0;i<10;i++)
{
if(scanf("%d",&a[i]) != 1) break;
if(a[i] == 0) break;
}
nn = i;
max=a[0];
count=1;
for(i=1;i<nn;i++)
{
if(max<a[i])
{
count = 1;
max = a[i];
}
else if(max==a[i])
{
count++;
}
}
printf("The largest number is %d\n",max);
printf("The occurrence count of the largest number is %d\n",count);
return 0;
}
This seems to work.
Code is OK other than the user needs to enter 10 numbers.
There is no need to store previous numbers, so code can simply examine each new number until '\n' is encountered. Just keep look for the end-of-line before looking for the number.
#include <limits.h>
#include <stdio.h>
#include <ctype.h>
int main(void) {
int count = 0;
int max = INT_MIN;
printf("Enter numbers: ");
for (;;) {
int ch;
int num;
while (isspace(ch = fgetc(stdin)) && ch != '\n') {
;
}
if (ch == '\n' || ch == EOF) break;
ungetc(ch, stdin);
if (scanf("%d", &num) != 1) break;
if (num >= max) {
count++;
if (num > max) {
max = num;
count = 1;
}
}
}
printf("The largest number is %d\n", max);
printf("The occurrence count of the largest number is %d", count);
return 0;
}

Resources