I wanna write a code which would add the digits before decimal and after decimal.
eg:- 12.22 would add upto 3.4 , 491.941 would give 5.5

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
  double a1[5],a ; //array of 5 numbers
  int b,len,i,sum=0,cnt = 0;
  char ch[10];

  for(i = 0;i<5;i++)  // accept numbers
  scanf("%lf",&a1[i]);

  while(cnt<5)
  {
	a = a1[cnt];
	 b = (int)(a);   //numbers before float
	 a = a  - (int)(a);  //remaining number
	 sprintf(ch,"%lf",a); //copy to string


	 while(b)
	  {
		 sum += b%10; 
		 b/=10;
	  }
	 if(sum >= 10)
	  {
		 sum = (sum % 10) + (sum /10); //if the resultants sum is a two digit num                            //convert it to single digit (assuming sum to be two digit)  
	  }
  printf("\n%d .",sum);
  sum = 0;
  i = 2;

	while(ch[i])
	 {

		sum += ch[i] - '0';
		i++;
	 }
	if(sum >= 10)
	 {
	  sum = (sum % 10) + (sum /10);
	 }

	 printf("%d",sum);
	 sum = 0;
	 cnt++;
  }
}

Similar thing can be done by reading it as string array.
But i wanted to know if it could be done without using string array or string functn. plainly by using any numeric datatype.

>>But i wanted to know if it could be done without using string array or string functn. plainly by using any numeric datatype

Yes. use modf() to split the float into integer and fractional parts. The write a function that adds together the digits of each part. Finally main() should put the two parts back together again into a single float.

You can use / and % operators to extract each digit

splitting is not problem. problem is reading after split 99.99 becomes 99&0.99 '%' doesn't work for 0.99 - illegal use of float points. i have to know the length of num to mul it by 10 to make it int. if there is any other logic behind / or % pls tell.

@AncientDragon and Rahul.menon

What Ancient Dragon has suggested and what you are trying to do is both right but I have a suggestion here which may sound a bit off the line.
Why not read the floating value as a string(char array) instead of a float ? Because as we know floating point variables are never stored internally as they look on screen which makes their comparision literally impossible without some suffixes to the numbers such as F.
So if your whole plan is to read a floating point value and add its integral and fractional part's digits and print it back then better read it as a string and play around until you have a better purpose to serve.

To do it as floats, do something like this

float x = 914.419;
float intpart, fractpart;
fractpart = modf(x, &intpart);

int x1 = (int)intpart;
int x2 = (int)(fractpart*1000.0);

Now you have two integers to work with. One problem is that some nmbers can not be represented exactly in memory, so fractpart may or may not be an exact value.

This article has been dead for over six months. Start a new discussion instead.