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
Related
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.
Input:
Enter an integer number: 1234567
Expected output:
7654321 // As a complete integer, not separate digits
I have tried by following this strategy: transform and store reversed order digits of an integer to a complete integer number:
# include <stdio.h>
int main(void){
int number=get_input_validation();
find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(number);
}
int get_input_validation(){
//Drop variables here
int number;
//Input validation
while(1){
//Taking input from the user
printf("Enter an integer number: ");
scanf("%d",&number);
int count=find_out_the_number_of_digit(number);
if(count>5 || count<5){
printf("Only 5 digits are allowed here\n");
}
else{
break;
}
}
return number;
}
int find_out_the_number_of_digit(int number){
int count=0;
//Getting total digits of a given number
while(number!=0){
number=number/10;
count++;
}
return count;
}
int find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(int number){
int complete_integer=0;
int value=10000;
while(number!=0){
int last_digit=0;
//get the last digit
last_digit=number%10;
//get the quotient
number=number/10;
complete_integer=complete_integer+last_digit*value;
value=value/10;
//To display the last digit
printf("%d",last_digit);
}
printf("\n");
printf("%d",complete_integer);
}
Now the problem is: This program works for only 5 digits like. From my code, I get the output like
Input:
12345
Output:
54321 // As a complete integer, not separate digits
If I give the input like 123456 or 1234 means greater or less than five digits then It does not work. It works for only exacts 5 digits of an integer.
What I want to achieve: I want that my program will give the expected output for any digits of a given integer. How can I do that?
In C it is good to write functions which do some separate tasks. Reversing the unsigned integer is very easy:
unsigned reverseUnsigned(unsigned val)
{
unsigned result = 0;
while(val)
{
result *= 10;
result += val % 10;
val /= 10;
}
return result;
}
int main(void)
{
printf("reversed: %u\n", reverseUnsigned(1234567));
}
https://godbolt.org/z/E3s9c8
Bear in mind that it will not work if reversed value is too large to be stored in the unsigned int.
The problem is your value of the value variable. At the moment you're telling the program to process 5 digits by setting value equal to 10^4, or 10000. Set the value to 10 to the power of (length of integer - 1):
int value=1;
for (int i = 1; i < find_out_the_number_of_digit(number); i++)
{
value *= 10;
}
void rev(int n){
int rem;
printf("reverse of that number is:");
while(n>0)
{
rem=n%10;
n=n/10;
printf("%d",rem);
}
}
int main()
{
int n;
printf("enter a number of more than two digits");
scanf("%d",&n);
rev(n);
return 0;
}
This code without writing a piece of code for digits places i.e.,
reverse = reverse * 10 + remainder;
also returns the same.
please explain if there is any mistake in my perspective.
regards.
Because you actually didn't reverse number, you are just printing it. If you want to store reversed number and use it later, you have to to do reverse = reverse * 10 + remainder;
What will you do if someone ask you to add a integer X with the reverse of the given number? Counting the reverse number always is a good idea than just printing it form last digit to first. This small change in your code may be very useful:
void rev(long long n){
long long rem = 0;
printf("reverse of that number is:");
while(n>0)
{
rem= rem*10+(n%10);
n=n/10;
}
printf("%lld",rem);
}
Here you can also return the value of rem for further use.
UPDATE:
As #Weather Vane says, what if user want to see the reverse number with leading zeros(if there any), the only way then to input the number as string. and reverse it. A string can reverse using strrev() function from <string.h>
strrev(string_name);
If it is a STL String than using reverse() function from <algorithm> will be useful.
reverse(string_name.begin(), string_name.end());
If you want to get the integer from the string you can do this like this:
long long str_to_num(string s)
{
long long integer = 0;
for(int i = 0; i < s.size(); i++){
integer = integer*10+(s[i]-'0');
}
return integer;
}
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;
}
I have an assignment that requires me to first set up integer arrays to store arbitrarily large numbers. By using each element of an int array, I can hold one digit per element because int variable types are 32 bits and can only reach up to about 2 billion before failing. I know that there are other libraries using BigInt but I wanted to make my own arrays instead.
I tested my code out, but it doesn't seem to be accepting values past 9 digits until it starts to fail.
int * toArray(int, int);
int main()
{
int n, *res, counter, i;
printf("Input: ");
scanf("%d", &n);
while(n>0){
n/=10;
counter++;
}
res = toArray(n, counter);
for(i=1;i<=counter;i++){
printf("%d", *(res)+i);
}
printf("\n");
}
int * toArray(int n, int counter)
{
int i;
int *numberArray = malloc(sizeof(int) * counter);
for(i=0; i< counter; i++)
{
numberArray[i] = n % 10;
}
return numberArray;
}
I want to be able to accept close to twenty digits at the very least. I know this can be done with int arrays, although char arrays (or strings) are also a possibility. But I wanted to use int arrays instead. Any help in understanding why it fails around 9 digits and suggestions for going past that would be very much appreciated. Thank you.
The problem is that you are reading an int from keyboard
scanf("%d", &n);
so therefore no matter how many digits you enter, you still will only get 9 digits.
In order to be able to enter an arbitrary number you would have to read it as a string instead, then convert it to your int array.
EDIT:
this way (for instance) would allow for 20 digits
char ch;
int digits[20];
int i = 0;
do
{
ch = fgetc(stdin);
if ( isdigit(ch) )
{
digits[i++] = ch - 48; // convert ASCII to int
}
}
while (isdigit(ch) && i < sizeof(digits)/sizeof(digits[0]));
#include<stdio.h>
#include<stdlib.h>
int *toArray(long long int n, int counter); int main() {
long long int n=0,copy_of_n=0;
int counter=0, i=0;
int *res=NULL;
printf("Input: ");
scanf("%lld", &n);//Refer note in the answer
copy_of_n=n;//see the while loop why use this.
while(n>0){
n/=10;//Good, but you are not storing it. copy_of_n does that.
counter++;//You didn't initialize this
}
res=toArray(copy_of_n, counter);
for(i=counter-1;i>=0;i--){//This ensures you get the numbers in a proper order and since index starts from 0 in the toArray function
printf("%d", res[i]);
}
printf("\n");
free(res);//You forgot this
return 0; }
int *toArray(long long int n, int counter) {
int i=0;
int *numberArray = malloc(sizeof(int) * counter);
memset(numberArray,0x00,counter*sizeof(int));//Good to do this
//Check for memory allocation
for(i=0; i< counter; i++)
{
numberArray[i] = n % 10;
n=n/10LL;//You have to remove the digits too
}
return numberArray; }
NOTE: Read in a while loop the integers in small parts because long long has limits of how many digits it can store. Another approach would be to store in a string and send split the string into exactly the max. no. of digits that can be stored in long long in the n variable and send it to the function, part by part.
long long size is implementation dependent, hence ensure you check the max. no. of digits it can accomodate.(It will ofcourse bypass your 9-digit limit as asked in question)