How to print all the prime numbers from 1 to 1000? - c

I'm trying to write a program that goes through all the numbers from one to a thousand, but it does not work. Here is what I wrote so far, I could not find the problem:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int i = 0, j = 0, mona = 0;
bool prime = true;
//for each number between 1-1000
//i go over the numbers between two(It's ok if the number is divisible by 1,Every number is divisible
by 1) and this number (not including the number itself)
//if the number is divisible by any number, it is not a prime number
for(i = 2; i <= 1000; i++)
{
for (j = 2; j < i; j++) {
if (i % j == 0)
prime = false;
if (prime)
{
printf("prime number: %d\n", i);
mona++;
}
}
}
printf("number of prime numbers: %d", mona);
return 0;
}
and this is the output i got:
prime number: 3
number of prime numbers: 1
I also see that I did not consider the number two.

This can be a solution:
int i, int j;
int count=0;
int mona=0;
for(i = 2; i <= 1000; i++)
{
for (j = 2; j < i; j++) {
if (i % j != 0)
count++;
}
if (count==i-2){
printf("prime number: %d\n", i);
mona++;
}
count=0
}
With "count", you count the number of division with rest different from 0. If all the division satisfy the previous condition, the number is prime. The number of division computed by second cycle for a specific number is equal to i-2.

You want
for(i = 2; i <= 1000; i++)
{
prime = true;
for (j = 2; j < i; j++) {
Clearly if the flag is tested every time around the outer loop it needs to be initialized every time around the outer loop.

Related

Program wont sum random elements from matrix array

everyone!
I create matrix with random elements:
static int array[10][10];
int i, j, m, n, sum = 0;
printf("Enter the order of the matrix\n");
scanf("%d %d", &m, &n);
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf("%d ", rand() % 10);
}
printf("\n");
}
And this is one function to sum row elements:
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
sum = sum + array[i][j];
}
printf("Sum of the %d row is = %d\n", i, sum);
sum = 0;
}
My problem is that program wont to sum it properly, program just print 0 for result.
Also, when I add manual elements, program works fine, but wont with random numbers.
Someone to help me? Thank you!
You haven't actually assigned the values to the array; you're just printing them.
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
int num = rand() % 10;
printf("%d ", num);
array[i][j] = num;
}
printf("\n");
}
is probably what you want.
Also the array has space for only 10 x 10 elements. So you need to validate that the inputs for m and n do not exceed that limit.
The default value of int type in C is 0. Because you do not enter the value to array, so all of values of this array are equal to 0. So sum = 0 after all calculations.
Try to initialize values for this array. For example, in the first for loop (the for loop content printf with rand() function):
array[i][j] = rand() % 10;
OR
array[i][j] = 1; // or whatever you want

Frequency of an Element Accruing In an Array

I am new to programming, I am trying to write a program that lets the user input numbers ranging from 0 to 1000, and the maximum number the user can input is 100. The numbers in the array don't have to be in order, and the program ends when the user inputs a negative number. After that, the program should determine which number occurs the most and the frequency of that occurrence.
I have written a similar code but not for this type of problem the code below showcases what I mean by similar code and any help would be appreciated
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char again;
do {
srand(time(0));
int myNumbers[10];
int i, n, findnum, time, num;
n = 10;
for (i = 0; i < n; i++) {
myNumbers[i] = rand() % 10 + 1;
}
for (i = 0; i < n; i++) {
printf("elements %d\n", myNumbers[i]);
}
printf("Enter number to find Occurrence: ");
scanf("%d", &findnum);
time = 0;
for (i = 0; i < n; i++) {
if (myNumbers[i]==findnum)
time++;
}
if (findnum>0) {
printf("Occurrence of %d is: %d times\n",findnum,time);
} else {
printf("The number %d is not present in the array\n",num);
}
do {
printf("Shall we play again (y/n)?: ");
while(getchar()!='\n');
scanf("%c", &again);
}
while(again !='y' && again !='n');
}
while(again =='y');
}
You will need a second array to count the frequencies. Worst case, the user entered unique numbers, so the second array should be as large as myNumbers. The array will hold two values: the number, and its count:
int myNumbers[10];
int myCount [10][2] = {0};
int n= 10;
You remember the first entry of myCount that is available:
int m= 0;
You cycle over all numbers:
for (i = 0; i < n; i++){
For each number, you check if it is already in the myCount and if yes, increment the count and then exit the loop:
for (j = 0; j < m; j++){
if (myCount[j][0] == myNumbers[i]){
myCount[j][1]++;
break;
}
}
If the number was not found, you add it:
if (j == m) {
myCount[m][0] = myNumbers[i];
myCount[m][1] = 1;
m++;
}
}
Now you can search the array for the number with the highest count.
Integrated the code is:
int myNumbers[10];
int myCount [10][2] = {0};
int n= 10;
int m= 0;
/* now fist read the input */
for (i = 0; i < n; i++){
for (j = 0; j < m; j++){
if (myCount[j][0] == myNumbers[i]){
myCount[j][1]++;
break;
}
}
if (j == m) {
myCount[m][0] = myNumbers[i];
myCount[m][1] = 1;
m++;
}
}
To do: search the array for the number with the highest count.

