Showing posts with label Sum of Digits. Show all posts
Showing posts with label Sum of Digits. Show all posts

Tuesday, May 06, 2014

Sum of Digits of a number Function (Recursive and Non Recursive) - C Program

Problem Question


A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:
(1) Without using recursion
(2) Using recursion

Explanation of Problem


We wish that the user enters a 5 digit number. We have to make 2 functions one of which will calculate the sum of digits normally, and other will use recursion to do the same.

Code


#include <stdio.h>

/**@Title: SumOfDigitsFunctions.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 06-05-2014*
*/

int digSum(int number)
{
  int sum = 0;
  while (number)
  {
    sum += number % 10;
    number /= 10;
  }
  return sum;
}

int digSumRec(int number)
{
  if (number)
    return (number % 10 + digSumRec(number / 10));
  else
    return 0;
}

int main()
{
  int number, sum = 0;
  printf("\n\nEnter a 5 digit number: ");
  scanf("%d", &number);
  printf("\nSum without recursion: %d\nSum with recursion: %d\n\n", digSum(number), digSumRec(number));
  system("pause");
  return 0;
}

Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This function has to be named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

int digSum(int number)
{
int sum = 0;
while (number)
{
sum += number % 10;
number /= 10;
}
return sum;
}


This is the first function that calculates the sum of digits normally. main() calls this functions with the user entered number as the argument. Inside the function, I have devised a while loop. Why have I used 'number' in the condition? Since I will extract the last digit and add it to the running sum into the variable 'sum', and also divide the number by 10 in each iteration. Once the number turns to be 0 on continuous dividing, the control comes out of the loop, and 'sum' is returned.

int digSumRec(int number)
{
if (number)
return (number % 10 + digSumRec(number / 10));
else
return 0;
}


This is our recursive function. In this case, we do the same thing as above, but instead of while loop, we achieve the same thing using recursion. The if condition is similar to the while loop block in the former function. The statement which executes when the 'if' block condition is true, calls the function digSumRec recursively, but the argument is passed as number / 10 instead of number. Thus as soon as number / 10 returns zero, the if block is not executed. Moreover, the return statement in the if block does the addition part. It extracts the last digit from the 'number' and adds to it what is returned by the recursive call to the procedure.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



Wednesday, April 02, 2014

Sum of first and last digit – C Program

Problem Question


If a four-digit number is input through the keyboard, write a program to obtain the sum of the first and last digit of this number.

Explanation of Problem


In this program the user will enter a 4-digit number. The program should extract the first and last digit of the number, find their sum, and display the result.

Code


#include <stdio.h>
/*Sum of first-n-last digit*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodelBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 02-04-2014**/
int main()
{
    printf("\n\nEnter a four digit number: ");
    int number, digitSum = 0, digit1, digit4;
    scanf("%d", &number);
    printf("\nCalculating sum of digits......");
    digit1 = (number % 10000) / 1000;
    digit4 = (number % 10);
    digitSum = digit1 + digit4;
    printf("\nThe sum of digits is: %d\n", digitSum);
    system("pause");
    return 0;
}

Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This function has to named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

digit1 = (number % 10000) / 1000;
digit4 = (number % 10);

The above piece of code reflects the part of the code in which we extract all the digits of the 4-digit number. ‘%’ operator (called the modulus operator) finds the remainder of the division of the number on left with the number on right of the operator. What I did here is, first I applied the modulus operator between the number and 10000. On dividing, the remainder found, with 1000, I found the digit at the thousand position of the number. This is possible because I am using the ‘int’ data type, which thus rejects the digits after the decimal. Similarly, the ones digit is found. You can try it on paper to justify my statement to yourself.

Once I have found the first and fourth digit of the four-digit number, I use the statement digitSum = digit1 + digit4; to find their sum.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



Monday, March 31, 2014

Sum of Digits (5-digit Number) – C Program

Problem Question


If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits. (Hint: Use the modulus operator ‘%’)

Explanation of Problem


In this program, we wish to get a user input which should be a 5 digit number. Then we shall extract the digits one by one and add them. This sum should then be displayed on the user terminal.

Code



#include <stdio.h>
/*Sum of Digits *
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 31-03-2014**/
int main()
{
    printf("\n\nEnter a five digit number: ");
    int number, digitSum = 0, digit1, digit2, digit3, digit4, digit5;
    scanf("%d", &number);
    printf("\nCalculating sum of digits......");
    digit1 = (number % 100000) / 10000;
    digit2 = (number % 10000) / 1000;
    digit3 = (number % 1000) / 100;
    digit4 = (number % 100) / 10;
    digit5 = (number % 10);
    digitSum = digit1 + digit2 + digit3 + digit4 + digit5;
    printf("\nThe sum of digits is: %d\n", digitSum);
    system("pause");
    return 0;
}

Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This functions has to named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

digit1 = (number % 100000) / 10000;
digit2 = (number % 10000) / 1000;
digit3 = (number % 1000) / 100;
digit4 = (number % 100) / 10;
digit5 = (number % 10);

The above piece of code reflects the part of the code in which we extract all the digits of the 5-digit number. ‘%’ operator (called the modulus operator) finds the remainder of the division of the number on left with the number on right of the operator. What I did here is, first I applied the modulus operator between the number and 100000. On dividing the remainder found with 10000, I found the digit at the ten-thousand position of the number. This is possible because I am using the ‘int’ data type, which thus rejects the digits after the decimal. Similarly, the other digits are found. You can try a it on paper to justify my statement to yourself.

digitSum = digit1 + digit2 + digit3 + digit4 + digit5; -> This is where we calculate the sum of the digits extracted above.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



Wednesday, March 19, 2014

Sum of Digits – Linux Shell Scripting

Problem Question


Write a script to calculate the sum of digits of the given number.

Explanation of Problem


Here we wish to write a Linux Shell Script that would accept one command line parameter (integer) and find the sum of it’s digits. Thus, in a sample run like:
sh SumOfDigits.sh 123
the output should be 6.

Code



#*SumOfDigits*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 19-03-2014
x=$1
a=0
b=0
while [ $x -gt 0 ]
 do
  a=$(( $x % 10 ))
  x=$(( $x / 10 ))
  b=$(( $b + $a ))
 done
echo Sum of digits of $1 is $b

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

x=$1 -> We save the command line argument into a variable named ‘x’. This variable is required since we are going to use it to segregate the digits by recursively dividing it with 10 and storing the remainder.

a=0 b=0 -> We use the variable ‘a’ to store the remainder using a=$(( $x % 10 )) and variable ‘b’ to store the sum using b=$(( $b + $a )).

while [ $x -gt 0 ] -> We use this while loop to do the operations stated above. Apart from that, we divide ‘x’ by 10 using x=$(( $x / 10 )) everytime in the loop and store the answer in ‘x’ because we want to reject the last digit as soon as we have stored it in variable ‘a’.

do done -> While loop block delimiters.

echo Sum of digits of $1 is $b -> echo command of the linux shell is then used to display the string following it. ‘$1’ implies the first command line argument, and ‘$b’ the sum we were required to calculate.

Output(s)