I need to build a program, that would write all numbers from 0 to 100, but will place an * instead of any number that contains the digit 3 or can be divided by 3. This is what I have so far. How can I make it work?
#include <stdio.h>
main() {
int i, c;
c = 100;
for (i = 0; i <= c; i++) {
if (i % 3 == 0) {
printf("*");
}
if (i)
printf("%d\n", i);
}
}
place an * instead of any number that contains the digit 3 or can be divided by 3.
OP's code took care of the "can be divided by 3" with i % 3 == 0.
How about a little divide and conquer for the "contains the digit 3"? Put a function in there.
if (contains_the_digit(i, 3) || (i % 3 == 0)) {
printf("*\n");
} else {
printf("%d\n", i);
}
Now what is left is to define contains_the_digit(int i, int digit)
Mathematically (nice and efficient):
bool contains_the_digit_via_math(int i, int digit) {
do {
if (abs(i % 10) == digit) { // Look at the least digit, abs() to handle negative `i`
return true;
}
i /= 10; // Now look at the upper decimal digits
} while (i);
return false;
}
Or textually:
bool contains_the_digit_via_string(int i, int digit) {
char buf[30]; // Something certainly big enough
sprintf(buf, "%d", i);
return strchr(buf, digit + '0') != NULL;
}
Or use your imagination for other ideas.
The key is to take your problems and reduce them to smaller ones with helper functions: divide and conquer.
Concert the number to a string
Replace '3' with '*' within that string
i.e.
int to_be_converted =12345612343242432; // Or summat else
char num[100]; // Should be more than enough
sprintf(num, "%d", to_be_converted);
for (int i =0; num[i]; i++) {
if (num[i] -- '3') num[i] = '*';
}
printf("Here you go %s", num);
That should do the trick
Just ad the bit to go through the numbers and check if divisible by 3. I leave that to the reader.
Seeing you forgot to add the return type int to your int main(), I think this is a good time to learn to write your own function!
In this case, you want a function that can check whether the last digit of a number is a 3 when you represent that number as base-10. That's easy! The function should look like (you need to #include <stdbool.h> at the beginning of your file, too):
bool ends_in_decimal_3(int number) {
// figure out a way to find the difference
// between number, rounded to multiples of 10
// and the original number. If that difference==3,
// then this ends in 3 and you can `return true;`
}
Armed with that function, you can see whether your i itself ends in 3, or whether i/10 ends in 3 and so on. Remembering that division / in C between ints always rounds down is a good trick to do that, and also an important hint on how to implement your rounding in ends_in_decimal_3.
I wrote a simple program (included below) that takes a 5-digit number, reverses and prints it.
#include <stdio.h>
#include <limits.h>
#include <math.h>
int main(void)
{
unsigned short num, revnum, digit, count;
count = 4;
revnum = 0;
fprintf(stdout, "Enter a five digit number in range [0 - %hu]: ", USHRT_MAX);
fscanf(stdin, "%hu", &num);
while (count >= 0) {
digit = num % 10;
num = num / 10;
revnum += digit * pow(10, count);
count--;
}
fprintf(stdout, "The number with digits reversed is %hu.\n", revnum);
return 0;
}
However the program when run, doesn't return anything post taking input and storing it in the num variable. It didn't crash/exit either. There is nothing wrong with the while loop's body, so I suspected an infinite loop and wrote a small program just to print out the count variable from a similar while loop
#include <stdio.h>
int main(void)
{
unsigned short count;
count = 4;
while (count >= 0) {
printf("%hu", count);
count--;
}
return 0;
}
This indeed turns out to be an infinite loop... a part of the output is:
...300653005530045300353002530015300052999529985299752996529955299452993529925299152990529895298852987529865298552984529835298252981529805297952978529775297652975529745297352972529715297052969529685296752966529655296452963529625296152960529595295852957529565295552954529535295252951529^C
My assumption is that the culprit is the count's type which is unsigned short. As this means it can't decrement below 0, so the final count-- when count already == 0 sets its value to USHRT_MAX and thus can never terminate the loop. Am I correct?
Your assumption is correct: being your variable unsigned it won't ever be evaluated as negative.
In your case, if you decrement the count variable when it is equal to 0 you get the value 65535 (USHRT_MAX).
The trivial solution is getting rid of the unsigned keyword:
short count = 4;
This solution is the best for the basic code provided in the question. Anyway, since in the "real code" could happen that changing the type of the counter is not an option, a check on count == 0 before decrementing could be the solution (credits to #Elijan9):
while (true)
{
/* ...; */
if (count == 0)
break;
--count;
}
I'm trying to convert a number in to a binary string:
void num_to_binary(const int num, char *binary) {
int number = num;
for(int i = 0; number > 0; i++){
binary[i] = number % 2;
number = number/ 2;
}
int length = strlen(binary);
binary[length] = '\0';
printf("%s", binary);
}
While I'm sure that the binary string contains what I want (I tested the code by using
printf("printed %d end",binary[i]); in the for loop), I was unable to print it out by writing the code printf("%s", binary);
Any suggestions would be much appreciated! Thank you.
you have to do binary[i] = !!(number % 2) + '0';, otherwise strlen() will find the null character (value zero) somewhere it shouldn't, it is probably the first character in your case. See the code below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void num_to_binary(const int num, char *binary) {
int number = num;
for(int i = 0; number > 0; i++){
binary[i] = !!(number % 2) + '0';
number = number/ 2;
}
int length = strlen(binary);
binary[length] = '\0';
printf("%s", binary);
}
int main(void)
{
char buffer[100];
num_to_binary(25, buffer);
return 0;
}
The issue is that you're setting the values of a character string to either 1 or 0. When that string gets printed, those numbers are interpreted by the ASCII table. Both 1 and 0 represent unprintable characters. In fact, 0 is called a "null terminator" which will cause C to stop printing when it sees that value.
Instead, you want the ASCII representations of "1" and "0", which are 31 and 30, respectively. So, you could replace that line with
binary[i] = 30 + number % 2;
EDIT:
It should be 30 + !!(number % 2). That will take care of the situation when number is negative.
binary[i] = number % 2; in this line, you're just storing a integer value to a string. And every time the value is either 0 or 1. So, printf("%s", binary); shows the charactera corresponding to ASCII 0 or 1.
The ASCII value for character '0' is 48 and '1' is 49. You have two ways:
binary[i] = number % 2 + 48; or,
binary[i] = number % 2 + '0';
I would like to make the output of a number to always have 6 digits
e.g.:
if number is 1 the output should be 100000
if number is 23 the output should be 230000
if number is 236 the output should be 236000
How can I do this with printf/sprintf?
printf and its variants can pad zeroes to the left, not to the right. sprintf the number, then add the necessary zeros yourself, or make sure the number is 6 digits long:
while(num < 100000)
num *= 10;
(This code assumes the number isn't negative, or you're going to get in trouble)
printf will return the number of character printed out. This you can print out the remaining zeros:
int num = 3; // init
int len = printf("%d", num);
for (int i = 0; i < 6-len; ++i)
printf("0");
You should add some error checks (for example, if len is larger than 6).
With sprintf, you can use memset on the remaining buffer, which will be easier.
You can't do it directly with printf (at least in a standard-conforming way), you need to alter your numbers beforehand.
Use the return value of printf (as in the first line of the for loop below)
#include <stdio.h>
int main(void) {
int number, width = 6;
for (number = 1; number < 9999999; number *= 7) {
int digits = printf("%d", number);
if (digits < width) printf("%0*d", width-digits, 0);
puts("");
}
return 0;
}
See code running at http://ideone.com/TolIv
As Luchian said, this behavior is unsupported in printf, unlike the much more common reverse (left) padding.
You could, however, easily enough generate the requested result with something like this:
char *number_to_six_digit_string(char *resulting_array, int number)
{
int current_length = sprintf(resulting_array, "%d", number);
while (6 > current_length) {
resulting_array[current_length++] = '0';
}
resulting_array[current_length] = '\0';
return resulting_array;
}
and then you could print the result:
char my_number[7];
printf("my number is %s, other stuff\n", number_to_six_digit_string(my_number, 13));
As a homework problem, I'm working on reading a decimal int from stdin, converting it to a different base (also provided from stdin) and printing it to the screen.
Here's what I've got so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, base, remainder, quotient;
printf("please enter a positive number to convert: ");
scanf("%d", &num);
printf("please enter the base to convert to: ");
scanf("%d", &base);
remainder = quotient = 1;
// validate input
if (num < 0 || base < 0) {
printf("Error - all numbers must be positive integers!\n");
return 1;
}
// keep dividing to find remainders
while (quotient > 0) {
remainder = num % base;
quotient = num / base;
num = quotient;
if (remainder >= 10) {
printf("%c", remainder + 55);
} else {
printf("%d", remainder);
}
}
printf("\n");
return 0;
}
This works great, only that the algorithm this uses calculates the converted numbers from least significant to most significant digit, thus printing it in reverse. So, for example, converting 1020 to hexadecimal ( 0x3FC ) will print CF3.
Is there a trick I could use to reverse these numbers to print in the correct order. I can only use if-else, while, simple math operators and printf()/getchar()/scanf() - no functions, arrays or pointers. thanks.
(removed original part of the post here, since it is not the solution)
Then the only solution I can see is to perform the loop that you have now the number of times that you have digits.
So, first you calculate all digits till you get to the last, and then print it.
Then you take the original value + base and start dividing again till you come to the second "highest value" digit, then print it.
It is a double loop and you calculate everything twice, but you don't use extra storage.
It's a good try, and well phrased question. If only we had more people asking questions in such a clear manner!
The restrictions seem artificial. I guess you haven't learned about functions, arrays, pointers etc., in your class yet, but I think this problem is not meant to be solved elegantly without functions and/or arrays.
Anyway, you can do something like this:
curr := base
pow := 1
while num / curr >= 1 do:
curr := curr * base
pow := pow + 1
while pow >= 1:
pow := pow - 1
print floor(num / base ** pow)
num := mod(num, base ** pow)
Basically, you are calculating how many digits you will need in the first loop, and then printing the digits in the correct order later.
Some specific issues with your code. I understand it's the beginning of a C class, but still, it's better to know of such issues now than to never realize them:
printf("please enter a positive number to convert: ");
You should add an fflush(stdout) after this to make sure the output appears before scanf() is called. By default, stdout is line buffered on many systems, so the prompt may not appear before your program waits for input.
printf("please enter the base to convert to: ");
Same as above.
if (remainder >= 10) {
printf("%c", remainder + 55);
} else {
printf("%d", remainder);
}
You're assuming ASCII character set. This need not be true. But without arrays or pointers, there's no easy way to print the alphabets corresponding to 10.... Also, your code may print weird characters for base > 36.
You should also be aware that it's very hard to use scanf() safely. Hopefully you will learn better ways of getting input later.
In one loop you can calculate the number of digits and the big_base.
In a second loop you can output the digits starting from the most significant, like this:
n = 1020, 3 hex digits, big_base = 16*16
1st step
1020 / (16*16) = 3
2nd step
n = 1020- 3*(16*16) = 252
252 / (16) = 15, F
3rd step
n = 252 - 15*16 = 12, C
Hey ! I recognize a famous homework I had in first year of my school too (#Epitech students : don't copy/paste the following code, try to come up with your own solution, it's for your own good ^^)
The solution to your problem is to perform the problem in a recursive way :
void my_putnbr_base(int num, int base)
{
int start;
int remainder;
remainder = num % base;
start = (num - remainder) / base;
if (start != 0)
my_putnbr_base(start, base);
if (remainder >= 10)
printf("%c", remainder + 55);
else
printf("%d", remainder);
}
Does your homework specifies that it should only work with positives numbers ? If not, it's easy to include the negative numbers handling :
void my_putnbr_base(int num, int base)
{
int start;
int remainder;
if (num < 0)
{
putchar('-');
my_putnbr_base(-num, base);
}
else
{
remainder = num % base;
start = (num - remainder) / base;
if (start != 0)
my_putnbr_base(start, base);
if (remainder >= 10)
printf("%c", remainder + 55);
else
printf("%d", remainder);
}
}
#arno : that's true, because the exemple code is using ASCII table. If we want something trully flexible we need the base in parameter. For example :
>> my_putnbr_base(4242, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
39U
>> my_putnbr_base(42, "0123456789ABCDEF")
2A
this implements the example :
void my_putnbr_base(int num, char *base)
{
int start;
int remainder;
int len;
len = strlen(base);
if (num < 0)
{
putchar('-');
my_putnbr_base(-num, base);
}
else
{
remainder = num % len;
start = (num - remainder) / len;
if (start != 0)
my_putnbr_base(start, base);
printf("%c", base[remainder]);
}
}
I hope it solves your problem !
edit: I didn't read correctly ^^ You are not allowed to use functions, so recursion is out of the question... Here is an interative way, you can put this in a main(). You can improve this code by adding the negative numbers handling and flexible bases, as I showed you :)
int my_putnbr_base_it(int num, int base)
{
unsigned int quotient = 1;
unsigned int remainder;
while ((num / quotient) >= base)
quotient *= base;
while (quotient)
{
if ((remainder = (num / quotient) % base) < 10)
printf("%d", remainder);
else
printf("%c", 55 + remainder);
quotient /= base;
}
return (0);
}
Hope it solves everything now !
You could rewrite the piece of code calculating each number to behave as a state machine. It will start in the initial state and compute the number of digits, then change the state to "print the Nth digit" to print the most significant digit, then change the state to proceed to the less significant digits, etc until it eneters the final state. Running this inside a loop you will output all digits in proper order.
You could use two loops. The first keeps generating powers of the base until it finds a power greater than the input number. The second starts from here (or rather, one power before) and works back to base^0 (i.e. 1) to compute the output digits most significant first.
Untested pseudo-code:
// Determine highest power, don't actually need "power" it's just there for illustration
power = 0;
baseraisedtopower = 1;
while (baseraisedtopower <= input)
{
baseraisedtopower *= base;
power++;
}
// Go back one step, could have saved previous result
baseraisedtopower /= base;
power--;
// Output
while (input > 0)
{
// Integer division, truncate
quotient = input / baseraisedtopower;
printf("%c", quotient + 55);
input -= quotient * baseraisedtopower;
baseraisedtopower /= base;
power--;
}
You can give a try at this approach.
It's more a proof of concept, you'll still need to handle some special case, but, hey, that's your homework :)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, base, remainder, quotient;
int divider;
printf("please enter a positive number to convert: ");
scanf("%d", &num);
printf("please enter the base to convert to: ");
scanf("%d", &base);
remainder = quotient = 1;
// validate input
if (num < 0 || base < 0) {
printf("Error - all numbers must be positive integers!\n");
return 1;
}
// First get the highest divider
divider = base;
while ( num / divider > base ) {
divider *= base;
}
do {
// Get the highest digit
remainder = num / divider;
// And update num accordingly
num -= remainder * divider;
divider /= base;
if (remainder >= 10) {
printf("%c", remainder + 55);
} else {
printf("%d", remainder);
}
} while ( divider );
printf("\n");
return 0;
}
Interesting task, you've got as a homework.
I am a beginner programmer to, and I've tried to resolve this task.
The following code is working (I haven't tested a lot, apparently is working). I am sure it's not the optimal&best solution, but was the only thing I've could come up with. It should work with any base. Unfortunately it won't convert 10->A, 11->B, etc.:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int nr,base,res,tp,tpb,tpbt,r,rnr,lp,lpt,i;
float baset,rt;
/** Read number */
printf("nr=");
scanf("%d",&nr);
/** Read base */
printf("base=");
scanf("%d",&base);
/** Returning result */
res=0;
/** Test if number is positive
and base is bigger than 2 */
if(nr<0||base<2){
/** Error */
res=1;
}
else{
/** Determine how many
digits are necessary */
lp=0;
baset=base;
while(baset>1){
lp++;
baset/=10;
}
/** Determine full power
of 10 when r has length of lp */
tpb=1;
while((lp--)>0){
tpb*=10;
}
/** Power of ten that will be
incremented */
tp=0;
/** Converted number (will be printed
as the result) */
rnr=0;
/** Algorithm */
while(nr>0){
r=nr%base;
nr/=base;
rt=r;
/** Temporary lp for
r */
lpt=0;
while(rt>1){
lpt++;
rt/=10;
}
/** Temporary tpb for
lpt */
tpbt=tpb;
for(i=0;i<lpt;i++){
tpbt/=10;
}
/** Build number */
rnr+=r*pow((double)(tpbt),(double)(tp++));
}
}
/** Show number */
printf("number is: %d \n",rnr);
return (res);
}
Based on what was suggested, the way to tackle this was to keep print the last number and repeat the loop for every digit. I kept track of the print condition by saving the previous quotient and printing when I got to it every time (then reseting the number and starting over), then reset it to the one before. Sounds complicated, but the change to the code was simple. My stop condition for the loop was when I had 2 consecutive prints, since most of the time it would just calculate quotient/remainder and print nothing, and when 2 digits print in a row, it's the last two. Anyway, here's the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, saved, base, remainder;
int quotient, prev_q, stop_q, just_printed;
printf("please enter a positive number to convert: ");
scanf("%d", &num);
printf("please enter the base to convert to: ");
scanf("%d", &base);
saved = num;
remainder = quotient = prev_q = just_printed = 1;
stop_q = 0;
// validate input
if (num <= 0 || base <= 0) {
printf("Error - all numbers must be positive integers!\n");
return 1;
}
// divide
while (1) {
remainder = num % base;
quotient = num / base;
num = quotient;
// print if it's the last number and reset num to the next
if (quotient == stop_q) {
if (remainder >= 10) { printf("%c", remainder + 55); }
else { printf("%d", remainder); }
// if 2 consecutive printing occur, this means it's time to end this
if (just_printed) { break; }
// next time print when hitting the previous quotient
stop_q = prev_q;
// reset the number to the original value
num = saved;
just_printed = 1;
} else {
just_printed = 0;
}
prev_q = quotient;
}
printf("\n");
return 0;
}
Thanks to everyone who pitched in!
We could use a recursive function to reverse the order of the digits of a number :
We'll need some mathematical functions from these libraries - stdlib.h and math.h
int reverse(int x)
{
if(abs(x)<=9)
{
return x;
}
else
{
return reverse(x/10) + ((x%10)*(pow(10, (floor(log10(abs(x)))))));
}
}
'If statement' is the base case for the recursive function.
'Else statement' may look intimidating at first but it's actually just simple arithmetic. floor(log10(abs(x))) gives us the number of digits of x, so ((x%10)*(pow(10, (floor(log10(abs(x))))))) is just putting the 'ones' place digit of the number to its correct place in accordance with the desired reversed number.
For better comprehension let's take an example, Let 123 be the number we need to reverse. The first thing that the function reverse will do is ask itself the reverse of 12 (reverse(x/10)) and when the function is called for the second time with argument 12 it'll ask itself the reverse of 1, Now this will be the base case for our function. It'll return 1 as abs(1)<=9, Now 2 will be prepended using ((x%10)*(pow(10, (floor(log10(abs(x)))))) it then will return 21 and 3 will be prepended by the same.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int reverse(int x);
int main()
{
int x, revInt;
scanf("%d", &x); // input : 123
revInt = reverse(x);
printf("%d", revInt); // output : 321
return 0;
}