0% found this document useful (0 votes)
12 views31 pages

Module 2 (PSP)

Uploaded by

Hamsa J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views31 pages

Module 2 (PSP)

Uploaded by

Hamsa J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Best VTU Student Companion App You Can Get

DOWNLOAD NOW AND GET


Instant VTU Updates, Notes, Question Papers,
Previous Sem Results (CBCS), Class Rank, University Rank,
Time Table, Students Community, Chat Room and Many
More

CLICK BELOW TO DOWNLOAD VTU CONNECT APP


IF YOU DON’T HAVE IT

* Visit https://vtuconnect.in for more info. For any queries or questions wrt our
platform contact us at: [email protected]
Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Module II

2.1 MANAGING INPUT AND OUTPUT OPERATIONS


Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file. C programming
language provides many built-in functions to read any given input and to display data on screen
when there is a need to output the result.
Input/Output(I/O) functions are divided into 2 types. They are:
1. Formatted I/O: The formatted functions are those which specifies data types and way in which
it should be read or printed. The formatted input function is scanf and output function is printf.
2. Unformatted I/O: The unformatted functions are those which does not specifies data types
and way in which it should be read or printed The unformatted input functions are getchar()
and gets(). The unformatted output functions are putchar() and puts().
2.1.1. Formatted function
1. Input function:
Syntax:
scanf(“Control String or format specifier” ,address of variables);
Example:
scanf(“%d%f”,&a,&b);
Rules for scanf:
1. Each variable to be read must have a filed specification;
2. For each field specification, there must be a variable address of proper type.
3. Any non-white space character used in the format string must have a matching character
in the user input.
4. Never end the format string with whitespace. It is a fatal error.
5. The scanf reads until:
 A whitespace character is found in a numeric specification
 The maximum number of characters have been read or
 An error is detected or
 The end of file is reached.

DEPARTMENT OF CSE, BIT 1


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Format Specifier:
It is used to specify the type of the value to be read or written using standard input output
functions.
Commonly used scanf format Codes
CODE MEANING
%c Read a single character
%d Read a decimal integer
%e Read a floating point value with exponents
%f Read a floating point value
%g Read a floating point value
%hd Read a short integer
%i Read decimal integer
%o Read a octal integer
%s Read a string
%u Read an unsigned decimal integer
%x Read a Hexadecimal integer
%lf Read a double
%[…] Read a String of word(S)

2. Output Function:
Syntax:
printf(“control string”, list of variable or expression);
Rules for printf:
Control String consist of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specification that define the output format for display of each item.
3. Escape sequence character such as \n, \t and \b.
Conversion Specification for printf:
Minimum
% flag padding precision Conversion code
width

Flag: It is use to specify the sign for justification either left justify or right justify. By default, if
the sign is not specified then it is right justified.
Minimum Width: Number of column available to store and display the value.

DEPARTMENT OF CSE, BIT 2


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Padding: if the value is lesser than number of width then the free space is padded with white space
or with zero.
Precision: For floating values after decimal point how many digits’ user like to display.
Conversion code: For different data types we have separate conversion code i.e., same as scanf
format code in above table.
Example:
printf(“the sum is %-04.2d”, a); where a=12
- indicate left justification
0 indicate padding with zero if pad value is not specified then default white space is
considered.
4 indicate minimum width i.e., 4 columns to display but we have the value of only two digits
of 2 so remaining two space is padded with zero
.2 if it is float value then after decimal point only two digits is displayed
d indicate conversion code for integer data type value
Output:
1 2 0 0

2.1.2. Unformatted function:


1. getchar() and putchar():
getchar() and putchar() are unformatted I/O functions which reads single character at a time
and displays single character at a time respectively at run time.
Syntax for getchar:
char ch;
ch=getchar();
Syntax for putchar:
putchar(ch);
2. gets() and puts():
gets() and puts() are unformatted I/O functions which reads a string at a time and displays
string at a time respectively.
Syntax for gets:
char ch;

