Modul 2 Last Part

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

FORMATTED INPUT
Formatted input refers to an input data that has been arranged particular format.
For example: 15.75 123 John
This line contains three pieces of data, arranged in a particular form. For example, the first part
of the data should be read into a variable float, the second into int, and the third part into char.
This is possible in C using the scanf function.
The general form of scanf is

scanf (“control string”, &arg1,&arg2,…&argn);

The control string (format string) specifies the field format in which the data is to be entered and
the arguments arg1,arg2….argn specifies the address of the location where the data is stored.
The format string contains format specifications, consisting of the conversion character %, a data
type character and an optional number specifying the field width.

Inputting integer numbers


The field specification for reading an integer number is:

%wd
The percentage sign (%) indicates that a conversion follows. w is an integer number that
specifies the field width of the number to be read and d, known as data type character, indicates
that the number to be read is in integer mode. Consider the following example:
scanf(“%2d %5d”, &num1,&num2);
50 31426
The value 50 is assigned to num1 and 31426 to num2. Suppose if the input data line is 31426 50,
then 31 is assigned to num1 and num2 will be assigned 426. The value 50 that is unread will be
assigned to the first variable in the next scanf().
scanf(“%d %d”, &num1,&num2); will read the data 31426 50
correctly and assign 31426 to num1 and 50 to num2.
An input field may be skipped by specifying *in the place of field width. For example, the
statement
scanf(“%d %*d %d”, &a,&b)
will assign the data
123 456 789
as follows: 123 to a

CSE, CITECH 2018-19 Page 53


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

456 skipped (because of *)


789 to b
The data type character d may be preceded by ‘l’(letter ell)to read long integers and h to read
short integers.

INPUTTING REAL NUMBERS


For example, the statement : scanf (“%f %f %f”, &x,&y,&z); with the input data
475.89 43.21E-1 678
will assign the value 475.89 to x , 4.321 to y, and 678.0 to z. If the number to be read is of
double type, then the specification should be %lf

INPUTTING CHARACTER STRINGS


A scanf function can input strings containing more than one character. Following are the
specifications for reading character strings:

%ws or %wc
The corresponding argument should be a pointer to a character array. %c may be used to read a
single character.
Reading of a string using%wc and %ws is illustrated in

Reading Blank Spaces


%s specifier cannot be used to read string with blank spaces.But this can be done with the help of
% [] specification.Blank spaces may be included within the brackets.

Reading mixed data types


The statement

scanf (“%d %c %f %s”, &count, &code, &ratio, name);


will read the data

15 p 1.575 coffee
correctly and assign the values to the variables in the order in which they appear.

Detection of errors in input


When a scanf function completes reading its list, it returns the value of number of items
successfully read.
Example:

scanf(“%d %f %s”,&a&b ,name);

CSE, CITECH 2018-19 Page 54


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

Will return the value 3 if the following data is typed in:

20 150.25 motor
and return the value 1 if the following line is entered

20 motor 150.25
Commonly used scanf format codes are given in the table

Commonly used scanf format codes


Code Meaning
%c Read a single character
%d Read a decimal integer
%e Read a floating point value
%f Read a floating point value
%g Read a floating point value
%h Read a short integer
%i Read adecimal or octal integer
%o Read octal integer
%s Read string
%u Read an unsigned decimal integer
%x Read hexadecimal integer
%[..] Read a string of word
The following letters may be used as prefix for certain conversion characters
h for short integers
l for long integers or double
L for long double

FORMATTED OUTPUT
We have seen the use of print function for printing captions and numerical results.
The general form of printf statement is

printf(“control string”,arg1,arg2,…..argn);

Control string consists of three types of items:


1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n,\t and \b
A simple format specification has the following form:
%w.p type-specifier

CSE, CITECH 2018-19 Page 55


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

Where w is an integer number that specifies the total number ofcolums for the output value and p
is another integer number that specifies the number of digits to the right of the decimal point (of
a real number) or the number of character to be printed from a string. Both w and p are optional.
Examples of formatted printf
printf(“programming in C”);
printf(‘’ “);
printf(‘’\n “);
printf(‘’%d,x “);
printf(‘’a = %f\n b=%f “,a ,b);
printf(‘’sum=%d “,1234);
printf(‘’\n\n “);

Output of Integer Numbers


The format specification for printing an integer number is:

%wd
Where w specifies the minimum field width for the output.
The following examples illustrate the output of the number 9876under different formats:

