wu :: forums
« wu :: forums - Function »

Welcome, Guest. Please Login or Register.
Nov 28th, 2024, 3:55pm

RIDDLES SITE WRITE MATH! Home Home Help Help Search Search Members Members Login Login Register Register
   wu :: forums
   riddles
   cs
(Moderators: william wu, SMQ, ThudnBlunder, towr, Eigenray, Grimbal, Icarus)
   Function
« Previous topic | Next topic »
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print
   Author  Topic: Function  (Read 573 times)
brock123
Newbie
*





   


Posts: 13
Function  
« on: Dec 6th, 2004, 8:38am »
Quote Quote Modify Modify

Please you can help me in this exercise:
 
Q) Write a program which reads an integer n and calls the function add_positions (int i, int j, long n) which returns the sum of digits between positions i and j of the integer n. Please note that the positions are counted starting from the least significant digit which is at position 0.(Use the while loop statement)
 
 
Example how does the program work?
 
if the user enter this number  
123456
and
the also enter this position 2 , 5
then the program must print the sum between this two positions i.e(4+3+2+1=10)
 
 
 
This is my soultion for this exercise but it does not work clearly.
 
#include<iostream.h>
int add_positions (int i,int j,long n)
{
 int digit,sum=0;
 while (n!=0)
 {
  digit=n%10;
  sum=sum+digit;
  n=n/10;
 }
 return sum;
}
int main()
{
 long n;
 int i,j,x;
 cout<<"Enter an integer number:";
 cin>>n;
 cout<<"Enter the two positions :";
 cin>>i>>j;
 x=add_positions(i,j,n);
 cout<<"The sum between the two positions is: "<<x<<endl;
 return 0;
}
 
 
and my problem is where is it the correct place to put the two positions inside the function.
 
 
 
and please if you have any exercise like that or different about functions try to post it here.
 
 
thanks for each one try to help me.
IP Logged
towr
wu::riddles Moderator
Uberpuzzler
*****



Some people are average, some are just mean.

   


Gender: male
Posts: 13730
Re: Function  
« Reply #1 on: Dec 6th, 2004, 8:56am »
Quote Quote Modify Modify

You should discard the first i-1 digits (i.e. not add anything to the total and divide n by 10 i-1 times). And the when you start adding digits, stop once you go beyond position j.
So you'll probably need a counter to keep track of which digit you are dealing with inside the while loop.
IP Logged

Wikipedia, Google, Mathworld, Integer sequence DB
brock123
Newbie
*





   


Posts: 13
Re: Function  
« Reply #2 on: Dec 7th, 2004, 2:13am »
Quote Quote Modify Modify

thank you very much.
IP Logged
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print

« Previous topic | Next topic »

Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board