C/C programing and data structures
Expert: Zlatko - 12/1/2011
Questionwrite a c program to add all numbers between 100 and 200 that contain the digit 5.
AnswerHello Hira
Here is a hint about how to do it.
Create a 'for' loop which counts from 100 to 200
Within the for loop, call a function. Let's name the function has_digit_5.
The has_digit_5 function takes each number from the for loop and returns 1 if the number has a 5, or returns 0 if the number does not have a 5.
Within the has_digit_5 function, you need to examine the number. There are 2 ways I can think of.
Method 1
---------------
Use sprintf to print the number into a buffer, then check the buffer for the character '5'. You can read about sprintf here:
http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
Method 2 :
---------------
Use the modulo operator (%) to get the last digit of the number and check it against 5.
last_digit = number % 10;
Check if last_digit is 5
Then use the division operator to divide the number by 10
number = number / 10
Keep doing the modulo and division until number is reduced to 0.
You may want to ask your instructor which method is wanted.
That should be enough to get you started. Show me some effort and I'll help you more.
Best regards
Zlatko