Why is this skipping numbers when I divide it? - c

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;
}

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 compare the digits of 2 integer numbers in c (without arrays and strings)

I am making simple example of little game about guessing numbers.
And I want to build a function which check the numbers and make two values as follows:
1) hits-the number of digits that contain in both number and in same place for both numbers.
2) misses-the number of the digits which contain in both number but not in the same place.
For example:
int systemNumber=1653;
int userGuess=5243;
in this example, in both numbers there are the digits 5 and 3. In both numbers the digit 3 in the same place. But, the digit 5 in systemNumber is not in the same place as userNumber. So, we have here 1 hit and 1 miss.
I've written the code for it with arrays, and I'd like to know if there is a way that I will be able to do this without array and strings.
Here is my code. Please, if you have any improvement for my code, I'd like to know it :)
#include <stdio.h>
#include <stdlib.h>
void checkUserCode(int num1[4], int num2[4]); // declare the function which check the guess
int hits=0, misses=0; // hits and misses in the guess
int main(void)
{
int userCode=0;
int userCodeArray[4];
int systemCodeArray[4]={1, 4, 6, 3};
int i=0;
// printing description
printf("welcome to the guessing game!\n");
printf("your goal is to guess what is the number of the system!\n");
printf("the number have 4 digits. Each digit can be between 1 to 6\nGood Luck!\n");
// input of user guess
printf("enter number: ");
scanf("%d", &userCode);
for (i=3; i>=0; i--)
{
userCodeArray[i]=userCode%10;
userCode=userCode/10;
}
checkUserCode(systemCodeArray, userCodeArray);
printf("there are %d hits and %d misess", hits, misses); // output
return 0;
}
/*
this function gets two arrays and check its elements
input (parameters): the two arrays (codes) to check
output (returning): number of hits and misses
if the element in one array also contains in the other array but not the same index: add a miss
if the element in one array also contains in the other array and they have the same index: add a hits
*/
void checkUserCode(int num1[4], int num2[4])
{
int i=0, j=0;
for (i=0; i<4; i++)
{
for (j=0; j<4; j++)
{
if(num1[i]==num2[j])
{
if (j==i)
hits++;
else
misses++;
}
}
}
}
Here is an example I wrote a while ago, which I tweaked for your problem:
I basically uses two for loops, the outer loop going over the first number, 1653, and the inner loop going over the second number, 5243. It basically compares each individual number in the first number against all the numbers in the second number.
Depending on the counters, it evaluates if equal numbers have been matched in the same positions, using modulo %10 to compare each number.
This is the code:
#include <stdio.h>
#include <stdlib.h>
int
main(void) {
int num1 = 1653;
int num2 = 5243;
int pos1, pos2, hit = 0, miss = 0, i, j;
pos1 = 0;
for (i = num1; i > 0; i /= 10) {
pos2 = 0;
for (j = num2; j > 0; j /= 10) {
if (i % 10 == j % 10) {
if (pos1 == pos2) {
hit++;
} else {
miss++;
}
}
pos2++;
}
pos1++;
}
printf("hits = %d\n", hit);
printf("misses = %d\n", miss);
return 0;
}

Specific digit count in an integer in C

For example: if user input is 11234517 and wants to see the number of 1's in this input, output will be "number of 1's is 3. i hope you understand what i mean.
i am only able to count number of digits in an integer.
#include <stdio.h>
int main()
{
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0)
{
n/=10;
count++;
}
printf("Digits in your number: %d",count);
return 0;
}
maybe arrays are the solution. Any help would be appreciated. thank you!
You don't need array. Try something like this:
int countDigits(int number, int digitToCount)
{
// Store how many times given number occured
int counter = 0;
while(number != 0)
{
int tempDigit = number % 10;
if(tempDigit == digitToCount)
counter++;
number = number/10;
}
return counter;
}
So, you've already found that you can convert 1234 to 123 (that is, remove the least significant digit) by using number / 10.
If we wanted to acquire the least significant digit, we could use number % 10. For 1234, that would have the value of 4.
Understanding this, we can then modify your code to take this into account:
int main() {
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0) {
if (n % 10 == 1)
count++;
n /= 10;
}
printf("Number of 1s in your number: %d", count);
return 0;
}
You may want to use convert your int to a string like this :
char str[100];
sprintf(str, "%d", n);
Then, you can just iterate on str in order to find the occurrences of your digit.

