Program that prints the digits of a number as characters (C language) - c

I have to do a program to take a number and print all the digits one by one as characters.
The code I have written is here:
#include <stdio.h>
#include <stdlib.h>
char digito(int, int);
int numberofdigits(int);
int main(void)
{
int num=0, test=0, kdigits=0, k=0;
char ch='\0';
printf("Enter a positive number:\n");
test=scanf("%d", &num);
if (teste!=1 || num<=0)
{
printf("Error: not a valid number.\n");
exit(EXIT_FAILURE);
}
kdigits = numberofdigits(num);
for(k=0; k<kdigits; k++)
{
ch= digito(num, k);
printf("The digit %d of the number is %c\n", k, ch);
}
return EXIT_SUCCESS;
}
int numberofdigits(int _n)
{
int count=0;
while (_n!=0)
{
_n/=10;
count++;
}
return count;
}
char digito(int _number, int _kdigit)
{
int flag=0, digit=0;
char ch='\0';
for (flag=0; flag<=_kdigit; flag++)
{
digit=_number%10;
_number/=10;
}
ch= digit + '0';
return ch;
}
Now the code is working pretty fine for relatively small numbers (up to 8 or 9 digits I would say).
But then something odd is happening: I tried to print the digits of the number 11111111111122 and obtained
The digit 0 of the number is 3;
The digit 1 of the number is 7;
The digit 2 of the number is 3;
The digit 3 of the number is 6;
The digit 4 of the number is 1;
The digit 5 of the number is 7;
The digit 6 of the number is 0;
The digit 7 of the number is 3;
I wonder why? Is it because it's a very large number? Because I tried even larger numbers and what happens is that the program enters the initial if clause that verifies the scanf reading. And that's ok. But the problem is that the program should also do the same with this number since it's bigger that the largest int.
Can someone help me fix this please?
Thanks!

There are two answers to two questions:
Q1) Why do I get wrong digits for the example?
A1) As others have commented: Because the example number is too high for the data type used, it matches the number which you find in the lower 32 bits: 30716370.
Q2) Why is the initial check "<0" not triggering for the example but does trigger for other, higher examples?
A2) Because the 30716370 is smaller than the biggest positive number which can be represented by a 32 bit signed int, which is 2147483647 == 0x7FFFFFFF. That one however is smaller (even in the number of digits, but that is not the point) than 11111111111122.
30716370 <
2147483647 <
11111111111122
The even higher numbers will by chance have the bit31 set, which makes the lower 32bit look negative. You could probably find other numbers which are too high but do not seem negative.

Related

How to find the number of digits int digits in c upto 100 or 1000 digits?

