ProblemSolvingThroughCProgramming-Chapter3
ProblemSolvingThroughCProgramming-Chapter3
net/publication/277143759
CITATIONS READS
0 37,809
1 author:
Rama M A
Maharani Lakshmi Ammanni College for Women
18 PUBLICATIONS 152 CITATIONS
SEE PROFILE
All content following this page was uploaded by Rama M A on 26 May 2015.
#include<stdio.h>
where the variable_name can be of char type or integer type. For example,
char ch;
ch=getchar( );
In the above statement, the execution of the program is halted until a key is pressed.
This key is stored in ch. The key pressed could be anything including return and tab
keys.
Sometimes, when the user requires to store the ASCII code of the key pressed, the
variable can be declared as int type.
Example 3.1
/* Program to show usage of getchar() */
#include <stdio.h>
void main()
{
char ch;
/* to clear the screen */
clrscr();
printf("\n\n Enter a Single character Please : ");
ch = getchar();
printf("\n You pressed %c ",ch);
printf("\n and its ASCII code is %d ",ch);
}
Output
Enter a Single character Please : b
You pressed b
and its ASCII code is 98
The getchar( ) function can also be used to read strings containing more than one
character, by reading one character at a time within a loop. getch( ) is similar to
getchar( ). However it does not wait for the user to press the enter key. It is unbuffered
version of getchar( ).
MANAGING INPUT AND OUTPUT OPERATIONS 99
putchar (variable_name) ;
Example 3.2
/* Program to show usage of putchar() */
#include <stdio.h>
void main()
{
char key;
/* to clear the screen */
clrscr();
printf("\n\n Type a Single character Please : ");
key = getchar();
printf("\n You pressed : ");
putchar(key);
putchar('\n');
}
Output
Type a Single character Please : M
You pressed : M
Functions Purpose
Any program which uses any one of the above functions must include the statement.
# include<ctype.h> in the program
Example 3.3
/* Program to convert upper case to lower case letters */
#include <stdio.h>
#include <ctype.h>
void main()
{
char ch;
/* Clears the screen*/
clrscr();
printf("\n Type an alphabet in upper case : ");
ch = getchar();
(isalpha(ch)>0) ? putchar(tolower(ch)):
printf("\n You did not type an alphabet");
/* Waits for a key press- used to see the output*/
getch();
}
MANAGING INPUT AND OUTPUT OPERATIONS 101
Output
Type an alphabet in upper case : S
s
Type an alphabet in upper case : u
u
Type an alphabet in upper case : 5
You did not type an alphabet
gets (string);
Example 3.4
Output
Enter your Address :18TH CROSS, MALLESWARAM
Your Address is : 18TH CROSS, MALLESWARAM ! Right
puts(expression);
where expression can be a string constant or a string variable. The string may
include blank space characters.
102 PROBLEM SOLVING TECHNIQUES USING C
Example 3.5
/* Program to show usage of puts() function */
#include <stdio.h>
void main()
{
char text[40];
clrscr(); // clears the screen
printf("\n Enter a line of text :");
gets(text);
puts("\n You typed the text :");
puts(text);
getch();
}
Output
Enter a line of text : MAHARANI LAKSHMI AMMANNI COLLEGE
You typed the text :
MAHARANI LAKSHMI AMMANNI COLLEGE
Every call to puts ( ) function is executed on a new line i.e., puts( ) function
automatically executes a line feed before printing the string.
%wd
where w is the field width and d is the data specifier. For example,
scanf("%3d",&a);
informs the compiler that the input would be an integer value which is a 3 digit number.
MANAGING INPUT AND OUTPUT OPERATIONS 103
The field width is optional. Further d is the format character for an integer. Fig. 3.2 lists
the data types and their corresponding format specifiers.
Every variable in the variable list must match the format specifiers in the
control string.
Every variable must be preceded by an ampersand symbol (&).
scanf( ) ignores all leading spaces, blanks, tabs, newlines or form feed characters
in input.
Comma, space or colon can be used as delimiters in the input stream. For
example, using the statement :
scanf("%d,%d,%f",&a,&b,&x);
the data 100, 200, 250.48 can be read into a, b and x respectively. In this case comma is
used as delimiter. Similarly, using the statement :
scanf("%d,%d",&x,&y);
the data 50 100 can be read into x and y using space as delimiter.
Reading of data input is terminated when the specifier and the data mismatch.
Unread data in an input stream is taken to be part of next scanf( ) statement.
This leads to errors.
The field width of real numbers is generally not specified in the scanf()
statement.
However the field width can be specified for integers. Care must be taken to see
that the field width can store the input data.
104 PROBLEM SOLVING TECHNIQUES USING C
Example 3.6
/* Program to show formatted input using scanf() function */
#include <stdio.h>
void main()
{
int a,b,c;
float x,y;
double p,q;
clrscr();
/* Conversion Specifiers for Integers */
printf("\n Enter 2 numbers :");
scanf("%d %d",&a,&b);
printf("\n a = %d b = %d\n",a,b);
printf("\n Enter a 9 digit number :");
scanf("%3d %3d %3d",&a,&b,&c);
printf("\n After splitting a 9 digit number: a = %d b= %d c = %d\n",a,b,c);
printf("\n Enter 3 integer numbers :");
scanf("%d %*d %d",&a,&b,&c);
printf("\n Skipping the 2nd number : a = %d b = %d c = %d\n",a,b,c);
/* Conversion Specifiers for Real numbers */
printf("\n\n Enter 2 real numbers x and y:");
scanf("%f %f",&x,&y);
printf("\n x = %f y= %f\n",x,y);
/* Conversion Specifiers for Double Precision numbers */
printf("\n\n Enter 2 double precision numbers p and q:");
scanf("%lf %lf",&p,&q);
printf("\n p = %lf q= %e\n",p,q);
}
Output
Enter 2 numbers :15 558
a = 15 b = 558
Enter a 9 digit number :123456789
After splitting a 9 digit number: a = 123 b= 456 c = 789
Enter 3 integer numbers :33 44 55
Skipping the 2nd number : a = 33 b = 55 c = 789
Enter 2 real numbers x and y:1234.555 8970.12345
x = 1234.555054 y= 8970.123047
Enter 2 double precision numbers p and q:1111122222.444 6666.8888888889
p = 1111122222.444000 q= 6.666889e+03
MANAGING INPUT AND OUTPUT OPERATIONS 105
%ws
is used to read the input data into the string variable addr. In this example, address
operator & is not attached to the variable addr since strings are directly accessed through
pointers (to be discussed in the chapter 8)
Example 3.7
/* Program to Input and Output a string*/
#include <stdio.h>
void main()
{
char name[20];
clrscr(); // Clears the screen
printf("\n Enter your name :");
scanf("%s",name);
printf("\n Your name is %s ! Right ",name);
getch();
}
Output
Enter your name : Rama
Your name is Rama ! Right
One main drawback of scanf( ) statement is that it cannot be used to read a line of
text containing blank spaces. In the example 3.7 suppose the input data is:
Arun Narayan
then the output would be
Arun
since blank spaces (also known as white space characters) are considered as
delimeters.
single characters and strings. The printf( ) function moves data from the computer's
memory to the standard output device.
When printf( ) is used to output values of variables or expressions, the formats are
supplied in its first argument called the control string. The variables to be printed are
listed after the control string. Commas are required to separate the control string and the
list of variables. The format is :
Integer Integer %d
Short %d
Short unsigned %u
Long %ld
Long assigned %lu
Hexadecimal %x
Long hexadecimal %lx
Octal %O (letter 0)
long octal %lo
Real float %f,%g
Double(with exponent) %If, %e, %E
Character %c
String %s
Example 3.8
/*Program to print floating-point output in 2 ways*/
void main( )
{
double x = 5000.0,y=0.0025;
printf("\n %f %f %f %f \n\n",x,y,x*y,x/y);
printf("\n %e %e %E %E",x,y,x*y,x/y);
}
Output
5000.000000 0.002500 12.50000 2000000.000000
5.000000e + 3 2.500000e - 03 1.250000E + 01 2.000000 E + 06
In example 3.8, the first line of output shows the values in standard floating point
format, without exponents. The second line shows the values in scientific notation, with
exponents. Notice that 6 decimal places are shown for each value. This can be altered by
specifying the field width, which is of the form
% - w.d type-specifier
where
(minus sign) is for left justification
w field width
d specifies the number of digits to the right of the decimal point.
. dot denotes the decimal point for real numbers
printf( ) function never starts automatically in a new line. Thus printf( ) requires a new
line character i.e., \n as part of the control string to start printing in a new line.
Format Output
1 2 3 4
printf("%d",x); 2 5 4 5
1 2 3 4 5 6 7
printf("%07d:",x); 0 0 0 2 5 4 5
1 2 3 4
printf("%3d",x); 2 5 4 5
1 2 3 4 5
printf("%-5d",x); 2 5 4 5
1 2 3 4 5 6
printf("%06d",-x); 0 2 5 4 5
Format Output
printf("%f",y); 2 5 . 4 5 4 5 0 0
printf ("%7.4f",y); 2 5 . 4 5 4 5
printf("%7.3f",y); 2 5 . 4 5 5
printf("%-7.3f",y); 2 5 . 4 5 5
printf("%10.3e",y); 2 . 5 4 5 e 0 1
printf("%10.3e",-y); 2 . 5 4 5 e 0 1
printf("%e",y); 2 . 5 4 5 4 5 0 e 0 1
%c or %wc
similarly
printf("% - 5c",ch);
gives the output
A
%s or %ws
Format Output
printf("%s",name); M A H A R A N I L A K S H M I
printf("%10s",name); M A H A R A N I L A K S H M I
printf("%20s",name); M A H A R A N I L A K S H M I
printf("%-20s",name); M A H A R A N I L A K S H M I
(iii) Readability of the output can be enhanced by printing appropriate headings and
messages.
(iv) Escape sequence \t (tab space) can be used to insert space between outputs.
The following example shows the formatted output of string.
Example 3.9
/* Program to show formatted printing of characters and strings */
#include <stdio.h>
void main()
{
char ch = 'a';
static char name[20] = "Maharani Lakshmi";
clrscr(); //clears the screen
/* Single character outputs */
MANAGING INPUT AND OUTPUT OPERATIONS 111
/* String Output */
printf("\n String Outputs \n");
printf("\n 12345678901234567890 <- Column Numbers");
printf("\n %s ",name); //Requires 16 columns
printf("\n %20s ",name); //Adds 4 leading spaces (16+4)
printf("\n %8.4s ",name); //prints 4 characters & adds 4 leading spaces
printf("\n %-8.4s ",name); //Right-justified & prints 4 characters
getch();
}
Output
Single Character Output
12345678901234567890 <- Column Numbers
a a
a
String Outputs
12345678901234567890 <- Column Numbers
Maharani Lakshmi
Maharani Lakshmi
Maha
Maha
Name: Suhasini
Class: MCA
Marks: 98
minimum field width specification, which is 15 characters. The last string contains only 5
characters and leading blanks are not added since width is 0.
Consider two integer variable x and y with values 27 and 117. Then in the statement
printf("%d %d\n",x,y);
the first %d called the format conversion specifier instructs that x will be printed as
a decimal integer (d stands for decimal) in a field as wide as may be necessary. Since x is
two-digit number, it will be printed in 2 columns. The second %d refers to y, which being a
3-digit number will be printed in a field 3 digit wide. The \n takes the cursor to the
beginning of next line. Since we have given a single space between the %d's in the control
string, there will be a single space separating the values of x and y as follows:
27 117
Suppose we introduce the format specification t for a tab between the %d's then
printf ("%d\t%d\n",x,y); will output the values separated by a tab (skips 7 columns)as
27 117
The output of printf("\tThe value of x = %d,\n\twhile y=%d.",x,y); will be
The value of x = 27,
while y = 117.
It is very important that there should be one-to-one correspondence between each
format conversion specifier and the list of variables or expressions. Since the % character
has a syntactic value in the control string, 2 consecutive occurrences %% are required in
the string, to print it as a literal in the output.
Example 3.10
Generally the compiler is installed on the computer in the C:\TC directory. Create a
folder in D: as IBSc and another folder TCTEMP. Save your programs in D:\IBSc.
TCTEMP will store all the .obj, .exe and .bak files of your C programs. Turbo C++ IDE
consists of menu driven environment giving all possible options for saving, opening,
compiling and running the C/C++ programs.
To start the IDE, a shortcut can be created on the desktop as follows :
(i) Open My Computer on the Desktop
(ii) Double click on C
(iii) Double click on TC folder
(iv) Double click on Bin folder
(v) Right click on TC (application) Fig. 3.7 MS-DOS
TC.EXE
(vi) Select and click on send to Desktop (create shortcut) (Figure 3.7)
Now a shortcut of Turbo C++ IDE is created on the desktop as shown.
Double click on the icon of TC++ IDE to get the opening screen as shown in Figure
3.8. Set the output folder to TCTEMP as follows:
i) Click Options.
ii) Select and click on Directories
iii) Type D:\TCTEMP under Output Directory.
Command Meaning
(iii) Once the program becomes error free, linking is done as shown in figure 3.13.
The program can also be executed on the DOS prompt by typing the file name. For
example, for the C program sum.C an executable file called sum.exe will be created in the
folder Tctemp. To execute the code :
(i) Select Alt + F and select DOS shell.
(ii) Type sum on the prompt.
The results will be displayed as shown in figure 3.16.
1. The dataname must be as close as possible to the general terminology used. For
example to calculate the area of a circle using the formula area = r2, the data
names can be area, pi and radius.
2. The datanames must not be too short or abbreviated so much that they lose their
identity. For example, simple interest should not be named as si. For such
datanames underscore can be used as in simple_interest.
3. In long datanames, the first letter of each word can be capitalized such as ProductId.
Since C is case sensitive, the programmer must be careful while typing these
datanames.
4. Do not create datanames that are too similar especially when there is a difference of
only one or two letters. For example total, totals. However, there can be a naming
pattern which makes it easy to remember those variable names.
5. Whenever abbreviations are used for datanames, they must clearly indicate the
word being abbreviated. Abbreviations must be used only for long words, not short
ones.
6. Try to avoid using generic datanames such as sum, total, emp etc.
7. Do not use literal values, if they change from system to system. Instead define
memory constants or defined constants in such cases. For example :
# define SPACE ‘‘
# define COMMA ‘,’
Since global variables can be used and changed by every part of the program which
is undesirable and against data hiding and data encapsulation.
3. A compiler error will occur if you do not close the format string in scanf or printf
statements.
4. Reading an integer with a float conversion code leads to error.
5. No comma after the format string in a read or write statement is a compile
error.
6. When a block comment is not closed with a */, it leads to error.
7. Not including libraries such as stdio.h or math.h for some mathematical
computations, leads to errors.
8. Misspelt functions such as printf or scanf will compile without errors, but will
get linker error.
9. Missing address operator (&) in a scanf statement is a run-time error.
10. Do not use commas or other characters in the format string of scanf statement.
This will lead to run-time errors, if the user does not type commas while
inputting data. For example in the statement :
scanf (“ %f ”, &x) ;
REVIEW QUESTIONS
xy xy
(a) (b) (c) (x + y) (x – y)
xy 2
8. Write a program to read the numbers
25.45, 55.20 43.77 and –25.45
The result must be rounded off to the nearest integer.
9. Write a program to read temperature in fahrenheit and convert it to celsius using
the formula
c = 5/9*(F 32)
10. Write a program to input an amount in paise and convert it to rupees and paise.
11. Write a program to input value in feet. Convert feet to yards, inches, cms, meters,
using yards = feet/3, Inches = 12*feet, cms = 2.54*inches and m = cms/100.
12. Write a program to find the radius of a circle. Input circumference.
13. Write a program to calculate the hypotenuse of a right angled triangle, whose base
and height and given.
14. Program to find the real roots of a quadratic equation ax 2 + bx + c = 0 using the
b b2 4ac
formulae x1 , x 2 . Input a, b, c.
2a
15. Write a program to calculate compound interest at the rate of R%, for a deposit of
Rs. P for N years, given
Amount = P(1 + R/100)N
16. Given the length of a side, write a C program to compute surface area and volume of
a cube.
124 PROBLEM SOLVING TECHNIQUES USING C
Decision Making
3.8 INTRODUCTION
The set of statements in a C program are normally executed sequentially in the
order in which they are written. Such programs have sequential structure. However, in
reality, the order of execution of statements may have to be changed, depending on certain
conditions. Such programs where decision making is involved are said to have selection
structure.
C provides us with statements which help to alter the flow of control, so that control
can be transferred from one part of the program to another. The control or decision
structures available are :
i) if() statement
ii) switch statement
iii) Ternary operator
iv) goto statement
goto statement is used for unconditional transfer of control.
If(conditional expression)
s1;
s2;
If the codnition is false or has a zero value, then statement s1 will be ignored and s2
will be executed.
The statement s1 can either be simple or compound. A simple statement contains
a single statement. A compound statement contains more than one statement.
When the condition is true, if a set of
statements have to be executed, they must be
enclosed in braces i.e.,
If (condition)
{
s1;
s2;
s3;
:
:
}
sn;
Example 3.11
Output
Enter value of x : 5
Sum=15
126 PROBLEM SOLVING TECHNIQUES USING C
c) int rain = 1;
if(rain==1)
{
printf("\n Wear a Raincoat");
printf("\n or hold an umbrella");
}
f) if(a = = b || a = = c || b == c)
printf("\n It is an isoceles triangle");
In example 3.12 == tests the equality of the value of the expressions on either side.
Instead if a = b (single =) is written, then the value of 'a' becomes equal to b and therefore
there is no comparison involved.
Example 3.12
/* Program to show what happens when = is given
instead of == in if statement */
#include<stdio.h>
void main()
{
int x=0;
clrscr();
if(x=0) //condition becomes false since x=0
printf(" x is 0, x==0 is true, but this statement will not be output \n");
if(x!=0)
printf(" x is 0, x!=0 is false, so this statement will not be output \n");
if(x=50)//condition becomes true since value of x is non zero
printf(" can you believe it, x is actually %d !\n", x);
}
Output
can you believe it, x is actually 50 !
DECISION MAKING AND LOOPING 127
In the above example, the first if() assigns a value 0 to x, so that the condition
becomes false. Hence the printf() statement is not executed.
In the second if() x! = 0 is false and therefore the printf() statement is not output. In
the third if() statement the value of x becomes 50 which is non-zero and hence the
condition becomes true. Thus the last printf() is executed.
If (condition)
s1;
else
s2;
s3;
Example 3.13
/*Program to determine if a given number is even or odd*/
#include<stdio.h>
void main()
{
int num,remain;
clrscr();
printf("\n Enter the number to be tested :");
scanf("%d",&num);
remain=num%2;
if(remain==0)
printf("\n % d is Even",num);
else
printf("\n %d is odd",num);
getch();
}
Output
Enter the number to be tested : 1279
1279 is odd
Enter the number to be tested : 38
38 is Even
Enter the number to be tested : 0
0 is Even (why?)
Example 3.14
//*Program to check whether a given year is a leap year*/
#include<stdio.h>
void main()
{
int yr,rem_4,rem_100,rem_400;
clrscr();
printf("\n Enter the 4 digit year to be checked :");
scanf("%d",&yr);
/* To find the remainders of division by 4, 100 & 400 */
rem_4 = yr%4;
rem_100 = yr%100;
rem_400 = yr%400;
if((rem_4==0 && rem_100!=0)||rem_400==0)
printf("\n %d is a leap year.",yr);
DECISION MAKING AND LOOPING 129
else
printf("\n %d is not a leap year ok !",yr);
getch();
Output
Enter the 4 digit year to be checked :2012
2012 is a leap year.
Enter the 4 digit year to be checked :2013
2013 is not a leap year ok !
Enter the 4 digit year to be checked :3000
3000 is not a leap year ok !
Example 3.15
/* Program to calculate absolute value of an integer*/
#include<stdio.h>
void main()
{
int num;
clrscr();
printf("\n Type a number :");
scanf("%d",&num);
if(num<0)
{
num=-num; //converts negative to positive number
printf("\n The absolute value is %d", num);
}
else
printf("\n The absolute value is %d",num);
getch();
}
Output
Type a number :-500
The absolute value is 500
Type a number :360
The absolute value is 360
Type a number :0
The absolute value is 0 (how?)
130 PROBLEM SOLVING TECHNIQUES USING C
Example 3.16
/*Program to show usage of char in if() statement*/
#include<stdio.h>
void main()
{
char wish;
clrscr();
printf("\n Want to go to movie Y/N ?");
wish=getchar();
if(wish=='Y'||wish=='y')
printf("\n Go and get ready quickly !");
else
printf("\n Go and start studying!");
}
Output
Want to go to movie Y/N ? Y
Go and get ready quickly !
Want to go to movie Y/N ? n
Go and start studying!
Want to go to movie Y/N ? y
Go and get ready quickly !
Want to go to movie Y/N ? A
Go and start studying!
Example 3.17
/* Program to show usage of nested if()*/
#include<stdio.h>
void main()
{
float hrs;
clrscr();
printf("\n Type the time in hours :");
scanf("%f",&hrs);
if(hrs >= 0.0 && hrs < 12.0)
printf("\n Good Morning");
else
if(hrs >= 12.0 && hrs < 17.0)
printf("\n Good Afternoon");
else
if(hrs >= 17.0 && hrs < 21.0)
printf("\n Good Evening");
else
if(hrs >= 21.0 && hrs < 24.0)
printf("\n Good Night");
132 PROBLEM SOLVING TECHNIQUES USING C
else
printf("\n Wrong Input");
getch();
}
Output
Type the time in hours :20.6
Good Evening
Type the time in hours : 5.0
Good Morning
Type the time in hours : 22
Good Night
Type the time in hours : 15
Good Afternoon
Type the time in hours : 50
Wrong Input
Example 3.18
/* Program to read a character and determine whether
it is an alphabet,digit or a special character*/
#include<stdio.h>
void main()
{
char ch;
clrscr();
printf("\n Enter a single character please:");
scanf("%c",&ch);
if((ch>='a' && ch<='z')||(ch>='A' && ch<='z'))
printf("\n It is an Alpahbet");
else
if(ch>='0' && ch<='9')
printf("\n It is a digit");
else
printf("\n It is a Special character");
getch();
}
Output
Enter a single character please: u
It is an Alphabet
Enter a single character please: !
It is a Special character
Enter a single character please: 7
It is a digit
DECISION MAKING AND LOOPING 133
The else-if() can be understood better with the help of a flowchart shown in
figure 3.22.
Example 3.19
An Instructor conducts 3 tests Test1, Test2 and final, each out of 50 marks. The
best marks out of Test1 and Test2 is selected and added to final test marks. This
gives the total marks scored out of 100. Next, grades are assigned as follows :
Marks Grade
0 – 39 F
40 – 49 D
50 – 59 C
60 – 74 B
75 – 100 A
Write a C program to input marks scored in the three tests and output the grade
of the student.
/* Program to print the grade of a student */
#include<stdio.h>
void main()
{
int test1,test2,final,marks;
char grade;
clrscr();
printf("\n Enter marks in Test1,Test2,final :");
scanf("%d %d %d",&test1,&test2,&final);
/* calculate total marks out of 100 */
if(test1 > test2)
marks = final + test1;
else
marks = final + test2;
/* assigning grades */
if(marks >= 0 && marks < 40)
grade = 'F';
else if(marks < 50)
grade = 'D';
else if(marks < 60)
grade = 'C';
else if(marks < 75)
DECISION MAKING AND LOOPING 135
grade = 'B';
else if(marks <= 100)
grade = 'A';
else
grade = 'X';
if(grade != 'X')
printf("\n Grade is %c",grade);
else
printf("\n Error in input!!");
}
Output
Enter marks in Test1,Test2,final :50 50 25
Grade is A
Enter marks in Test1,Test2,final :20 10 30
Grade is C
Enter marks in Test1,Test2,final :20 10 15
Grade is F
Enter marks in Test1,Test2,final :40 39 80
Error in input!!
Example 3.20
A company has 4 categories of employees. The rent allowance is based on the
following rules :
Category1 30% of salary
Category2 20% of salary
Category3 15% of salary
Category4 10% of salary
Write a C program to read employee category and salary and print the rent
allowance.
/* Program to calculate rent allowance based on employee category */
#include<stdio.h>
void main()
{
int cat;
float sal,rent;
clrscr();
printf("\n Enter the category and salary of Employee :");
scanf("%d %f",&cat,&sal);
if(cat == 1)
rent = sal * 0.3;
136 PROBLEM SOLVING TECHNIQUES USING C
else if(cat == 2)
rent = sal * 0.2;
else if(cat == 3)
rent = sal * 0.15;
else if(cat == 4)
rent = sal * 0.1;
else
{
printf("\n Wrong Input ");
exit();
}
printf("\n The rent allowance = %7.2f",rent);
getch();
}
Output
Enter the category and salary of Employee : 1 35000
The rent allowance = 10500.00
Enter the category and salary of Employee : 4 10000
The rent allowance = 1000.00
Enter the category and salary of Employee :23 3000
Wrong Input
switch is the keyword, which checks the value of the variable or expression given
within parentheses with a list of case values val1, val2, ....... valn, known an
case labels.
Each case value must be unique within a switch statement. The values can be in
any order.
Statements s1, s2, etc can be a single statement or a block or statements. Case
value can also be given without any statements.
Each case label is followed by a : (colon) and the cases are listed in a set of curly
braces.
When the switch statement is executed depending on the value of the variable or
expression, the corresponding set of statements is executed. If the switch value
does not match with any of the case labels listed, the statements corresponding
to default are executed.
The default case is optional. When default is not given control passes to
statement-x if no match is found.
The break statement, the last statement of every case including the default, is
necessary. The break statement is used to transfer control to the first-statement
outside the switch block i.e., statement-x. If absent, control flows to the next case.
This property may be used to advantage when multiple values of the variable say
val1, val2 and val3 must execute the same set of statements. For example :
case 1 :
case 2 :
Example 3.21
/* Program to calculate rent allowance based on employee category */
#include<stdio.h>
void main()
{
int cat;
float sal,rent;
clrscr();
printf("\n Enter the category and salary of Employee :");
scanf("%d %f",&cat,&sal);
switch(cat)
{
case 1 :
rent = sal * 0.3;
break;
case 2 :
rent = sal * 0.2;
break;
case 3 :
rent = sal * 0.15;
break;
case 4 :
rent = sal * 0.1;
break;
default :
printf("\n Wrong Input ");
break;
}
printf("\n The rent allowance = %7.2f",rent);
getch();
}
Output
Enter the category and salary of Employee :2 36000
The rent allowance = 7200.00
140 PROBLEM SOLVING TECHNIQUES USING C
Example 3.22
/* Program to compute decimal value of a hexadecimal digit */
#include<stdio.h>
#include<ctype.h>
void main()
{
char hexa;
clrscr();
printf("\n Enter a hexadecimal digit :");
hexa = getchar();
/* converting all lower case to upper case
using toupper() function */
hexa = toupper(hexa);
switch(hexa)
{
case 'A' :
case 'B' :
case 'C' :
case 'D' :
case 'E' :
case 'F' : printf("\n Decimal value of hexadecimal digit is %d",hexa-65+10);
break;
/* Characters A-F use the same conversion formula.
Hence only one statement for cases A to F */
case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' : printf("\n Decimal value of hexadecimal digit is %d",hexa-48);
break;
/* ASCII code of zero is 48 */
default : printf("\n you typed a non-hexadecimal digit ");
break;
}
getch();
}
Output
Enter a hexadecimal digit :F
Decimal value of hexadecimal digit is 15
Enter a hexadecimal digit :8
Decimal value of hexadecimal digit is 8
Enter a hexadecimal digit :*
you typed a non-hexadecimal digit
DECISION MAKING AND LOOPING 141
Example 3.23
A cloth showroom offers discount on purchase of items as follows :
Purchase amount Discount
0 – 100 5%
101 – 200 7.5%
201 – 300 10%
Above 300 15%
Write a program to calculcate the net amount to be paid after discount.
142 PROBLEM SOLVING TECHNIQUES USING C
When the label is placed after the goto statement, it is known as forward jump.
However when the label is placed before the goto statement, it is known as
backward jump as shown in figure 3.26.
Each label in a program must be unique. No two statements can have the same
label.
goto is also used in combination with if() statement as a looping structure.
Sometimes goto statements result in endless loops known an infinite loops, due
to the uncodnitional transfer of control.
goto can be used to transfer control out of a loop or nested loops, depending on
some condition.
In structured programming goto statements must be avoided.
Example 3.24
/* Program to reverse a number using if() and goto */
#include<stdio.h>
void main()
{
int n,rem,rev = 0;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
start :
if(n == 0)
/* terminates the loop when n=0 */
goto finish;
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
goto start;
finish :
printf("\n The reversed number is : %d",rev);
getch();
}
Output
Enter a number : 1234
The reversed number is : 4321
Enter a number : 5678
The reversed number is : 8765
144 PROBLEM SOLVING TECHNIQUES USING C
LOOPING
3.16 INTRODUCTION
Loops are required whenever a set of statements must be executed a number of
times. We know that a computer is capable of executing a set of statements repetitively
with precision. This looping capability allows programmers to develop programs
containing repetitive or iterative processes, which would otherwise require thousands of
statements to be executed.
A looping structure is one, where a sequence of statements are executed repeatedly
until some condition for termination of the loop is satisfied.
Thus a loop consists of two parts; the body of the loop and the control statement. The
control statement checks the given condition and then executes the set of statements in
the body of the loop.
Control structures can be classified into two categories depending on the position of
the control statement. They are :
a) Entry-controlled loops
b) Exit-controlled loops
Entry
Check False
Condition ?
Body of
loop
Exit
Fig. 3.27 : Entry-controlled Loop
The loops in which the control conditions are tested before looping are known as
Entry-controlled Loops. In such loops the body (or domain) of the loop will be executed
only when the condition is true. Otherwise the domain of the loop is not executed and
control is transferred to the next statement outside the domain of the looping structure.
Figure 3.27 depcits the working of an entry-controlled loop.
Thus the body of the loop will be executed repeatedly untill the control condition
becomes false.
DECISION MAKING AND LOOPING 145
The loops in which the control condition are tested at the end of the body of the loop
are known as Exit-controlled Loops.
In this case the body of the loop will be executed at least once since the condition is
tested at the end of the loop. Thus the looping statements will be executed repeatedly until
the control condition becomes false. Figure 3.28 iillustres the working of an exit-controlled
loop.
The test condition stated in the looping structure is very important. It must be such
that the control is eventually transferred outside the loop, once the desired number of
executions are performed.
Entry
Body of
loop
Check False
Condition ?
True
Next statement
In a case where the test condition never becomes false, an infinite loop is set up and
the statements within the domain are executed repeatedly. Therefore care must be taken,
to avoid infinite loops.
In general, a looping structure consists of the following steps :
a) Initializing a counter.
b) Executing the statements in the domain of the loop.
c) Testing the condition in the control statement. The testing could be either to
match the given condition or to determine whether the loop has been executed
the specified number of times.
d) Incrementing the counter.
The three types of looping constructs available are :
1) The while() loop
2) The do-while () loop
3) The for(; ;) loop
146 PROBLEM SOLVING TECHNIQUES USING C
while (expression)
{
Statements;
...
Domain of
...
... Loop
}
next_statement;
Example 3.25
i++;
}
printf("\n Sum = %d",sum);
}
Output
Enter the value of n : 5
Sum = 15
Enter the value of n : 0
Sum = 0
Example 3.26
/* Program to calculate the LCM and GCD of two positive integers */
#include <stdio.h>
void main()
{
int m,n,temp,lcm,gcd;
clrscr();
printf("\n Enter two integers m & n :");
scanf("%d %d", &m, &n);
temp = m * n;
/* Calculation of gcd */
while(m != n)
{
if(m > n)
m = m - n;
else
n = n - m;
}
gcd = n;
lcm = temp / gcd; // computing lcm
printf("\n LCM = %d GCD = %d", lcm, gcd);
getch();
}
Output
Enter two integers m & n :12 16
LCM = 48 GCD = 4
148 PROBLEM SOLVING TECHNIQUES USING C
Example 3.27
/* Program to reverse an integer number */
#include<stdio.h>
void main()
{
int num,rev,remain;
clrscr();
printf("\n Enter a number :");
scanf("%d",&num);
/* initialize rev to 0 */
rev = 0;
while(num !=0)
{
remain = num % 10;
rev = rev * 10 + remain;
num = num / 10;
}
printf("\n Reversed number is = %d",rev);
Dry Run
}
rev = 0, num = 678
Output
remain rev num
Enter a number : 590
8 8 67
Reversed number is = 95
7 87 6
Enter a number : 678
6 876 0
Reversed number is = 876
Example 3.28
/* Program to generate the first n Fibonacci Numbers */
#include<stdio.h>
void main()
{
int i = 3,fib1 = 0,fib2 = 1,fib,n;
clrscr();
printf("\n How many Terms ? ");
scanf("%d",&n);
printf("\n %d \n %d",fib1,fib2);
while(i < n)
{
fib = fib1 + fib2;
printf("\n %d",fib);
fib1 = fib2;
fib2 = fib;
i++;
}
DECISION MAKING AND LOOPING 149
getch();
}
do
{
Statements;
... Body of
...
Loop
...
}
while (condition);
next_statement;
Example 3.29
/* Program to find the sum of digits of a number */
#include<stdio.h>
void main()
{
int num,sum = 0,rem;
clrscr();
printf("\n Enter a positive number ");
scanf("%d",&num);
do
150 PROBLEM SOLVING TECHNIQUES USING C
{
rem = num % 10;
sum = sum + rem;
num = num / 10;
}
while(num > 0);
False
{
next_statement
Fig. 3.31 : Structure of for loop
In this example, i is set to 1 and the condition i < = 10 is checked. Since the
condition is true 1 is printed.
Next i is increment to 2 and again the condition is checked. Since the condition is
true, 2 is printed. This process continues until i becomes 11. Since the condition here
becomes false, the loop is terminated. The output is :
1
2
3
.
.
10
The output is :
10
9
8
:
1
6) The two semi-colons are compulsory, but the three expressions are not.
Any one or all the them may be absent, for (; ;) is a valid statement. For example :
152 PROBLEM SOLVING TECHNIQUES USING C
for (i = 3; ;)
printf("\n%d",i);
and
i = 3;
for(; ;)
printf("\n%d", i);
are same. Since there is no test condition, they form infinite loops.
8) The advantage in a for (; ;) loop is that all the three actions of initializing, checking
and incrementing of the loop index is done in the for (; ;) statement itself. The
comparison of the three types of loops is as shown in figure 3.32.
Fig. 2.32 : (a) for(; ;) loop (b) while( ) loop (c) do-while( )loop
x = 2;
for (i = 1; i <=10;i++)
{
-
-
x++;
}
Thus the initialization section and the incrementation section have two variables.
10) The test condition in a for (; ;) loop can be a compound condition containing the
control variable and any other external variable. In the program segment below, i is
the control variable and sum is an external variable.
sum = 0,
for (i = 1; i<=10 & & sum <=100; i++)
{
sum = sum + i;
printf("\n%d%d", i, sum);
11) for (; ;) loop can be used as delay loop using the null statement as follows :
This loop causes a time delay since it is repeated 1500 times without executing any
statements. The semi colon at the end of for( ) loop is known as a null statement.
Therefore C compiler will not give an error message, when a semi colon is placed at the
end of a for (; ;) and care must be taken to avoid such mistakes.
Example 3.30
/* Program to check whether a number is prime or not */
#include<stdio.h>
void main()
{
int n,i;
clrscr();
printf("\n Enter a positive number please :");
scanf("%d",&n);
if(n <= 1)
{
printf("\n %d is not prime",n);
getch();
exit();
}
154 PROBLEM SOLVING TECHNIQUES USING C
Output
Enter a positive number please : 11
11 is prime
Enter a positive number please : 10
10 is not prime
Example 3.31
Output
Enter the number of terms :10
Enter the value of x :2
Summation of series = 2047.000
DECISION MAKING AND LOOPING 155
Example 3.32
/* Program to print the sum of the series S = 1 + 1/2 + 1/3 + ....+ 1/n */
#include<stdio.h>
void main()
{
int n,i;
float sum = 0;
clrscr();
printf("\n Enter value of n :");
scanf("%d",&n);
for(i = 1; i <= n; i++)
sum = sum + 1.0 / i;
printf("\n Summation = %7.3f ",sum);
}
Output
Enter value of n :10
Summation = 2.929
printf("\n i j");
for(i=1; i<=5;++i)
{
for(j=0;j<=9; j++)
outer
{ inner
printf("\n%d %d", i,j); loop
loop
}
}
Firstly i is initialized to 1 and the condition i <=5 is tested. Since the condition is
true control passes to the next for() statement.
Next the value of j is initialized to zero and the condition j < = 9 is tested. Since
it is found to be true, the body of the inner loop is executed, giving the output.
1 0
156 PROBLEM SOLVING TECHNIQUES USING C
The inner loop is repeatedly executed as long as the conditions is true. When j =
10 control is transfered back to the outer loop and i incremented. The condition
is again tested and control passes to the inner for() loop.
This process continues until the outer loop is completed. The output of the nested
loop is as shown :
i j
1 0
1 1
1 2
:
1 9
2 0
2 1
:
5 9
Example 3.33
/* Program to generate a given Pattern with numbers */
#include <stdio.h>
void main()
{
int r , c ; /* r is row and c is column */
clrscr();
printf("\n\n\n Number Pattern\n\n\n");
for(r = 1; r <= 4; r++) // Outer loop for rows
{
for(c = 1; c <= r ; c++) // Inner loop for columns
printf(" %d ",c);
printf("\n");
}
getch(); //to see the results
}
Output
Number Pattern
1
1 2
1 2 3
1 2 3 4
DECISION MAKING AND LOOPING 157
Example 3.34
/* Program to generate a given Pattern */
#include <stdio.h>
void main()
{
int r , c ,num = 6 ; /* r is row and c is column */
clrscr();
printf("\n\n\n Given Pattern\n\n\n");
for(r = num; r >= 1; r--) // Outer loop for rows
{
for(c = 1; c <= r ; c++) // Inner loop for columns
printf("%2d",r);
printf("\n");
}
getch(); // to see the results
}
Output
Given Pattern
666666
55555
4444
333
22
1
Example 3.35
/* Program to generate a given Pattern with numbers */
#include <stdio.h>
void main()
{
int r , c1 , c2 , n,m,p ; /* r is row and c1,c2 are columns */
clrscr();
printf("\n Enter the number of rows: ");
scanf("%d",&n);
printf("\n\n Number Pattern \n\n");
p = 1;
for(r = 1; r <= n; r++) // Outer loop for rows
{
for(c1 =1;c1<2*n-r;c1++)
printf(" "); // printing leading spaces
for(c2 = 1; c2 <= r ; c2++,p++) // Inner loop for columns
printf("%d",p); //p prints upto middle of row
for(c2 = r-1;c2>=1;c2--,p--)
{
m = p-2; //m prints latter half of row
158 PROBLEM SOLVING TECHNIQUES USING C
printf("%d",m);
}
printf("\n");
}
getch(); //to see the results
}
Output
Enter the number of rows: 5
Number Pattern
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
Example 3.36
/* Program to generate a given Pattern with numbers */
#include <stdio.h>
void main()
{
int r , c , k = 10 , i; /* r is row and c is column */
clrscr();
printf("\n\n\n Triangle Pattern\n\n\n");
for(r = 1; r <= 4; r++) // Outer loop for rows
{
for(i = 1; i <= k; i++) // for printing spaces
printf(" ");
for(c = 1; c <= r ; c++) // Inner loop for columns
printf(" %d ",r);
printf("\n");
k = k - 2;
}
getch(); //to see the results
}
Output
Triangle Pattern
1
2 2
3 3 3
4 4 4 4
DECISION MAKING AND LOOPING 159
Example 3.37
/* Program to find prime numbers in the range m to n where m and n
are positive integers and m< n */
#include <stdio.h>
void main()
{
int m,n,i,j,isprime;
clrscr();
printf("\n Enter lower and upper limit of the range m & n : ");
scanf("%d %d",&m,&n);
if(m<= 1)
m=2; //starting value of the range is made 2
printf("\n The Prime numbers are :\n\n");
for (i = m;i<=n;i++)
{
isprime = 1;
/* This loop checks i for a prime number */
for (j = 2;j<= i/2;j++)
{
if(i % j ==0)
{
isprime = 0;
break;
}
} /* End of j loop */
if(isprime)
printf("\n %d",i);
} /* End of i loop */
getch();
}
Output
7
11
13
17
19
23
160 PROBLEM SOLVING TECHNIQUES USING C
Example 3.38
/* Program to sum Exponential series up to n terms
Exponential series is e = 1 + x/1! + x^2/2! + ..... + x^n/n! */
#include <stdio.h>
#include <math.h>
void main()
{
int n,i;
float expo,x,fact;
clrscr();
printf("\n How many terms ? ");
scanf("%d",&n);
printf("\n Enter value of x : ");
scanf("%f",&x);
expo =1; fact = 1; /* initialize expo and fact to 1 */
for(i=1; i<=n ; i++)
{
fact = fact * i;
expo = expo + pow(x,i)/fact;
}
printf("\n exp(x) from Summation of Series : %f",expo);
printf("\n Library function value of Exp(x) : %f",exp(x));
getch();
}
Output
How many terms ? 15
Enter value of x : 2
exp(x) from Summation of Series : 7.389057
Library function value of Exp(x) : 7.389056
if (condition2)
if (condition2)
goto loop; Exit goto loop;
Jump from exit
within loop from
loop nested
loop : loops }
}
loop :
}
finish :
while(condition) do for ( ; ; )
{ { {
if (condition) for ( ; ; )
break; {
if (condition)
break; if (condition)
Exit Exit Exit break;
from from from
} inner }
loop loop loop
} while (condition1);
}
continue ;
The continue statement can be included within a for( ), while( ) or a do-while( ) loop.
Continue statement transfers control to the test condition in do-while ( ) and while ( )
loops. However in a for ( ) loop, the continue statement re-directs controls to the increment
expression, evaluates third-exp and then tests the condition in second-exp. Some examples
of continue within loops are shown in figure 3.36.
Continue should not be used outside loops since it does not do anything goto
statement in structured programming must be avoided.
while(condition1) do for ( ; ; )
{ { {
} }
}
while (condition1);
It closes all open files, flushes memory buffers and returns the value of n to the
function that called it.
n represents the exit status of the program, n = 0 represents error free
termination and n! = 0 means otherwise.
The value of n can be used to diagnose the error.
The default value of n is taken as zero which need not be specified. Thus the
default form is exit();
DECISION MAKING AND LOOPING 163
viii)The number of times a loop gets executed is calculated using the formula:
9 0
n int 1 5
2
164 PROBLEM SOLVING TECHNIQUES USING C
do-while while()
1. The condition is tested at the 1. The condition is examined at
end of the loop. It is an Exit- the beginning of the loop. It is
controlled loop. an Entry-controlled loop.
2. The do-while() loop operates 2. The while() loop continues to opera-
as long as the condition is true. tes as long as the condition is true.
3. The do-while() loop is executed 3. The while() loop may not be
at least once. executed at all.
a statement consists of multiple expressions use parentheses to make sure that the
compiler will interpret it, as you need.
(iii) Use of Communication
Ensure that you communicate with the user from the very first statement in your
program. The first message could identify the program and the last with a display
that says the program is done.
(iv) Indentation Rules
Indent statements that depend on previous statements.
Align else statements with their corresponding if statements.
Place the opening brace and on a separate line. The statements within braces
must be beyond the opening and closing braces.
Code only one statement on a single line.
Further indent nested statements according to the above rules.
(v) Negative Logic
Negative logic refers to expressions that start with not or those containing multiple
not expressions within negative logic is not simple or clear. Try to avoid it.
(vi) Selection statements
The rules for coding selection statements according to the order of importance are :
Code positive statements whenever possible.
Code the normal or expected condition first.
Code the most probable conditions first.
(vii) Determining Algorithm Efficiency
While comparing two different algorithms which solve the same problem, often, one
algorithm is found to be more efficient than the other. Therefore the study of
algorithm efficiency was given a name algorithmic by Brassard and Bratley.
Algorithmics is defined as “the systematic study of the fundamental techniques used
to design and analyse efficient algorithms”
If a function is linear, i.e., it contains no loops, then its efficiency is a function of
the number of instructions it contains. The general format is :
f (n) = efficiency
where n is the number of elements to be processed.
Linear Loops
Consider the following segment of code :
The body of the loop is executed 500 times. Since the efficiency is proportionate to
the number of iterations, it is
f (n) = n
Nested Loops
To analyse nested loops, the number of iterations of each loop must be determined
first. Then the total number of iterations would be:
Iterations = Outerloop iterations * Inner loop iterations.
REVIEW QUESTIONS
b) void main()
{
int i = 0, j = 0;
do
{
if(i%5 = =0)
{
170 PROBLEM SOLVING TECHNIQUES USING C
j++;
printf("%d",j);
}
++i;
}
while(i<20);
printf("\nj = %d", j);
}
c) void main()
{
int i = 0, j = 0;
for (i = 1, i<10, j++)
{
if(i%2 = = 1)
{
j = j + i;
else j - - ;
printf("%d",j);
continue;
}
printf("\nj = %d",j);
}
}
d) void main()
{
int i, j, k = 0;
for(i = 0; i<4; i++)
{
for(j = 0; j<i; ++j)
x+= i+j1;
printf("%d", k);
break;
}
printf("\nk = %d",k);
}
e) void main()
{
int i, j, k, x = 0;
for (i = 0; i<5; i++)
for (j = 0; j<i; j++)
{
switch (i + j 1)
{
case 1 ;
DECISION MAKING AND LOOPING 171
case 0 : x = x + 1;
break;
case 2 :
case 3 : x = x + 2;
defaut : x = x + 3;
} //end of switch
printf("%d",x);
}//end of for
printf("/nx = %d",x);
}//end of main()
8. Determine how many times the body of each loop will be executed.
a) i = 5; j = 50; b) x = 1;
while(i<=j) do
{ {
i = j/i; -
- x += 2;
- }
} while (x<5);
c) int i;
for(i = 1; i<=5; i = i + 2/3)
{
-
}
d) int x = 10, y = 7;
while (x%y>=0)
{
x++;
y+=2;
}
9. Find errors if any, in each of the program segments. All variables contain valid
values.
a) while (K! = 10); b) n = 0;
{ do
K = 1; {
sum ++; printf("%d",n);}
count++; while(n=1)
}
172 PROBLEM SOLVING TECHNIQUES USING C
e) m = 1; n = 0; f) int i = 1;
for(m + n<10;;); for(;;)
- {
printf("\n Hello"); printf("%d",i++);
- if(i>10)
break;
m = m + 15; }
10. Which of the following is not an infinite loop ? Justify your answer.
a) while(1) b) for(; ;) c) x = 0;
{ { do
- - {
- - /*no change*/
} } }
while (x==0);
d) #define TRUE 0
--
While (TRUE)
{
-
-
}
11. Given a = 0;
while(a<5)
printf("\n%d",a++);
How many times does the loop execute.
b) if(x = = 1)
a+b =c
else
a = =0
c) if(p>0)| | (a>0)
printf("\n Negative");
b) #define VERY_HAPPY 1
#include<stdio.h
main()
{
if(VERY_HAPPY)
printf("\n Thank You Very Much, God");
else
(printf("\n Things could be better, God");
}
3. Write a program to read a single digit and print it in English (i.e., 2 must
produce Two on the screen).
4. Write a program to input two numbers and determine whether :
a) the first is positive, negative or zero.
b) the second is positive, negative or zero.
c) The first is even or odd.
d) The second is even or odd.
e) Whether the first is exactly divisible by the second.
5. Write a program to find the reminder of M divided by N.Do no use % operator.
6. Write a program to read temperature in Fahrenheit and convert it to Celsius. The
program must be terminated when input is 999. Print the temperatures in the form
of a table.
7. Write a program to read a number within 25 and print its corresponding Roman
number (1 – I, 2 – II)
b) if(num>100||num<0)
printf("\n Range error");
c) if(marks1>60&&marks2>70)|| total>200)
printif("\nselected");
else
printf("\n Not Selected");
12. Write the corresponding statement to the following conditions, given temp is
a float type of variable.
a) print ICE, if value of temp <0.
b) print WATER, if value of temp is between 0 and 100.
c) print STEAM, if value of temp exceeds 100.
17. a) * * b) | | | | |
* * |
* |
* * |
* * | | | | |
18. To generate the first 5 perfect numbers.
19. Generate the pyramid using nested loops.
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 9 9 8 7 6 5
20. To generate factorials of 1 to n numbers.
21. To read the weight of 50 girls and count the number of girls whose weight is
between 45 and 55.
22. To find the sum of the cosine(x) series
x2 x4
cos x 1 .....
2! 4 !
1 1 1
23. To print the summation of using the series 4 1 .......
3 5 7
24. To generate 3 digit armstrong numbers (like 153) such that 13 + 53 + 33 = 153.
25. To find the largest and smallest of n numbers.
176 PROBLEM SOLVING TECHNIQUES USING C
n!
nC =
r r ! * * (n r )!
__________