How do i print all the odd numbers? - c

I want to print all the odd numbers from 14 to 156 using an infinite loop, break and continue. But, when i run it does not display anything!!
int main()
{
int x;
int y = 14;
while(x) {
if(y % 2 == 0) {
continue;
}
else if(y % 3 == 0) {
printf("%d\n", y);
}
if(y == 156) {
break;
}
y++;
}
return 0;
}

The problem with your code is that it uses an operation with unpredictable results. Specifically, declaring int x; without initializing it, and then using it as your termination condition in while(x) is the problem. On many platforms and compilers, this will retain whatever value was already in the memory occupied by x. In that case, you may see no print statements because x starts with the value zero and the loop never runs.
You should make your loop into an infinite loop:
int main()
{
int x;
for(x = 14; ; x++) {
if(x % 2 == 0) {
continue;
}
if(x >= 156) {
break;
}
printf("%d\n", x);
}
return 0;
}
[IDEOne link]
This will print the values excluding 156 itself. To include 156, put the break condition after the printf call:
printf("%d\n", x);
if(x >= 156) {
break;
}
Alternatively you can change >= to just >.
You do not need else if you have break or continue.
If you have to use a while loop, the situation is a tad more complex because you have to increment before you continue to avoid an infinite loop:
int main() {
int x = 14;
while(1) {
if(x % 2 == 0) {
x++;
continue;
}
if(x >= 156) {
break;
}
printf("%d\n", x++);
}
return 0;
}
[IDEOne Link]
You can avoid the extra increment if you can forgo the continue:
int main() {
int x = 14;
while(1) {
if(x % 2) {
printf("%d\n", x);
}
if(x++ == 156) {
break;
}
}
return 0;
}
[IDEOne Link]
I have also removed your check for x % 3 == 0 since it is not clear what the purpose of that is within the constraints of your problem.

With an infinite loop:
#include <stdio.h>
#include <stdlib.h>
int main() {
int y=14;
while(1){
if(y & 1){
printf("%d\n",y);
}
if(y>=156){
break;
}
y++;
}
return 0;
}
Preferred method, with for loop:
#include <stdio.h>
#include <stdlib.h>
int main() {
int start=14;
start |= 1; //This will increment by one if your start value is even
for (start; start<=146; start+=2) {
printf("%d\n", start);
}
return 0;
}

An infinite loop with a break is not the right way to do this. Use a "for" loop and your code will be much clearer. Start it at 15 and increment by 2 until 156.

There are several problems in your logic.
1. Variable `x` is of no use. You can use variable `y` to terminate the loop.
2. No need to check if the number is a multiple of 3.
3. No need to check for even numbers is either.
I have modified the code and it is giving correct results but I'll urge you to read the above points and try to get the code right.
int main()
{
int y = 14;
while(y) {
if (y==156)
break;
if(y % 2 != 0) {
printf("%d ",y);
}
y++;
}
return 0;
}
A better and faster way would be to start with 15 and increment variable y's value by 2 till its <=156.
int main()
{
int y = 15;
while(y) {
if (y==157)
break;
printf("%d ",y);
y+=2;
}
return 0;
}

Your code has undefined behavior because the variable x is uninitialized and used as the condition in the while statement. You could fix this with while (1) but there would indeed be an infinite loop in your program because the test for evenness occurs before the test for termination on 156.
The problem is solved simply with a standard for loop:
#include <stdio.h>
int main(void) {
for (int y = 14; y < 156; y++) {
if (y % 2 != 0) {
printf("%d\n", y);
}
}
return 0;
}
Which can be simplified as this, only enumerating odd numbers:
#include <stdio.h>
int main(void) {
for (int y = 15; y < 156; y += 2) {
printf("%d\n", y);
}
return 0;
}
If you are required to use break, continue and a infinite loop, you can indeed use the classic forever C loop, a for loop without a termination condition:
#include <stdio.h>
int main(void) {
for (int y = 14;; y++) {
if (y == 156)
break;
if (y % 2 == 0)
continue;
printf("%d\n", y);
}
return 0;
}

Well ...
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
/* Prints even or add numbers between to and from.
Works for negative numbers.
Works up and down.
*/
int print_even_or_odd(long long from, long long to, int even)
{
if (((INT32_MAX < from) || (INT32_MIN > from)) ||
((INT32_MAX < to) || (INT32_MIN > to)))
{
fprintf(stderr, "Invalid input.\n");
errno = EINVAL;
return -1;
}
printf("from=%d to %d\n", (int) from, (int) to);
int sign = (to < from) ?-1 :1;
/* Adjust "from" to next even/odd number. */
if ((!even && !(from & 1)) || (even && (from & 1)))
{
from += sign;
}
/* Adjust "to" to the previous even/odd number. */
if ((!even && !(to & 1)) || (even && (to & 1)))
{
to -= sign;
}
{
size_t steps = (size_t) (sign * ((to - from) / 2)) + 1;
if (0 == steps)
{
printf("Nothing to do.\n");
return 0;
}
while (1)
{
if (0 >= steps)
{
break;
}
--steps;
printf("%d\n", (int) (to - sign * 2 * (int) steps));
continue; /* as having continue is a requirement ... ;-) */
}
}
return 0;
}
int main(void)
{
print_even(14, 156, 0);
print_even(156, 14, 0);
print_even(-14, -156, 0);
print_even(-156, -14, 0);
}

