C program - sum of digits without include the same digit twice [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I do the sum of the digits like that:
while(number>0)
{
sum+=number%TEN;
number=number/TEN;
}
but I need that if the number is (for example) 123444 so it'll include only one 4 in the sum. how can I do that?

Have an array of all digits initialized to zero
int digits[10] = { 0 };
Then before adding a digit you check if digits[that_digit] is zero, if yes you set it to 1 and add to sum, if no keep going ...
while(number>0)
{
int one = number%TEN;
if ( ! digits[one]) {
sum+=one;
digits[one] = 1;
}
number=number/TEN;
}
Edit, no array version
Add an int initialized to 0, the bit i indicates if that digit i has already been summed.
If 1 was added, bit 1 set to 1, if 2, bit 2 set to 1 etc...
int bits = 0;
while(number>0)
{
int one = number%TEN;
if (!(bits & (1<<one))) {
sum+=one;
bits |= 1<<one;
}
number=number/TEN;
}

First you should put some code here whatever you tried, to give you basic idea to solve your problem I am putting simple code below.
#include<stdio.h>
#include<malloc.h>
int main()
{
int input, digit, temp, sum = 0;
printf("Enter Input Number :\n");
scanf("%d",&input);
temp = input;
//first find how many digits are there
for(digit = 0 ; temp != 0 ;digit++, temp /= 10);
//create one array equal to no of digits, use dynamic array because once you find different digits you can re-allocate memory and save some memory
int *p = malloc(digit * sizeof(int));
//now store all the digits in dynamic array
p[0] = input % 10;//1
for(int i = 0; i < digit ;i++) {
input /= 10;
p[i+1] = input %10;
if(p[i] != p[i+1])
sum = sum + p[i];
}
printf("sum of different digits : = %d \n",sum);
free(p);
p = 0;
return 0;
}
Explanation of this code I mentioned in comments itself, it may not work for all test case, remaining try yourself.

Related

Sum of odd numbers using recursion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This might be simple but I'm new to recursion in c. I want to find the sum of odd integers based on user's input. For example if user inputs 3, function returns 9 (1 + 3 + 5 = 9)
int recursiveSumNOdd(int n)
{
int start = -2; //later start = start+2, so it starts at 0
int n1 = n*2; //total number of digits with rec
int num = 0;
int sum=0;
int count=0;
if(start>=n1)
{
return 0;
}
else
{
start = start+2;
count++;
sum = sum +recursiveSumNOdd(start);
}
return sum;
}
Explanations in comment:
int recursiveSumNOdd(int n) {
if (n == 1 || n == 0)// first "if" in a recursive is its stop condition
return n;
return 2 * n - 1 + recursiveSumNOdd(n-1); // formula for 2->3, 3->5 etc
}
int main(void) {
printf("%d\n", recursiveSumNOdd(3));
return 0;
}
NB: You may want to handle integer overflow
NB2: You can have a mathematics formula to return instantly the result, it is way better, but I guess it was to understand better recursion?
return n * n; // the sum of odd numbers is the square of user's input
You are over-complicating things.
You cannot have the sum of negative elements.
int sum_n_odd(unsigned n)
{
What is the sum of 0 (zero) elements?
if (n == 0) return 0;
If you knew the sum of n - 1 numbers, what is the sum of n numbers?
return sum_n_odd(n - 1) + something; // something is easy to figure out
}

How can I print the base two representation of a number without using any array in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to print my characters BEFORE the previously printed character using printf. For example:
printf("1")
printf("0")
would need to output:
01
Is there a way to do this? I cannot use arrays. To be clear I'm printing in base two (binary) representation using a divide by two algorithm:
for(int i = 0; i < 16; i++){ // 16 bit int
tmp = num % 2;
if(tmp == 1){
printf("1");
} else {
printf("0");
}
num /= 2;
}
The above code prints the binary representation backwards.
Here is my solution to print binary without using array. you can ignore initial zeros by adding another if condition.
#include<stdio.h>
int main(){
int num =50;
int i;
for(i=15;i>=0;i--){
if( (1<<i) & num){
printf("1");
}
else printf("0");
}
return 0;
}
output:
0000000000110010
Recursion can perform like a "print before". #rici
The below does not always print 16 digits, just the decimal digits needed.
void print_binary(unsigned n) {
// Break the digits into 2 groups: 1) the one least digit and 2) the rest.
unsigned last_digit = n/10;
unsigned all_the_other_more_significant_digits = n/10;
// Let us print those more significant digits first;
if (all_the_other_more_significant_digits > 0) {
print_binary(all_the_other_more_significant_digits);
}
// Now print the last digit
printf("%u", last_digit);
}

finding the sum of digits? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried this problem using for loop but i did not got the correct output as specified . i do not know what is the problem in my code ?
#include <stdio.h>
int main()
{
int T,N;
scanf("%d %d" ,&T,&N);
for(int i=N;i>0;i=i/10)
{
int r=N%10;
int sum=0;
sum=sum+r;
printf("The sum is : %d" ,sum);
}
}
The sum is : 5The sum is : 5The sum is : 5The sum is : 5The sum is : 5
The output is coming like this while we just need sum of digits printed
for(int i = N; i > 0 ; i = i/10)
{
int r = N % 10; // calculating remainder of UNMODIFIED input, so will
// ALWAYS be last digit
int sum = 0; // you are initializing the sum to 0 for every single iteration
sum = sum + r; // so this will *always* result in 0 + N % 10
printf("The sum is : %d", sum);
}
To fix, you need to initialise the sum just once to collect all of the single digits. Additionally, you need to use the modified value:
int sum = 0;
for(int i = N; i > 0 ; i = i/10)
{
int r = i % 10;
// ^ (!)
sum += r; // alternative variant...
printf("The sum is : %d\n", sum);
// ^^ for better output formatting
}
Until now we are still printing the sum with every iteration as well. That might be useful, if you want to follow how the sum evolves (assuming input was 1210):
The sum is 0
The sum is 1
The sum is 3
The sum is 4
But actually, you'd rather want to print only the result, wouldn't you? So you'd move the printing out of the loop as well:
for(...)
{
...
}
printf("The sum is : %d\n", sum);
Alternative variant: If you don't need the value of N afterwards any more anyway, you can iterate directly on it:
for( ; N > 0; N /= 10)
// ^ empty initialization, nothing to be done...
{
int r = N % 10; // NOW using N is fine...
...
}
Finally: if you compare with != instead of >, you can cover negative intput (as you use signed integers...) as well.
Edit according to question:
it asked input and output like this. Input 3 12345 31203 2123 Output 15 9 8
Well, in this case, you need a double loop:
int t;
// well, actually, you should check if you did get correct input:
if(scanf("%d", &t) != 1))
{
// invalid input
// appropriate error handling, e. g. printing a message and:
return -1;
}
for( ; t > 0; --t) // handles the number of tasks to solve
{
int n; // inside loop: read in a new value with every task
scanf("%d", &n); // TODO: check input, see above
int sum = 0;
for(...) { ... } // loop handling the input value, see above
printf(...);
}