This is my code:`
#include <stdio.h>
void main() {
int n;
int count = 0;
printf("Enter an integer: ");
scanf("%d", &n);
// iterate until n becomes 0
// remove last digit from n in each iteration
// increase count by 1 in each iteration
while (n != 0) {
n /= 10; // n = n/10
++count;
}
printf("Number of digits: %lld", count);
}
I am able to run the code finely but when I enter 15 or 16 digits of number as input then it always shows me that the number of digits is 10. And another problem with this code is that suppose if I input 000 then I want the output to be 3 digits but this code is not able to do that as the condition in the while loop becomes instantly false. So how write a code that enables me to take upto 100 or 1000 digits as input and also enables me to input 0s as well.
Note: This program should be solved using a loop and in C language
I found a answer to the question here in stackoverflow written in c++ that I couldn't even understand as I am a beginner and I am learning C.
Link to the answer:
How can I count the number of digits in a number up to 1000 digits in C/C++
Instead of reading a number, read a string and count the digits:
#include <stdio.h>
int main() {
char buffer[10000];
int n;
printf("Enter an integer: ");
if (scanf("%9999s", buffer) == 1) {
for (n = 0; buffer[n] >= '0' && buffer[n] <= '9'; n++)
continue;
printf("Number of digits: %d\n", n);
}
return 0;
}
You can also use the scanf() scanset feature to perform the test in one step:
#include <stdio.h>
int main() {
char buffer[10000];
int n;
printf("Enter an integer: ");
if (scanf("%9999[0-9]%n", buffer, &n) == 1) {
printf("Number of digits: %d\n", n);
}
return 0;
}
32 bits signed integer has the max value equals 2,147,483,647 so, if you input a bigger one, it will not be stored. I'd make it receiving a string and get its length, like so:
#include <stdio.h>
#include <string.h>
int len = strlen("123123123123132");
You are taking int variable and you are trying to count a number like whose digit is 100 or 1000. it will not fit with int. so take input as a string and count the length of string.

How to get summation in C?

How to make a program to read elements from input like:
1 3
and give me the summation of that:
4
#include <stdio.h>
int main(void){
char x[3];
scanf(" %c",&x);
printf("%d\n",x[0]+x[2]);
}
In your approach you seem to read in a string and treat several positions of that string as numbers. Besides the fact that there are several mistakes in implementing this approach, the main thing actually is that you've taken the wrong approach. Drawbacks (not all, just some) are: you only consider numbers of exactly one digit; you assume that user input is exactly mapped to your array with exactly one "blank" position between the numbers of interest (as you access x[0]+x[2] with hard-coded indexes 0 and 2); you are limited to exactly two "numbers" to be summed up; ...
I'd rather scan integral values (i.e. using %d and data type int) within a loop until one enters something that is not a valid number. This solves all of above mentioned issues:
int main() {
int sum=0;
int num=0;
printf("type in numbers to be summed up (type a non-number to exit):\n");
while (scanf("%d",&num)==1) {
sum += num;
}
printf("sum: %d\n",sum);
}
Intput/Output:
type in numbers to be summed up (type a non-number to exit):
10 20 30 x
sum: 60
There's a few things missing here.
For one thing, you're only reading one character with %c. You're storing it in &x, which, though confusing, is technically legal: since it's a sequence of 3 char-sized elements in memory, &x is a valid character address. However, x[1] and x[2] remain uninitialized; you're not setting them anywhere.
Secondly, you're not converting it to an integer value so it still has the value of the character '1' not decimal 1. '1' + '1' (note single quotes) will evaluate to 49 + 49 (note lack of quotes), 49 being the ascii equivalent to the character '1' - very different from the decimal value 1.
Finally, you're only summing the first and third character (the latter, being uninitialized, has an unknown value, certainly not one from your input). The second character is not a part of the final result.
If you want to read 3 integers, you should scan for ints, not characters, and you should scan for the number of them you wish to read. That would allow you to read numbers above 9 correctly.
But perhaps you do want to scan for one digit at a time; in which case, you'll certainly want to convert each digit character to it's integer equivalent. Since the digits 0 to 9 are contiguous and in ascending order in ascii, you can simiply subtract '0' from the character to get its decimal equivalent ( '1' - '0' == 1, '9'-'0'==9, etc.) But for this to work, you must ensure that you really have read a digit and not just any char. You might do so by verifying that its value was between '0' and '9', inclusive.
Regardless of whether you wish to sum integers or digits, you'll want to ensure you're reading each value you're going to sum before computing the final sum.
It might make more sense, given your use case, to keep scanning for ints in a loop until you run out of ints on the input stream. You don't really need to store them each; you can read one int at a time and add it to a running total.
Putting that all together, you might end up with something like this. Take these ideas and implement your running sum, and you'll have what you want for characters.
#include <stdio.h>
int main() {
char c; // we'll store our input here as we go
while( scanf(" %c", &c) == 1 ) { //one thing matched
if(c >= '0' && c <= '9'){ // it's a digit
printf("Read %c, decimal value of digit is %d\n", c, (int)(c-'0') );
}else {
printf("Invalid digit %c\n", c);
}
}
}
I run like this:
$ gcc -o t t.c && echo '1 2 3 4 5' | ./t
Read 1, decimal value of digit is 1
Read 2, decimal value of digit is 2
Read 3, decimal value of digit is 3
Read 4, decimal value of digit is 4
Read 5, decimal value of digit is 5
Change to scanf("%d") like described below to read multi-digit integers instead, changing the code accordingly.
#include <stdio.h>
int main() {
int c; // we'll store our input here as we go
while( scanf(" %d", &c) == 1 ) { //one thing matched
printf("Read %d; wasn't that easy?\n", c);
}
}
$ gcc -o t2 t2.c && echo '1 2 3 4 5' | ./t2
Read 1; wasn't that easy?
Read 2; wasn't that easy?
Read 3; wasn't that easy?
Read 4; wasn't that easy?
Read 5; wasn't that easy?
That approach can read any integer repesentation up to the min/max size of int, including multiple digits and even negative numbers:
$ gcc -o t2 t2.c && seq -1 -10 | ./t2
Read -1; wasn't that easy?
Read -2; wasn't that easy?
Read -3; wasn't that easy?
Read -4; wasn't that easy?
Read -5; wasn't that easy?
Read -6; wasn't that easy?
Read -7; wasn't that easy?
Read -8; wasn't that easy?
Read -9; wasn't that easy?
Read -10; wasn't that easy?
You could try:
int n1;
int n2;
scanf("%d %d", &n1, &n2);
int sum = n1 + n2;
printf("%d\n", sum);
If you want to add more than two numbers together, you could try:
printf("Enter how many numbers you want to add:\n");
int n;
scanf("%d", &n);
int sum;
for (int i = 0; i < n; i++) {
int in;
scanf("%d", &in);
sum += in;
}
printf("%d\n", sum);
Note:
At first the answer had C++ in the title and so I answered with C++ like this:
If you don't mind using cin and cout, you could try:
int n1;
int n2;
cin >> n1 >> n2;
cout << n1 + n2;
Running this program with n integers will return their sum by iterating from argv[1] to argv[n]. argv[0] is the name of the program.
Example:
./sum 1 3 returns 4
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i;
int sum;
if (argc > 1)
{
for (i = 1; i < argc; i++)
{
sum += (int)strtol(argv[i], NULL, 10);
}
printf("%d\n", sum);
}
else
{
fprintf(stderr,"Invalid number of arguments\n");
return(EXIT_FAILURE);
}
return(EXIT_SUCCESS);
}
You could use an array and a loop. This is a simple method.
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0, allocation[5],i,num;
printf("enter the number of elements");
scanf("%d",&num); // how many numbers are there??
printf("Enter the elements");
for(i=0;i<num;i++)
{
scanf("%d",&allocation[i]); //allocate the elements in the array say 3,4,5
sum=sum+allocation[i];
//0+3, sum=3
//3+4, sum=7
//7+5, sum=11
}
printf("Sum= %d",sum); //print Sum=11
getch();
}
#include <stdio.h>
int main () {
int num1,num2;
printf("Enter two numbers");
scanf("%d %d", &num1 &num2);
printf("Sum is = %d", num1+num2);
return 0;
}

how to identify whether a number is a binary code or a decimal in C

I've tried making a calculator that first reads the input from the user and then decides wheter the input is in binary or in decimal and then converts it.
i got almost everything but can't come up with the identifier! here's the code that i got:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int a;
char num[100];
int number[100];
int decimal_binary (int n);
int binary_decimal (int n);
void errorcode(void);
bool bin, decim;
int main (){
bin (false);
decim (false);
printf ("enter a number: ");
gets (num);
a = strlen(num);
if (a > 8){
errorcode();
//printf("That is an invalid number!");
//exit(45);
}
for (int i=0; i < a; i++){
number[i] = num[i] -'0';
printf("%d", number[i]);
}
int decimal_binary(int n){
int rem, i=1, binary = 0;
while (n != 0)
{
rem =n%2;
n/=2;
binary+=rem *i;
i*=10;
}
return binary;
}
int binary_decimal(int n)
{
int decimal = 0, i=0, rem;
while (n!-0){
rem = n%10;
n/=10;
decimal += rem *pow(2,i);
++i;
}
return decimal;
}
}
void errorcode(void){
printf("That is an invalid number!");
exit(45);
}
There is no such way to detect whether the number entered was binary or decimal just by analysing the characters of the number entered. However, if you study the Microsoft Windows calculator application that ships along with the OS, the "programmer" type of calculator takes an input whether the entered number is binary or decimal from the user, then internally in its code it would check whether the entered number was a valid binary or decimal number.
In short, your code will have to tell the user to specify what number is entered.
I would recommend studying the Microsoft calculator application's "programmer" type calc in order to help you understand what you want to achieve.
I believe the correct answer to this question is that binary numbers can be identified with the 0b prefix. Ex: 0b11111111 is the byte 0xFF, or 255 decimal. Notice the 0x prefix on the hex number. Decimal numbers have no prefix.. In fact, if you lead your 'decimal' number with a zero, the compiler will think that it is an octal number and treat it as base 8.

How to get the number of digits of an integer?

The program below is sufficent enouhgh to find the length of any string length that is given to the input, however, i need to find the length of an integer variable, rather than a string.
Entering a number to this does work, but not if i scan s as a int type.
int main()
{
char s[1000];
char i;
int u=5;
do
{
char s[1000];
char i;
int u=5;
system("cls");
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d",i);
getch();
}
while(u==5);
getch();
}
So all i need is either this little program modified to accept intger variables, or a way to transform a calculated int variable into a string.
Any ideas?
Edit: Length = Amount of characters so 25 has 2, 3456 has 4 etc
You can calculate the length of n in base m with the formula:
ceil(log(n + 1, m))
Where ceil is the ceiling (round up) function, and log(a, b) is logarithms of a in base b.
You may use the below code to find the number of digits of an integer:
int count=0;
while(n!=0)
{
n/=10;
++count;
}
Where n is your input integer and count will be the it's length.
If you want to read an integer as an integer i,e with %d and count number of digits in that integer, have a look at below code snippet.
int no,length=0;
printf("Enter number");
scanf("%d",&no);
while(no!=0)
{
length+=1;
no=no%10;
}
printf("Length=%d",length);
To determine the number of characters to print a decimal number (assuming value is the int), you could do the following:
int intlen = 0;
if (value < 0) // for negative values, allow a char for the minus sign
{
value = -value;
++intlen;
}
while (value >= 10) // as long as the value is 1 or more,
{
value /= 10; // divide by 10,
++intlen; // ...and add one to the length
}
++intlen; // add one for last digit (even if it's zero)
It's probably easier to use the ceil/log function described above, but this one does not require the math library (if that is an issue)
Another brute-force approach would be as follows:
char temp[12];
int intlen = sprintf(temp,"%i",value);
This utilizes the fact that sprintf returns the number of characters placed in the string buffer.
#include<stdio.h>
main()
{
int count=1,n;
scanf("%d",&n);
while(n/=10)
count++;
printf("result=%d",count);
}
count gives the number of digits in number n

Nothing is printed

so this is the logic that came to my mind while trying to think of a procedure to convert
a binary number into a decimal number. I cannot seem to figure out what's wrong with the program which is preventing it from showing any kind of output at all.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,temp,r,rev,i, ct;
rev=0;
printf("Enter a number in base 10");
scanf("%d", &n);
// n is the decimal number
temp=n;
while(temp>0)
{
r=temp%2;
if (r==1)
break;
else
ct++;
temp/=2;
// ct will count the number of zeros from the top
}
while(temp>0)
{
r=temp%2;
rev=(rev*10 + r);
}
printf("%d", rev);
for(i=0;i<ct;i++)
{
printf("%i", 0);
}
return 0;
}
Your code has multiple problems:
1) ct is an uninitialized variable. Initialize it to 0.
2) The part that calculates the binary in single loop, needs temp=temp/2 to calculate the next digit in binary.
while(temp>0)
{
r=temp%2;
rev=(rev*10 + r);
temp/=2; // You need this
}
3) Your program can handle only a very small set of integers as you represent the binary number using an integer variable (rev). And you'll run into the integer overflows even when inputting small numbers such as 2047 (depending on whether the LSB of the binary is 1 and INT_MAX on your platform).

Resources