Find the sum of digits of a number(in c) - c

I need to find the sum of the digits of a number. For example, the sum of the digits of the number 1123 is 1+1+2+3 =7
My idea:
1)User enters and integer
2)I calculate the number of digits in the number(in case above - 4 digits)
3)Than using for loop I divide users number by 10 to the power of 1,2...till the number of digits(not including the last one) and sum the numbers.
Here is my code:
int main (void)
{
int result,sum,n;
int div = 10,counter = 0,number;
printf("Enter the integer:");
scanf("%i",&number);
while(result >0){
result = number/div;
div *= 10;
++counter;
}
printf("The number consists of %i digits\n",counter);
sum = 0;
for(n=1;n<counter;++n){
sum += number/pow(10,n);
}
printf("%i",sum);
return 0;
}
the first part(while loop) separately works correct. But together with second part(for loop) it gives me incorrect result(0 digits from the while loop and the sum is also zero). Can you explain why does it happen?
How can I correct my solution?
P.S I know that exist more efficient solutions of my problem, but i want to use my own algorithm.

Several problems here:
When you first enter the while loop, result has not been initialized. Attempting to read an uninitialized variable is undefined behavior.
When you do the division, you aren't adding digits. You're adding the number divided by successive powers of 10. In the case of 1123, you're actually adding 112 + 11 + 1. You need to use modulus instead of division to get the digits.
You can do the adding and counting of digits in a single loop as follows:
sum = 0;
while(number > 0){
sum += number % 10;
number /= 10;
++counter;
}
printf("The number consists of %i digits\n",counter);
printf("%i",sum);

much simpler:
result = number;
sum = 0;
counter = 0;
while(result != 0){
sum += result % 10;
result /= 10;
++counter;
}
printf ("Counter:%d sum:%d\n", counter, sum);

