The reverse of the number is getting printed many times. How do I print it just once?
For example, if I give input as 1234 then the output is coming out as 4321 4321 4321 4321.
#include <stdio.h>
#include <stdlib.h>
//function declaration
void printReverse(int);
int main()
{
int n;
printf("\n\t\t\t\t\t\tThis program prints reverse of a given number");
printf("\nEnter a number: ");
scanf("%d",&n);
//if someone enters 0
if(n==0)
{
printf("%d",n);
exit(0);
}
//function call
printReverse(n);
return 0;
}
void printReverse(int n)
{
static int rev=0;
//base case
if(n)
{
int rem = n % 10;
rev = rev*10 + rem;
printReverse(n/10);
}
printf("%d ",rev);
}
The way your printReverse function is currently written, the last line (printf("%d ",rev);) will always be executed whenever the function is called, because there is no code path through the function that skips that line. So, when the recursion has reached the point where the given argument is zero, you will get that line being called each time on the 'rewind' of the stacked, recursive calls (once for each digit in the initial n).
To fix this, you can either enclose that printf line in an else block:
void printReverse(int n)
{
static int rev = 0;
if (n) {
int rem = n % 10;
rev = rev * 10 + rem;
printReverse(n / 10);
}
else { // Only print the result when we're finished (n = 0):
printf("%d\n", rev);
}
}
Or, accomplishing much the same thing, add a return statement after you make the recursive call:
void printReverse(int n)
{
static int rev = 0;
if (n) {
int rem = n % 10;
rev = rev * 10 + rem;
printReverse(n / 10);
return; // Don't print on the rewind from recursion
}
printf("%d\n", rev);
}
C Program to reverse a given number using Recursive function
based on https://beginnersbook.com/2014/06/c-program-to-reverse-a-given-number-using-recursive-function/
#include <stdio.h>
int sum=0, rem;
int reverse_function(int num) {
if(num) {
rem=num%10;
sum=sum*10+rem;
reverse_function(num/10);
}
else
return sum;
return sum;
}
int main() {
int num,reverse_number;
//Take the number as an input from user
printf("Enter any number:");
scanf("%d",&num);
//Calling user defined function to perform reverse
reverse_number=reverse_function(num);
printf("The reverse of entered number is :%d",reverse_number);
return 0;
}
Output:
Related
Write a program that prints the sum of digits for the entered interval limits. To calculate the sum of
digits form the corresponding function.
#include <stdio.h>
void suma(int a ,int b ){
int s= 0,i;
for(i=a;i<=b;i++){
while(i != 0 ){
int br = i % 10;
s+=br ;
i = i/10;
}
printf("%d\n",s);
}
}
int main(void){
int a,b;
printf("enter the lower limit of the interval: "); scanf("%d",&a);
printf("enter the upper limit of the interval: "); scanf("%d",&b);
suma(a,b);
return 0;
}
when i set a to be 11 and b to be 13 program does first 3 sums but after that it doesent stop.why doesn't it stop. But if i set a to 3 digit number program gives me first sum but then gives me random sums
The reason why your code is not working is because in your while-loop, you are changing the value of i, but i is also used in the for-loop. This results in undefined behaviour. In order to fix this, I would suggest breaking the problem up in two functions. One for calculating the sum of a the digits of a number, and one function that adds these sums in a particular range.
int sumNumber(int number) {
int sum = 0;
while(number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
int suma(int a ,int b){
int totalSum = 0;
for(int i=a;i<=b;i++){
int sum = sumNumber(i);
totalSum += sum;
}
return totalSum;
}
This way, you are not modifying i in the while-loop.
You are mixing up the two loop variables. As arguments are passed by value just a instead of introducing an unnecessary variable. Minimize scope of variables. Check the return value from scanf() otherwise you may be operating on uninitialized variables.
#include <stdio.h>
void suma(int a, int b) {
for(; a <= b; a++) {
int s = 0;
for(int i = a; i; i /= 10) {
s += i % 10;
}
printf("%d\n", s);
}
}
int main(void){
printf("enter the lower limit of the interval: ");
int a;
if(scanf("%d",&a) != 1) {
printf("scanf failed\n");
return 1;
}
printf("enter the upper limit of the interval: ");
int b;
if(scanf("%d",&b) != 1) {
printf("scanf failed\n");
return 1;
}
suma(a,b);
}
and example run:
enter the lower limit of the interval: 10
enter the upper limit of the interval: 13
1
2
3
4
I was unreasonably annoyed by how the code was formatted. Extra white space for no reason including at end of line, missing white space between some operations, variables lumped together on one line.
It's a really good idea to separate i/o from logic as in #mennoschipper's answer. My answer is as close to original code as possible.
i did function like this and it works now
void suma(int a ,int b ){
int s= 0,i;
int x ;
for(i=a;i<=b;i++){
x = i;
while(x != 0 ){
int br = x % 10;
s+=br ;
x = x/10;
}
printf("%d\n",s);
s = 0;
} }
I am running this code, and the print commands are not actually resulting in any printing. Can anyone please advise? I do have a couple of comments at the end that will preface my two other functions, but for now, I am just interested in knowing why the prints aren't appearing even though my code doesn't show any errors.
Thanks!
# include <cs50.h>
# include <stdio.h>
int length(long number);
int start_chars(long number);
//Main
int main (void)
{
long number = get_long("Number: ");
int length(long number);
int start_chars(long number);
}
//Number length count
int length(long number)
{
int len = 0;
do
{
len ++;
number /= 10;
}
while (number > 0);
return len;
printf("Length: %d", len);
}
//Number first characters
int start_chars(long number)
{
long charsnum = number;
while (charsnum >= 100)
{
charsnum /= 10;
}
return charsnum;
printf("First 2 digits: %ld", charsnum);
}
//Length & character count congruity
//Checksum
A function is terminated immediately after the return statement.
Your printing statement is after the return statement in those functions. That is why, they don't appear when you run the code.
So, put them before the return statement and you should be able to see them in the output. Moreover, for some clean output, do use \n inside those printf.
Then, inside your main function, look at these statements:
int length(long number);
int start_chars(long number);
Those are function declarations and not how functions are called in C. Store the return value in a variable. Since you just want to see those printf statements get executed, change that to:
length(number);
start_chars(number);
when you use return in your functions they will end immediately.
and so your printf line won't be executed.
printf should be before return.
Like the answers above, you made an error in your code where you are printing after the return statement.
Here is the correct code :
# include <cs50.h>
# include <stdio.h>
int length(long number);
int start_chars(long number);
//Main
int main (void)
{
long number = get_long("Number: ");
int length(long number);
int start_chars(long number);
}
//Number length count
int length(long number)
{
int len = 0;
do
{
len ++;
number /= 10;
}
while (number > 0);
printf("Length: %d", len);
return len;
}
//Number first characters
int start_chars(long number)
{
long charsnum = number;
while (charsnum >= 100)
{
charsnum /= 10;
}
printf("First 2 digits: %ld", charsnum);
return charsnum;
}
//Length & character count congruity
//Checksum
here is the link to the file(google docs link) containing my code -
#include<stdio.h>
int len(int);
void main()
{
int n,p;
printf("enter number");
scanf("%d",&n);
p=len(n);
printf("length of entered number is %d",p);
}
int len(int num)
{
int i,c,b;
for(i=1;i<=50;i++){
b=10*i;
if(num<b) {
return(i);
break;
}
}
}
Computing b=10*i; makes no logical sense. Did you want to raise 10 to a given power?
The normal way of solving this problem is to repeatedly divide by 10 until 0 is reached (using integer arithmetic), and count the number of divisions made. That is the number of digits in the original number. This method is also not vulnerable to integer overflow:
unsigned digits = 0;
for (; num /= 10; ++digits);
return digits;
int len(int num){
int i = 0;
if(num == 0)
return 1;
while(num!=0){
num = num / 10;
i++;
}
return i;
}
here we divide num by 10 until it reaches 0, and each time loop executes we increment the count i++
frontmatter i am not able to recognize your answer but i think this following code is helpful as per your title.
#include<stdio.h>
#include<conio.h>
void main()
{
char a[50000];
int i,c=0;
printf("enter number:");
fflush(stdin);
gets(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]>=0 || a[i]<=9)
{
c++;
}
}
printf("\n %d digit number",c);
getch();
}
I have a problem with C program. The idea of it is similar to Armstrong number checking. Say if the input number is 123. Program needs to check if condition, for example 123=1^1+2^2+3^3 is true. I know how to add digits,but have a problem with powers. It is obvious that I need a loop for powers from 1 to the number of digits. In Armstrong number algorithm you have similar power on every digit. For example 153=1^3+5^3+3^3. Here is what I have so far:
#include<stdio.h>
int main()
{
int n,d,s=0,o,i,k;
printf("n=");scanf("%d",&n);
d=n;
while(d!=0)
{
o=d%10;
s=s+o;
d=d/10;
k++
}
printf("sum:%d",s);
printf("number of digits:%d",k);
return 0;
}
Thanks for the answers.
You need first get the lenth of number, which is used to determine how many times you need to get into loop to calculate each bit.
For example, number 123, you first need to know the number is 3 bits len, then you can mutilply number 3 three times, number 2 twice, and number 1 once.
I use a temporary string to achieve this
here is code, a little bit alteration on yours
#include <stdio.h>
#include <string.h>
#define MAX_NUM_LEN 16
int main()
{
char tmp_num[MAX_NUM_LEN] = {0};
int len,n,d,s=0,o,i,tmp_len, tmp_o;
printf("n=");scanf("%d",&n);
sprintf(tmp_num, "%d", n);
len = strlen(tmp_num);
tmp_len = len;
d=n;
while(d!=0)
{
o=d%10;
for (tmp_o = 1, i = tmp_len; i > 0; i--)
tmp_o *= o;
s=s+tmp_o;
d=d/10;
tmp_len--;
}
printf("sum:%d\n",s);
printf("number of digits:%d\n",len);
return 0;
}
results:
According of what I've understood I think this is what the OP is looking for:
int power(int base, int exp)
{
if (base == 0) return 0;
int result=1;
while (exp-- > 0) result*=base;
return result;
}
void calculate(int number)
{
int d=number;
int tmpnumber=number;
int n=0;
while (d > 0)
{
n++;
d /=10;
}
printf("Number of digits: %d\n", n);
int k=0;
int sum=0;
while (n--)
{
// get digits from left to right
d=number / power(10, n);
k++;
sum+=power(d, k);
number %= power(10, n);
printf("%d^%d=%d\n", d, k, power(d, k));
}
printf("\n%5d %5d", tmpnumber, sum);
}
int main(int argc,char *argv[])
{
int value;
while (TRUE)
{
printf("Enter value (0 = Quit): ");
scanf("%d", &value);
if (value <= 0) return 0;
calculate(value);
printf("\n");
}
}
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;
}