Regarding if else statements in C language - c

Please explain to me why this code is wrong for the task and below I have explained all the four conditions -[][1]
#include stdio.h
int main()
{
int n;
scanf ("%d", &n); //taking input
if (n / 2 != 0)
{
printf ("Weird"); //checking first condition
}
else if (n % 2 == 0 && 2 <= n <= 5)
{ //checking second condition
printf ("Not Weird");
}
else if (n % 2 == 0 && 6 <= n <= 20)
{ //checking third condition
printf ("Weird");
}
else if (n % 2 == 0 && n > 20)
{ //checking fourth condition
printf ("Not Weird");
}
else
{
printf ("Error");
}
return 0;
}
this is the image for the question[1]: https://i.stack.imgur.com/OtY7o.png**

Testing for Odd or Even
n / 2 != 0 does not test whether n is odd. n/2 calculates the quotient that results from dividing n by 2 (rounding any fraction down). So 0/2 is 0, 1/2 is 0, 2/2 is 1, 3/2 is 1, 4/2 is 2, and so on. So n / 2 != 0 is true for all n other than −1, 0, and 1.
To test whether a number is odd, you can use n % 2 != 0. n%2 calculates the remainder from the division. If it is zero, n is even. If n is not zero, n is odd.
Using Else Efficiently
Once you have tested whether n is odd using n % 2 != 0, you do not have to test whether it is even in the else clauses. The else expressions and their statements will be evaluated only if the if expression is false, which happens (after the correction above) only when n is even. So we do not need to test again.
Testing For an Interval
In C, 2 <= n <= 5 does not test whether n is between 2 and 5. It is parsed as (2 <= n) <= 5. This is evaluated by comparing 2 to n, which produces 0 (if false) or 1 (if true). This result, 0 or 1, is then used in … <= 5. Since 0 and 1 are both less than or equal to 5, the result is always 1 (for true).
To test whether n is greater than or equal to 2 and less than or equal to 5, you must write this out explicitly: 2 <= n and n <= 5, which we join with the “and” operator, &&: 2 <= n && n <= 5.
Other Issues
The proper form for including stdio.h is #include <stdio.h>, not #include stdio.h.
A proper declaration for main is int main(void), not int main().
Corrected Program
A program with these issues corrected is:
#include <stdio.h>
int main(void)
{
int n;
scanf("%d", &n); //taking input
if (n % 2 != 0)
{
printf ("Weird"); //checking first condition
}
else if (2 <= n && n <= 5)
{ //checking second condition
printf ("Not Weird");
}
else if (6 <= n && n <= 20)
{ //checking third condition
printf ("Weird");
}
else if (n > 20)
{ //checking fourth condition
printf ("Not Weird");
}
else
{
printf ("Error");
}
return 0;
}

There is a typo in the line:
if (n / 2 != 0)
The compiler will not complain, but you will get unexpected results at run time.
Here you meant to check if the remainder of division by 2 is not equal to zero (i.e.: modulus operator), and not the division by 2. This line should be
if (n % 2 != 0)
Second thing: you can't tell C to compare values in ranges like this 2 >= n >= 4. You will have to split the comparison into 2 comparisons. This line:
else if (n % 2 == 0 && 2 <= n <= 5)
Should be:
else if (n % 2 == 0 && 2 <= n && n <= 5)
You will need to fix all the lines that have this comparison as well.

Related

how can i exit the program without it returning a value?

output is 0 when entered 1001 or something greater than it.
it should give 0 when the number isn't abundant and should exit if entered number is greater than the limit ,have tried using goto exit.
#include <stdio.h>
void main()
{
int n;
printf("Enter the number\n");
scanf("%d", &n);
int i, sum = 0;
if (1 <= n <= 1000)
{
for (i = 2; i < n; i++)
{
if (n % i == 0)
sum = sum + i;
}
(sum > n) ? printf("1") : printf("0");
}
else
return;
}
The condition in this if statement
if (1 <= n <= 1000)
is equivalent to
if ( ( 1 <= n ) <= 1000)
the result of the sub-expression 1 <= n is either 0 or 1. So this value is in any case less than 1000.
From the C Standard (6.5.8 Relational operators)
6 Each of the operators < (less than), > (greater than), <= (less than
or equal to), and >= (greater than or equal to) shall yield 1 if the
specified relation is true and 0 if it is false. The result has type
int.
You need to write
if (1 <= n && n <= 1000)
using the logical AND operator.
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )

C program to print all the prime numbers from 1-300

I have written this code for C to print prime numbers from 1-300
GNU GCC Compiler shows the following error:
error: invalid operands to binary % (have ‘double’ and ‘int’)
if (sqrt(num) == 0 || sqrt(num) % 2 != 0)
My code is this:
#include <stdio.h>
#include <math.h>
int main() {
/*Created by Suvid Singhal Date:- January 2, 2017*/
int num;
printf("Welcome to 1-300 prime numbers C Program!!!");
for (num = 0; num <= 300; num++) {
if (sqrt(num) == 0 || sqrt(num) % 2 != 0) {
printf("%d\n", num);
} else {
continue;
}
}
return 0;
}
You have lots of thing going wrong in your answer.
Let's check them one by one.
Your idea about prime number is not clear. A prime number has no divisior except the number and 1. (1 is not a prime number).
How to check if a number is prime or not?
You can check all the `numbers <=square root of (x). So you need to check if someone (except 1 ) divides the number. If yes then it is not prime else it is.
Implementation Details
int check= 0;
for(int i=2;i<=(int) sqrt(x);i+=1)
if(n%i == 0)
{
check = 1;
n is non-prime;
break; // no need to check
}
if(check == 0)
n is prime
sqrt() return double and ...
Modulous can be applied over an int so you have to cast it to that.
If you want to avoid it all
for(int i=2;i*i<=x;i++)
...
For you to study
Learn about sieve method to get the primes. For 300 numbers probably it doesn't matter what you use but in case it is 10000000 then you will definitely want to give it a read.
% operator is for integers. You may want to use fmod() or an integer cast.
if ( sqrt( num ) == 0 || fmod( sqrt( num ), 2 ) != 0 )
or
if ( sqrt( num ) == 0 || (int) sqrt( num ) % 2 != 0 )
This should fix your compilation errors.
ps: If you are looking for an awesome way to generate prime numbers, see Sieve of Erastosthenes
In the code sample you have given, it is not quite clear how you intend to determine whether a number is prime or not. You have the following condition if (sqrt(num) == 0 || sqrt(num) % 2 != 0) to apparently determine a number as prime. But this condition is syntactically invalid. As others have pointed out, you can't do modulo operation on a non-int number as returned by the sqrt function. What value, do you think, is returned by the operation sqrt(num) % 2 and what has it do with a number being prime? Your usage of continue has also no importance. Maybe you are a little confused between break and continue. I am giving you a sample program. Try to learn what your mistakes are from this:
int isPrime = 1;
for(int i=2;i<=300;i++) {
isPrime = 1;
for(int j=2; j!=i && j <= ceil(sqrt(i));j++) {
if(i%j == 0) {
//Not a prime number
isPrime = 0;
break;
}
}
if(isPrime) {
printf("%d\n", i);
}
}
Changing
if( sqrt(num) == 0 || sqrt(num) % 2!=0 )
to
if( sqrt(num) == 0 || (int)sqrt(num) % 2!=0 )
Should fix compilation errors. See error: invalid operands to binary % when taking modulus of float for more info.

scanf does not ask for input

It takes a lot of time to compile, and some random number shows up, apparently the scanf() doesn't ask for the input
#include <stdio.h>
int main() {
int a;
//a = 1472464;
scanf ("%d", &a);
if ((a % 6) && (a %4) == 0)
{
printf("Input %d is divisible by 6 and 4\n", a);
}
else {
printf(" Input %d is not divisible by 6 and 4\n", a);
}
printf("Hello, World!\n");
return 0;
}
This line is wrong:
if ((a % 6) && (a %4) == 0)
It should be:
if ((a % 6) == 0 && (a %4) == 0)
I don't see any other obvious problem with the code.
The expression (a % 6) && (a %4) == 0 does not compare both modulo-operations with zero. Instead it does (a % 6) which will result on a number between 0 and 5, and use that as a boolean value that it then uses with the result of (a %4) == 0.
Instead you need to do each comparison separately: (a % 6) == 0 && (a % 4) == 0
The important thing to know here is that in C only zero and a null pointer is considered "false". Anything that is not zero (or a null pointer) is true.
That means that if a for example is 4 then a % 6 will be "true" since a % 6 is 4 which is not zero. Conversely when a is for example 6 then a % 6 will be 0 which is "false".
So using only a % 6 will actually give the opposite result to what you want, it will be "true" when a is not evenly dividable by 6.

C Programming: What conditions do I put for an if statements for numbers 1 to 35 inclusive?

Okay I need help with translating sentences to condition statements in C.
For example, if I want my input to be from 1 to 35 (inclusive), and only want odd integer inputs, how would I go about making a conditional statements?
Is it:
int n;
while(1){
printf("What is the value for n you wish to use (please use an odd number?: ");
scanf("%d", &n);
if(n%2=0 && n<=35 && n>=1)
if(n<1)
break;
}
if (n%2=0 && n<=35 && n>=1)
is (almost) the condition for even numbers, those exactly divisible by 2. Note that the equality operator is ==. For odd, you want
if (n%2==1 && n<=35 && n>=1)
With this, you do not need any more if statements.
This n%2=0 should be (for odd numbers) n%2 == 1
And if you want to break on a number not matching your conditions, use something like this in the loop:
if(!((n%2 == 1) && (n<=35) && (n>=1)))
break;
}
Now if you want to break from a loops if any one of following condition get satisfies
The number must be above 1
The number must be below 35
The number must be odd
Then you can write:
if(n%2==1 || n>=35 || n<=1) break;
First, let's define the tests for 1 to 35 inclusive. C supports short circuiting, we should test the simple things -
if (n > 0 && n < 36) /* <---- 1 to 35 */
if (n >= 1 && n <= 35) /* <---- 1 to 35 */
or
#define MIN 1
#define MAX 35
if (n >= MIN && n <= MAX) /* MIN to MAX */
However, your code is incorrect. The second if will ever evaluate to true since the first requires n>=1
if(n%2=0 && n<=35 && n>=1)
if(n<1)
break;
I believe you wanted
if (n > 35 || n < 1) {
break;
}
A test for even should just continue (and not end the loop), or you could test for odd and just display those,
if (n % 2 == 0) continue;
or
if (n % 2 != 0) printf("%i\n", n);

Find out max divisor of a positive integer

I need to find the biggest divisor of a positive integer and output it. Divisor should not be 1 or be equal to the integer itself. If it's a prime number the output should be "0". I have this code so far. However it doesn't work. It only works when I use "break" instead of "return 0" statement, but according to the task I should not use break :( How can I fix it? Thnx
#include <stdio.h>
int main() {
int input, maxDiv;
int div = 2;
scanf("%d", &input);
for ( ; div <= input/2; div += 1 ) {
if ( input % div == 0 ) {
maxDiv = input / div;
return 0;
} else {
maxDiv = 0;
}
}
printf("%d\n", maxDiv);
return 0;
}
You can rewrite it this way
int main(){
int input, maxDiv = 0;
int div = 2;
scanf("%d", &input);
for(; !maxDiv; div++)
if(!(input%div))
maxDiv = input/div;
printf("%d\n", ( maxDiv == 1 || input < 0 ? 0 : maxDiv ) );
return 0;
}
It is an infinite loop that will exit as soon as maxDiv != 0. The complexity is O(sqrt (n)) as there is always a divisor of n less than or equal to sqrt(n), so the code is bound to exit (even if input is negative).
I forgot, you have to handle the case where input is zero.
Maybe you can declare a flag?
#include <stdio.h>
int main() {
int input, maxDiv;
int div = 2;
char found = 0;
scanf("%d", &input);
for ( ; div <= input/2 && !found ; div += 1 ) {
if ( input % div == 0 ) {
maxDiv = input / div;
found = 1;
} else {
maxDiv = 0;
}
}
printf("%d\n", maxDiv);
return 0;
}
You can stop the loop when you reach sqrt(input)... it's not that difficult to find a perfectly good integer sqrt function.
There's not a lot of point dividing by all the even numbers after 2. In fact there's not a lot of point dividing by anything except the primes. It's not hard to find the primes up to sqrt(INT_MAX) (46340, for 32-bit integer)... there are tables of primes freely available if you don't want to run a quick sieve to generate same.
And the loop...
maxdiv = 0 ;
i = 0 ;
sq = isqrt(input) ;
while ((maxdiv == 0) && (prime[i] < sq))
{
if ((input % prime[i]) == 0)
maxdiv = input / prime[i] ;
i += 1 ;
} ;
assuming a suitable integer sqrt function and a table of primes... as discussed.
Since you are looking for the largest divisor, is there a reason you're not looping backward to 2? If there isn't, then there should be no need for a break statement or any special logic to exit the loop as you should keep looping until div is greater than input / 2, testing every value until you find the largest divisor.
maxDiv = -1;
for (div = input / 2;
div >= 2 && maxDiv == -1;
--div)
{
if (input % div == 0)
maxDiv = div;
}
maxDiv += (maxDiv == -1);
printf ("%d\n", maxDiv);
I added the extra condition of maxDiv being -1, which is like adding a conditional break statement. If it is still -1 by the end of the loop, then it becomes 0 because maxDiv += 1 is like writing maxDiv = -1 + 1, which is 0.
Without any jump statement such as break, this sort of test is what you must do.
Also, regarding your code, if I input 40, the if statement will be triggered when div is 2, and the program will end. If the return 0 is changed to a break, maxDiv will be 2, not 20. Looping backward will find 20 since 40/2=20, and 40%20==0.
Let us denote D to the max divisor of a given composite number N > 1.
Then, obviously, the number d = N / D is the min non-trivial divisor of N.
If d would not a primer number, then d would have a non-trivial divisor p < d.
By transitivity, this implies that p is a divisor of N, but this fact would contradict the fact that d is the min divisor of N, since p < d.
So, d must be a prime number.
In particular, it is enouth to search over those numbers which are less than sqrt(N), since, if p is a prime number greater than sqrt(N) which divies N, then N / p <= sqrt(N) (if not, *p * (N / p) > sqrt(N)sqrt(N) == N, wich is absurd).
This shows that it's enough to do the search the least divisor d of N just within the range of primer numbers from 2 to sqrt(N).
For efficiency, the value sqrt(N) must be computed just once before the loop.
Moreover, it is enough a rough approximation of sqrt(N), so we can write:
#include <math.h>
#include <stdio.h>
int main(void)
{
int N;
scanf("%d",&N);
// First, we discard the case in that N is trivial
// 1 is not prime, but indivisible.
// Change this return if your want.
if (N == 1)
return 0;
// Secondly, we discard the case in that N is even.
if (N % 2 == 0)
return N / 2;
// Now, the least prime divisor of N is odd.
// So, we increment the counter by 2 in the loop, by starting in 3.
float sqrtN = fsqrt(N); // square root of N in float precision.
for(d = 3; d <= sqrtN; d += 2)
if (N % d == 0)
return N/d;
// If the loop has reached its end normally,
// it means that N is prime.
return 0;
}
I think that the problem is not well stated, since I consider that a better flag to signalize that N is prime would be a returned value of 1.
There are more efficient algorithms to determine primality, but they are beyond the scope of the present question.

Resources