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(...);
}
Related
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
}
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is the program I wrote. I get a blank output when I execute it. Can't figure out what's wrong with it.
#include <stdio.h>
void main() {
int a, b = 0, s, n;
printf("The armstrong numbers are-");
for (n = 1; n <= 10000; n++) {
s = n;
while (n > 0) {
a = n % 10;
b = b + a * a * a;
n = n / 10;
}
if (b == s)
printf("%d ", s);
}
}
As others have suggested Don't change n inside the for loop as your loop depends on the variable n. you have to set b back to 0 for each iteration.
Your program is not very much readable as others might not understand what does a,b,n and s mean. So, always use meaningful variable names like this: (see comments for more description)
#include<stdio.h>
int main(void) //correct signature for main function
{
int digit; //instead of a
int sum=0; //instead of b
int number; //instead of n
printf("The armstrong numbers are-");
for(number = 1; number <= 10000; number++)
{
int temporary = number; //temporary integer to store number value
sum = 0; //sum must be reset to 0 at the start of each iteration
while(temporary > 0)
{
digit = temporary % 10;
sum = sum + (digit * digit * digit);
temporary = temporary / 10;
}
if(sum == number) //if sum obtained == number, print it!
printf("%d ",number);
}
return 0;
}
output:
The armstrong numbers are-1 153 370 371 407
Don't change n inside the for loop.
you have to set b back to 0 for every n.
Hope I helped
The loop variable n was getting modified in the loop. So use the temporary variable s to do the inner while loop. And variable b must be initialized to zero every time you check for a new number. It's a good practice to define the variable within block that you use rather than defining everything globally or in the start of main.
#include <stdio.h>
int main() {
int n;
printf("The armstrong numbers are-");
for (n=1; n<=10000; n++) {
int a, b=0, s=n;
while (s > 0) {
a = s % 10;
b = b + (a*a*a);
s = s / 10;
}
if (b == n)
printf("%d ", n);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Need to make a C code that asks of the user to input one number, and the code will check whether the number is a "Cullen's number" or not.
A number is Cullen's number as long as you can calculate it by doing "2^n * n + 1".
Examples of Cullen's numbers:
3=2^1 * 1 + 1
9=2^2 * 2 + 1
25=2^3 * 3 + 1
Here's the code I was working on, any help?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int num, brojP, potency = 0, numRepeats = 0, endResult=0, isCullen;
printf("Unesite broj");
scanf("%d", &num);
do
{
potency = potency + 1; // initializing "potency" and at the same time making it one number larger at each repeat of the loop
do
{
brojP = 2*potency;
numRepeats = numRepeats + 1;
} while (numRepeats < potency); // this entire loop is used for "2^n" part
endResult = brojP * potency + 1; // calculate the "2^n * n + 1"
numRepeats = 0;
if (endResult == num)
{
isCullen = 1;
break;
}
} while (endResult < num);
if (isCullen == 1)
printf("Number inputted is Cullen's number\n");
else
printf("Number inputted isn't Cullen't number\n");
return 0;
}
This loop is wrong:
do
{
brojP = 2*potency;
numRepeats = numRepeats + 1;
} while (numRepeats < potency); // this entire loop is used for "2^n" part
You need to multiply the result from the previous iteration by 2 each time, but you're multiplying potency by 2 instead. Since potency doesn't change, you're just doing the same assignment over and over. Do it like this:
brojP = 1;
for (numRepeats = 0; numRepeats < potency; numRepeats++) {
brojP *= 2;
}
It would maybe be more efficient if you used dichotomic search. As you store your result in an int, I assume that the max size for the entered number is 2^32 (int are most frequently coded on 32 bits).
You can try with potency = 16 and then if the entered number is bigger with 2^24, etc
If (let's say) you try for n = 6 then n = 7 and none of them is working, you know that it is not a Cullen's number.
You will at most calculate log2(32)=5 times.
EDIT: By the way, why don't you just use the math.h library?
This question already has answers here:
Why for loop in C only passes once?
(2 answers)
Closed 3 years ago.
int input;
int factorial;
int half;
printf("Enter the number you wish to calculate: ");
scanf("%d", &input);
for(x=1; x<input; x++);
{
half = input - 1;
factorial = input * half;
}
printf("%d\n", factorial);
return 0;
It's running once, giving me the input number * (input number - 1), exam, input is 5 its giving out 20. What am I doing wrong that is preventing it from continuing running?
You have a ; after the for-loop. Remove that and you'll be fine:
for(x=1; x<input; x++) {
// your stuff
}
You still have to fix another error in your loop, as mentioned in the other answers.
You don't change input in your loop, so your code boils down to (for your sample input of 5):
for (i = 1; i < 5; i++) {
half = 5 - 1;
factorial = 5 * 4;
}
factorial 5 (5!) would be 5 * 4 * 3 * 2 * 1, which should be:
factorial = 1;
for (i = input; i > 1; i--) {
factorial = factorial * i;
}
What am I doing wrong?
There are many things that you are doing wrong:
Naming a variable half is wrong, unless you assign a value that is truly a half of something to it
Your loop does not use the previous value of factorial
You always multiply input by input-1, and never change the input
You do not initialize factorial to 1
P.S. The fact that your loop runs empty is the least of your troubles.
P.P.S. To do it right, consider how you do it on paper: you start with 1, and then keep multiplying the previous result by numbers from 2 to input. Now write the same algorithm as a C program: use factorial as your intermediate result, and x from the loop as your "current number between 1 and input.
You're not actually changing the state, so you should only ever get input * (input - 1). Why? Well, half will always be input - 1, and input will never change. Meanwhile the value of factorial is simply assigned to that product every time you step through the loop.
I think what you intended is
factorial = 1;
// no sense in starting from 1, factorial already is 1
for(x = 2;
// using <= so as to *include* the original input value.
x <= input; x++)
{
// the same things a factorial = factorial * x
factorial *= x;
}
BTW: You may wish to compensate for negatives too.
Your loop uses the same values each time (input and half)
try
factorial = 1;
for(x=2; x<=input; x++)
{
factorial *= x;
}