Related

finding prime numbers between a range in C

I am trying to find the prime numbers in a range using C language. My code does not give an output and I think there is a logical error here which I cannot figure out. Can anyone please help?
#include <stdio.h>
int main() {
int lowerLevel;
int upperLevel;
int i; //counter variable
int prime = 0;
int flag = 0;
printf("Enter the lower limit and upper limit of the range followed by a comma :");
scanf("%d %d", &lowerLevel, &upperLevel);
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
}
Your code does not check for prime numbers, it merely checks that there is at least one even number between 2 and upperlevel, which is true as soon as upperlevel >= 2. If there is such an even number, nothing is printed.
You should instead run a loop from lowerlevel to upperlevel and check if each number is a prime and if so, print it.
Here is a modified version:
#include <stdio.h>
int main() {
int lowerLevel, upperLevel;
printf("Enter the lower limit and upper limit of the range: ");
if (scanf("%d %d", &lowerLevel, &upperLevel) != 2) {
return 1;
}
for (int i = lowerLevel; i <= upperLevel; ++i) {
int isprime = 1;
for (int p = 2; p <= i / p; p += (p & 1) + 1) {
if (i % p == 0) {
isprime = 0;
break;
}
}
if (isprime) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
This method is simplistic but achieves the goal. More efficient programs would use a sieve to find all prime numbers in the range without costly divisions.
Optimal method with Sieves of Eratosthenes
You should use the sieves of Eratostenes algorithm, it is way more efficient to get the different prime number.
it does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime number, 2
Basically you consider all numbers prime by default, and then you will set as false the prime number, see below code:
#include <stdio.h>
/// unsigned char saves space compared to integer
#define bool unsigned char
#define true 1
#define false 0
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
void printPrimesRange(int lowerLevel, int n) {
if (lowerLevel < 0 || n < lowerLevel) // handle misused of function
return ;
bool isPrime[n + 1];
memset(isPrime, true, n + 1);
int cnt = 0; // NB: I use the counter only for the commas and final .\n, its optional.
if (lowerLevel <= 2 && n >= 2) { // only one even number can be prime: 2
++cnt;
printf("2");
}
for (int i = 3; i <= n ; i+=2) { // after what only odd numbers can be prime numbers
if (isPrime[i]) {
if (i >= lowerLevel) {
if (cnt++)
printf(", ");
printf("%d", i); // NB: it is better to print all at once if you can improve it
}
for (int j = i * 3; j <= n; j+=i*2) // Eratosthenes' Algo, sieve all multiples of current prime, skipping even numbers
isPrime[j] = false;
}
}
printf(".\n");
}
int main(void) {
int lowerLevel;
int upperLevel;
printf("Enter the lower limit and upper limit of the range with a space in-between:"); // space, not comma
scanf("%d %d", &lowerLevel, &upperLevel);
printPrimesRange(lowerLevel, upperLevel);
return 0;
}
Let's follow the logic of your code:
#include <stdio.h>
#include <string.h>
int main() {
int lowerLevel;
int upperLevel;
int i; //counter variable
int prime = 0;
int flag = 0;
printf("Enter the lower limit and upper limit of the range followed by a comma :");
scanf("%d %d", &lowerLevel, &upperLevel);
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
}
First of all, you have a loop:
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
this loop tries to find a number i that is a multple of 2, because as soon you get one, you jump out of the loop. So your loop can be expressed better as:
for (i = 2; i <= upperLevel && i % 2 != 0; ++i) {
}
/* i > upperLevel || i % 2 == 0 */
if (i <= upperLevel && i % 2 == 0) {
flag = 1;
}
We still need to check if i <= upperLevel && i % 2 == 0 to set the variable flag = 1 if we exited the loop because i was a multiple of 2, but the break; is not necessary because we are already out of the loop.
Now let's check that the first value we initialize i is, indeed 2 (which is a multiple of 2) and the consecuence of this is that the loop is never going to be entered. Se we can eliminate it completely, giving to:
i = 2;
if (i <= upperLevel && i % 2 == 0) {
flag = 1;
}
now, the second clause of the if test is always true, so we can take it off, giving:
i = 2;
if (i <= upperLevel) {
flag = 1;
}
Now, let's append the second part:
i = 2;
if (i <= upperLevel) {
flag = 1;
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
so, the first thing we see here is that your ++i; statement is nonsense, as it is the last statement to be
executed before exiting the program, so we can also take it off.
i = 2;
if (i <= upperLevel) {
flag = 1;
}
if (flag == 0) {
printf("%d", i);
}
return 0;
Now we see that you print the value of i only if the value of flag is zero, but flag only conserves its zero value if the value of i > upperLevel, and as i is fixed, the printing of i only occurs if you input a value of upperlevel that is less than 2.
We can rewrite the above code as this:
if (2 > upperLevel) {
printf("%d", 2);
}
Your program will print 2 only if you provide a value of upperLevel less than 2.

C Programming: Removing Unnecessary Commas From Result of Prefix Sum Code

I recently made code in C that reads a set of numbers until zero (zero ends the number set) and prints its prefix sum:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, sum;
sum = 0;
while(x)
{
scanf("%d", &x);
sum += x;
if(x != 0)
{
printf("%d,", sum);
}
else{
break;
}
}
return 0;
}
If I were to type 2 3 5 7 11 0: It would print the following:
2,5,10,17,28,
I was wondering how to remove the comma by the number 28 or to add commas to numbers until the last number?
My preferred solution, adapted to the code in the question, is:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int sum = 0;
int x;
const char *pad = ""; /* Or put a prefix here */
while (scanf("%d", &x) == 1 && x != 0)
{
sum += x;
printf("%s%d", pad, sum);
pad = ","; /* Or use ", " if you prefer */
}
putchar('\n');
return 0;
}
Note that this code does not test the uninitialized variable x on the first iteration (unlike the code in the question), and it checks that the scanf() succeeds before using the value (unlike the code in the question). These are routine precautions you should be taking. It would be possible to adapt the code to keep track of how many bytes have been printed on the line (what's the return value from printf()?) and arrange for pad to contain "\n" (instead of a comma, or ",\n" if you want a comma at the end of all lines except the last) when the line gets 'too long'.
Note too that if you type the numbers at the program, the output gets messy. If the program is reading from a built-in list of numbers, or reading from a file, then you get good outputs.
You could use the following approach:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 0;
int sum = 0;
int i = -1;
int ret;
while(1)
{
i++;
ret = scanf("%d", &x);
if(ret != 1)
break;
sum += x;
if(x != 0)
{
if(i == 0)
printf("%d", sum);
else
printf(",%d", sum);
}
else
{
break;
}
}
printf("\n");
return 0;
}
Output:
1
2
3
0
1,3,6
Print the comma before all but the first value. It's not elegant but it works.
if(x != 0)
{
if(sum == x) // On the first pass, sum == x
printf("%d", sum);
else
printf(",%d", sum);
}
Of course, this could break if you have negative values. In that case, keeping a counter or bool would be better.
print comma only after the first iteration (use a custom flag) , print result no matter what:
int first_iteration = 1;
...
if (!first_iteration)
{
printf(",");
}
sum += x;
first_iteration = 0;
printf("%d", sum);
There is always a clumsy but tried-and-true method:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, sum;
sum = 0;
comma = 0;
while(x)
{
scanf("%d", &x);
sum += x;
if(x != 0)
{
if (comma != 0)
{
printf(",");
}
printf("%d", sum);
comma = 1;
}
else{
break;
}
}
return 0;
}