Sum of prime numbers in array

I need to input from keyboard some random values and put them in an array. After that I need to print the average of the prime numbers only. This is my code but it doesn't work:
#include<stdio.h>
#include<conio.h>
int main()
{
int v[50], n, i, nrprim = 0, sum = 0, j;
float medie = 0;
printf("dati numarul de elemente al vectorului:\t");
scanf("%d", &n);
for ( i = 0; i < n; i++)
{
printf("dati elmentele vectorului:\t");
scanf("%d", &v[i]);
}
for(i=0; i<n; i++)
for(j=2; j<v[i]; j++)
{
if(v[i]%j!=0)
{
sum = sum + v[i];
nrprim++;
}
}
medie =( sum/nrprim);
printf("%f", medie);
_getch();
return 0;
}
You're adding to sum and nrprim every time you find a number that isn't a factor of it. For instance, when i == 8, you'll add to them when j is 3, 5, 6, or 7.
A number is only prime if none of the numbers below it are factors. You have to wait until the end of the j loop to know this.
And if you want fractions in the average, you need to convert one of the values to float before dividing. Otherwise you get integer division.
#include<stdio.h>
#include<conio.h>
int main()
{
int v[50], n, i, nrprim = 0, sum = 0, j;
float medie = 0;
printf("dati numarul de elemente al vectorului:\t");
scanf("%d", &n);
for ( i = 0; i < n; i++)
{
printf("dati elmentele vectorului:\t");
scanf("%d", &v[i]);
}
for(i=0; i<n; i++)
int is_prime = 1;
for(j=2; j<v[i]; j++)
{
if(v[i]%j == 0)
{
is_prime = 0;
break;
}
}
if (is_prime) {
sum = sum + v[i];
nrprim++;
}
medie = float(sum)/nrprim;
printf("%f", medie);
_getch();
return 0;
}
Your prime check is wrong. Instead of testing whether a number can't be divided by any other number, you're considering a number a prime when you find the first number that you can't divide it by. So when you for instance test if 9 is prime, you say "yes" because it couldn't be divided by 2, without checking if it can be divided by 3. Try something like this instead:
int flag;
for (i = 0; i < n; i++)
{
flag = 1;
for (j = 2; j < v[i]; j++)
{
if (v[i] % j == 0)
{
flag = 0;
break;
}
}
if (flag) {
sum = sum + v[i];
nrprim++;
}
}
Also, your program crashes if no prime number is entered, so you need to handle that case as well. I would suggest something such as:
if (nrprim) {
medie = (sum / nrprim);
printf("%f\n", medie);
}
else {
printf("Error: no prime numbers were entered.\n");
}

Program doesn't work with 10 values in array