First of all, for best debugging, use a number which has different digits, like 12345.
To do debugging, calculate and print the digit separately from accumulating it. That is, instead of sum += <... complex code ...>, do it like this:
int digit = ...
printf("Next digit is %i\n", digit);
sum += digit;
Also (you should discover this by debugging, but it's obvious enough to note directly), your algorithm for calculation of digits is wrong. Do something like this:
int div = 1;
for (...)
{
digit = number / div % 10;
div *= 10;
}
Note that I don't use pow here, because pow uses floating-point arithmetic, which has limited accuracy. If your int has 64 bits of precision (unlikely but possible), floating-point will calculate nonsense for large numbers (it has only 53 bits of precision).

There are many errors in the code, but overall the whole approach is wrong. Counting the digits is unnecessary.
A simpler way would be:
unsigned temp = number, sum = 0;
while (temp) {
sum += temp % 10;
temp /= 10;
}
Notice that you know when to stop looping because temp becomes 0 (temp as a condition is equivalent to temp != 0). You don't need to know the number of digits in advance.

If going with your code, this'll work:
for(n=1;n<=counter;++n){
sum += number%10;
number /= 10;
}
printf("%d",sum);

Simpler solution:
int c, n=0, sum=0;
printf("Enter number");
while((c=getchar())!='\n') { // IMPORTANT: '\n' in unix, '\r' in windows
if(c<'0' || c>'9') {
printf("Bad value");
break;
}
sum+=c-'0'; // c is the ASCII code of the digit, so you have to subtract an offset
n++;
}
printf("Number of digits: %d", n);
printf("Sum of digits: %d", sum;

Related

How to store a value of a variable and update it's value inside a loop in C language?

I am new to programming in C and I am doing some activities for my first year in CS. The following activity consists of calculating the sum of squares of the digits of a user input number and the output should be as follows:
Number: 1234
  n=1234; sum=16
  n=123; sum=25
  n=12; sum=29
  n=1; sum=30
Result: 30
I have got it for the most part, the thing that I don't understand is how to store a value in a variable, update said variable and print the result, all whilst being inside a loop.
This is what I came up with:
int main() {
int num,i,sum=0,result,square;
printf("Calculate the sum of the square of the digits of a number\n" );
printf("Number:");
scanf("%d", &num);
i=0;
while(num>i)
{
sum=num%10;
square=sum*sum;
printf("\nn=%d; sum= %d",num,square);
num=num/10;
}
result=sum;
printf("\nResult: %d",sum);
return 0;
}
How can I sum the square of the digits all together and print them as the example given?
Write something like the following
int digit = num % 10;
square = digit * digit;
sum += square;
printf("\n=%d; sum= %d", num, sum );
Pay attention to that the variable i is redundant:
i=0;
while(num>i)
just write
while ( num != 0 )
Also introducing the variable result is redundant and does not make sense because it is used nowhere.
You need a variable, keeping track of the input number (num), a variable keeping track of the sum ('sum') and a variable with the current digit (digit). Every iteration, you can calculate the digit, square it and add it to the sum. The a += b operation is equivalent to a = a + b, in case you are wondering. The same is for a /= b. Also a concept you can use (but don't have to), is implicit boolean conversion. When using a comparison (like num != 0 or num > 0) you can replace it with the number itself. In C, 0 equals false and everything else equals true.
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Calculate the sum of the square of the digits of a number\n" );
printf("Number:");
scanf("%d", &num);
while (num) { // is equal to num != 0
int digit = num % 10;
sum += digit * digit;
printf(" n=%d; sum= %d\n", num, sum);
num /= 10;
}
printf("Result: %d\n", sum);
return 0;
}
EDIT:
Some people prefer to use num != 0 or num > 0, because it is more readable. You should stick to it too for the start, until you are paid to confuse your coworkers.

This code is running properly when I use 1 digit numbers. But It's keep lagging on more digit numbers

Something is wrong. I'm trying to make a cade which can count number count of any natural number. Like number count of 2 is 1, 30 is 2, 456 is 3. My code is running for 1 digit numbers but not for two digit numbers.
#include<stdio.h>
void main(void)
{
int num,count,check;
float div;
printf("Enter a natural number\n");
scanf("%d", &num);
while (num<=0)
{
printf("Error\n");
printf("Enter a number\n");
scanf("%d", &num);
}
while(num>1)
{
count=1;
check=10;
div=num/check;
if(div<=1)
{
printf("Number count is\n%d", count);
break;
}
check = check*10;
count = count+1;
}
}
The problem with your solution is that after check and count are modified at the end of the loop, they are re-declared to 1 and 10 respectively at the beginning of the loop at every passage.
You need to move the declaration just before the while loop.
Also div doesn't need to be a float given that the decimal part of this number is irrelevant.
You could also use less variables by replacing check by 10 and
using num directly instead of temporarily storing results in div.
I think this might be a simpler solution
#include <stdio.h>
int main(){
int num = 0, digits = 0;
while (num <= 0)
{
printf("Enter a natural number\n");
scanf("%d", &num);
num == 0 ? printf("Error\n") : 0;
}
for( ; num > 0; digits++)
num /= 10;
printf("number of digits: %d\n", digits);
}
As num is continuously divided by 10, the decimal of the result gets truncated since num is an int while digits steadily increases.
It is time to learn to use a debugger. Using it would have immediately shown the major problem in your code: you reset the value of count and check inside the loop. So if you enter a number greater or equal to 10, you enter an infinite loop because you will consistently divide that number by 10 and find that the result is >= 1!
There is another less important problem: you use if(div<=1) when it should be if(div<1). Because 10/10 is 1 and has 2 digits...
After those fixes you should have:
...
check = 10;
count = 1;
while (num > 1)
{
div = num / check;
if (div < 1)
{
printf("Number count is\n%d", count);
break;
}
check = check * 10;
count = count + 1;
}
return 0; // main shall return an int value to its environment...
}
Which correctly gives the number of decimal digit on positive integers. But as you were said in comments, you should always test the return value of scanf (what is the user inadvertently types a t instead of 5 for example?).
That being said, this answer intends to show you what the problems were, but Keyne's solution is better...

Sum and average for n numbers with -1 as exit integer

Hello I have a small problem with my code and I want to understand it. My task is to write a program that take the sum and average for n numbers with while loops or nested while loops with if conditions, when you want to exit the code you should enter -1. The code is down below. The problem I have is that I can't get it to exclude the -1 from the calculation. What am I doing wrong. And it is suppose to be a simple code.
int main(void) {
int count;
float sum, average, number;
sum = 0;
count = 0;
printf("Calculate sum and average (-1 to quit)\n");
while (number!=-1) {
scanf("%f", &number);
sum = sum + number;
count = count + 1;
}
average = sum / count;
printf("Sum=%f", sum);
printf(" Average=%f", average);
}
in the while block, you read the number and then add it to your average calculation, and only then after the iteration repeats you're checking if it's different than -1 to stop the iteration:
there are obviously different ways to solve it:
one way can be to use while(true) and in the while block after you read the number add an if statement to compare it with -1 and break out of the loop
while (true) {
scanf("%f", &number);
if (number == -1) break;
sum = sum + number;
count = count + 1;
}
Reordering the different steps could solve this:
int main(void) {
int count;
float sum, average, number=0.0f;
sum = 0;
count = -1;
printf("Calculate sum and average (-1 to quit)\n");
while (number!=-1) {
sum = sum + number; // first time no effect with 0
count = count + 1; // first time "no effect" counting to 0
scanf("%f", &number); // will not be counted or summed if -1
}
average = sum / count;
printf("Sum=%f", sum);
printf(" Average=%f", average);
}
Think it through with immediatly entered -1:
sum is 0+0, suitable for no numbers being added up
count is -1+1==0, suitable for no numbers
dividing by 0 should be avoided, but that is a separate issue
Think it through with one number:
number is read in with sum==0 and count==0
is not -1, so loop iterates again
sum and count are updated meaningfully
-1 one is entered
loop ends without processing -1
By the way, comparing a float for identity is risky. You would be safer if you could compare more "generously", e.g. while (number>-0.5).
I think you should take the input at the last of the loop as it will get check in the next iteration. And when -1 comes up it will not be added.
#include <stdio.h>
int main(){
int count=0;
float sum=0, average=0, number=0;
printf("Calculate sum and average (-1 to quit)\n");
while(number!=-1){
sum = sum + number;
count = count + 1;
scanf("%f", &number);
}
average = sum / count;
printf("Sum=%f", sum);
printf(" Average=%f", average);
}
Code needs to test number as -1 before including it in the summation. OP's code test almost does this right. OP's code test for -1 before number is even assigned leading to undefined behavior (UB).
float number;
while (number!=-1) { // UB!
Also good to test the return code of scanf() for success.
while (scanf("%f", &number) == 1 && number != -1) {
sum = sum + number;
count = count + 1;
}

Manipulating random number arrays

The question: Given integer values of x and y generate 20 random values within [x, y] interval and put them in an array. Print the array. Determine the index of the largest even negative number in it (ranging from 0 to 19). Account for the possibility that there might be no such number in the array. Calculate the sum of all positive odd numbers. You are only allowed to go through the
array values once. You should define separate functions for generating random numbers and checking even and odd numbers.
What I have written:
#include <stdio.h>
int random(int min, int max, int arr[]){
int i, j = 1;
for(i = 0; i<20; i++){
arr[i] = min + rand() % (max+1 - min);}
for(i = 0; i<20; i++){
printf("%d. %d\n", j, arr[i]);
j++;}
return arr[20];}
int evenodd(int arr[], int size){
int i, holder, sum, index = 1;
holder = arr[i];
for(i = 0; i<20; i++){
if (holder>0){
if (holder%2 == 0){
sum = sum;}
else{
sum += i;}}
else{
sum = sum;}}
printf("\nThe sum of all odd positive numbers is %d.", sum);
for(i = 1; i<20; i++){
int top = arr[0];
if (arr[i]<0){
if(arr[i]<top){
top = arr[i];
index = i;}
else{
top = top;}}
else{
top = top;}}
printf("\nThe index of the largest negative number is %d", index);}
int main()
{
int min, max;
printf("Please input the minimum desired random number: ");
scanf("%d", &min);
printf("\nPlease input the maximum desired random number: ");
scanf("%d", &max);
int a[20];
random(min, max, a);
evenodd(a, 20);
}
It prints out fine, but the sum of positive odd number is wrong, as well as the index of the largest negative number.
In your loop for(i = 1; i<20; i++) when finding negative numbers, you begin the loop by resetting the value of top to be arr[0], and thus you will always be doing your comparisons against the first value of the array. Perhaps you want to move that initialization out of the loop.
I see several issues with your code (especially with respect to your problem statement), but the summation procedure is not working because you are initializing variable "holder" only once, that too, before the for loop. Also, you are using an uninitialized varaible "i" as an index for the array arr. A lot can go wrong here!
By the way, Please use proper indentation to make your code more readable.
Four things
1) You did not initialize your sum to zero for odd positive numbers. So you should do that.
2) In calculating the sum you should do sum+=sum[i] and not sum+=i;
3) You initialized your index to 1 and not 0 for index of the largest negative number. If the first element is your smallest negative your answer should be zero. Right now for both first and second element you will give answer as 1. If you want a range from 1 to 20 you can output i+1 in the prints. I think you also have to do if(arr[i]>top) to find the largest negative integer assuming -10 is larger than -20 which is usually the case
4) Your implementation in three still wont account for the fact that no such number exists. What I recommend doing is initialize your top to largest negative integer. Range of values in C Int and Long 32 - 64 bits . And you can set your index to -1. Compare this to the entire array and if your index is -1 in the end. Then you print that no such element exists. You also have to check if the integer you are comparing is even. You can do the summing and the even negative integer in one loop as the two things are independent of each other

