void main() {
int low, high, odds = 0;
do {
printf("Please enter a number:");
rewind(stdin);
scanf("%d", &low);
} while (low <= 0);
do {
printf("Please enter the second number:");
rewind(stdin);
scanf("%d", &high);
} while (high < 2 * low);
printf("The odd numbers between %d and %d are: ", low, high);
for (odds = low;odds <= high;odds ) {
if (odds % 2 != 0)
{
printf(" %d", odds);
}
}
printf(".\n");
system("pause"); }
I enter the input which '1' for 'low' variable while '10' for 'high' variable then it shows the result: "The odd numbers between 1 and 10 are 1 3 5 7 9. ".So, how can I improve or change my code by printing output:"The odd ..... 1,3,5,7,9."?
CodePudding user response:
To add commas
int first = 1;
for (odds = low;odds <= high;odds ) {
if (odds % 2 != 0)
{
if(first){ // to prevent comma before first number
first = 0;
} else {
printf("%s",",");
}
printf(" %d", odds);
}
}
could have been
printf("%c", ',');
. Ie a single character, but I used %s just in case you want to add more padding
CodePudding user response:
One nice thing about odd numbers is that you know exactly where they are. Rather that iterating over all the values and checking if each is odd, just find the first odd value and increment by 2:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
int low = argc > 1 ? strtol(argv[1], NULL, 10) : 1;
int high = argc > 2 ? strtol(argv[2], NULL, 10) : 10;
printf("The odd numbers between %d and %d are: ", low, high);
if( low % 2 == 0 ){
low = 1;
}
for( int odd = low; odd <= high; odd = 2 ){
printf("%s%d", odd == low ? "" : ", ", odd);
}
putchar('.');
putchar('\n');
return 0;
}