C Program (Prime Number in a given range) - c

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

Related

How to get sequence of numbers and then print the last 5?

Im trying to make a program that will get sequence from the user that end with 0, and then i want to print the last 5 numbers (not including the 0).
I can assume that the user will input all the numbers in one line and will end it with 0.
I wrote that code but something is wrong with it, I think its something about the scanf line.
Input:
1 6 9 5 2 1 4 3 0
Output: no output
#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;
printf("please enter more than %d number and than enter 0: \n", N);
last_input = 0;
while (last_input<N) {
scanf(" %d", &j);
if (j == '0') {
last_input = N;
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}
printf("The last %d numbers u entered are:\n", N);
for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);
}
for (j=0; j<last_input; ++j) {
printf(" %d", arr[j]);
}
return 0;
}
This comparison
if (j == '0') {
does not make a sense because the user will try to enter the integer value 0 instead of the value (for example ASCII 30h or EBCDIC F0h) for the character '0'.
You need to write at least
if (j == 0) {
Due to these sub-statements of the if statement
last_input = N;
break;
this for loop
for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);
}
is never executed and does not make a sense.
This statement
last_input=-1;
results in breaking the order of the N last elements in its output. And moreover the result value of the variable last_input will be incorrect.
You need to move elements of the array one position left. For this purpose you can use a loop of standard C function memmove.
The program can look the following way.
#include <stdio.h>
#include <string.h>
int main( void )
{
enum { N = 5 };
int arr[N];
printf( "Please enter at least not less than %d numbers (0 - stop): ", N );
size_t count = 0;
for (int num; scanf( "%d", &num ) == 1 && num != 0; )
{
if (count != N)
{
arr[count++] = num;
}
else
{
memmove( arr, arr + 1, ( N - 1 ) * sizeof( int ) );
arr[N - 1] = num;
}
}
if (count != 0)
{
printf( "The last %zu numbers u entered are: ", count );
for (size_t i = 0; i < count; i++)
{
printf( "%d ", arr[i] );
}
putchar( '\n' );
}
else
{
puts( "There are no entered numbers." );
}
}
The program output might look like
Please enter at least not less than 5 numbers (0 - stop): 1 2 3 4 5 6 7 8 9 0
The last 5 numbers u entered are: 5 6 7 8 9
I made some changes based on ur comments and now its work fine!
#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;
printf("please enter more than %d number and than enter 0: \n", N);
last_input = 0;
while (last_input<N) {
scanf("%d", &j);
if (j == 0) {
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}
printf("The last %d numbers u entered are:\n", N);
for (j=(last_input); j<N; ++j) {
printf("%d ", arr[j]);
}
for (j=0; j<last_input; ++j) {
printf("%d ", arr[j]);
}
return 0;
}
thank u guys <3.

School exercice in c about prime numbers

Make a program that asks the user for an integer and says if the
number is prime or not. A number greater than 1 is prime if only
is divisible by 1 and by itself. Then, it will tell us what the prime number is.
example:
Enter a number: 8
8 is not first. The first one immediately superior to 8 is 11.
Enter a number: 5
5 is first. The first one immediately above 5 is 7.
I can only solve first part.
Here is my code:
#include <stdio.h>
int main() {
int num, i;
do {
printf("Enter a numer: ");
scanf("%d", & num);
}
while (num < 1);
for (i = 2; i < num; i++) {
if (num % i == 0)
printf("Its prime");
}
if (num % 1 == 0 && num % num == 0)
printf("Not prime");
return 0;
}
Try this logic. Not tested
#include <stdio.h>
int main()
{
int num, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
int isPrime=IsPrime(num)
if(isPrime==0){
numNext=num+1;
int nextPrimeNum=checkNextPrime(numNext);
}
}
int IsPrime(int num){
for(i = 2; i <= num/2; ++i)
{
// condition for nonprime number
if(num%i == 0)
{
flag = 1;
break;
}
}
if (num == 1)
{
flag=1;//neither prime nor composite
}
return flag;
}
int checkNextPrime(int numNext){
int isNextPrime=IsPrime(numNext)
if(isNextPrime==0){
printf("This is the required output :"numNext);
return numNext;
}
else{
numNext=numNext+1;
checkNextPrime(int numNext)
}
}

