How will the value of i be incremented here? [duplicate] - c

This question already has answers here:
For vs. while in C programming?
(19 answers)
Closed 5 months ago.
This is a approach for Weather a number is prime or not
QUESTION:
int main()
{
int i, num, b;
printf("ENTER A NUMBER : \n");
scanf("%d", &num);
for (i = 2; i <= num - 1; i++)
{
if (num % i == 0)
break;
}
if (i == num)
printf("PRIME");
else
printf("NOT A PRIME");
return 0;
}
How will the value of i will be incremented if loop is completed..The condition for stopping is num-1 then how in next statement value of i will be == num
Ex: if i enter 5 loop will run till 4 and value of i will be 4 then how will it will be == num..
Hope question is understood.

The body of the for loop is executed as long as the test condition is true. That means, when the loop stops executing because of the test condition (rather than because of the break), the test condition is false.
Therefore, when the loop ends this way, i <= num - 1 is false. Since num is 5, that means i <= 4 is false, which occurs when i has become 5.

I got your point , Let's analyze it together
First let's be clear about prime numbers
A prime number is a number that is only divisible by itself and one
so , if we iterate from 2 till the number - 1 we are including all the numbers in range 2 & number-1 and in case any of those numbers are divisible by our variable
then it's not a prime and we break the loop before it reaches number-1
I see you're confused in the stopping condition
the stopping condition is number!
the loop is valid till number -1
then it increments
so i will be equal to the number and the condition of the loop is not satisfied
in this case we can say that we reached all numbers between 2 and number -1 and found nothing divisible by our variable
hence it's prime
else if the counter i didn't reach the number itself this means that the loop went into a break
and a break means we found a divisible integer
so it's not prime
Hope this helped!

Related

Issue with using multiple relational operators in C

I'm new to programming, but I searched for this topic before asking and still can't figure out what my program is doing wrong.
I have this:
int i;
do
{
i = get_int("Enter positive integer between 1-10: \n");
}
while(1>i && i<10)
I want to ask the user for a positive integer between one and ten. it doesn't accept anything less than one, which is good, but it will take anything positive. I understand how I can't do 1>i<10 since it reads it from left to right but I can't get it to recognize it has to follow both operators. What is my issue?
You probably want the loop to run the loop as long as user inputs a number between 1 to 10. Your condition in the while loop isn't correct. It should be as follows -
while(i>1 && i<10); # runs as long as i is in range 1 to 10
However, If you want to break the loop as soon as the user inputs any number inside the 1 to 10 range, then you should use the following -
while(!(i>1 && i<10)); # runs as long as i is outside the range 1 to 10
i can't get it to recognize it has to follow both operators.
Why would it be more applicable when the integer has to meet both criteria?
do {
....
} while(test);
When the test returns true, the input is re-tried as the loop iterates again. What is the criteria for re-trying, not what is the criteria for passing.
Input only needs to fail one of two tests to re-try: too low or too high. Hence the need for "or" (||).
} while(i < 1 || i > 10);
Your loop condition is incorrect. You should have used logical OR instead of logical AND.
This worked for me.
do
{
i= get_int ("Enter positive integer between 1-10: \n");
} while (i<1 || i>10);
you have been mistaken (syntax mistake) inside the while expression (2 mistakes their, the logic is not right and a syntnatx error with 1<i) - see fixes inline:
int i = 0; /*its better if you initialize the i here*/
do
{
i= get_int ("Enter positive integer between 1-10: \n");
}
while((i > 1) && (i < 10));
I want to ask the user for a positive integer between one and ten.
I think you want an integer in the range with inclusive 1 and 10.
When how will look such a condition of a valid positive integer?
It will look the following way
1 <= i && i <= 10
So the do while loop must continue its iterations while this condition is not true. So in the condition of the loop you should write a negation of the above condition
int i;
do
{
i= get_int ("Enter positive integer between 1-10: \n");
} while ( !( 1 <= i && i <= 10 ) );
If to remove the parentheses then the condition will look like
int i;
do
{
i= get_int ("Enter positive integer between 1-10: \n");
} while ( 1 > i || i > 10 ) );

