Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C Exercises: Sum of the digits equals to another given number

C Basic Declarations and Expressions: Exercise-141 with Solution

Write a C program that reads n digits (given) chosen from 0 to 9 and prints the number of combinations where the sum of the digits equals to another given number (s). Do not use the same digits in a combination.

For example, the combinations where n = 3 and s = 6 are as follows:
1 + 2 + 3 = 6
0 + 1 + 5 = 6
0 + 2 + 4 = 6

Sample Solution:

C Code:

#include <stdio.h>
int combination(int n, int s, int a)
{
	int i,result = 0;
	if (n == 1)
	{
		if (s >= a && s <= 9)
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}

	for (i = a; i <= 9; i++)
	{
	        
		result += combination(n - 1, s - i, i + 1);
	 
	}

	return result;
}

int main()
{
	int  n,s;
        printf("Input the number:\n");
		scanf("%d", &n);
		printf("\nSum of the digits:\n");
		scanf("%d", &s);
		if (n != 0 && s != 0)
		{
			printf("Number of combinations: %d\n",combination(n,s,0));
		}
		
	return 0;
}

Sample Output:

Input the number:
3

Sum of the digits:
6
Number of combinations: 3

Flowchart:

C Programming Flowchart: Sum of the digits equals to another given number.

C programming Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C program to which reads a sequence of integers and find the element which occurs most frequently.
Next: Write a C program which reads the two adjoined sides and the diagonal of a parallelogram and check whether the parallelogram is a rectangle or a rhombus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



C Programming: Tips of the Day

Static variable inside of a function in C

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

Ref : https://bit.ly/3fOq7XP