Programs Let Us C
Programs Let Us C
more than 1000. If quantity and price per item are input through the keyboard, write a
program to calculate the total expenses.
Logical Operators
Example 2.4: The marks obtained by a student in 5 different subjects are input through the
keyboard. The student gets a division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
Write a program to calculate the division obtained by the student.
In all other cases the driver is not insured. If the marital status, sex and age of the driver are
the inputs, write a program to determine whether the driver is to be insured or not.
For loop
Factorial
double Factorial(int i)
{
double x = 1;
if (i <= 1)
return 1;
do
{
x *= i--;
} while (i > 0);
return x;
First Method
1 List the multiples of both numbers. For example, you're trying to find the least
common multiple of 9 and 12.
2 Multiply both 9 and 12 by 2, 3, 4, etc. The multiples of 9 are: 18, 27, 36, 45, 54, 63,
72 and 81. The multiples of 12 are: 24, 36, 48, 60, 72, 84, 96 and 108.
3 Examine the list, and decide which is the smallest number that both lists have in
common. In Step 2, 36 is the number that both lists have in common. Therefore, 36 is the
least common multiple.
Second Method
Determine the greatest common factor between the two numbers. Again, use the numbers
9 and 12. The greatest common factor is 3.
Multiply the numbers 9 and 12. The number you get is 108.
Divide the answer you get in Step 2 by the greatest common factor from Step 1. In this
example, divide 108 by 3. The answer is 36, which is the least common multiple.
Read more: How to Find the Least Common Multiple of Two Numbers | eHow.com
http://www.ehow.com/how_2265550_find-least-common-multiple-
two.html#ixzz0yRfzBUq7
For LCM:
Code:
/* a & b are the numbers whose LCM is to be found */
int lcm(int a,int b)
{
int n;
for(n=1;;n++)
{
if(a%n == 0 && b%n == 0)
return n;
}
}
For GCD:
Code:
/* a & b are the numbers whose GCD is to be found.
Given a > b
*/
int gcd(int a,int b)
{
int c;
while(1)
{
c = a%b;
if(c==0)
return b;
a = b;
b = c;
}
}
Use the Euclidean Algorithm GCD(x,y) = GCD(y,r) where x and y are two integers and r
is the remainder when you divide x by y. For example, take the integers 543 and 75 to get
GCD(543,75) = GCD(75,18).
Repeat Step 1 until the remainder is zero. Carrying out the above example, GCD(75,18) =
GCD(18,3) = GCD(3, 0).
Record the value of y when r is zero. This is the GCD. Using basic math, we find that the
greatest common divisor of 543 and 75 is 3.