C how to check and point a '0' in a int number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Imagine we've got an int number = 1040 or int number = 105 in a C program, and we want to know if this number contains a 0 and in which position/s are they. How could we do it?
Examples
1040 -> position 0 and 2.
1000 -> position 0, 1 and 2.
104 -> position 1.
56 -> NO ZEROS.
Thanks!
I would divide by 10 and check the remainder. If remainder is 0, then last position of the number is 0. Then repeat the same step until number is less than 10
#include<iostream>
int main(void)
{
long int k = 6050404;
int iter = 0;
while (k > 10) {
long int r = k % 10;
if( r == 0) {
std::cout << iter << " ";
}
k = k / 10;
iter++;
}
}
I would convert it to a string; finding a character in a string is trivial.
As a rule of thumb, if you are doing maths on something, it's a number; otherwise, it's probably (or should be treated as) a string.
Alternatively, something like:
#include <stdio.h>
int main(void) {
int input=1040;
int digitindex;
for (digitindex=0; input>0; digitindex++) {
if (input%10==0) {
printf("0 in position %i\n",digitindex);
}
input/=10;
}
return 0;
}
This basically reports if the LAST digit is 0, then removes the last digit; repeat until there is nothing left. Minor modifications would be required for negative numbers.
You can play with this at http://ideone.com/oEyD7N

How to put an integer to an array of digits [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to put a number like 123456 in to a array of digits. Could you please give me a hint to the process? Can i define an array with unknown number of elements?
First calculate no of digits
int count = 0;
int n = number;
while (n != 0)
{
n /= 10;
cout++;
}
Now intialize the array and assign the size:
if(count!=0){
int numberArray[count];
count = 0;
n = number;
while (n != 0){
numberArray[count] = n % 10;
n /= 10;
count++;
}
}
If you don't mind using char as the array element type, you can use snprintf():
char digits[32];
snprintf(digits, sizeof(digits), "%d", number);
Each digit will be represented as the character values '0' though '9'. To get the integer value, subtract the character value by '0'.
int digit_value = digits[x] - '0';
"Can i define an array with unknown number of elements ?"
If the number is too large you can input it as string and then accordingly extract digits from it
Something like following :
char buf[128];
int *array;
//fscanf(stdin,"%s",buf);
array = malloc(strlen(buf) * sizeof(int)); //Allocate Memory
int i=0;
do{
array[i] = buf[i]-'0'; //get the number from ASCII subtract 48
}while(buf[++i]); // Loop till last but one
int x[6];
int n=123456;
int i=0;
while(n>0){
x[i]=n%10;
n=n/10;
i++;
}
Here are teh steps. First, get the size needed to store all the digits in the number -- do a malloc of an array. Next, take the mod of the number and then divide the number by 10. Keep doing this till you exhaust all digits in the number.

Resources