Home > Backend Development > C++ > In a C program, print numbers containing only the digits 0 and 1 so that their sum is N

In a C program, print numbers containing only the digits 0 and 1 so that their sum is N

王林
Release: 2023-09-09 12:49:02
forward
853 people have browsed it

In a C program, print numbers containing only the digits 0 and 1 so that their sum is N

Given an integer n, the task is to print numbers consisting only of 0 and 1, and their sum is equal to the integer n.

The numbers containing only 0 and 1 are 1, 10, 11 so we must print all the numbers that can be added to equal n.

Like, we enter n = 31 then the answer can be 10 10 11 or 10 10 10 1

Example

Input: 31
Output:10 10 10 1
Copy after login

Algorithm

int findNumbers(int n)
START
STEP 1: DECLARE AND ASSIGN VARAIBALES m = n % 10, a = n
STEP 2: LOOP WHILE a>0
   IF a/10 > 0 && a > 20 THEN,
      SUBTARCT 10 FROM a AND STORE BACK IT IN a
      PRINT "10 "
   ELSE IF a-11 == 0 THEN,
      SUBTRACT 11 FROM a AND STORE
      BACK IN a
      PRINT "11 "
   ELSE
      PRINT "1 "
      DECREMENT a BY 1
   END IF
END LOOP
STOP
Copy after login

Example

#include <stdio.h>
// Function to count the numbers
int findNumbers(int n){
   int m = n % 10, a = n;
   while(a>0){
      if( a/10 > 0 && a > 20 ){
         a = a-10;
         printf("10 ");
      }
      else if(a-11 == 0 ){
         a = a-11;
         printf("11 ");
      }
      else{
         printf("1 ");
         a--;
      }
   }
}
// Driver code
int main(){
   int N = 35;
   findNumbers(N);
   return 0;
}
Copy after login

Output

If we run the above program, it will generate the following output:

10 10 1 1 1 1 11
Copy after login

The above is the detailed content of In a C program, print numbers containing only the digits 0 and 1 so that their sum is N. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template