How to add the numbers present in a string? - c

#include<string.h>
#include<stdio.h>
void main()
{
char *a="12345"; //Add number of that string
}
How can i add number of that string
example :
sum=1+2+3+4+5
sum=15
How can i do that?

int sum = 0;
char *a = "12345";
while (*a) {
sum += *a - '0';
a++;
}
printf("sum=%d\n", sum);

I'd like to provide a pretty basic solution to this question..
1)convert the given string to integer and store it's value into a variable, lets say n using the function atoi() function. know more about it by clicking THIS!. and by the way it's pretty easy to understand, it just changes the string mentioned inside brackets to integer.
2)and then using a for loop calculate the sum.
Here I have provided my solution to your problem, I don't think you'll have any problems in tracing out the code. If any help is required, feel free to comment :)
Here's my code below:
#include <stdio.h>
#include <string.h>
int main()
{
int n,i,sum=0; //i is loop parameter and sum is used to store the sum of numbers
char *a="12345";
n=atoi(a); //atoi(string) function is used to change a string into integer
printf("%d",n);
for(i=0;a[i]!='\0';i++) //loop to calculate the sum
{
sum=sum+(n%10);
n=n/10;
}
printf("\n\nsum = %d\n\n",sum);
}
Hope it's helpful.

Related

recursion c, program does not display

im facing an problem in this program, may anyone tell me, what im doing wrong, the program won't display anything after i give it input.
(Code is about sum of digits enter #example 12345 = 15)
#include<stdio.h>
int sum(int num);
int sum(int num){
int total=0;
if(sum==0){
return total;
}
else{
total+=num%10;
num/=10;
return sum(num);
}
}
int main()
{
int num,k;
printf("Enter 5 positive number: ");
scanf("%d",&num);
printf("Sum is: %d",sum(num));
}
Here is a rule of thumb, whenever you have a non-stopping recursion program try to verify your base cases.
Here you are verifying sum the function instead of num the parameter. The C compiler let's you do that because functions in C are pointers, and pointers hold the addresses as numeric value.
You just need to change the condition from sum==0 to num==0. It will now print something. However, the logic of your program is still wrong. You can change your sum function to this.
int sum(int num){
if(num==0) {
return 0;
}
return num % 10 + sum(num/10);
}
And you can try learning more about recursion through stack since recursion is basically just stack.
In your code the total gets initialized to zero every time the function is called. and a variable named sum is not initialized. Just change sum==0 to num==0.I have also given the logic to sum the digits of a number.

Keep getting the same answer when writing a recursive function

Note: I'm fairly new to C programming so I don't know everything just yet.
So I'm working on this assignment for my programming class where I have to write a recursive function count_digits( ) that counts all the digits in a string. I wrote the program and got it to compile but when I type in a number, it always gives me the same answer.
This is what my code is:
#include <stdio.h>
int count_digits(int num)
{
static int count=0;
if(num>0)
{
count++;
count_digits(num/10);
}
else
{
return count;
}
}
int main()
{
int number;
int count=0;
printf("Enter any number:");
scanf("%d",&number);
count=count_digits(number);
printf("\nTotal digits in [%d] are: %d\n",number,count);
return 0;
}
Your non void function returns nothing if num is greater than zero. The compiler should warn you about not returning value. The fix:
return count_digits(num/10);
there are a few things to consider:
What happens if you call your function count_digit() more than one time in the program?
What if you enter 0, 10, 100 as number?
Perhaps you should rethink using a static variable here.
Also for debugging, insert some printfs (or use the debugger) in count_digit() to check how your function behaves.

Integer to Binary Conversion Program Fails for Some Inputs

I wrote code for getting binary form of an integer. It works well for inputs like 1 or 10. However, it is failing for inputs like 256. (It gives 0000000 s output and misses the one).
#include <stdio.h>
#include <math.h>
int number_of_binary_digits_required(int n){
return ceil(log(n))+1;
}
void print_array(int * a, int n){
int i = 0;
for (;i<n;i++){
printf("%d\t", a[i]);
}
}
int main(){
int num = 256;
int binary[100];
int n = number_of_binary_digits_required(num);
int bin_digits = n-1;
while (num){
int temp = num%2;
num = num / 2;
binary[bin_digits] = temp;
//printf("%d\n", bin_digits);
bin_digits--;
}
print_array(binary, n);
//printf("%d", number_of_binary_digits_required(num));
//for(bin_digits = 0;bin_digits < number_of_binary_digits_required(num);bin_digits++)
//printf("%d",binary[bin_digits]);
}
Why is the issue coming and how to resolve it?
Thanks you!
C's log function gives result with a base of e, not 2. This is why some numbers give unexpected result in your program since you calculate using that. There is a function log2 which is what you need i think.
Your use of a logarithmic function to compute the number of digits in conjunction with ceil will suffer due to floating point undershoot.
A more reliable way of calculating the number of binary digits is to divide by two repeatedly until zero is attained.
The first mistake is to use log(n), which calculates log of n base e.
Instead use log2(n)
Hope it helps. :-)

power int number while in loop

OK, so my task is to get a single digit from a natural number and sum the square numbers (Using function while, which means no arrays yet :S). For instance I type 123 so sum=1*100+2*10+3*1; However the problem is that the digit could be whatever. My problem is that the power rises with int but its like so - 1, 10, 99, 1000. The problem for me is 99. Also answer is looping but I'll fix it later. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int N,
number=0,
answer=0,
a=1,
i=0;
printf("Type natural number: ");
scanf("%d",&N);
while(N>i)
{
number=N%10;
N/=10;
a=10;
a=pow(a,i);
answer+=number*number*a;
printf("%d\n", answer);
i++;
}
return 0;
}
Try it the other way around. Don't make the input an integer. Start at the beginning of the stream, get the character, convert it to an int 'number'. Then do
answer = 10 * answer;
answer += (number * number);
This will build up your answer little by little. Note that I am not sure that this is what you are asking for due to your example not seeming to match the code.
Let me know if this is off-base and I will update it.

Issuies with the fibonacci series and c

#include <stdio.h>
#include <math.h>
int fib();
int scan;
int main() {
scanf("%d", &scan);
printf("%d\n", fib());
scanf("%s");
return 0;
}
int fib() {
return floor((pow(1+sqrt(5)/2, scan)-(-pow(1-sqrt(5)/2, scan)))/sqrt(5));
}
I'm pretty new to programming with C and decided to try and calculate any number in the Fibonacci series. I based it off of my lua script here. I'm at a loss of what I've done wrong, could someone give me some insight?
You have the formula wrong. You want fib to be:
int fib() {
return round((pow((1+sqrt(5))/2, scan)-(-pow((1-sqrt(5))/2, scan)))/sqrt(5));
}
instead. You were missing parenthesis around the 1+sqrt(5) and 1-sqrt(5) terms and were using floor instead of round, which was underestimating the fibonacci numbers in my tests. (This mostly has to do with low precision in the pow function. The seventh fibonacci number, 13, came out to 12.969)
You also probably want to change
scanf("%s");
to
char tmp;
scanf("%c", &tmp);
Since the way you have it incorrectly omits an argument.
Hope this helps!

Resources