PDA

View Full Version : C Programs...



ashutosh_cool16
10-09-2003, 12:42 PM
Can ne1 explain how these programs can be written?


1) If a five digit number is input through the keyboard, write a program to calculate the sum of its digits.

(Hint : Use the modulus operator '%')
The division operator / , returns the quotient on dividing one number by another, whereas the modulus operator % gives the remainder on dividing one number by another.
For eg.
a = 12 % 3 would store 0 in a.
a = 13 % 5 would store 3 in a.



2) If a five digit no. is input through the keyboard, write a program to reverse the number.

3) If a four digit number is input through the keyboard, write a program to obtain the sum of the first and last digit of this number.




And yes, one more question....

If suppose i have to find the aggregate of marks of 5 subjects entered by a user.... and i use an array for storing the marks... eg. marks[ 4 ]
this means that the marks of the 5 subjects are stored in order in the array... How do i find the aggregate now? How to add the individual array elements?

I know there is another method for doin this.. but i am interested using arrays.


Help will be appreciated...

Cheers
Ashutosh

ilw
10-09-2003, 12:48 PM
modulus 10 will return the 1st digit eg 522 % 10 = 2
modulus 100 the second , 522 % 100 = 22
22 - (522 % 10) = 20 (if you just want the digit divide by 10)
modulus 1000 the third,
etc
store the digits in an array or 5 separate variables and play with them as you llike

To sum them you do a loop
for (count =0; count <5 ; count++)
{
sum = sum + array[count];
}

lynx
10-09-2003, 01:05 PM
1)
int answer,i,n,input;
:
:
for (n=10000,a=i=0;i<5;i++)
{
answer += (input/n) % 10;
n /= 10
}


2)
int answer,i,m,n,input;
:
:
for (m=1,n=10000,a=i=0;i<5;i++)
{
answer += ((input/n) % 10) * m;
n /= 10
m *= 10;
}


3)
int answer,input;
:
:
answer = input / 1000 + input % 10;


finally)
int answer,i,marks[5];
:
:
for (answer=i=0;i<5;i++)
{
answer += marks[i];
}

in each case, you can adjust the number of digits/marks by changing the upper limit on i.