Listing digits in an int, without losing 0 - c

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

Related

Using a for loop to add integers from an array

I'm writing a program that takes in your student number(8 digits long), prints each digit on its own new line, and then gets the sum of all the digits in the number
(E.g. Student Number - 20305324, Sum - 19)
#include <stdio.h>
#include <string.h>
int main(void) {
char student_number[8];
int i = 0;
int sum = 0;
printf("Enter your student number: ");
scanf("%s", student_number);
// ensures input is only 8 digits - WORKS
while (strlen(student_number) < 8 || strlen(student_number) > 8){
printf("Enter your student number: ");
scanf("%s", student_number);
}
// prints each digit of the student number on a new line - WORKS
while (student_number[i] != '\0'){
printf("%c\n", student_number[i]);
i++;
}
// sum all the digits in the student number and print - DOESN'T WORK
for (i=0;i<8;i++){
sum = sum + student_number[i];
printf("%d\n", sum);
}
printf("Sum of the numbers is %d", sum);
}
OUTPUT
The problem I'm encountering is when my for loop attempts to add each digit in the student number. The output I expect here is 19, but for some reason the sum evaluates to some bizarre number like 403
}
Would someone mind pointing out where exactly the fault in my for loop is or if it is elsewhere? Thanks :)
Firstly, your array char student_number[8]; cannot hold 8-character string because there are no room for terminating null character. You must allocate one more element.
Then, you should convert the characters to corresponding numbers. Character codes for digits are defined to be continuous, so this can be done by subtracting '0' from the character code.
Also you should set a limit of length of string to read via scanf() to avoid buffer overrun. One more good practice is checking the return values of scanf() to see if something is successfully read.
Fixed code:
#include <stdio.h>
#include <string.h>
int main(void) {
char student_number[10]; // *** allocate enough elements (one more than needed to catch too long input)
int i = 0;
int sum = 0;
printf("Enter your student number: ");
if(scanf("%9s", student_number) != 1){ // *** limit the length to read and check the result
fputs("read error\n", stderr);
return 1;
}
// ensures input is only 8 digits - WORKS
while (strlen(student_number) < 8 || strlen(student_number) > 8){
printf("Enter your student number: ");
if(scanf("%9s", student_number) != 1){ // *** limit the length to read and check the result
fputs("read error\n", stderr);
return 1;
}
}
// prints each digit of the student number on a new line - WORKS
while (student_number[i] != '\0'){
printf("%c\n", student_number[i]);
i++;
}
// sum all the digits in the student number and print -DOESN'T WORK
for (i=0;i<8;i++){
sum = sum + (student_number[i] - '0'); // *** convert characters to numbers before adding
printf("%d\n", sum);
}
printf("Sum of the numbers is %d", sum);
}
When you read characters as a string, the values of the char objects are codes for the characters. Your C implementation is likely using ASCII codes, in which 48 is the code for “0”, 49 is the code for “1”, 65 is the code for “A”, and so on.
To convert a code x for a digit to the value of the digit, use x - '0'.
I think that the task was to read the number not the string.
void printDigitsAndSum(unsigned number)
{
unsigned mask = 1;
unsigned sum = 0;
while(number / (mask * 10)) mask *= 10;
while(mask)
{
printf("%u\n", number / mask);
sum += number / mask;
number %= mask;
mask /= 10;
}
printf("Sum: %u\n", sum);
}
int main(void)
{
unsigned number;
if(scanf("%u", &number) == 1)
printDigitsAndSum(number);
else printf("Wrong number\n");
}
https://godbolt.org/z/1edceh

Transform and store reversed order digits of an integer to a complete integer number

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

Why is this skipping numbers when I divide it?

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

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

Resources