Prime numbers

Hello,
I want to make a program which checks how many numbers are 'till it meets number 0.
I've tried this - but it doesn't work.
Can anyone fix it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  #include <iostream>

using namespace std;

int main()
{
    int n;
    int i;
    int c=0;
    int x;
    cout<<"Enter your number\n";
    cin>>n;
    while(n!=0)
    {
    for (int i=1; i<=n; i++)
    {
    if (n%i==0)
    c++;
    }
    if (c==2)
    {
    x++;
    }
    if (n==0)
        cout<<"The number of prime numbers is:\n";
        cout<<x;
        return 0;
}
This doesn't even compile: Where is the end of your "while" loop?
It was if(n>0) before I posted. But when I saw it when posting I knew it wasn't right, because it can be negative numbers, I think, but it stops when it meets 0. Can you help me?
Have you tried running it here (click the gear next to your code)?
No. But if it doesn't even compile, it's not okat anyway.
Add a right curly brace } after line 27.
learn to indent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

int main() {
	int n;
	int i;
	int c = 0;
	int x;
	cout << "Enter your number\n";
	cin >> n;
	while(n != 0) {
		for(int i = 1; i <= n; i++) {
			if(n % i == 0)
				c++;
		}
		if(c == 2) {
			x++;
		}
		if(n == 0)
			cout << "The number of prime numbers is:\n";
		cout << x;
		return 0;
	}
there you may notice the missing brace.

> how many numbers are 'till it meets number 0.
I don't understand you, please, rephrase.

> while(n != 0)
you never modify `n', tautology.

1
2
3
4
	int n;
	int i;
	int c = 0;
	int x;
use meaningful names for your variables, you it's easier to understand what you are doing.
@ne555:
that's what my friend told me, and I've tried to help him. I didn't really understand either. I think he wants to enter a string of numbers, from x to 0. And the program should display how many prime numbers are in that range.
1- Brackets are missing
2- While(n!=0)[infinite loop] now what condition is always true you need to use n--; in order to break from loop
3-Always initialize local variable with zero so that the garbage value will not store in the variable
4-i like your problem :)
try this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int main() {
	int n=0;
	int i=0;
	int x= 1;
	cout << "Enter your number\n";
	cin >> n;
	while(n != 0) {
		
		for(int i=2;i<n;i++)
		{
			if(n%i==0)
			break;
			else if(n==i+1)
			x++;
		}
		n--;
	}
	cout<<"The number of prime numbers is:\n";
        cout<<x;
        return 0;
		
}
Last edited on
change line 8 with:
int x = 1
because i start on loop with i = 2 ; else jump prime number 2
thnx @ar2007 for identifying my mistake
Topic archived. No new replies allowed.