How do I go through a certain number and extract digits smaller than 5 using a recursive function?

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;
}

Listing digits in an int, without losing 0

I'm writing a program that list the digits of integer input.
example:
Please enter an integer number: 5021
The digits are:
5
0
2
1
The program works fine except when it comes to numbers ending in 0 since I have reversed the number first using a while loop (while num>0)in order to print the numbers in the order shown above. I hope someone can point me in the right direction as I really can't seem to think of another way just now :)
sorry couldn't figure out how to add code without doing 4 spaces in front of each line (is there another(easier) way to add code?).
int main() {
int userInt; /* integer input by user */
int revInt; /* reversed integer */
printf("Please enter an integer number: ");
scanf("%d", &userInt);
/* reverse int */
revInt = reverseInteger(userInt);
/* print digits */
printDigits(revInt);
return 0;
}
int reverseInteger(int num) {
long sum = 0;
int remainder;
while(num) {
remainder = num%10; /* get last digit of number */
sum = sum*10 + remainder; /* move digits by one place in sum and add remainder of number */
num = num/10; /* remove last digit of number */
}
return sum;
}
void printDigits(int num) {
int remainder;
printf("The digits are:\n");
while(num) {
remainder = num%10; /* get last digit of number */
printf("%d \n", remainder); /* print last digit */
num = num/10; /* remove last digit of number */
}
}
The maximum number of digits in an int is small so you could safely use recursion in this case:
#include <stdio.h>
#include <stdlib.h>
void
print_digits(unsigned n) {
div_t q = div(n, 10);
if (q.quot > 0) print_digits(q.quot);
printf("%d\n", q.rem);
}
int main() {
print_digits(50210);
return 0;
}
Output
5
0
2
1
0
In your code for ReverseInteger, the variable remainder always keeps the last digit of the digit of the number you've entered (even when there are zeros at the end). So your function is almost ready, we can just tweak it a little bit:
void reverseIntegerAndPrint(int num) {
int remainder;
while(num) {
remainder = num%10; /* get last digit of number */
printf("%d \n", remainder); /* prints last digit!! */
num = num/10; /* remove last digit of number */
}
return;
}
You need to store the number of times you passed in the loop in reverseInteger and reuse this information when you loop in printDigits function.
Instead of reversing your integer in an int, you also can just store all the digits in the reverse order in an array and store in another integer variable the number of digits. Then you can print the elements of array (the digits) element by element starting from the end.
Before reverting the number,do something like this:
while(number%10 == 0)
{
number /= 10;
}
...//invering code here
The problem is that reverseInteger(1) == reverseInteger(10) == reverseInteger(100) == reverseInteger(1000) == ... and hence, once you use this function (which returns an int) you've already lost the information you need. One solution is to count the trailing zeros first, leading to something like this (assuming userInt > 0):
int numTrailingZeros = 0;
while(!(userInt % 10)) {
++numTrailingZeros;
userInt /= 10;
}
revInt = reverseInteger(userInt);
printDigits(revInt);
while(numTrailingZeros) {
printf("0 \n");
--numTrailingZeros;
}
Also is possible to convert it to string and print reserved:
#include "stdio.h"
#include "string.h"
int main(void)
{
int i,j;
char s[20];
scanf("%i", &i);
sprintf(s, "%i", i);
for(j=strlen(s); j>0; j--) {
printf("%c \n", s[j-1]);
}
}

Resources