Easy C project to show repeated numbers

I have a problem with this code.... The project should show me repeated number in the input number. For example:
$ ./a.out
Enter a number: 9893746595
Repeated: 9 5
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a[10], b[10] ;
int n,t;
printf("Enter a number: ");
for(n=0; n<10;n++)
{
scanf("%d", &a[n]);
n=t;
a[n]=b[t];
}
for(n=0;n<10;n++)
{
for(t=n;t<10;t++)
{
if(a[n]=b[t])
printf("%d", a[n]);
}
}
return 0;
}
if(a[n]=b[t]) assigns b[t] to a[n].
You most likely wanted to use if(a[n] == b[t]) to compare those values.
It's a good idea to compile using the -Wall -Wextra -Werror flags so all warnings are enabled and treated like errors (so you can't simply ignore them). With those flags the compiler will yell at you for doing an accidental assignment.
Your code is bogus. ;-)
The usual approach here is to create an array of 10 ints, one for each digit, and count the occurrences of each digit in the user-supplied number.
There's an idiomatic technique to get the digits of a number num one at a time: use num % 10 to get the last digit, and num / 10 to get the number without its last digit. Then your program might look something like this:
int dcount[10] = {0}; // 10 ints, all initialized to 0
scanf("%d", &num);
while(num) {
dcount[num % 10]++; // increment dcount[i], where i is the last digit of num
num /= 10; // "remove" last digit from num
}
for (int i = 0; i < sizeof(dcount)/sizeof(dcount[0]); i++)
printf("%d occured %d times\n", i, dcount[i]);
I didn't test the above code, so there may be some minor flaws. The general principle should be clear, though.
Hope that helps.
Your code assigns t to n before t has been initialized.
This is bound to cause problems. I haven't fully studied the rest of your code but you should start by initializing t before using it. If that still doesn't work, provide information such as what it does or doesn't do.
You might want to look at the first for loop. t is read from without ever being written to. Same for b. And, you are overwriting the just read in variable a[n] with b[t]. In the conditional for if, you meant == where = is written.
If you turn on every option in your compiler to emit warnings and strictly check for standard language compliance, it would have caught these.
int main()
{
int i, number, digitCount[10];
// Before starting, set the digit count for each digit to 0
for (i = 0; i < 10; i++)
{
digitCount[i] = 0;
}
// Store the entire number in one int
printf("Enter a number: ");
scanf("%d", &number);
// Find the remainder of number / 10 in order to get the last digit
// Divide number by 10 in order to remove that digit
// Continue to peel off digits until you reach zero
while (number != 0)
{
digitCount[number % 10]++;
number /= 10;
}
// For each digit which is counted more than once, print it
printf("Repeated: ");
for (i = 0; i < 10; i++)
{
if (digitCount[i] > 1)
{
printf("%d ", digitCount[i]);
}
}
return 0;
}

Resources