ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
a function that takes an integer as a parameter and adds the alternate digits and every 3rd digit in the integer?
The simple addition of digits of number is like this way Can any one help me with the changes or modifications we need to do in this
#include<stdio.h>
int main(){
int num,sum=0,r;
printf("Enter a number: ");
scanf("%d",&num);
for(;num!=0;num=num/10){
r=num%10;
sum=sum+r;
}
printf("Sum of digits of number: %d",sum);
return 0;
}
For eg: given an integer 158176
your program should add
- 1,8,7 which are in the position 0,2,4 of the integer AND
- 5,1,6 which are in position 1,3,5 of the integer AND
- 8,6 which are in every 3rd place in the integer.
So the answer will be 1+8+7=16, 5+1+6=12 and 8+6=14. The output will be 16,12,14
Instead of using multiple divisions like you're doing right now, why don't you convert the number to a string and then process it character by character, using an index as indication of whether you're pointing to an even position or an odd position or a position divisible by 3?
Code:
# include <stdio.h>
# include <stdlib.h>
int main (){
int num, i, size;
int nOdd, nEven, nThree;
char buf[30];
nOdd = nEven = nThree = 0;
printf ("Enter a number:");
scanf ("%d", &num);
size = sprintf(buf,"%d", num);
for (i = 0; i < size; i++){
if ( i % 2 == 0 )
nEven+=buf[i] - '0';
else
nOdd+=buf[i] - '0';
if ((i+1) % 3 == 0 )
nThree+= buf[i] - '0';
}
printf ("Initial number = %d\neven = %d\nodd = %d\nthree = %d", num, nEven, nOdd, nThree);
return EXIT_SUCCESS;
}
itoa() is not in standard C (maybe you've seen it on other systems), so I had to resort to sprintf for the conversion.
Well, you could reuse the sample you posted but paying attention to a couple of things.
In your code, you're extracting digits from the units upwards so, feeding 127 as num to the program you'll have:
You need an index while looping which tells you the original position of the digit and this can be done if you extract the number of digits in num prior to running the loop (i.e. 3 in 127 case). This way you'll extract the correct even and odd digits.
I left for you to fill in DIGITS_IN_NUM and PRINT_OUTPUT as those should be fairly easy to figure out.
1) Why is DIGITS_IN_NUM easy for a beginner to figure out?
2) Please don't provide direct answers (even incomplete ones) for homework assignments. Provide explanations, or answer specific questions, or point out the bugs in what the student has tried, or make suggestions. But don't do the assignment for them.
If you don't want to figure out DIGITS_IN_NUM in advance, and you only want to go through the sequence of digits once backwards, you still can easily compute the odd and even sums, you simply don't know which was which until you reach the end. That is OK because you don't need to know which was which until it is time to print them.
That idea is uglier for "every third" because you would need to compute at least two more sums as you run through the digits backwards. Then at the end, the one you print might be one of those two or might need to be computed from the total (from the odd/even sums) minus the two of three sums. It is a bit messy just to get the sum of every third digit. But it is a valid approach.
Another approach: Using a recursive function could give a simpler looking solution, but actually takes more space at run time than an array or string solution.
Of course you could also compute DIGITS_IN_NUM in advance.
1) Why is DIGITS_IN _NUM easy for a beginner to figure out?
He already did that iteratively in his own code (likely without noticing it).
The OP said he's a beginner with C, but I thought he could know the math needed to determine that number without a loop on every digit to count them.
Quote:
Originally Posted by johnsfine
2) Please don't provide direct answers (even incomplete ones) for homework assignments. Provide explanations, or answer specific questions, or point out the bugs in what the student has tried, or make suggestions. But don't do the assignment for them.
You're right, I just went into over-zealous mode.
Will try to restrain myself next time.
Your countDigits function is not very good, because it can only be used once per run of the program and because it gives the wrong answer if the original number is zero. But neither of those are your serious problem.
You never initialized any of nEven, nOdd, or nThree which is a serious problem.
Quote:
Code:
for(i = count; i >= 0; i--
Think though how many times the loop will be executed with those instructions. Is that the number of times you want the loop executed? I know you copied that code from 414n, but you should understand what you are copying and not just trust it. (That isn't directly a serious error, because of the value of num during the "error". But I expect your instructor would still grade it as an error. I would.)
Quote:
Originally Posted by Balvinder87
For eg: given an integer 158176
your program should add
- 1,8,7 which are in the position 0,2,4 of the integer AND
- 5,1,6 which are in position 1,3,5 of the integer AND
- 8,6 which are in every 3rd place in the integer.
Think through what value i will have for each "position" of your 6 digit example. Is that what you intended? Hint start by thinking about what value i has on the first time through the loop when the code is working on the last digit. This is best fixed together with fixing the earlier non serious error.
Please, put code inside [code][/code] tags, as it's a lot more readable. Also, are you indenting your code?
What's not working properly?
Adding to what johnsfine said:
the test for digits in a divisible by 3 position needs to be adjusted (my fault) because now we're counting from "count" backwards, so you need to check that (i+1) isn't greater than (count);
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.