Using an If statement to find prime numbers

The following is a piece of code that shows an output stating whether a number, entered by a user, is a prime number or not.
#include <stdio.h>
#include <stdlib.h>
int a,b;
int main(void) {
printf("Enter number: ");
fflush(stdout);
scanf("%d",&a);
for (b = 2; b < a; b++)
{
if (a % b == 0)
break;
}
if (b<a)
{
printf ("%d is divisible by %d\n", a, b);
}
else
{
printf ("%d is prime \n", a);
}
return 0;
}
The piece of code, written above, is not mine and it identifies a prime number successfully everytime (i.e the printf statement of the else clause gets printed).
My understanding of the if statement is that an else clause in an if-else statement belongs to the nearest if statement which doesn't already have an else clause. And so, having said that, I believe the else clause, in the above piece of code, belongs to the nearest if statement.
My question is this: If the user enters a prime number like 31 or 37 or any other prime number, how does the printf statement of the else clause get printed?
The condition if (b<a) (of the second if statement) will always be true considering that b will only be incremented to (a-1). And so if the user enters the number 31, the variable b will only be incremented to 30. Shouldn't it be the case that the printf statement of the second if statement gets printed, regardless of whether the number entered by the user is prime or not, considering that the condition if (b<a) will always be true?
How does the above piece of code print all the prime numbers correctly, and therefore, work alright? (when, according to my limited understanding of the way the if statement works, it shouldn't)
The condition if (b<a) (of the second if statement) will always be true considering that b will only be incremented to (a-1).
That is not the case. If no divisor is found, the for loop continues until the condition b<a is false. This happens when b == a, not b == a-1. The loop body isn't run when the loop condition is false, but the increment has happened nevertheless.
This loop
for (b = 2; b < a; b++)
{
if (a % b == 0)
break;
}
can be interrupted in two cases. The first one is when a is divisible by b
if (a % b == 0)
break;
But for prime numbers this condition is always will be equal to false.
So the other case when the loop will be interrupted is when b after increment
for (b = 2; b < a; b++)
^^^
will became equal to a. In this case the condition
for (b = 2; b < a; b++)
^^^^^
will be equal to false and the control will be passed to the if-else statement.
If so then b is equal to a and a is a prime number.
First, you are correct, the whitespace between
if (b<a)
{
...
}
and
else
{
...
}
doesn't matter. The else indeed belongs to the if.
Second, it's not true that the if (b<a) is always true. As long as a % b == 0 never returned true, the loop continues until b==a, which fails the condition. They could have also written if (b!=a).

Can't Understand Code fragment

I cannot understand how the code is giving output of the prime factors of input..and what is the use of temp variable in this code?another question is what is the purpose of i=1 in the code fragment?
#include<stdio.h>
int main()
{
int number,i,temp;
scanf("%d",&number);
if(number<0)
{
printf("%d = -1 x ",number); //just printing
number=number*-1; //multiplication by -1
}
else
{
printf("%d = ",number); //just printing
}
for(i=2;i*i<=number;i++)
{
if(number%i==0)
{
printf("%d x ",i);
number=number/i;
temp=i;
i=1;
}
}
printf("%d\n",number);
return 0;
}
sample input:100
sample output:100 = 2 x 2 x 5 x 5
sample input:20
sample output:20 = 2 x 2 x 5
As previously mentioned, temp is unused.
The way this prints the prime numbers is by trying over and over to divide the number by the smallest number possible. That is the purpose of i=1.
So take 175.
First, the loop is initialized at 2. It then increments i until 175 % i == 0. When this happens, it means that i is a factor of 175. So it prints i and divides 175 by i. This ensures you won't double-count the factor. Here, this will happen first for i == 5. So now, num = 175/5 = 35.
At this point, i is reset to 1. The first thing that happens at the end of the loop block is that i is incremented to 2. So now again, it looks for the smallest factor. Again, it finds 5.
If i was not set to 1, the program would keep going up and it would miss the fact that 5 is a factor of 175 twice.
Eventually, when i > number, the program knows that it has found all the factors. This is because factors have to be less than the number they are factors of.
Hope this helps.
temp isn't used. i=1 resets the checking for factors at 1 once a factor is found
Here in this code..
i = 1
resets i as you want the prime factors.. else if it let to increment you will get values like 4 and 6 also.. which would be wrong.
no use of
temp = i;
Here temp variable is not used at all. You may remove it from pgm.
i=1 is done, so that checking of remainder if(number%i==0) can be started from value 2 again.

figure out the prime numbers between 0 and 1000?

I'm trying to make a programm that can calculate the prime numbers between 0 and 1000, the compiler says it has no warning and no erros too, but when i run the programm it gives me an execution error, i have no ideia what it is, does anybody could take a look at my code??
NOTE: i'm a beginner in programming.
#include <stdio.h>
#include <stdlib.h>
int main(){
int i=0;
for (i=0;i<1000;i++){
if (i % 1 == 0 && i % i == 0){
printf("%d",i );
}
printf(" ");
}
return 0;
}
You are performing a division by zero in
i % i == 0
for i = 0.
Moreover, even if you start you cycle from i = 1, the code will give you every integer between 1 and 999, for the expression
i % 1 == 0 && i % i == 0
is true whenever i != 0. Here is a fixed algorithm (not the most efficient, admittedly):
#include <stdio.h>
int main(){
int i; /* no need to initialize to zero */
int j; /* we need a second counter */
for (i=2;i<1000;i++){ /* start from 2 -- one is not prime */
for (j=2;j<i;j++){ /* check for nontrivial divisors */
if (i % j == 0) {
break; /* nontrivial divisor found -> not a prime */
}
}
if (j == i) { /* this means the cycle above run till end */
printf("%d ",i ); /* hence no nontrivial divisors, hence a prime */
}
}
printf("\n");
return 0;
}
The problem is with the expression i % i. In the first iteration of your loop, i is 0, so you are dividing by zero.
You should iterate from 1 to 1000, because dividing with 0 is not allowed and it gives floating point exception.
Also, your algorithm is not correct.
Use code from here:
http://www.programmingsimplified.com/c/source-code/c-program-for-prime-number
What happens when i is 0? My guess is you want to start your loop at 1 (as well as fix your prime number check).
Below python code may help you for following purposes:
To figure out the total number of primes in the range of 0 to given number (upper limit)
To know about each and every number whether that is prime or not
The Complete list of primes fall in the specified range
primes=[]
limit = int(input('What is the maximum limit?'))
for n in range(2,limit+1):
for x in range(2,n):
if n%x == 0:
print('{} -> Not prime'.format(n))
break
else:
primes.append(n)
print('{} -> Prime'.format(n))
print(primes)
print('Total {} primes found'.format(len(primes)))
If you don't want non-prime numbers to display then you can comment out #print('{} -> Not prime'.format(n)) this line and if you don't even want to know all primes comment the consecutive print statement as well i.e. #print('{} -> Prime'.format(n))

Compound conditions using while loop in C.

The program is ignoring Stop when amt is 0 until after 10 numbers have been entered. The program also doesn't stop after 10 numbers have been entered. Where is my error?
main() {
int amt;
int tot = 0; /* running total */
int i = 0; /* counts number of times in loop */
while (amt!=0 || i < 10)
{
printf("Enter a number (enter 0 to stop): ");
scanf("%d", &amt);
tot = tot + amt;
i++;
}
printf("The sum of those %d number is %d.\n", i, tot);
}
Your test is happening before amt is assigned. Thus its results are undefined. This test should be moved to the end of the iteration, i.e. a do/while. Whilst you could assign amt to some non-zero value this feels slightly untidy to me.
And surely you mean to use logical AND rather than logical OR? You only want to continue iterating if both amt is non-zero AND i<10.
Of course, if you did move the test to the end of the iteration then you would have to account for the fact that i had been incremented inside the loop.
In order to stop after 10 numbers or amt=0 (whichever first is met) you'll have to change the loop condition to while (amt!=0 && i < 10)
int amt;
Since you do not initialize it. It has some random value and that causes the Undefined Behavior in your program.
You should always initialize local variables with values.

Resources