Format output
printf (“%d”, 9876)
9 8 7 6
printf(“%6d”, 9876 ) 9 8 7 6
printf(“%2d”, 9876) 9 8 7 6
printf(“%-6d” 9876)
9 8 7 6
printf(“%06d” 9876)
0 0 9 8 7 6
It is possible to force the printing to be left –justified by placing a minus sign directly after the %
character. It is also possible to pad with zero the leading blanks by placing a 0(Zero) before the
field width specifier Zero (0) are known as flags.
Long integers specifying ld in the place of d in hd short integers.

Output of Real Numbers


The output of real number may be displayed in decimal notation using the following format
specification:

CSE, CITECH 2018-19 Page 56


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

%w.p f
The integer w indicates the minimum number of positions that are to be used for the display of
the value and the integer p indicates the number of digits to be displayed after the decimal
point(precision). The value, when displayed, is rounded to p decimal places and printed right-
justified in the field of w columns.
We can also display a real number in exponential notation by using the specification:

%w.p e
The following examples illustrate the output of the number y=98.7654 under different format
specifications:

Format output
printf(“%7.4f”,y) 9 8 . 7 6 5 4
printf(“%7.2f”,y) 9 8 . 7 7
printf(“%-7.2f”,y) 9 8 . 7 7
printf(“%f”,y) 9 8 . 7 6 5 4
printf(“%10.2e”,y) 9 . 8 8 e + 0 1
Printf(“%11.4e”,-y) - 9 . 8 7 6 5 e + 0 1
printf(“%-10.2e”,y) 9 . 8 8 E + 0 1
printf(“%e”,y)
9 . 8 7 6 5 4 0 e + 0 1
Printing of a single character
A single character can be displayed in a desired position using the format

%wc
The character will be displayed right-justified in the field of w columns. We can make the
display left – justified by placing a minus sign before the integer w. The default value for w is 1

Printing of Strings
The format specification for outputting string is similar to that of real number. It is the form
%w.ps
Where w specifies the field width for display and p instructs that only the first p characters of the
string are to be displayed. The display is right –justified.
The following examples show the effect of variety of specifications in printing a string “NEW
DELHI 110001”, containing 16 characters (including banks)

Specification output
CSE, CITECH 2018-19 Page 57
C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

%s
N E W D E L H I 1 1 0 0 0 1

%20s N E W D E L H I 1 1 0 0 0 1

%20.10s N E W D E L H I
%0.5s N E W D
%-20.10s N E W D E L H I
%5s N E W D E L H I 1 1 0 0 0 1
Mixed data output
It is permitted to mix data types in one printfstatement.For example, the statement of the type
printf(“%d%f%s%c”,a,b,c,d);
Commonly used printf format codes

Code Meaning
%c Print a single character
%d Print a decimal integer
%e Print a floating point value in exponent form
%f Print a floating point value without exponent
%g Print a floating point value either e-type or f-type depending on
%i Print assigned decimal integer
%o Print a octal integer, without leading zero
%s Print a string
%u Print a unsigned decimal integer
%x Print a hexadecimal integer,without leading Ox

The following letters may be used as prefix for certain conversion characters
h for short integers
l for long integers or double
L for long double

THE GOTO STATEMENT

So far we have discussed ways of controlling the flow of execution based on certain
specified conditions. C supports the goto statement to branch unconditionally from one point to
another in the program.

CSE, CITECH 2018-19 Page 58


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

The goto requires a label in order to identify the place where the branch is to be made. A label is
any valid variable name, and must be followed by a colon. The label is placed immediately
before the statement where the control is to be transferred. The general forms of goto and label
statements are shown below:

Syntax:

During running of a program when a statement like

goto begin;

is met, the flow of control will jump to the statement immediately following the label begin: This
happens unconditionally.

If the label: is before the statement goto label; a loop will be formed and some statements will be
executed repeatedly. Such a jump is known as a backward jump. On the other hand, if the label:
is placed after the goto label; some statements will be skipped and the jump is known as forward
jump.

A goto is often used at the end of the program to direct the control to go to the input statement, to
read further data. Consider the following example

Program (here goto works like a loop)


#include <math.h>
main()
{
float x, y;
int count;
count = 1;

CSE, CITECH 2018-19 Page 59


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

printf("Enter FIVE real values \n");


read:
scanf("%f", &x);
printf("\n");
if (x < 0)
printf("Value %d is negative\n",count);
else
{
y = sqrt(x);
printf("%f\t %f\n", x, y);
}
count = count + 1;
if (count <= 5)
goto read;
printf("\nEnd of computation");
}