DEPARTMENT OF CSE, BIT 3


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

gets(ch);
Syntax for puts:
puts(ch);

2.2 BRANCHING AND LOOPING STATEMENTS


Statements cause an action to be performed by the program. The different types of
statements are:
 Conditional Statements
 Unconditional Statements
 Iterative Statements
2.2.1 CONDITIONAL (or) BRANCHING STATEMENTS
A conditional (or) branching statement is a control structure that allows selecting one or
more execution paths in a program.
The different conditional statements in C are:
1. if statement
2. if-else statement
3. Nested if-else statement
4. else-if ladder
5. switch statement
A selection statement is a conditional statement that allows choosing between two (or)
more executing paths in a program. The different types are:
1. One-way selector (Ex: An if statement with no else statement)
2. Two-way selector (Ex: An if-else statement)
3. n-way selector (Ex: A switch statement)
2.2.1.1 “if” Statement
Explanation:
“if” statement is a one-way selection statement which executes statements based on
whether the condition is true (or) false. If the condition is true, then the set of statements associated
with if is executed. If the condition is false, then the statements will be skipped and statement Y
will be executed. Relational operators are used to specify the conditions.

DEPARTMENT OF CSE, BIT 4


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Syntax:
if(conditional expression)
{
Statements;
}
Statement Y;
Flowchart:

Example: Program to add 10 marks if student scores more than 20.


#include<stdio.h>
main()
{
int marks;
printf(“Enter marks”);
scanf(“%d”, &marks);
if(marks>20)
{
Marks=marks+10;
}
printf(“ Marks=%d”,marks);
}
Output:
1. Enter marks: 25

DEPARTMENT OF CSE, BIT 5


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Marks=35
2. Enter marks: 15
Marks=15
2.2.1.2. ”if-else” Statement
Explanation:
“if-else” statement is a two-way selection statement which executes statements based on
whether the condition is true (or) false. If the condition is true, then the set of statements associated
with “if” is executed (i.e., Statement X) and then the rest of the code (i.e., Statement A) will be
executed skipping the “else” part. If the condition is false, then the set of statements associated
with else is executed (i.e., Statement Y) and then the rest of the code (i.e., Statement A) will be
executed skipping the “if” part.
Syntax:
if (conditional expression)
{
Statement X;
}
else
{
Statement Y;
}
Statement A;
Flowchart:

DEPARTMENT OF CSE, BIT 6


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Example: Program to check greatest of 2 numbers.


#include<stdio.h>
main()
{
int a,b;
printf(“Enter 2 numbers\n”);
scanf(“%d%d”, &a,&b);
if(a>b)
{
printf(“ %d is greatest”,a);
}
else
{
printf(“ %d is greatest”,b);
}
}
Output:
1. Enter 2 numbers
35 25
35 is greatest
2. Enter 2 numbers
15 25
25 is greatest

2.2.1.3 “Nested if-else” Statement


Explanation:
“Nested if-else” statements can be used within an if-else statement. If both the conditions
are true, then the statements within inner if (or) else will be executed.
Working:
Case1: if the “conditional expression1” is true, then “conditional expression2” is checked. If the
“conditional expression2” is true, then Statement X is executed. If the “conditional expression2”
is false, then the control comes out of both the “if” and executes “statement A”.

DEPARTMENT OF CSE, BIT 7


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Case 2: if the “conditional expression1” is false, then else is executed. If the “conditional
expression3” is true, then Statement Y is executed. If the “conditional expression3” is false, then
Statement Z is executed. Later the control comes out of “if/else” and executes “statement A”.
Syntax:
if (conditional expression1)
{
if (conditional expression2)
{
Statement X;
}
}
else
{
if (conditional expression3)
{
Statement Y;
}
else
{
Statement Z;
}
}
Statement A;
Flowchart:

DEPARTMENT OF CSE, BIT 8


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Example: Program to check greatest of 3 numbers.