C - Reading and 2d int array with rows terminated by 0 until end of input

I am trying to write a program in C that will read max of 50 rows of 5 integers and print them after reaching end of stdin.
#include <stdio.h>
#include <stdlib.h>
int readInput(int numbers[][5], int row) {
int x, i = 0;
while (1) {
if (scanf("%d", &x) !=1 ) exit (1);
if (x == 0) {
return 1;
}
if (feof(stdin)) {
return 0;
}
numbers[row][i] = x;
i++;
}
}
int main ( void ) {
int numbers[50][5];
int row = 0; int val;
int i,j;
while (1) {
val = readInput(numbers, row);
if ( val == 1){
row++;
continue;
} else if (val == 0) {
break;
}
}
for (i = 0; i < row+1; i++) {
for ( j = 0; j < 5; j++) {
printf("%d ", numbers[i][j]);
}printf("\n");
}
}
Problem is that no matter how I try to tell the program that the endless loop in main needs to end, it never does. I really need to understand the concept of reaching end of input, that is why I dont want to simply write a loopthat finishes after a certain amount of iterations, I want to learn how to break the loop after reaching end of stdin.
Your current code doesn't capture the EOF that scanf may return.
You can try something like:
int readInput(int numbers[][5], int row) {
int x, i = 0;
while (1) {
int t = scanf("%d", &x); // Save return value
if (t == EOF) return 0; // Check for EOF
if (t !=1 ) exit (1);
if (x == 0) {
return 1;
}
numbers[row][i] = x;
i++;
}
}
CTRL+D (or CTRL+Z for windows) can be used to indicate EOF

