I'm working on this program that should output 10 prime numbers. So my problem is that I dont know how to tell the program to stop as soon as 10 prime numbers have been stored in the array. I tried to do sizeof(primes)/siseof(int) == 10 , but its not working.
Help me please. Thanks in advance
int ar[100],primes[10],j,n,i,var;
printf("Enter a prime ,\n");
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
if (IsPrime(ar[i])) {
primes[i] = ar[i];
if( sizeof(primes) / sizeof(int) == 10) break;
} else {
printf("%d is not a prime number\n", ar[i]);
}
}
printf("\narray :\n");
I'm going to pitch something a bit more in line with your stated intention:
#define MAX_PRIMES 10
int main(int argc, char * argv[])
{
int inval;
int primes[MAX_PRIMES];
int count = 0;
printf("Enter a prime number,\n");
while (count < MAX_PRIMES)
{
scanf("%d", &inval);
if (IsPrime(inval))
{
primes[count] = inval;
count++;
}
else
{
printf("%d is not a prime number\n", inval);
}
}
printf("\nThe elements of the array are:\n");
for (int i = 0; i < MAX_PRIMES; i++)
{
printf(" %d", primes[i]);
}
}
int ar[100] was replaced with int inval because there doesn't seem to be any need to store the input values.
for(i=0;i<n;i++) replaced with while (count < MAX_PRIMES) because the previous version would stop at n whether 10 primes had been found or not.
printf(" %d",ar[i]) was replaced with printf(" %d", primes[i]) because the stated desired output is 10 primes, not the input array.
Could be a stupid tyop or two in there because I haven't run it.
Use a counter variable. Use this as the index of the primes array, because otherwise you'll write outside the bounds of the array if the user enters more than 10 numbers to try.
int ar[100],primes[10],j,n,i,var;
int primesFound = 0;
printf("Enter a prime number,\n");
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
if (IsPrime(ar[i])) {
primes[primesFound] = ar[i];
primesFound++;
if( primesFound == 10) break;
} else {
printf("%d is not a prime number\n", ar[i]);
}
}
printf("\nThe elements of the array are:\n");
for(i=0;i<n;i++)
{
printf(" %d",ar[i]);
}
Just add a counter
int ar[100],primes[10],j,n,i,var;
printf("Enter a prime number,\n");
int counter = 0; // here you declare a counter
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
if (IsPrime(ar[i])) {
counter++ // here you increase your counter
primes[i] = ar[i];
if (counter == 10) break;
} else {
printf("%d is not a prime number\n", ar[i]);
}
}
printf("\nThe elements of the array are:\n");
for(i=0;i<n;i++)
{
printf(" %d",ar[i]);
}
Now, why the if( sizeof(primes) / sizeof(int) == 10) break; doesn't work? Because your primes is an array, which is declared statically and so its size is always a constant, which is equal to 10 * sizeof(int).
Related
I wrote up a piece of code to find whether a number is prime or not and here it is.
#include <stdio.h>
void main() {
int i, n;
printf("Enter value for n: ");
scanf("%d", &n);
if (n <= 3) {
printf("It is a prime number");
}
for (i = 2; i < n; i++) {
if (n % i == 0) {
printf("It's not prime number \n");
break;
} else {
printf("It is a prime number \n");
break;
}
}
}
However, when my input is 33, instead of the output printing It's not a prime number, since 33 is divisible by 3 and 11, it prints that It is a prime number.
What is the problem with my code here?
In your code, the first time the for loop is executed it immediately triggers either the if condition or else, then breaks, reaches the end and returns. The loop runs a total of 1 iteration max. Change to the following:
for (i = 2; i <= n / i; i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("It is a prime number \n");
Here the for runs correctly. It checks for all dividends, only then it's over and prints the false condition. Note you can optimize your code and only check up to the square root of n, because after that it can't hit true.
And add a return statement here, because the program is already over and doesn't need to continue:
if (n <= 1){
printf("It's not a prime number");
return 0;
}
if (n <= 3){
printf("It is a prime number");
return 0;
}
This also screens off 0, 1, and negative integers which are not prime numbers.
You almost got it right: you just have to make sure the program exits after having established whether a number is prime.
Also, you can stop the loop at n/i.
Last, but not least: main should return a int.
#include <stdio.h>
int main(void){
int i,n;
printf("Enter value for n: \n");
scanf("%d", &n);
if (n <= 3){
printf("It is a prime number\n");
return 0;
}
for (i = 2; i < n/i; i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("It is a prime number \n");
return 0;
}
There are multiple problems:
void main() should be int main()
you should check the return value of scanf and reject negative numbers
0 and 1 are not considered prime numbers.
you should end the program if the number matches the first test.
you output the result after a single test: it is correct if the test if (n % i == 0) is true as you have found a divisor, but if you have not, you should iterate, testing all possible divisors up to and including floor(sqrt(n)).
Here is a modified version:
#include <stdio.h>
int main() {
int i, n;
printf("Enter value for n: ");
if (scanf("%d", &n) != 1) {
printf("input error, not a number\n");
return 1;
}
if (n < 0) {
printf("number should be positive: %d\n", n);
return 1;
}
if (n <= 1) {
printf("%d is not a prime number\n", n);
return 0;
}
for (i = 2; i < n / i; i++) {
if (n % i == 0) {
printf("%d not prime number (divisible by %d)\n", n, i);
return 0;
}
}
printf("%d is a prime number\n", n);
return 0;
}
You might want to try this:
#include <bits/stdc++.h>
int main(){
int i,n;
printf("Enter value for n: ");
scanf("%d", &n);
if (n <= 1){
printf("It is a prime number");
}
for (i = 2; i <= sqrt(n); i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("A prime Number");
return 0;
}
This is happening because in your code for i = 3 and n = 33, if condition is failing which leads to else block directly and hence you are getting output as "It is a prime number".
I have started learning C language. I wrote this program to find all prime numbers between the given range but I am unable to get the expected output.
Can anyone tell me what's wrong with this program please?
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++) {
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
getch();
}
I just suggest getting rid of that count variable.
How do you know if a number N is prime? If for every j in the range (2 to N-1) you have N%j != 0.
So:
In the inner loop, use j from 2 to N-1 (instead of from 1 to N as you used tio do). In fact N%1 and N%N will be 0
The first time you find a j so that N % j == 0 break. You are sure it's not prime
Why incrementing count? For a prime number the j counter will be equal to i (because you looped until j<i, and the last j++ made j
equal to i). So just check for j == i and print the prime number i
#include <stdio.h>
#include <conio.h>
int main( void )
{
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
// Was for(j=1; j<=i; j++)
for(j=2; j<i; j++)
{
if(i % j == 0)
{
//Was count++;
break;
}
}
//Was if(count==2)
if(j == i)
{
printf("%d\t",i);
}
}
getch();
return 0;
}
Here you are.
#include <stdio.h>
int main( void )
{
printf( "Enter the range of numbers (two unsigned integer numbers): " );
unsigned int first = 0, last = 0;
scanf( "%u %u", &first, &last );
if ( last < first )
{
unsigned int tmp = first;
first = last;
last = tmp;
}
do
{
int prime = first % 2 == 0 ? first == 2 : first != 1;
for ( unsigned int i = 3; prime && i <= first / i; i += 2 )
{
prime = first % i != 0;
}
if ( prime ) printf( "%u ", first );
} while ( first++ != last );
putchar( '\n' );
return 0;
}
The program output might look like
Enter the range of numbers (two unsigned integer numbers): 0 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
As for your program then you need re-initialize the variable count before the inner loop
for(i=min; i<=max; i++) {
count = 0;
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
And the inner loop is inefficient.
Need to reset the value of count. It starts at count=0, then for any inputs, the loops will count up. The For each outer loop index, it will go like this:
1 (1%1=0 --> count++, count = 1)
2 (2%1=0 --> count++, and 2%2=0 --> count++, count = 3)
3 (3%1=0 --> count++, and 3%3=0 --> count++, count = 5)
etc... until max is reached.
You can use a simple isprime function to check whether a number is prime or not and then call the function for the given interval.
To find whether a number is prime or not , we can use a simple primality test to check it.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool isprime(int n)
{
if(n <= 1) return false;
if(n <= 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
for(int i = 5;i*i <= n;i += 6)
{
if(n%i == 0 || n%(i + 2) == 0)
{
return false;
}
}
return true;
}
int main()
{
int a,b;
printf("Enter the first number :");
scanf("%d",&a);
printf("Enter the second number :");
scanf("%d",&b);
for(int i = a;i <= b;i++)
{
if(isprime(i)) printf("%d ",i);
}
return 0;
}
There is a simple change you should do:
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
count=1;
for(j=2; j<=i; j++)
{
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
}
My answer may be a bit late, but since it's the same issue, i'll write it here in case it helps someone else coming to this thread in the future.
My code is written from the POV of a beginner (No complex functions or data types are used) as this is a code that mostly they will get stuck on.
Working:
User inputs the range.
Using the for loop, each number in the range is sent to the isprime function which returns TRUE or FALSE after checking the condition for being a prime number.
if TRUE : program prints the number.
if FALSE : program skips the number using continue function.
#include<stdio.h>
int isprime(int num);
int main() {
int min, max;
printf("Input the low number: ");
scanf("%d", &min);
printf("Input the high number: ");
scanf("%d", &max);
for(int i = min; i<=max; i++) {
if(isprime(i) == 1) {
printf("%d ", i);
}
else if(isprime(i) == 0){
continue;
}
}
return 0;
}
int isprime(int num) {
int count = 0;
for(int i=2; i<=(num/2); i++) {
if(num % i == 0 ) {
count ++;
}
else{
continue;
}
}
if(count>0){
return 0;
}
else if (count == 0){
return 1;
}
}
I have created a code that writes out the sum of all even numbers.
But every time it loops the sum of the last run is saved and added in the sum of the new run. how do i make it have a new loop?
sorry for my bad english, and thx in advance
int main()
{
int number = 0;
int sum = 0;
printf("Welcome to\"Sum Evens\"!");
do
{
printf("\ninput a number: ");
scanf(" %d", &number);
if (number == 0)
{
printf("Goodbye, have a nice day!\n");
break;
}
printf("\nSum:");
if (number % 2 != 0)
{
number -= 1;
}
for (int i = 0; i <= number; i += 2)
{
printf(" %d ", i);
if (i != number)
{
printf("+");
}
sum += i;
}
printf("= %d\n", sum);
} while (number != 0);
system("pause");
return 0;
}
Watch these sort of problems melt away if you declare your variables as close to their first use as possible.
In your case, move int sum = 0; to just before the for loop.
I am trying to make a program that will convert a number into its prime factorization. For example, 2048=2^11 the program will output 211 (since this value will be used in a different function.). The program then prints the prime factorization and the number in a file. The issue I'm having is having the two functions, digitCount and FdigitCount, run in a loop and read the values from the file and then compare the amount of digits in the prime factorization to the number of digits in the normal number, then if it is less, printing the numbers out.
int digitCount(int n){
int digits = 0;
while(n!=0) {
n/=10; //divides the number by 10 and adds one to the digits until it is no longer divisible by 10.
++digits;
}
return digits;
}
int fdigitCount(int p){ //this function is used the count the digits of the prime factorization.
int fdigits = 0;
while(p!=0) {
p/=10; //divides the number by 10 and adds one to the fdigits until it is no longer divisible by 10.
++fdigits;
}
return fdigits;
}
int main(void) {
FILE* primes = NULL; //file pointer to the file that will contain all the prime factors of a number
int num;
int count;
int digits;
int limit;
int i;
int j=2;
int fdigits;
int frugalNum;
int normNum;
primes = fopen("primes.txt", "w+");
if (primes == NULL){
printf("Could not open primes.txt");
}
printf("Enter a limit: ");
scanf("%d", &limit);
for (i=2; i <= limit; i++){
num = i;
j = i;
count = 0;
if (num%2 == 0){
while (num%2 == 0)
{
num = num/2;
count++;
}
if (count > 1){
fprintf(primes, "2%d", count);
}
else {
fprintf(primes, "2");
}
}
else if(num%2 != 0) {
for (int i = 3; i <= sqrt(num); i = i+2)
{
// While i divides n, print i and divide n
count = 0;
while (num%i == 0)
{
num = num/i;
count++;
}
if (count > 1){
fprintf(primes, "%d%d", i, count);
}
else if (count==1){
fprintf(primes, "%d", i);
}
}
}
if (num > 2){
fprintf (primes, "%d", num);
}
fprintf(primes, " %d", j);
fprintf(primes, "\n");
}
while (!feof(primes)){
fscanf(primes, "%d %d", &frugalNum, &normNum);
if (fdigitCount(frugalNum) < digitCount(normNum)){
printf("%d\n", normNum);
}
}
fclose(primes);
return 0;
}
You shouldn't read the file by looping until feof() returns true. It returns true after you've passed the EOF, and so the last values you read will be garbage. Change your loop to:
while (fscanf(primes, "%d %d", &frugalNum, &normNum) == 2) {
/* Do stuff with frugalNum and normNum */
}
Additionally, I couldn't help noticing that digitCount() and fdigitCount() do exactly the same thing. Why do you need both of them?
In the main method below I'm trying to call a sort function and after function selects that latter from the user input it has to print the sort accordingly with the for loop at the end. But I have a warning that reads "loop will run at most once (loop increment never executed)" pointing at the array[arraySize]. Does it have to do with the return type or the other for loop above? What's happening here? Can anyone point out and explain please. Thanks much! Here's the code below:
int main()
{
long array[100], arraySize;
char sort;
long maxi = 100;
for(arraySize = 0; arraySize < maxi; arraySize++)
{
printf("Enter any positive integer, enter 0 to stop: ");
scanf("%li", &num);
if(num < 0) {
arraySize--;
printf("I said positive!");
count++;
}
else if(num == 0) {
maxi = arraySize;
}
else {
array[arraySize]=num;
arraySize--;
}
}
printf("Please enter A for ascending or D for descending order\n");
scanf("%s", &sort);
bubble_sort(array, arraySize, sort); //calling the sort function
printf(" Sorted list in the selected order:\n");
for (arraySize = 0; arraySize < num; arraySize++) {
printf("%ld \n", array[arraySize]);
puts("");
return 0;
}
}
EDIT: Thanks everyone for all your suggestions. I did make a few changes and here's what I have so far. Now it's skipping the A/D user input along with the bubble_sort function logic. Here's what it does as a final output: Note: long num is declared as a global variable!
int main()
{
long array[100], arraySize;
char sort;
long maxim = 100;
for(arraySize = 0; arraySize < maxim; arraySize++)
{
printf("Enter any positive integer, enter 0 to stop: ");
scanf("%li", &num);
if(num < 0)
{
arraySize--;
printf("I said positive! \n");
count++;
}
else if(num == 0)
{
maxim = arraySize;
}
else
{
array[arraySize]=num; //arraySize--;
}
}
printf("Please enter A for ascending or D for descending order: \n");
scanf("%c", &sort);
bubble_sort(array, maxim, sort); //calling the sort function
printf("Sorted list in the selected order:\n");
for (arraySize = 0; arraySize < maxim; arraySize++)
{
printf("%ld \n", array[arraySize]);
}
puts("");
return 0;
}
Any more suggestions will be appreciated!
There are a few other problems, but let's talk about your warning. You have this code:
for (arraySize = 0; arraySize < num; arraySize++) {
printf("%ld \n", array[arraySize]);
puts("");
return 0;
}
The corrected indentation should make it obvious why that loop will run at most once.
It seems your print loop has a typo, and should be corrected to:
for (arraySize = 0; arraySize < maxi; arraySize++) {
Also the call to bubble_sort() should use maxi rather than arraySize.
The last character entered gets stored in sort and that character is most probably \n.
Changing scanf("%c", &sort); to scanf(" %c", &sort); should solve the problem.
Note the space before %c.