#include<stdio.h>
main()
{
int a, b, c;
printf(“Enter 3 numbers\n”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf(“ %d is greatest”,a);
}
else
{
printf(“ %d is greatest”,c);
}
}
else
{
if(b>c)
{
printf(“ %d is greatest”,b);
}
else
{
printf(“ %d is greatest”,c);
}
}
}
Output:
1. Enter 3 numbers 15 25 35
35 is greatest
2. Enter 3 numbers 45 25 35
45 is greatest

DEPARTMENT OF CSE, BIT 9


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

2.2.1.4 “else-if ladder” Statements:


Explanation:
“else-if ladder” is a multi-way selection statement which executes statements based on
whether the condition is true (or) false. If more than one “if-else” statements are used (when
multiple decisions has to be made) in sequence, then it is called else-if ladder.
Working:
Case1: If the condition1 is true, then the set of statements associated with “if” is executed (i.e.,
Statement X) and then the rest of the code (i.e., Statement A) will be executed skipping the other
“if-else” part.
Case2: If the condition1 is false, then Conditon2 is checked. If the condition2 is true, then the set
of statements associated with else-if(condition2) is executed (i.e., Statement Y) and then the rest
of the code (i.e., Statement A) will be executed skipping the “if-else” part.
Case3: If the condition2 is false, then the set of statements associated with else is executed (i.e.,
Statement Z) and then the rest of the code (i.e., Statement A) will be executed.
Syntax:
if (conditional expression1)
{
Statement X;
}
else if (conditional expression2)
{
Statement Y;
}
…… (multiple else if can be used)
else
{
Statement Z;
}
Statement A;

DEPARTMENT OF CSE, BIT 10


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Flowchart:

Example: Program to check whether a given number is positive, negative or “zero” number.
#include<stdio.h>
main()
{
int a;
printf(“Enter the number\n”);
scanf(“%d”,&a);
if(a==0)
{
printf(“%d is a zero number\n”,a);
}
else if(a>0)
{
printf(“%d is a positive number\n”,a);
}
else
{
printf(“%d is a negative number\n”,a);
}
}

DEPARTMENT OF CSE, BIT 11


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

2.2.1.5 Switch statement:


A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.
The following rules apply to a switch statement:
 The expression used in a switch statement must have an integral or enumerated type, or be of a
class type in which the class has a single conversion function to an integral or enumerated type.
 You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon. (i.e., case value1: )
 The constant-expression for a case must be the same data type as the variable in the switch, and
it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
 A switch statement can have an optional default case, which must appear at the end of the switch.
The default case can be used for performing a task when none of the cases is true. No break is
needed in the default case.
Syntax:
switch(expression)
{
case value1: block1;
break;
case value2: block2;
break;
case value3: block1;
break;
default: default statement;
}

DEPARTMENT OF CSE, BIT 12


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Flowchart:

Example: Program to check whether a given character is “vowel” or not.


#include<stdio.h>
main()
{
char ch;
printf(“Enter a character:\n);
scanf(“ %c”,&ch);
switch(ch)
{
case ‘a’: printf(“ It is a Vowel\n”);
break;
case ‘e’: printf(“ It is a Vowel\n”);
break;
case ‘i’: printf(“ It is a Vowel\n”);

DEPARTMENT OF CSE, BIT 13


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

break;
case ‘o’: printf(“ It is a Vowel\n”);
break;
case ‘u’: printf(“ It is a Vowel\n”);
break;
default: printf(“ It is a consonant\n”);
}
}
Output:
1. Enter a character:
a
It is a Vowel
2. Enter a character:
u
It is a Vowel
3. Enter a character:
x
It is a consonant

DEPARTMENT OF CSE, BIT 14


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

2.2.2 UNCONDITIONAL STATEMENTS