Coding for multiple modes in C?

My assignment is to find all possible modes for a set of numbers (0 to 100).
We were told to do so using arrays and also to count the frequency that each number occurs.
I've coded for the mode, however, my program does not work is there are multiple modes (example: 1, 2, 7, 7, 9, 10, 7, 2, 2. In this stance, 2 and 7 are both the mode and my program needs to print both of them, but mine doesn't).
I think I might have to make another array set, but I'm not sure? Any advice would be appreciated.
Here is what I have:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main() {
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i <= 100) { //setting all values to 0
c[i] = 0;
i = i + 1;
}
scanf("%d", &x); // scanning in the test scores
while ((x >= 0) && (x <= 100)) { // counting how often each score appears
c[x] = c[x] + 1;
if (c[x] >= mode) {
mode = x;
}
scanf("%d", &x);
}
printf("THE MODE(S) ARE %d\n", mode);
i = 0;
while (i <= 100) { //printing all values so long as they've occurred at least once
if (c[i] > 0) {
printf("%d occurs %d times\n", i, c[i]);
}
i = i + 1;
}
}
You have to count the highest frequency of any number and if that frequency equals the frequency of any other number then that number will also be mode.
So the changes that you need to do are:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main ()
{
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i <= 100) //setting all values to 0
{
c[i] = 0;
++i;
}
scanf("%d", &x); // scanning in the test scores
while ((x >= 0) && (x <= 100)) // counting how often each score appears
{
c[x] = c[x] + 1;
if (c[x] >= mode)
{mode = c[x];}
scanf("%d", &x);
}
for(i=0;i<=100;i++){//printing all values having highest frequency
if (c[i]==mode)
{
printf("THE MODE(S) ARE %d\n", i);
}
i = 0;
while (i<=100) //printing all values so long as they've occurred at least once
{
if (c[i] > 0)
{
printf("%d occurs %d times\n", i, c[i]);
}
++i;
}
}
Instead of determining the mode in the main entry loop, you should determine the maximum count. Then you can print all values with this count of occurrences in a final loop.
You should also check the return values of scanf().
I would also advise to use an initializer for the array to avoid a loop and to use for loops that more clearly identify the initialization, test and increment of the loop index.
Here is a corrected version of your code:
#include <stdio.h>
int main() {
int x, i, c[101] = { 0 }, max_repeat;
printf("please enter test scores between 0 and 100\n");
max_repeat = 0;
// read the test scores and compute the maximum repeat count
while (scanf("%d", &x) == 1 && x >= 0 && x <= 100) {
c[x] += 1;
if (max_repeat < c[x]) {
max_repeat = c[x];
}
}
printf("The mode(s) are");
for (i = 0; i <= 100; i++) {
if (c[i] == max_repeat) {
printf(" %d", i);
}
}
printf("\n");
return 0;
}

C - nested for loop patern