Output

Enter FIVE real values

50.70

50.750000 7.123903

40

40.000000 6.324555

-36

Value 3 is negative

75

75.000000 8.660254

CSE, CITECH 2018-19 Page 60


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

11.25

11.250000 3.354102

End of computation

Program (use goto to write a program to perform the sum of first n natural numbers)
void main()

int i=0,n,sum=0;

printf(“enter n”);

scanf(“%d”,&n);

loop:

sum=sum+i;

i=i+1;

if(i<=n)

goto loop;

printf(“sum=%d”,sum);

Program (use goto to write a program to check if the input marks is pass or fail)
void main()

int marks;

printf(“enter marks”);

scanf(“%d”,&marks);

if(marks<50)

goto fail;

else

goto pass;

fail:

CSE, CITECH 2018-19 Page 61


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

printf(“failed”);

exit(0);

pass:

printf(“passed”);

Program (use goto to write a program to check if the input number is odd or even)
void main()

int n;

printf(“enter a number”);

scanf(“%d”,&n);

if(n%2==0)

goto even;

else

goto odd;

even:

printf(“even”);

exit(0);

odd:

printf(“odd”);

Return statement : return statement terminates the execution and returns control to the calling
function.

Syntax: return expression;

Example: return 0; 0 will be returned to calling function.

Additional Features of for loop

CSE, CITECH 2018-19 Page 62


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

For example, more than one variable can be initialized at a time in the for statement. The
statements

p = 1;
for (n=0; n<17; ++n)
Can be rewritten as
for (p=1,n=0; n<17; ++n)
Like the initialization section, the increment section may also have more than one part. For
example the loop
for(n=1, m=50; n<=m; n=n+1, m=m-1)
{
p=m/n;
printf(“%d %d %d\n”, n, m, p);
}
is perfectly valid. The multiple arguments in the Increment section are separated by commas.
The third feature is that the test-condition may have any compound relation and the testing need
not be limited only to the loop control variable. Consider the example below:
sum 0;
for (i =1; i < 20 && sum < 100; ++i)
{
sun = sum+i;
printf("%d %d\n”, i, sum);
}
Another unique aspect of for loop is that one or more sections can be omitted, if necessary.
Consider the following statements

m=5;
for (; m !=100;)
{
printf(“%d\n”,m);
m=m+5;
}
we can set up time delay using the null statement(;) as follows:
for(i=1;i<=1000;i++);
The loop is executed 1000 times without producing any output; it simply causes a time delay.
Nesting of for loop
Nesting of for loops that is one for statement within another for statement, is allowed in C. For
example two loops can be nested as follows:

Syntax:

CSE, CITECH 2018-19 Page 63


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

Write a C program using nested for loop to print the following pattern.

i) * ii) 1 2 3 4
* * 1 2 3
* * * 1 2
* * * * 1

main()
{
int i,j;
for (i=1;i<=4; i++)
{
for (j=1;j<=i; j++)
{
printf(“*\t”);
}
printf(“\n”);
}
}

