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)
Related
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define BUFFER 512
void getCount(int *numCount, int *count);
int sumNumbers(int *numSum, int *sumNumOutput);
int main(void) {
printf("Enter a number greater than 0: ");
char string[BUFFER];
int numMain = 0;
int countMain = 0;
int sumNumMain = 0;
fgets(string, BUFFER, stdin); // gets user input and stores it in string
numMain = atoi(string); // converts the string to numerical and sets sum to the value. If there is a letter in the string, it will be zero.
int numCountMain = numMain;
int numSumNum = numMain;
getCount(&numCountMain, &countMain); // gets how many integers there are
sumNumbers(&numSumNum, &sumNumMain);
printf("Count: %d\n", countMain);
// printf("Sum: %d\n", sumNumMain);
return 0;
}
//shows how many integers were entered
void getCount(int *numCount, int *count){
while(*numCount > 0){
*numCount /= 10;
++*count;
}
return;
}
int sumNumbers(int *numSum, int *sumNumOutput){ // make it so that it isolates a number, then adds it to a universal sum variable
int increment = 1;
int count = 0;
while(*numSum > 0){ // gets the count of the number
while(*numSum > 0){
*numSum /= increment;
++count;
printf("numSum: %d\n",*numSum);
increment *= 10;
}
}
}
Let's say I put in 12345 as the number. It counts the number of digits in there just fine, but when it gets to isolating the individual digits using division, it skips over the third number. In the case of 12345, it would be:
12345
1234
12
0
I'm thinking this is a case of the increment running amok, but I can't find a fix for this. Also I know when I fix this, it will not solve the problem that I have to isolate the individual numbers. That's where the increment comes in and I know I have to use the modulus, but if someone can help me out with that after I take care of this, that would be great too.
Also, in case it isn't obvious, the code that has the problem I'm assuming is the bottom lines.
You are dividing by 1, 10, 100, 1000. So you are getting 12345, 1234, 12.
Try
while (*numSum > 0) {
++count;
printf("numSum: %d\n",*numSum);
*numSum /= 10;
}
I tried to solve the Small Factorial problem on SPOJ and got 'Wrong answer'. I wrote the following code :
#include <stdio.h>
int main() {
int t,i, num;
unsigned long long int fact=1;
scanf ("%d", &t);
while (t-- >0) {
fact=1;
scanf ("%d", &num);
for (i=num; i>0; i--) {
fact*=i;
}
printf ("%llu\n",fact);
}
return 0;
}
This code is not finding factorial for large inputs like 100. What are the changes required?
In C and C++ you have the maximum allowed range from -2^63+1 to +2^63-1 which is for long long data type. As you can see this range is still too small to store >20 digits.
You have to use a char array to store single digit per array index.
one way to do this in C++:
#include<stdio.h>
#include<iostream>
int main()
{
int t;
char a[200]; //array will have the capacity to store 200 digits.
int n,i,j,temp,m,x;
scanf("%d",&t); //enter total elements
while(t--)
{
scanf("%d",&n); // enter no. one at a time
a[0]=1; //initializes array with only 1 digit, the digit 1.
m=1; // initializes digit counter
temp = 0; //Initializes carry variable to 0.
for(i=1;i<=n;i++)
{
for(j=0;j<m;j++)
{
x = a[j]*i+temp; //x contains the digit by digit product
a[j]=x%10; //Contains the digit to store at position j
temp = x/10; //Contains the carry value that will be stored on later indeces
}
while(temp>0) //while loop that will store the carry value on array.
{
a[m]=temp%10;
temp = temp/10;
m++; // increments digit counter
}
}
for(i=m-1;i>=0;i--)
printf("%d",a[i]);
printf("\n");
}
return 0;
}
it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr ยง6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}
I'm trying to calculate the size of the file . The process I've followed is to read the file and store it in an array and calculate its size. However,I really don't know ... I tried n number of ways..I've to pass this size as an attribute to the frequency function.along with the name of the array.
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int ??????, int x)
{
int count = 0;
int u;
for (u = 0; u < ??????; u++)
{
if ( theArray[u]==x)
{
count = count + 1 ;
/*printf("\n%d",theArray[u]);*/
}
else
{
count = count ;
}
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int r = 0;
int num;
int theArray[100];
int there[100];
int n;
int g;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",(integers[i]));
there[r] = integers[i];
i++;
}
//printf("%d",there[r]);
//printf("\n%d",file);
//fclose(file);
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf("\n%d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,????????,x);
getch();
fclose(file);
}
?????? is the size of the integer array from where i read the file and stored it.
I could not find a way to calculate the size of the array into which i copied my file. My idea is to calculate the frequency of a number in that file and calculate the probability of it's occurrence and thereby calculating entropy..Suggestions please!
I don't know why you are initializing so many variables and some of them with awkward names like ??????.
Your main problem is that the call to function should be
frequency(integers, i, x);
Your code with the awkward irrelevant parts removed will look like
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int number, int x)
{
int count = 0;
int u;
for (u = 0; u < number; u++)
{
if ( theArray[u]==x)
count++;
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int num;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",integers[i]);
i++;
}
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf(" %d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,i,x);
getch();
fclose(file);
}
There are a lot of parts of this code that don't make sense, but I assume it is your debugging trying to figure out what is wrong. The answer to your specific question is:
For each value read from the file you set integers[i] to the value and then increment i. Thus i is the count of items in integers. You then pass integers to frequency(), so i should be passed to the second parameter as the count.
Note that if there are more than 100 values in the file, you will over index integers and cause unpredictable behavior.
To calculate length of array:
int len= sizeof(arr)/sizeof(arr[0]);
It will give length of array without looping.
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