wu :: forums (http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi)
riddles >> cs >> Function
(Message started by: brock123 on Dec 6th, 2004, 8:38am)

Title: Function
Post by brock123 on Dec 6th, 2004, 8:38am
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.

Title: Re: Function
Post by towr on Dec 6th, 2004, 8:56am
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.

Title: Re: Function
Post by brock123 on Dec 7th, 2004, 2:13am
thank you very much.



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