main()
{
int i,j;
for (i=4;i>=1; i--)
{
for (j=1;j<=i; j++)

CSE, CITECH 2018-19 Page 64


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

{
printf(“%d\t”,j);
}
printf(“\n”);
}
}
Just like for, even while and do while can be nested.
void main()
{
int x,y,sum;
for(x=1;x<=2;x++)
{
for(y=1;y<=2;y++)
{
sum=x+y;
printf(“\nx=%d”,x);
printf(“\ny=%d”,y);

printf(“\nsum=%d”,sum);

void main()
{
int x,y,sum;
x=1;
while(x<=2)
{
y=1;
while(y<=2)
{
sum=x+y;
printf(“\nx=%d”,x);
printf(“\ny=%d”,y);

printf(“\nsum=%d”,sum);

y++;

CSE, CITECH 2018-19 Page 65


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

x++;

Output:

x=1

y=1

sum=2

x=1

y=2

sum=3

x=2

y=1

sum=3

x=2

y=2

sum=4

JUMPS IN LOOPS

C permits a jump from one statement to another within a loop as well as a jump out of a loop.

Unconditional jump statements in C: goto, break, continue, exit, return

Jumping out of a loop

An early exit from a loop can be accomplished by using the break statement or the goto
statement.

Syntax for break: break;

CSE, CITECH 2018-19 Page 66


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

These statements can also be used within while, do, or for loops. When a break statement-is
encountered inside a loop, the loop is immediately exited and the program continues with the
statement immediately following the loop.

Another important use of goto is to exit from deeply nested loops when an error occurs. A simple
break statement would not work here.

Jumping within and exiting from the loop with goto statement

Program (to print first 10 even numbers not greater than 10)
void main()

CSE, CITECH 2018-19 Page 67


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

int i;

for(i=2;i<=20;i=i+2)

if(i>10)

break;

printf(“%d\t”,i);

Program (Input 100 numbers, stop on encountering a negative value. Find the sum and
average of inputted values)
void main()

int i;

float n,sum=0,average;

for(i=0;i<100;i++)

scanf(“%d”,&n);

if(n<0)

break;

sum=sum+x;

average=sum/i;

printf(“sum=%f,average=%f”,sum,average);

Skipping a part of loop

CSE, CITECH 2018-19 Page 68


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

During the loop operations, it may be necessary to skip a part of the body of the loop under
certain conditions. Like the break statement, C supports another similar statement called the
continue statement.
However, unlike the break which causes the loop to be terminated, the continue, causes the loop
to be continued with the next iteration after skipping any statements in between. The continue
statement tells the compiler, "SKIP THE FOLLOWING STATEMENTS AND CONTINUE
WITHTHE NEXT ITERATION". The format of the continue statement is simply

Syntax:

continue;

The use of the continue statement in loops is Illustrated

Avoiding goto
As mentioned earlier, it is a good practice to avoid using goto. When goto is used, many
compilers generate a less efficient code. In addition, using many of them makes a program logic
complicated and renders the program unreadable. The goto jumps shown in below fig would
cause problems and therefore must be avoided

CSE, CITECH 2018-19 Page 69


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

Fig: Avoid goto

Program (to print first 10 even numbers except 6 and 8)


void main()

int i;

for(i=2;i<=20;i=i+2)

if(i==6||i==8)

continue;

printf(“%d\t”,i);

Program (Input 1000 numbers, stop on encountering 9999. Find the square root of each
number only if it is non negative)
#include<stdio.h>

#include<math.h>

void main()

int i=0,negative=0;

float n,sq;

for(i=0;i<1000;i++)

scanf(“%d”,&n);

CSE, CITECH 2018-19 Page 70


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

if(n==9999)

break;

if(n<0)

negative++;

printf(“number is negative”);

continue;

sq=sqrt(n);

printf(“square root of %f is %f”,n,sq);

printf(“number of negative numbers that are input %d”,negative);

printf(“number of numbers that are input %d”,i);

Jumping out of the program

We have just seen that we can jump out of a loop using either the break statement or goto
statement. In a similar way, we can jump out of a program by using the library function exit( ).
In case, due to some reason, we wish to break out of a program and return to the operating
system, we can use the exit() function, as shown below

…………
………...
If (test-condition) exit(0);
………..
………..
The exit() function takes an integer value as its argument Normally zero is used to Indicate
normal termination and a nonzero value to indicate termination due to some error or abnormal
condition. The use of exit() function requires the inclusion of the header file <stdlib.h>
Return statement : return statement terminates the execution and returns control to the calling
function.

Syntax: return expression;

CSE, CITECH 2018-19 Page 71


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

Example: return 0; 0 will be returned to calling function.

Structured programming

Structured programming is an approach to the design and development of programs. It is a


discipline of making a program's logic easy to understand by using only the basic three control
structures:

 Sequence (straight line) structure


 Selection (branching) structure
 Repetition (looping) structure

The use of structured programming techniques helps ensure well-designed programs that are
easier to write, read, debug and maintain compared to those that are unstructured.

Structured programming discourages the implementation of unconditional branching using


jump statement such as goto, break and continue.

CONCISE TEST EXPRESSIONS

We often use test expressions in the if, for, while and do statements that are evaluated and
compared with zero for making branching decisions.
We can write concise test expressions without using any relational operators.
if (expression ==0)
is equivalent to
if(!expression)
similarly,
if (expression! = 0)
is equivalent to
if(expression)
for example, if (m%5==0&&n%5==0) is same as if(!(m%5)&&!(n%5)
Programs
1. Program to compute the roots of a quadratic equation by accepting the coefficients.
Print appropriate messages.
Algorithm:
Step1: [Initialize]
start
Step2: [Input the coefficients of quadratic equation]
Read a,b,c.
Step3: [Check for valid coefficients]
If (a==0)
Then invalid coefficients. Go to step 6
Step4:[Compute discriminate value as d]
d=b*b-4*a*c

CSE, CITECH 2018-19 Page 72


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

Step5: [Check for d value to compute roots]


5.1:if (d>0) then
print real and distinct roots
root1=(-b+√d)/(2*a)
root2=(-b-√d)/(2*a)
print root1,root2
go to step 6
5.2:if (d==0) then
print real and equal roots
root1 = root2= -b/(2*a)
print root1,root2
go to step 6
5.3:if (d<0) then
print real and imaginary
real=-b/(2*a)
imag=(√fabs(d))/(2*a)
print root1 as real+iimag
print root2 as real-iimag
goto step 6
Step 6: [Finished] Stop
Flow Chart:

CSE, CITECH 2018-19 Page 73


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

Program:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
floata,b,c, d,root1,root2,real,imag;
printf("Enter the three coefficients:\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0)
{
printf("Invalid coefficients");
exit(0);
}
d=b*b-4*a*c;
if(d>0)
{

CSE, CITECH 2018-19 Page 74


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

root1=(-b+(sqrt(d)))/(2.0*a);
root2=(-b-(sqrt(d)))/(2.0*a);
printf("The roots are real and distinct....\n");
printf("root1=%f \n root2=%f\n",root1,root2);
}
else if(d==0)
{
root1=root2=-b/(2.0*a);
printf("The roots are real and equal....\n");
printf("root1=%f \n root2=%f\n",root1,root2);
}
else
{
real=-b/(2.0*a);
imag= sqrt(fabs(d))/(2.0*a);
printf("The roots are complex and imaginary....\n");

printf("root1=%f+i %f \n root2= %f-i%f",real,imag,real,imag);


}
return 0;
}
Test Cases:
Test Input Parameters Expected Output Obtained Output
No
1 a=0, b=0, c=1 Invalid Coefficients Invalid Coefficients
2 a=1, b=6, c=9 Roots are real and equal Roots are real and equal
root1=-3, root2=-3 root1=-3, root2=-3
3 a=1, b=-5, c=3 Roots are real and distinct Roots are real and distinct
root1=4.30, root2=0.69 root1=4.30, root2=0.69
4 a=1, b=4, c=7 Roots are complex and Roots are complex and
imaginary imaginary
root1= -2+i1.73, root2= -2- i1.73 root1= -2+i1.73, root2= -2-
i1.73
2. Computation of Binomial Coefficients
Problem: Binomial coefficients are used in the study of binomial distributions and reliability
of multicomponent redundant systems. It is given by

B(m,x) = , m >= x

A table of binomial coefficients is required to determine the binomial coefficient for any set
of m and x

Problem Analysis: The binomial coefficient can be recursively calculated as follows:

CSE, CITECH 2018-19 Page 75


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

B(m,o) = 1

Further,

B(o,o) = 1

That is, the binomial coefficient is one when either x is zero or m is zero. The program prints

the table of binomial coefficients for m = 10. The program employs one do loop and one

while loop.

Program (method-1)
#include<stdio.h>

#define MAX 10

int main()

int m, x, binom;

printf(" m x");

for (m = 0; m <= MAX ; m++)

printf("%4d", m);

m = 0;

do

printf("\n");

printf("%4d", m);

CSE, CITECH 2018-19 Page 76


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

x = 0;

binom = 1;

while (x <= m)

if(m == 0 || x == 0)

printf("%4d", binom);

else

binom = binom * (m - x + 1)/x;

printf("%4d", binom);

x = x + 1;

m = m + 1;

while (m <= MAX);

return 0;

Output

CSE, CITECH 2018-19 Page 77


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

Program (method-1)
#include<stdio.h>

#define MAX 10

int factorial(int n);

int main()

int m, x, binom;

printf(" m x");

for (m = 0; m <= MAX ; m++)

printf("%4d", m);

m = 0;

do

printf("\n");

printf("%4d", m);

x = 0;

binom = 1;

while (x <= m)

if(m == 0 || x == 0)

printf("%4d", binom);

else

binom = factorial(m)/(factorial(m-x)*factorial(x));

printf("%4d", binom);

CSE, CITECH 2018-19 Page 78


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

x = x + 1;

m = m + 1;

while (m <= MAX);

return 0;

int factorial(int n)

int f=1,i;

for(i = 1; i <= n; i++)

f=f*i;

return f;

}
Output

Plotting of Pascal's Triangle

Pascal’s triangle is named after a French mathematician called Blasie Pascal. It is a triangular array of the
CSE, CITECH 2018-19 Page 79
C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

binomial coefficients. To build the triangle, start with 1 at the top, then continue placing numbers below it in a
triangular pattern. Each number is the numbers directly above it added together.

#include <stdio.h>

int factorial(int n);

int ncr(int n,int r);

int main()

int n, i, j;

printf("enter n:");

scanf("%d",&n);

for(i = 0; i <= n; i++)

printf("\n");

for(j = 0; j <= n-i; j++)

printf(" ");

for(j = 0; j <= i; j++)

printf("%4d", ncr(i,j));

return 0;

int factorial(int n)

CSE, CITECH 2018-19 Page 80


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

int f=1,i;

for(i = 1; i <= n; i++)

f=f*i;

return f;

int ncr (int n, int r)

return factorial(n) / ( factorial(n-r) * factorial(r) );

The output should look like this – when n=5

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Some More Programming Examples:


Program (to print the binomial cofficient)

#include <stdio.h>

int factorial(int n);

int ncr(int n,int r);

int main()

CSE, CITECH 2018-19 Page 81


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

int n,r;

printf("enter n and r(r<=n):");

scanf("%d%d",&n,&r);

printf("binomial coefficient for the given n and r is %d", ncr(n,r));

return 0;

int factorial(int n)

int f=1,i;

for(i = 1; i <= n; i++)

f=f*i;

return f;

int ncr (int n, int r)

return factorial(n) / ( factorial(n-r) * factorial(r) );

Output: Enter n and r(r<=n): 4 2

Binomial coefficient for the given n and r is 6

CSE, CITECH 2018-19 Page 82


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

Program (to find gcd of two numbers using ternary operator and for loop)
void main()

int a,b,min,i;

printf(“enter two numbers”);

scanf(“%d%d”,&a,&b);

min=a<b?a:b;

for(i=min;i>0;i--)

if((a%i==0)&&(b%i==0)

printf(“gcd is %d”,a);

break;

}
Program (to find gcd of two numbers using Euclid’s Algorithm)
void main()

int a,b,r;

printf(“enter two numbers”);

scanf(“%d%d”,&a,&b);

while(b!=0)

r=a%b;

a=b;

b=r;

CSE, CITECH 2018-19 Page 83


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

printf(“gcd is %d”,a);
}
Program (to read a sentence and count the frequency of vowels and consonants)
#include<stdio.h>

#include<string.h>

void main()

int vc=0,cc=0;

char s[100],ch;

printf(“Enter a sentence”);

gets(s);

for(i=0;i<strlen(s);i++)

if(isalpha(s[i]))

ch=tolower(s[i]);

if(ch==’a’|| ch==’e’|| ch==’i’|| ch==’o’|| ch==’u’)

vc++;

else

cc++;

printf(“vowels count =%d”,vc);

printf(“consonants count =%d”,cc);

}
Program (to print Fibonacci series upto n)
#include<stdio.h>

CSE, CITECH 2018-19 Page 84


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

void main()

int num1=0,num2=1,n,i,fib;

printf(“Enter n”);

scanf(“%d”,&n);

printf(“%d\t%d\t”,num1,num2);

for(i=3;i<=n;i++)

fib=num1+num2;

printf(“%d\t”,fib);

num1=num2;

num2=fib;

Program (to print nth number of Fibonacci series)


#include<stdio.h>

void main()

int num1=0,num2=1,n,i,fib;

printf(“Enter n”);

scanf(“%d”,&n);

for(i=3;i<=n;i++)

fib=num1+num2;

num1=num2;

num2=fib;

CSE, CITECH 2018-19 Page 85


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

printf(“nth number of fibonacci series is %d”,fib);

Program (to print n, 2n, 2-n from n=1 to 20)


#include<stdio.h>

#define maxsize 20

void main()

long int n,p;

double q;

p=1;

for(n=0;n<=maxsize;n++)

if(n==0);

p=1;

else

p=p*2;

q=1/(double)p;

printf(“%ld\t%ld\t%lf”,n,p,q);

Program (to find xn)


#include<stdio.h>

void main()

int n,x,i,y=1;

printf(“enter n,x”);

scanf(“%d%d”,&n,&x);

CSE, CITECH 2018-19 Page 86


C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping

for(i=1;i<=n;i++)

y=y*x;

printf(“result is %f”,y);

CSE, CITECH 2018-19 Page 87

You might also like