![]() |
[c]Storing values into an array
I have a problem, and I'm not sure how to begin.
The problem I have is to write a function that asks a user to enter an integer, then output the number of times a digit appears. So my ouput looks like this: Enter an integer: 1034029 The sign : + The counts of digits: 0 2 1 1 2 1 3 1 4 1 5 0 6 0 7 0 8 0 9 1 Since this problem looks similar to the last problem I had, and posted in another thread, I guess what I was thinking of doing is storing the user inputed integer into an array, after that's done everything else should be just like the problem in the other thread. What would be the best way of storing the values into an array. Should I create a loop to store the values, and once a return value '\0' is entered it stops, or should I use gets? Or is there a better way of doing this? |
One way is to just input it as a c_style string
Code:
char line[1000]; otherwise input it as an integer and use divide and mod to extract the digits. Both are easy to do. |
I came up with something, but there's probably a way to simplify it even more. Here's my code:
Code:
|
Your method is very bad. You are looping through the same string multiple times.
Instead use 1 loop over the string and use an array of counters to count the digits. You should be able to reduce your loop body to 1 line of code (if you assume valid input). |
Sorry I'm late, but here's one way to do it. I hope the comments help:
Code:
/* count.c Code:
Enter an integer: 8675309 - Jenny don't lose my number! |
All times are GMT -8. The time now is 09:07 AM. |
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project