Basically, the max size of the array is 10 and the user is allowed to enter up to 10 values. If the user enters -1 or 0, before entering the ten values, then the loop stops and goes to the next loop. My problem is is that it works perfectly UNTIL I enter 10 values. The result will divide by 9 instead of 10 and print that there are 9 values in the array.
#include <stdio.h>
int main(void)
{
float numbers[10];
int i;
int n;
int count =0;
for(i = 0; i<10; i++)
{
scanf("%f", &numbers[i]);
if(numbers[i] == -1)
break;
if(numbers[i] == 0)
break;
count++;
}
n = count-1;
float sum = 0;
float average;
for(i = 0; i<=n; i++)
{
sum = sum + numbers[i];
}
average = sum/count;
printf("The average price of the %d products is %.2f.\n", count, average);
return 0;
} //this is the fixed solution.
You should not write n=count-1; write n=count; instead. And move count++ to the end of loop.
#include <stdio.h>
int main(void)
{
float numbers[10];
int i;
int n;
int count =0;
for(i = 0; i<10; i++)
{
scanf("%f", &numbers[i]);
if(numbers[i] == -1)
break;
if(numbers[i] == 0)
break;
count++;
}
n = count;
float sum = 0;
float average;
for(i = 0; i<n; i++)
{
sum = sum + numbers[i];
}
average = sum/a;
printf("The average price of the %d products is %.2f.\n", n, average);
return 0;
}
I'm pretty sure it is because of this line
n = count-1
Can you explain why you are subtracting 1? In the case where you input 10 numbers, count will equal 10. After subtracting 1 you will then only iterate thru the first 9 indexes in the array.
If you need to subtract 1 (to account for the user inputting a 0 or -1), then change the condition in the last for loop to be <= instead.
for(i = 0; i<=n; i++)
There are two things has to be considered in this program.
1 . n = count-1;
for(i = 0; i<n; i++)
The count variable contains the number of element in the array, while n has been assigned to count - 1 to access from the 0th position , but while iterating the loop condition `i<n` make the loop to run n-1 time (i.e 9 times in this case).
So that the sum calculation failed to calculate the last array element.
average = sum/a;
The variable average and sum are float , whereas n is an int, so the type conversion has to be made while calculating the average.
average = sum/(float)a;
NOTE : a should be replaced by count , which hold the exact count of the element in array.
The complete corrected code is,
#include <stdio.h>
int main(void)
{
float numbers[10];
int i;
int n;
int count =0;
for(i = 0; i<10; i++)
{
scanf("%f", &numbers[i]);
count++;
if(numbers[i] == -1)
break;
if(numbers[i] == 0)
break;
}
n = count-1;
float sum = 0;
float average;
for(i = 0; i<=n; i++)
{
sum = sum + numbers[i];
}
average = sum/(float)count;
printf("The average price of the %d products is %.2f.\n", count, average);
return 0;
}

Printing prime numbers up to n

I have written some code to ask the user for n, then print the prime numbers up to n. However when I use it, i.e with 10, it only prints the non-prime numbers
/* Asks for the amount of prime numbers you would like to print, then prints them */
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
check = 0;
for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
if (check == 1) {
printf("%d\n", i);
}
}
}
}
return 0;
}
How many prime numbers would you like to print? 10
4
6
6
8
8
9
10
10
I've tried everything but I think I am missing something really trivial!
This is how it should be:
for (i = 2; i <= n; i++)
{
check = 0;
for (j = 2; j < i ; j++)
{
if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}
Also, in the inner loop you don't have to divide the number till j < i. You don't have to go beyond i/2.
As Weather Vane said, the mod operator % returns 0 if i is exactly divisible by j and if this is true then the number is not prime. Your conditional statement is backwards.
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++)
{
check = 0;
for (j = 2; j < i ; j++)
{
if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}
return 0;
}
How many prime numbers would you like to print? 10
2
3
5
7
Several problems.
First, when you set check = 1, that means that i divides evenly, so n is not prime, so you shouldn't print it. You should be printing the number when check == 0.
Second, you're printing each time through the inner loop. You should test check at the end of the loop, to ensure that none of the numbers divided it.
As an improvement, there's no need to keep checking once you find one number that divides evenly. So you can break out of the inner loop as soon as you set check = 1.
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
check = 0;
for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
break;
}
}
if (check == 0) {
printf("%d\n", i);
}
}
return 0;
}
try looking at this code
#include <stdio.h>
int IsPrime(int num)
{
int i = 2;
for (i = 2; i < num; i++) if (num % i == 0) return 0;
return 1;
}
int main(void)
{
int n, i;
char *nStr = (char*)malloc(10);
printf("How many prime numbers would you like to print? ");
fgets(nStr, 9, stdin);
n = atoi(nStr);
for (i = 1; i <= n; i++) if (IsPrime(i)) printf("%d\n", i);
getchar();
return 0;
}
and about your code, you should print the number only if check remains 0.

Resources