Why does my program return the same character?

This is a program that checks whether the input number is a product of two prime numbers ('Y') or not ('N').
#include <stdio.h>
// the function checks if the number is prime
int is_prime(int z) {
int i;
for(i=2; i<z; i++){
if(z%i == 0){
return 0;
}
return 1;
}
}
/* the function checks if the given number is a
product of two prime numbers bigger than 2*/
int is_prime_product(int x) {
int j;
for(j=2; j<x; j++){
if(x%j == 0){
if(is_prime(x/j) && is_prime(j)){
return 1;
break;
}else return 0;
}
}
}
int main() {
int n=0;
int c;
do{
c=getchar();
if((c>='0') && (c<='9')){
n= n*10+(c-'0');
}
} while (('0'<=c) && (c<='9'));
if(is_prime_product(c)){
putchar('Y');
}else{
putchar('N');
}
return 0;
}
I don't know why this program always returns 'Y' even when it should return 'N'. I just don't see where the mistake is.
Partial answer: Better version of is_prime:
int is_prime(int z)
{
if(z <= 1) return 0;
if(z == 2) return 1;
int i;
for(i=3; i<sqrt(z); i+=2)
{
if(z%i == 0) return 0;
}
return 1;
}
After the test for 2 it is enough to test for odd factors up to the square root of your test number. (Also fixed the curly braces)
Cause of your error:
if(is_prime_product(n)) ...
tests the input number nnot the last character c
Edit
Some hints for better (more readable, more reliable, and so on) code:
Use types matching the problem (bool instead of int)
Use good variable names (i only for loops, z only for floats)
use meaningful variable names (number instead of n)
consistent braces, spacing around operators
These things make a difference!
Have a look:
bool is_prime(unsigned int number)
{
if(number <= 1) return false;
if(number == 2) return true;
for(unsigned int factor = 3; factor < sqrt(number); factor += 2)
{
if(number % factor == 0) return false;
}
return true;
}
Please cheak your is_prime() function. The code return 1; should be after the for loop.You can try the following:
int is_prime (int z)
{
int i;
for (i = 2; i < z; i++)
{
if (z % i == 0)
{
return 0;
}
}
return 1;
}
and your function is_prime_product () should be written as follow:
int is_prime_product (int x)
{
int j;
for (j = 2; j < x; j++)
{
if (x%j==0&&is_prime (x / j) && is_prime (j))
{
return 1;
}
}
return 0;
}
also you should use if (is_prime_product (n)) instead of if (is_prime_product (c)).
I have modified some of your code from main function.
Please try with below code once,
Instead of this main function code:
int main() {
int n=0;
int c;
do{
c=getchar();
if((c>='0') && (c<='9')){
n= n*10+(c-'0');
}
} while (('0'<=c) && (c<='9'));
if(is_prime_product(c)){
putchar('Y');
}else{
putchar('N');
}
return 0;
}
Use this code:
int main() {
int n=0;
int c;
scanf("%d",&c);
do{
if((c>='0') && (c<='9')){
n= n*10+(c-'0');
}
} while (('0'<=c) && (c<='9'));
if(is_prime_product(c)){
putchar('Y');
}else{
putchar('N');
}
return 0;
}

Finding Prime numbers from 1 to 300 in C

I have typed the following program in C language:
#include <stdio.h>
int main ()
{
int i = 1, a = 2;
while (i <= 300)
{
while (a < i)
{
if (i % a == 0)
break;
else
printf ("%d\n", i);
a++;
}
i++;
}
return 0;
}
The program is printing many non-prime values too like 295, 275, etc...
Please help, I'm a beginner and lacks much experience.
Beside the fact that you're not resetting a to 2, the printf() statement is not placed correctly. This will print any number of i that cannot be divided by 2 (even if it can be divided by another number).
Change your code like this:
#include <stdio.h>
int main ()
{
int i = 1, a = 2, is_prime;
while (i <= 300)
{
is_prime = 1;
while (a < i)
{
if (i % a == 0) {
is_prime = 0;
break;
}
a++;
}
if(is_prime)
printf ("%d\n", i);
a = 2;
i++;
}
return 0;
}
You need to set a back to 2 before you enter the loop:
#include <stdio.h>
int main ()
{
int i = 1, a = 2;
while (i <= 300)
{
a = 2; // add this line
while (a < i)
{
if (i % a == 0)
break;
else
printf ("%d\n", i);
a++;
}
i++;
}
return 0;
}
Your method isn't very fast. You should read this page http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

Resources