Unconditional statements are the statements which transfer control (or) flow of execution
unconditionally to another block of statements. They are also called jumping statements.
The four types of unconditional statements are:
1. break: It stops the current and succeeding iteration. It transfers the control out of the loop. It
breaks the entire loop execution.
Example:
#include<stdio.h>
main()
{
int i;
for(i=1;i<=5;i++)
{
printf(“ Iteration %d\n”,i);
if(i==3)
{
break;
}
printf(“i=%d\n”,i);
}
}
Output:
Iteration 1
1
Iteration 2
2
Iteration 3
2. continue: It stops the current iteration and continues the next iteration. That is it transfers the
control to the next iteration of the same loop. It breaks that current iteration of the loop.
Example:
#include<stdio.h>

DEPARTMENT OF CSE, BIT 15


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

main()
{
int i;
for(i=1;i<=5;i++)
{
printf(“ Iteration %d\n”,i);
if(i==3)
{
continue;
}
printf(“i=%d\n”,i);
}
}
Output:
Iteration 1
1
Iteration 2
2
Iteration 3
Iteration 4
4
Iteration 5
5
3. goto: A “goto” statement provides an unconditional jump from the goto to a labeled statement.
Here label is an identifier and it can be set anywhere in the program above or below to goto
statement. If the label statement is set above the goto then it is called backward jump and if it
is set below it is called forward jump.
Forward jump Syntax:
goto label_name;
…..
label_name: Statements

DEPARTMENT OF CSE, BIT 16


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Backward jump Syntax:


label_name: Statements
…..
goto label_name;
4. return: Statement terminates the execution of a function and returns control to the calling
function.
Syntax: return expression; //Value of expression is returned.

DEPARTMENT OF CSE, BIT 17


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

2.2.3 ITERATIVE/ LOOPING STATEMENT


2.2.3.1 Introduction
Why use loop?
When you need to execute a block of code several number of times then you need to use
looping concept in C language.
Advantage with looping statement:

 Reduce length of Code

 Take less memory space.

 Burden on the developer is reducing.

 Time consuming process to execute the program is reduced.

Definition:
Looping statement are the statements execute one or more statement repeatedly several
number of times until a given condition fails. These statements are also called repetitive or
iterative statements.

DEPARTMENT OF CSE, BIT 18


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Looping Process:
Step1: Initialize a condition variable
Step 2: Test the condition variable as specified in the conditional expression for the execution
of the loop.
Step 3: If the condition is true, then execute the steps inside the loop where the updating of the
condition variable is done and go to step 2.
Step 4: If the condition in step 2 is false, then stop execution of loop and continue with
execution of rest of the statements in the program.
Depending upon the position of a control statement in a program, a loop is classified into
two types:
1. Entry controlled/ Pre-Test loop:
The condition is checked before executing the body of a loop. The body of the loop
executes zero (or) more times.
2. Exit controlled/ Post-Test loop:
The condition is checked after executing the body of a loop. The body of the loop executes
at least one time.

2.2.3.2 Types of looping constructs


‘C' programming language provides us with three types of loop constructs:
1. The while loop (Pre-test/Entry controlled)
2. The do-while loop (Post-test/Exit controlled)
3. The for loop (Pre-test/Entry controlled)

DEPARTMENT OF CSE, BIT 19


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

2.2.3.2.1 While Loop:


Definition:
A while loop is a pre-test loop where the condition is checked first and then the body of
the loop is executed. It executes the statements in the loop until the condition of the while loop
evaluates to true. Loop gets terminated when the condition becomes false.
Working:
 The initialization for the while loop are done first.
 Then the expression is evaluated to true/false. If it is evaluated to false, the control comes
out of the loop without executing the body of the loop and Statement A that is present after
the while loop is executed.
 If the expression is evaluated to true, the statements inside the body of the loop is executed.
 The loop variable is updated inside the body of the loop and then the control goes back to
beginning of the while-statement and expression is again evaluated to true or false.
Syntax:
while (condition)
{
statements;
}
Statement A;
Flowchart:

DEPARTMENT OF CSE, BIT 20


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Example: Program to print first 5 natural numbers.