how to get output like flipped floyds triangle? and how's the best way to solve it?
Example :
5555
_555
__55
___5
note : _ is a space
already tried lot of code but still I cant get output like that.
one of my code:
#include<stdio.h>
int main () {
int a,b,c,n;
scanf("%d",&n);
for(a=1;a<=n;a++) {
for(b=n;b>=a;b--) {
printf(" ");
}
for(c=1;c<=a;c++) {
printf("*");
}
printf("\n");
}
}
This is not the best way... but the code is similar to the one posted by you.
int main()
{
int a, b, c, n;
scanf("%d", &n);
for (a = n; a > 0; a--)
{
for (b = n; b >= a; b--)
{
printf(" ");
}
for (c = 1; c <= a; c++)
{
printf("*");
}
printf("\n");
}
}
In the original post you first for loop was
for(a=1;a<=n;a++)
which meant the 2nd for loop would print n*space and the 3rd for loop would print 1 star.
By changing the first for loop to
for (a = n; a > 0; a--)
Everything gets inverted so first loop will print no space and last for loop n*stars.
As a joke;)
#include <stdio.h>
int main( void )
{
int n = 5555;
while (n)
{
printf("%5d\n", n);
n /= 10;
}
return 0;
}
The program output is the same as required.:)
5555
555
55
5
If to use loops then the program for example can look like
#include <stdio.h>
int main( void )
{
const char c = '5';
while (1)
{
printf("Enter a non-negative number (0 - exit): ");
unsigned int n;
if (scanf("%u", &n) != 1 || n == 0) break;
putchar('\n');
for (unsigned int i = 0; i < n; i++)
{
unsigned int j = i + 1;
printf("%*c", (int)j, c);
while (j++ < n) putchar(c);
putchar('\n');
}
putchar('\n');
}
return 0;
}
Its output might look like
Enter a non-negative number (0 - exit): 10
5555555555
555555555
55555555
5555555
555555
55555
5555
555
55
5
Enter a non-negative number (0 - exit): 0
The inner while loop can be substituted for the for loop
for ( ; j < n; j++ )

Detect if the number in the array has been already input (C program)

I am kind of confused. I'd like to make a program where if the number in the array has been already input, then it will detect it and say it was repeated, so the program would tell the user to put another non-repeated integer.
#include <stdio.h>
#define SIZE 5
int main()
{
int array[SIZE];
int i;
int j;
for (i = 0; i < SIZE; i++)
{
printf("[%d] Insert a number: ", i + 1);
scanf("%d", &array[i]);
j = i - 1; // This is the closest that I've gotten guys. But I need to create a loop to make j be -1 until it finds a repeated number in the array.
if (array[i] == array[j])
{
printf("The number is repeated");
i--;
}
if (array[i] > 1000)
{
printf("Sorry, the number you entered cannot be bigger than 1000\n");
i--;
}
if (array[i] < 0)
{
printf("Sorry, the number you entered cannot be less than 0\n");
i--;
}
}
for (i = 0; i < SIZE; i++)
{
printf("The array inside is %d\n", array[i]);
}
return 0;
}
As you can see, I did something similar. I just put j = i - 1 so basically it will tell the program that it was repeated. However, I suppose that I should create a loop that will subtract -1 to j until it finds the repeated value (if there is one). I just not have any idea how to create that loop and make it work.
Thank you very much!
The checks can be done the following way (without testing)
int array[SIZE];
int i;
for (i = 0; i < SIZE; i++)
{
int valid = 1;
int num;
do
{
printf("[%d] Insert a number: ", i + 1);
scanf("%d", &num );
if ( !( valid = !( num > 1000 ) ) )
{
printf("Sorry, the number you entered cannot be bigger than 1000\n");
}
else if ( !( valid = !( num < 0 ) ) )
{
printf("Sorry, the number you entered cannot be less than 0\n");
}
else
{
int j = 0;
while ( j < i && num != array[j] ) j++;
if ( !( valid = j == i ) )
{
printf("The number is repeated");
}
}
} while ( !valid );
array[i] = num;
}
This should work for you:
#include <stdio.h>
#define SIZE 5
int main() {
int array[SIZE];
int numberCount, repeatCount;
for(numberCount = 0; numberCount < SIZE; numberCount++) {
printf("[%d] Insert a number:\n>", numberCount + 1);
scanf("%d", &array[numberCount]);
for(repeatCount = 0; repeatCount < numberCount; repeatCount++) {
if (array[numberCount] == array[repeatCount]) {
printf("\nThe numbe is repeated\n");
numberCount--;
break;
}
}
if (array[numberCount] < 0) {
printf("\nSorry, the number you entered cannot be less than 0\n");
numberCount--;
}
if (array[numberCount] > 1000) {
printf("\nSorry, the number you entered cannot be bigger than 1000\n");
numberCount--;
}
}
printf("\n\n");
for(numberCount = 0; numberCount < SIZE; numberCount++)
printf("The array inside is %d\n", array[numberCount]);
return 0;
}

Resources