LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Program doesn't print output (https://www.linuxquestions.org/questions/linux-newbie-8/program-doesnt-print-output-701070/)

palisetty_suman 01-30-2009 12:40 PM

Program doesn't print output
 
Hi,
I have written a program on c++. It doesn't give any errors but it does't give any output.my code is as follows.It is to print prime numbers from 3 to 100.

------------------------------------------------------------------

#include<iostream>
using namespace std;
int main()
{
int i,j,num,k;
cout<<"Enter the prime range number"<<endl;
cin>>num;
for(i=3;i<=num;i++)
{
for(j=1;j<=i;j++)
{
if(i%j==0)
k++;
}
if(k==2)
cout<<i<<endl;
}
}
---------------------------------------------------------------------
Please help me out.

dorian33 01-30-2009 12:56 PM

'k' is not initalized, so what 'k++' does mean?

palisetty_suman 01-30-2009 12:59 PM

k
 
K is just like counter. K is initialised.
int k; which is equal to k=o.

The problem is with returning value I guess. Please check there.

dorian33 01-30-2009 01:12 PM

Quote:

Originally Posted by palisetty_suman (Post 3426550)
int k; which is equal to k=o.

Really?
So try this:
Code:

#include<iostream>
using namespace std;
int main(){
 int k;
  cout<<k<<endl;
}


palisetty_suman 01-30-2009 01:21 PM

Dorian,
I tried what you said and for k, i am getting some value 1262164 but not 0. I am wrong with that. I accept but I should get some or the other answer for it. Isn't it. Now I will initialize k to 0.

palisetty_suman 01-30-2009 01:26 PM

I have changed my code to this and I am able to print only 3. Please predict where is the mistake i am doing.

-------------------------------------------------------------------------------------


#include<iostream>
using namespace std;
int main()
{
int i,j,k=0;
for(i=3;i<=100;i++)
{
for(j=1;j<=i;j++)
{
if(i%j==0)
k++;
}
if(k==2)
cout<<i<<endl;
}
}



-----------------------------------------------------------------------------------------

paulsm4 02-01-2009 05:59 PM

Hi -

If you want help (especially help with homework), please:

1. Put your code in code blocks
2. Explain more about what you're trying to get your code to do
For example, add a few comments at important places in your program.
3. Q: what does "k==2" mean (in terms of your program)?
How does it relate to a "prime number"?
Do you expect "k==2" to occur many times, or just once in your program?

palisetty_suman 02-01-2009 06:50 PM

Prime numbers
 
I am able to run the program. Thanks.I got the result.


All times are GMT -5. The time now is 03:43 AM.