#include<stdio.h>
main()
{
int i=1; //initializing the variable
printf(“ The first 5 natural numbers are:\n”);
while(i<=5) //while loop with condition
{
printf("%d\n",i);
i++; //increment operation
}
}

Output:
The first 5 natural numbers are:
1
2
3
4
5

2.2.3.2.2 Do-While Loop:

Definition:
A do-while loop is a post-test loop where the body of the loop is executed and then the
condition is checked. It executes the statements in the loop until the condition of the loop evaluates
to true. Loop gets terminated once the condition becomes false.
Working:
 The statement inside the body of do-while are first executed one after the other.

 Then, the expression is evaluated. If the expression is evaluated to true, the body of the loop is
executed again and the process is repeated.
 If the expression is evaluated to false, control comes out of the do-while and A-statements that
appear after the do-while loop is executed.

DEPARTMENT OF CSE, BIT 21


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Syntax:
do
{
statements;
} while (condition);
Statement A;

Flowchart:

Example: Program to print first 5 natural numbers.


#include<stdio.h>
main()
{
int i=1; //initializing the variable
printf(“ The first 5 natural numbers are:\n”);
do //do-while loop
{
printf("%d\n",i);
i++; //increment operation
} while(i<=5); // condition
}

DEPARTMENT OF CSE, BIT 22


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Output:
The first 5 natural numbers are:
1
2
3
4
5
2.2.3.2.3 FOR LOOP
Definition:
A “for” loop is a pre-test loop where the condition is checked first and then the body of the
loop is executed. It executes the statements in the loop until the condition of the while loop
evaluates to true. Loop gets terminated when the condition becomes false.
Working:
Step1: Initialize the conditional variable(i=1)
Step 2: Check the condition(i<=5)
Step 3: If the condition is true, execute the steps inside the loop. Then goto step 5
Step 4: If the condition is false, go out the for loop and goto step 6
Step 5: Update the variable(i++) and goto step 2.
Step 6: Execute statement A.
Syntax:
for(initialization; condition; updation)
{
statements;
}
Statement A;
Flowchart:

DEPARTMENT OF CSE, BIT 23


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Example: Program to print first 5 natural numbers.


#include<stdio.h>
main()
{
int i;
printf(“ The first 5 natural numbers are:\n”);
for(i=1;i<=5;i++) //for loop with initialization, condition and updation.
{
printf("%d\n",i);
}
}

Output:
The first 5 natural numbers are:
1
2
3
4
5

DEPARTMENT OF CSE, BIT 24


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

FINDING ROOTS OF A QUADRATIC EQUATION


The standard from of a quadratic equation is ax2+bx+c= 0, where a, b and c are real
numbers and a!=0. The term b2-4ac is known as the determinant of a quadratic equation.
The determinant tells the nature of the roots.
1. If the determinant is greater than 0, then roots are real and distinct.
2. If the determinant is equal to 0, then roots are real and equal.
3. If the determinant is less than 0, then roots are complex and imaginary.
Algorithm: To compute all possible roots of the quadratic equation

Step 1: Start
Step 2: [Input coefficients of quadratic equation]
read a, b, c
Step 3: [Check for the valid coefficients]
if a=0 and b=0 then
print “Invalid coefficients”
else a=0 then
root1 = -c/b
print “Linear equation”
print root
Step 4: [Compute discriminate value]
disc = b+b-4*a*c
Step 5: [Based on discriminate value, classify and calculate all possible roots and print them]
if disc=0 then
root1 = root2 = -b/(2*a)
print “The roots are real and equal”
print root1, root2
else if disc>0 then
root1 = (-b+⎷disc)/(2*a)
root2 = (-b -⎷disc)/(2*a)
print “The roots are real and distinct”
print root1,root2
else
real = -b/(2*a)
imag = ⎷disc / (2*a)
print “The roots are real and complex”
print root1,root2
end if
end if
Start 6: Stop

DEPARTMENT OF CSE, BIT 25


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

Program:

#include<stdio.h>
#include<math.h>
void main()
{
float a,b,c,disc,root1,root2,real,img;
printf("enter a,b,c values\n");
scanf("%f %f %f",&a,&b,&c);
if((a==0)&&(b==0))
{
printf("roots cannot be determined\n");
}
else if(a==0)
{
printf("linear equation\n");
root1=-c/b;
printf("Root1=%.3f\n",root1);
}
else
{
disc=b*b-4*a*c;
if(disc==0)
{
printf("The roots are real and equal\n");
root1=root2=-b/(2*a);
printf("Root1=%.3f\n Root2=%.3f\n",root1,root2);
}
else if(disc>0)
{
printf("The roots are real and distinct\n");
root1=(-b+sqrt(disc))/(2*a);
root2=(-b-sqrt(disc))/(2*a);
printf("Root1=%.3f\n Root2=%.3f\n",root1,root2);
}
else
{
printf("The roots are real and imaginary\n");
real=-b/(2*a);
img=sqrt(fabs(disc))/(2*a);
printf("Root1=%.3f+i%.3f\n Root2=%.3f-i%.3f",real,img,real,img);
}
}
}

DEPARTMENT OF CSE, BIT 26


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

COMPUTATION OF BINOMIAL COEFFICIENTS


The binomial coefficient C(n, r) is the number of ways of picking ‘r’ unordered outcomes
from ‘n’ possibilities, also known as a combination or combinational number.
C(n,r)= n!/((n-r)!*r!)
Algorithm: Calculating factorial of number
Step1: Start
Step2: Read num
Step3: Initialize variable fact to 1
Step4: for i=num to 1
fact=fact*1;
end for
Step5: Print fact
Step6: Stop

Algorithm: Calculating Binomial Coefficient


Step1: Start
Step2: Read n and r
Step3: Initialize variable x, y and z to 1
Step4: Calculate x as factorial of n
Step5: Calculate y as factorial of (n-r)
Step6: Calculate z as factorial of r
Step7: Calculate Binomial coefficient nCr as x/(y*z)
Step8: Stop

Program:
#include<stdio.h>
main()
{
int i,n,r;
long int x=1, y=1, z=1, nCr;
printf(Enter the value of n and r\n”);
scanf(“%d%d”, &n,&r);
for(i=n; i>=1; i--)
{
x=x*i;
}
for(i=n-r; i>=1; i--)
{

DEPARTMENT OF CSE, BIT 27


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

y=y*i;
}
for(i=r; i>=1; i--)
{
z=z*i;
}
nCr=x/(y*z);
printf(“ %dC%d=%d”,n,r,nCr);
}

DEPARTMENT OF CSE, BIT 28


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

PLOTTING OF PASCALS TRIANGLE


The simplest view of Pascal Triangle is that it may be generated by affixing a one on either
end of the new row and then generating all the numbers in between by adding together the two
numbers above them. Ex: 6=3+3.

Algorithm: Plotting Pascal Triangle


Step1: Start
Step2: initialize num to 1
Step3: read number of rows
Step4: for i=0 to rows
for space=1 to rows-1
print “ “
end for
for j=0 to i
if j is equal to 0 (or) i is equal to 0
assign 1 to num
else
calculate num as num *(i-j+1)/j
end if
print num
end for
move to next line using “\n”
end for
Step5: Stop

Program:
#include<stdio.h>
main()
{

DEPARTMENT OF CSE, BIT 29


Download VTU Connect App Now From Google Play Store Go Digital, Go Green, Save Paper
C PROGRAMMING FOR PROBLEM SOLVING

int rows,num=1,space,i,j;
printf("Enter number of rows: ");
scanf(‘%d”,&rows);
for(i=0; i<rows; i++)
{
for(space=1; space<=rows-i; space++)
printf(“ “);
for(j=0; j<=i; j++)
{
if(j==0 || i==0)
num=1;
else
num=num*(i-j+1)/j;
printf(“%4d”,num);
}
printf(“\n”);
}
}

DEPARTMENT OF CSE, BIT 30

You might also like