Professional Documents
Culture Documents
Shadan Women'S College of Engineering & Technology: (Affiliated To JNTU, Hyderabad)
Shadan Women'S College of Engineering & Technology: (Affiliated To JNTU, Hyderabad)
TECHNOLOGY
Primary goal of this course is to make acquaint the students to know the programming
language and also to know how ‘C’ can be used to write serious program on IBM. Here
the main importance is given to the knowledge and concepts that are needed to exploit
the capabilities of the microcomputer through C.
More over programming is a ‘ART’ purely depends on the logic of the problem solving .
As it is said that problem solving has many methods, but the requirement is the efficient
way of solving a problem.
And more over the language C contains the control structures necessary to make
programmers readable and also allows basic concepts like looping, functions, pointers;
file .concepts is to be implemented in variety of ways.
2
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
These are the instructions for the students while attending the lab:
Before entering the lab the student should carry the following
things(mandatory)
2. Class notes
4. Lab manual
5. Lab Record
Student must sign in and sign out in the register provided when attending the
lab session without fail
Come to the lab in time. Students, who are late more than 15 min.,will not be
allowed to attend the lab
Read the manual carefully before coming to the lab and be sure about what
you are supposed to do
Copy all the programs to observation which are taught in clas before attending
the lab session
3
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
REQUIREMENTS
Hardware Requirements:
Processor Pentium I
RAM: 64MB
Hard Disk 100 MB
Software Requirements:
4
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
INTRODUCTION ABOUT C
History of C
ABOUT C LANGUAGE :
DOCUMENTATION SECTION
LINK SECTION
DEFINITION SECTION
Declaration part
Executable part
SUBPROGRAM SECTION
5
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
To develop the program in high level language and translate into machine level
language we are having following steps.
I. Algorithm
6
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
b. Input / Output: Each algorithm can take zero. One or more input data and must
produce one or more output values.
d. Effectiveness: Each step must be effective in the sense that it should be primitive
( easily convertible into program statement) and can be performed exactly in a finite
amount of time.
Step1: Begin
Step2: read a,b
Step3: add a and b and store in variable c
Step4: display c
Step5: stop
II. Flowchart
1. It is possible that the person who formulates the problem is not aware of the
k2details of programming. The programmer is not in a position to formulate the
problem. The flow chart acts as a link between the person who formulates the
problem and the programmer.
2. If the program written by one person is read by another, the job of understanding
the logic is made easier by reference to the flow chart. The flow chart helps the
programmer to modify the existing program.
7
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
III. Programming
A computer program is the list of instructions a computer follows in carrying out its
computations.
8
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
a. Problem understanding:
In Fibonacci series only the first two numbers (0 and 1) are defined.
Each number, after the first, is derived from the sum of its two nearest
predecessors.
Therefore we can say that
New number = sum of last two numbers.
1 = 0+1
2 = 1+1
K2 3 = 1+2
5 = 2+3
8 = 3+5
b. Problem Definition:
Define three variables one for new number and two for the last two numbers, as SUM,
A and B.
A – used to store the number previous to the last number,
B – used to store the last number,
SUM – used to store the sum of A and B.
c. Algorithm development:
Step 1: Read the total number of required values in the series, N.
Step 2: Initialize the variables A and B to 0 and 1 respectively and SUM to 0.
Step 3: Also initialize a Counter I to 2.
Step 4: Compute the next value by adding A and B and store it in SUM.
Step 5: Display the value of SUM.
Step 6: Transfer the value of B to A and SUM to B.
Step 7: Increment the Counter I by 1.
Step 8: If the value of I is less than or equal to N, then go to step4, else go to step 9.
Step 9: End of the program
9
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
KEYWORDS
C89 has 32 keywords (reserved words with special meaning): auto, break, case,
char, const, continue, default, do, double, else, enum, extern, float, for, goto, if,
int, long, register, return, short, signed, sizeof, static, struct, switch, typedef,
union, unsigned, void, volatile, and while.
C99 adds five more keywords: inline, restrict, _Bool, _Complex, and _Imaginary.
OPERATORS
C supports a rich set of operators, which are symbols used within an expression to
specify the manipulations to be performed while evaluating that expression. C has
operators for:
arithmetic: +, -, *, /, %
assignment: =
augmented assignment: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
bitwise logic: ~, &, |, ^
bitwise shifts: <<, >>
boolean logic: !, &&, ||
conditional evaluation: ? :
equality testing: ==, !=
calling functions: ( )
increment and decrement: ++ and --
Member selection: ., ->
object size: sizeof
order relations: <, <=, >, >=
reference and dereference: &, *, [ ]
sequencing: ,
sub expression grouping: ( )
type conversion: (typename)
10
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
PROGRAMS
Week: 1 (A)
Description:
To find factors of a given number is nothing but factorial of a number
Ex: factorial of 5 is 5*4*3*2*1=120.
Algorithm:
Step 1. Start
Step 2. Read the number n
step 3. [Initialize]
i=1, fact=1
step 4. Repeat step 4 through 6 until i=n
step 5. fact=fact*i
step 6. i=i+1
step 7. Print fact
step 8. Stop
Flow Chart:
11
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Program:
#include<stdio.h>
#include<conio.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,fact=1;
printf("Enter any number : ");
scanf("%d", &n);
for(i=1; i<=n; i++)
fact = fact * i;
printf("Factorial value of %d = %d",n,fact);
}
Output:
Enter any number : 5
Factorial value of 5 is :120.
Record at least 3 results
Week- 1 (B)
Write a C program to find the roots of a quadratic equation
Description
Nature of roots of quadratic equation can be known from the quadrant = b2-4ac
If b2-4ac >0 then roots are real and unequal
If b2-4ac =0 then roots are real and equal
If b2-4ac <0 then roots are imaginary
Algorithm:
Step 1: start
Step 2: read the a,b,c value
Step 3: if b*b-4ac>0 then
Root 1= (-b+ pow((b*b-4*a*c),0.5))/2*a Root 2= (-b-
pow((b*b-4*a*c),0.5))/2*a
Step 4: if b*b-4ac=0 then
Root1 = Root2 = -b/(2*a)
Step 5: Otherwise Print Imaginary roots. Goto step 7.
Step 6: print roots
Step 7: stop
12
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Program:
#include<stdio.h>
#include<math.h>
void main()
{
float a,b,c,r1,r2,d; clrscr();
printf("Enter the values for equation:");
scanf("%f%f%f",&a,&b,&c);
/* check the condition */
if(a==0)
printf("Enter value should not be zero ");
else
{
d=b*b-4*a*c;
/* check the condition */
if(d>0)
{
13
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
r1=(-b+sqrt(d)/(2*a));
r2=(-b-sqrt(d)/(2*a));
printf("roots are real and unequal\n");
printf("%f\n%f\n",r1,r2);
}
else if(d==0)
{
r1=-b/(2*a);
r2=-b/(2*a);
printf("roots are real and equal\n");
printf("root=%f\n",r1);
printf("root=%f\n",r2);
}
else
printf("roots are imaginary");
}
getch();
}
Output:
1. Enter the values for equation: 1, 6, 9
Roots are real and equal
Root= -3.0000 Root= -
3.0000
2. Enter the values for equation: 2, 7, 6
Roots are real and unequal
Root= -6.75
Root= -7.25
3. Enter the values for equation: 1, 2, 3
Roots are imaginary
Record
2 at least 3 results
14
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Week – 2
2-A) Write a C program to determine if the given number is a prime number or not.
Description:
Prime number is a number which is exactly divisible by one and itself only
Ex: 2, 3,5,7,………;
Program:
#include <stdio.h>
void main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i<=n/2; ++i)
{
// condition for nonprime number
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
getch();
}
Output:
15
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
2-B). A Fibonacci sequence is defined as follows: the first and second terms in the
sequence are 0 and 1. Subsequent terms are found by adding the preceding two
terms in the sequence. Write a C program to generate the first n terms of the
sequence.
Description:
A Fibonacci series is defined as follows:
The first term in the sequence is 0
The second term in the sequence is 1
The sub sequent terms 1 found by adding the preceding two terms in the
sequence Formula: let t1,t2,…………tn be terms in Fibonacci sequence
t1=0, t2=1 tn=tn-2+tn-1……where n>2
Algorithm:
Step 1: start
Step 2: initialize the=0, b=1
Step 3: read n
Step 4: if n== 1 print a go to step 7. else goto step 5
Step 5: if n== 2 print a, b go to step 7 else print a,b
Step 6: initialize i=3
i) if i<= n do as follows. If not goto step 7
c=a+b
print c
a=b b=c
increment i value
goto step 6(i)
Step 7: stop
Flow Chart:
16
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
2-B) A Fibonacci sequence is defined as follows: the first and second terms in the
sequence are 0 and 1. Subsequent terms are found by adding the preceding two terms
in the sequence. Write a C program to generate the first n terms of the sequence.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,n,i;
clrscr();
printf("enter n value");
scanf("%d",&n);
a=0;
b=1;
if(n==1)
printf("%d",a);
else if(n==2)
printf("%d%d",a,b);
else
{
printf("%d%d",a,b);
//LOOP WILL RUN FOR 2 TIME LESS IN SERIES AS THESE WAS
PRINTED IN ADVANCE
for(i=2;i<n;i++)
{
c=a+b;
printf("%d",c);
a=b;
b=c;
}
}
getch();
}
Output:
1. Enter n value : 5
01123
2 Record at least 3 results
17
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Week – 3
3-A). Write a C program to construct a pyramid of numbers
Description:
In this program the we have to construct output in the pyramid shape manner
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("Enter pyramid range:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n-i;j++)
printf(" ");
for(j=0;j<i;j++)
printf("%d ",i);
printf("\n");
}
getch();
}
Output:
1
22
333
4444
55555
Record at least 3 results
18
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Algorithm:
Main program:
Step 1: start
Step 2: declare x,i,n,s=0,c
Step 3: read x value
Step 4: for i=0 , n=0; i<=10; i=i+2, n++ goto step 5
Step 5: s=s+(pow(-1,n)*pow(x,i)/fact(i))
Step 6: print s value
Step 7: stop
Sub program:
Step 1: while x!=0 goto Step 2
Step 2: y=y+x; x—
Step 3: return y
Step 4: return to main program
Flow Chart:
19
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Program:
#include<stdio.h>
#include<math.h>
long fact(int);
void main()
{
int x,i,n;
float s=0,c;
clrscr();
printf("\n enter the value of x\t");
scanf("%d",&x);
/*perform the looping operation*/
for(i=0,n=0;i<=10;i=i+2,n++)
s=s+(pow(-1,n)*pow(x,i)/fact(i));
printf("\n the result is %f",s);
getch();
}
/* calling sub program*/
long fact(int x)
{
long int y=1;
while(x!=0)
{
y=y*x;
x--;
}
return y;
}
Output:
1. Enter the value of x : 1
The result is 0.540302
Record at least 3 results
20
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Week – 4
4-A).The least common multiple (LCM) of two positive integers a and b is the smallest
integer that is evenly divisible by both a and b. Write a C program that reads two
integers and calls LCM (a, b) function that takes two integer arguments and
returns their LCM. The LCM (a, b) function should calculate the least common
multiple by calling the GCD (a, b) function and using the following relation:
Description:
LCM of these sets of numbers. Multiply each factor the greatest number of times it
occurs in any of the numbers. 9 has two 3s, and 21 has one 7, so we multiply
3 two times, and 7 once. This gives us 63, the smallest number that can be divided
evenly by 3, 9, and 21.
GCD means Greatest Common Divisor. i.e the highest number which divides the
given number
Ex: GCD (12,24) is 12
Formula: GCD= product of numbers/ LCM of numbers
LCM (Least Common Multiple) of two numbers is the smallest number which can be
divided by both numbers.
For example LCM of 15 and 20 is 60 and LCM of 5 and 7 is 35.
LCM of two numbers ‘a’ and ‘b’ can be calculated using following formula.
a x b = LCM(a, b) * GCD (a, b)
LCM(a, b) = (a x b) / GCD(a, b)
Program:
#include <stdio.h>
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
21
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
void main()
{
int a, b;
clrscr();
printf(“\n Enter a, b values:\n”);
scanf(“%d%d”,&a,&b);
printf("\n LCM of %d and %d is %d ", a, b, lcm(a, b));
getch();
}
Output:
Enter a, b values:
15
20
LCM of 15 and 20 is 60
Record at least 3 results
4- B). Write a C program that reads two integers n and r to compute the ncr value
using the following relation:
nC (n, r) = n! / r! (n-r)! . Use a function for computing the factorial value of an
r
integer.
Description:
#include<stdio.h>
void main()
{
int n,r,ncr;
clrscr();
printf("\n Enter the value of n and r: ");
scanf("%d %d",&n,&r);
ncr=fact(n)/(fact(r)*fact(n-r));
printf("\n The NCR factor of %d and %d is %d",n,r,ncr);
getch();
}
22
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
int fact(int n)
{
int i=1;
while(n!=0){
i=i*n;
n--;
}
return i;
}
OUTPUT
Week – 5
5- A). Write C program that reads two integers x and n and calls a recursive function
to compute xn.
#include <stdio.h>
#include <conio.h>
void main()
{
int x, y;
double result;
clrscr();
printf("Enter any number: ");
scanf("%d", &x);
printf("Enter power of the number: ");
scanf("%d", &y);
getch ();
}
Output:
Week – 5
5-B). Write a C program that uses a recursive function to solve the Towers of Hanoi
problem.
Description:
24
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
The algorithm or the working procedure, which is to be repeated for a finite number
of steps, is illustrated below:
A, B and C are rods or pegs and n is the total number of discs, 1 is the largest disk and 5
is the smallest one.
Move n-1 discs from rod A to B which causes disc n alone in on the rod A
Transfer the disc n from A to C
Transfer n-1 discs from rod B to C so that they sit over disc n
Program:
/* C Program to Solve Towers of Hanoi Problem */
#include<stdio.h>
void main()
{
int disks;
char source, destination, aux;
clrscr();
printf("\nEnter No. of Disks:");
scanf("%d",&disks);
printf("\nEnter Source, Destination and Auxillary Disk Names:");
scanf("%s%s%s",source, destination, aux);
hanoi(disks,source,destination,aux);
getch();
}
25
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Output:
26
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
5- C). Write a C program that reads two integers and calls a recursive function to
compute ncr
Description:
Example:
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
Program:
# include <stdio.h>
# include <conio.h>
long fact(int) ; //function is declared at the top first.
void main()
{
long i, ncr ;
int n, r ;
clrscr() ;
printf("Enter the value for N : ") ;
scanf("%d", &n) ;
printf("\nEnter the value for R : ") ;
scanf("%d", &r) ;
if(n >= r)
{
ncr = fact(n) / (fact(n-r) * fact(r)) ;
printf("\n The NCR value is : %ld", ncr) ;
}
else
printf("\n Calculating NCR value is not possible") ;
getch() ;
}
27
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
long fact(int i)
{
long x ;
if(i == 0)
return 1 ;
else
{
x = i * fact(i - 1) ;
return x ;
}
}
OUTPUT:
Week- 6
6- A) Write a C program to generate all the prime numbers between 1 and n, where n
is a value supplied by the user using Sieve of Eratosthenes algorithm.
Description:
Prime number is a number which is exactly divisible by one and itself only
Ex: 2, 3, 5, 7…
Algorithm:
Step 1: start
Step 2: read n
Step 3: initialize i=1,c=0
Step 4:if i<=n goto step 5 If not goto
step 10
Step 5: initialize j=1
Step 6: if j<=1 do as the follow. If no goto step 7 i)ifi%j==0
increment c
ii) increment j
iii) goto Step 6
Step 7: if c== 2 print i
Step 8: increment i
Step 9: goto step 4
28
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Flow Chart:
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,fact,j;
clrscr();
printf("\n Enter the number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact=0;
//THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT.
for(j=1;j<=i;j++)
{
if(i%j==0)
fact++;
}
if(fact==2)
printf("\n %d",i);
}
getch( );
29
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Output:
6-B). Write a C program that uses non recursive function to search for a Key value in
a given list of integers. Use linear search method.
Description:
The linear search is most simple searching method. It does not expect the list
To be sorted. The key which is to be searched is compared with each element of the
list one by one. If a match exists, the search is terminated. If the end of list is
reached it
If the search has failed and key has no matching in the list.
Algorithm:
1. Start
5. search<--linear(a,n,x)
9. stop
30
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Program:
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,n,a[10],key;
clrscr();
for(i=0;i<=n;i++)
{
if(key==a[i])
{
printf("\nElement %d found at %d",key,i+1);
break;
}
}
if(i==n)
printf("\n Element %d not found in array",key);
getch();
}
Output:
enter range for array:4
enter elements into array:
56 43 12 88 9
31
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Week – 7
7- A). Write a menu-driven C program that allows a user to enter n numbers and then
choose between finding the smallest, largest, sum, or average. The menu and
all the choices are to be functions. Use a switch statement to determine what
action to take. Display an error message if an invalid choice is entered.
Program:
#include<stdio.h>
void main()
{
int array[50],c,small,large,sum=0,n,i;
float avg;
printf("Enter the size of the elements\n");
scanf("%d",&n);
printf("Enter the elements into the array\n");
for(i=0;i<n;i++)
scanf("%d",&array[i]);
printf("1: Smallest\n2:Largest\n3:Sum\n4:Average\n");
printf("Enter your choice\n");
scanf("%d",&c);
switch(c)
{
case 1: small=array[0];
for(i=0;i<n;i++)
{
if(small>array[i])
small=array[i];
}
printf("Smallest element in the list=%d",small);
break;
case 2:large=array[0];
for(i=0;i<n;i++)
{
if(large<array[i])
large=array[i];
}
printf("Largest element in the list=%d",large);
break;
case 3:
for(i=0;i<n;i++)
{
sum=sum+array[i];
}
printf("sum of elements in the list=%d",sum);
break;
case 4:for(i=0;i<n;i++)
{
sum=sum+array[i];
32
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
}
avg=sum/n;
printf("avg of elements in the list=%f",avg);
break;
default:
printf("Invalid choice\n");
}
}
OUTPUT:
Enter the size of the elements 2
Enter the elements into the array
46
1: Smallest
2:Largest
3:Sum
4:Average
Enter your choice 1
Smallest element in the list=4
7- B) Write a C program that uses non recursive function to search for a Key value in
a given sorted list of integers. Use binary search method.
Description:
Binary search is a vast improvement over the sequential search.
For binary search to work, the item in the list must be in assorted order.
The approach employed in the binary search is divide and conquer.
If the list to be sorted for a specific item is not Sorted, binary search fails.
ALGORITHM:
BINARY SEARCH
1. Start
2. Read the value of n
3. for i=1 to n increment in steps of 1
Read the value of ith element into array
4. Read the element(x) to be searched
5. search<--binary(a,n,x)
6. if search equal to 0 goto step 7 otherwise goto step 8
7. print unsuccessful search
8. print successful search
9. stop
1. start
2. initialise low to 1 ,high to n, test to 0
3. if low<= high repeat through steps 4 to 9 otherwise goto step 10
Program:
/*write a c program for implementing binary search method using function */
#include<stdio.h>
#include<conio.h>
int BinarySearching(int arr[20], int max, int element)
{
int low = 0, high = max - 1, middle;
while(low <= high)
{
middle = (low + high) / 2;
if(element > arr[middle])
low = middle + 1;
else if(element < arr[middle])
high = middle - 1;
else
return middle;
}
return -1;
}
void main()
{
int i, element, limit, arr[50], position;
printf("Enter the Limit of Elements in Array:\t");
scanf("%d", &limit);
printf("Enter %d Elements in Array: \n", limit);
for(i = 0; i < limit; i++)
scanf("%d", &arr[i]);
34
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
35
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Week – 8 (A)
Write a C program that implements the Bubble sort method to sort a given list of
integers in ascending order.
Description:
Bubble sort is the simplest and oldest sorting technique.
This method takes two elements at a time. It compares these two elements. If first
elements are less than second one, they are left un-disturbed. If the first element is
greater than second one then they are swapped.
The procedure continues with the next two elements goes and ends when all the
elements are sorted.
But bubble sort is an inefficient algorithm.
The order of bubble sort algorithm is O(n2).
1. start
2. read the value of n
3. for i= 1 to n increment in steps of 1
Read the value of ith element into array
4. call function to sort (bubble_sort(a,n))
5. for i= 1 to n increment in steps of 1
print the value of ith element in the array
6. stop
Program:
#include<stdio.h>
void main()
{
int i,j,t,a[5],n;
clrscr();
printf("\n Enter the range of array:");
scanf("%d",&n);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\n The sorted order is:");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
getch();
}
Input/Output:
Enter the range of array: 3
Enter elements into array: 3 2 1
the sorted order
is: 1 2 3
37
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Week – 8 (B)
Write a C program that reads two matrices and uses functions to perform the
following:
(i). Addition of two matrices
(ii).Multiplication of two matrices
Description:
Program takes the two matrixes of same size and performs the addition an also
takes the two matrixes of different sizes and checks for possibility of
multiplication and perform multiplication if possible.
Algorithm:
Step 1: start
Step 2: read the size of matrices A,B – m,n
Step 3: read the elements of matrix A
Step 4: read the elements of matrix B
Step 5: select the choice for you want. If you select case 1 then goto matric
addition.Else goto Step 7.
Step 6: print Sum of matrix A and B
Step 7: if you select case 2 then goto matrix multiplication
Step 8: check if n=p, if not print matrices cannot be multiplied
Step 9: Otherwise perform the multiplication of matrices
Program:
#include<stdio.h>
void main()
{
int ch,i,j,m,n,p,q,k,r1,c1,a[10][10],b[10][10],c[10][10];
clrscr();
printf("************************************");
printf("\n\t\tMENU");
printf("\n**********************************");
printf("\n[1]ADDITION OF TWO MATRICES");
printf("\n[2]MULTIPLICATION OF TWO MATRICES");
printf("\n[0]EXIT");
printf("\n**********************************");
printf("\n\tEnter your choice:\n");
scanf("%d",&ch);
if(ch<=2 &ch>0)
{
38
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
printf("Valid Choice\n");
}
switch(ch)
{
case 1:
printf("Input rows and columns of A & B
Matrix:");
scanf("%d%d",&r1,&c1);
printf("Enter elements of matrix
A(r1*C1):\n"); for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements of matrix
B(r1*C1):\n"); for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&b[i][j]);
}
printf("\n =====Matrix Addition=====\n");
for(i=0;i<r1;i++)
{
For(j=0;j<c1;j++)
printf("%5d",a[i][j]+b[i][j]);
printf("\n");
}
break;
case 2:
printf("Input rows and columns of A matrix:");
scanf("%d%d",&m,&n);
printf("Input rows and columns of B matrix:");
scanf("%d%d",&p,&q);
if(n==p)
{
printf("matrices can be multiplied\n");
printf("resultant matrix is %d*%d\n",m,q);
printf("Input A matrix\n");
read_matrix(a,m,n);
printf("Input B matrix\n"); /*Function call to read
matrix*/
read_matrix(b,p,q);
/*Function for Multiplication of two matrices*/
printf("\n =====Matrix Multiplication=====\n");
for(i=0;i<m;++i)
for(j=0;j<q;++j)
{
39
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
c[i][j]=0;
for(k=0;k<n;++k)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
case 0:
printf("\n Choice Terminated"); exit();
break;
default:
printf("\n Invalid Choice");
}
getch();
}
40
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Output:
1.
************************************
MENU
**********************************
[1]ADDITION OF TWO MATRICES [2]MULTIPLICATION
OF TWO MATRICES [0]EXIT
**********************************
Enter your choice:
1
Valid Choice
Input rows and columns of A & B Matrix:2 2
Enter elements of matrix A: 2 2 2 2
Enter elements of matrix B: 2 2 2 2
=====Matrix Addition=====
4 4
4 4
************************************
MENU
**********************************
[1]ADDITION OF TWO MATRICES [2]MULTIPLICATION
OF TWO MATRICES [0]EXIT
**********************************
Enter your choice:
2
Valid Choice
Input rows and columns of A matrix:2 3
Input rows and columns of B matrix:2 2
Matrices cannot be multiplied.
************************************
MENU
**********************************
[1]ADDITION OF TWO MATRICES [2]MULTIPLICATION
OF TWO MATRICES [0]EXIT
**********************************
Enter your choice:
2
Valid Choice
Input rows and columns of A matrix: 2 2
Input rows and columns of B matrix: 2 2
Matrices can be multiplied resultant matrix
is 2*2 Input A matrix 2 2 2 2
Input B matrix 2 2 2 2
=====Matrix Multiplication=====
Resultant of two matrices:
8 8
8 8
Record 2 results:
41
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Week – 9 (A)
Write a C program that uses functions to perform the following operations:
i). to insert a sub-string into a given main string from a given position.
ii). to delete n characters from a given position in a given string.
i). to insert a sub-string into a given main string from a given position.
Description:
In this program we need to insert a string into another string from a specified
position.
Algorithm:
Step 1: start
Step 2: read main string and sub string Step 3:
find the length of main string(r) Step 4:
find length of sub string (n)
Step 5: copy main string into sub string
Step 6: read the position to insert the sub string (p)
Step 7: copy sub string into main string from position p-1
Step 8: copy temporary string into main string from position p+n-1 Step
Step9: print the strings
Step 10: stop
Program:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char a[10];
char b[10];
char c[10];
int p=0,r=0,i=0;
int t=0;
int x,g,s,n,o;
clrscr();
puts("\n Enter First String:");
gets(a);
puts("\n Enter Second String:");
gets(b);
printf("\n Enter the position where the item has to be inserted: ");
42
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
scanf("%d",&p);
r = strlen(a);
n = strlen(b);
i=0;
//Copying the input string into another array
while(i <= r)
{
c[i]=a[i];
i++;
}
s = n+r;
o = p+n;
//Adding the sub-string
for(i=p;i<s;i++)
{
x = c[i]; if(t<n)
{
a[i] = b[t]; t=t+1;
}
a[o]=x;
o=o+1;
}
printf("%s", a);
getch();
}
Output:
1.enter first string: computer
enter second string: gec
enter the position where the item has to be inserted:3 comgecputer
Record 2 Results:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void delchar(char *x,int a, int b);
void main()
{
char string[10];
int n,pos,p;
clrscr();
puts("\n Enter the string:");
gets(string);
printf("\n Enter the position from where to delete: ");
scanf("%d",&pos);
printf("\n Enter the number of characters to be deleted: ");
scanf("%d",&n);
43
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
delchar(string, n,pos);
getch();
}
{
if ((a+b-1) <= strlen(x))
{
strcpy(&x[b-1],&x[a+b-1]);
puts(x);
}
}
Output:
Week – 9(B)
Write a C program that uses a non recursive function to determine if the given string
is a palindrome or not.
Description:
In this program we have to read the string and check for the given string is
palindrome or not.
Palindrome means when the string is reverse also it should be the same as
given string.
Program:
#include<stdio.h>
#include<string.h>
{
if (str[l++] != str[h--])
{
printf("\n %s is Not Palindrome\n", str);
return;
}
}
printf("\n %s is palindrome\n", str);
}
void main()
{
char string[40];
clrscr();
printf("\n ****Program to test if the given string is a
palindrome****\n"); printf("\n Enter a string:");
scanf("%s",string);
isPalindrome(string);
getch();
}
Output:
1. Enter the string: malayalam
malayalam is a palindrome
Week – 10 (A)
Program:
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
char text[100],word[10],rpwrd[10],str[10][10];
int i=0,j=0,k=0,w,p;
clrscr();
45
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
if (text[k]!=' ')
{
str[i][j] = text[k];
j++;
}
else
{
str[i][j]='\0';
j=0; i++;
}
}
str[i][j]='\0';
w=i;
for (i=0; i<=w; i++)
{
if(strcmp(str[i],word)==0)
strcpy(str[i],rpwrd);
printf("%s ",str[i]);
}
getch();
}
Output:
46
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Week – 10 (B)
Write a C program that reads 15 names each of up to 30 characters, stores them in
an array, and uses an array of pointers to display them in ascending (i.e. alphabetical)
order
Description:
In this program we have to take 15 names, and print them in ascending order
Program:
#include <stdio.h>
#include <string.h>
void main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;
clrscr();
printf("Enter the value of n \n");
scanf("%d", &n);
printf("Enter the names n”);
for (i = 0; i < n; i++)
{
scanf("%s", name[i]);
strcpy(tname[i], name[i]);
}
for (i = 0; i < n - 1 ; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf("\n----------------------------------------\n");
printf("Input NamestSorted names\n");
printf("------------------------------------------\n");
for (i = 0; i < n; i++)
{
printf("%s\t\t%s\n", tname[i], name[i]);
}
printf("------------------------------------------\n");
getch();
}
47
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Output:
----------------------------------------
Input Names Sorted names
------------------------------------------
heap class
stack heap
queue object
object program
class project
program queue
project stack
------------------------------------------
Week – 11(A)
2’s complement of a number is obtained by scanning it from right to left and
complementing all the bits after the first appearance of a 1. Thus 2’s complement of
11100 is 00100. Write a C program to find the 2’s complement of a binary number.
Description:
In this program the given binary number is first covert the numbers 0 to1 and 1 to 0.
And finally add the 1 to the converted number. Then we will get the 2’s complement
number.
Algorithm:
Step 1: Start
Step 2: declare the subprogram “complement(char *a)” Step 3:
initialize the variable i
Step 4: read the binary number
Step 5: perform the loop operation. if it is true then follows. if not goto step 7
i) for(i=0;a[i]!=’\0’;i++)
ii) if(a[i]!=’0’&&a[i]!=’1’) then displayed the number is not valid. enter the
correct number.
iii) Exit the loop
Step 6: call sub program ‘complemt(a)’ . Step 7: stop
Sub program:
48
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
49
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
}
for(i=l-1; i>=0; i--)
{
if(i==l-1)
{
if (b[i]=='0')
b[i]='1';
else
{
b[i]='0';
c=1;
}
}
else
{
if(c==1 && b[i]=='0')
{
b[i]='1';
c=0;
}
else if (c==1 && b[i]=='1')
{
b[i]='0';
c=1;
}}}
b[l]='\0';
printf("The 2's complement is %s", b);
}
Output:
1. Enter the binary number101010
The 2's complement is 010110
Week – 11 (B)
Write a C program to convert a positive integer to a roman numeral. Ex. 11 is
converted to XI.
Description:
In this program we have convert the given decimal number to roman
number.
Program:
#include<stdio.h>
#include<conio.h>
#include<process.h>
50
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
FILE *fs,*ft;
char ch;
clrscr();
if(argc!=3)
{
puts("Invalid number of arguments.");
exit(0);
}
fs = fopen(argv[1],"r");
if(fs==NULL)
{
puts("Source file cannot be opened.");
exit(0);
}
ft = fopen(argv[2],"w");
if (ft==NULL) // check the condition if the file pointer is NULL or not
{
puts("Target file cannot be opened.");
fclose(fs);
exit(0);
}
while(1)
{
ch=fgetc(fs);
if (ch==EOF) // check the condition if the file is end or not
break;
else
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
getch();
}
Output:
source.c
this is source text ouput.c
Command line arguments
source.c ouput.c source.c
this is source text ouput.c
this is source text
Command line arguments
source.c
Invalid number of arguments.
51
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
Week – 12 (A)
A. Write a C program to display the contents of a file to standard output device.
procedure:
1. Declare a file pointer fp in read mode
2. Read the characters of file
3. Write to characters to stdout.
This program takes the number from user and stores in file. After you compile
and run this program, you can see a text file program.txt created in C drive of
your computer. When you open that file, you can see the integer you entered.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen(“one.txt”, “w”);
printf(“\n Enter Data press Ctrl+Z:\n”);
while( ( ch=getchar() )!=EOF)
{
Putc(ch,fp);
}
fclose(fp);
fp=fopen(“one.txt”, “r”);
printf(“\n The output data is:\n”);
while( ( ch=getc() ) ! = EOF)
printf(“%c”, ch);
fclose(fp);
getch();
}
OUTPUT:
Enter Data press Ctrl+Z:
This is cp class^z
The output data is:
This is cp class
12-B) Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents.
#include<stdio.h>
#include<process.h>
void main()
{
FILE *fp1, *fp2;
52
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
char a;
clrscr();
fp1=fopen(“test.txt”, “w”);
printf(“\n Enter Data press Ctrl+Z:\n”);
while( ( ch=getchar() )!=EOF)
{
Putc(ch,fp1);
}
fclose(fp1);
fcloseall();
getch();
}
OUTPUT:
Enter Data press Ctrl+Z:
This is cp class^z
The text in UPPER CASE:
THIS IS CP CLASS
13-A) Write a C program to count the number of times a character occurs in a text
file. The file name and the character are supplied as command-line arguments.
#include <stdio.h>
void main()
{
FILE *fp;
char ch,temp;
int freq = 0;
53
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
clrscr();
fp=fopen(“file.txt”, “w”);
printf(“\n Enter Data press Ctrl+Z:\n”);
while( ( ch=getchar() )!=EOF)
{
Putc(ch,fp);
}
fclose(fp);
fp = fopen(“file.txt”, "r");
while(!feof(fp))
{
tmp = fgetc(fp);
if (tmp == ch)
freq++;
}
OUTPUT:
Enter Data press Ctrl+Z:
This is cp class ^z
Enter the character to be counted: s
The File has 4 instances of letter s.
13-B). Write a C program to compare two files, printing the first line where they
differ.
#include <stdio.h>
void compare_two_binary_files(FILE *,FILE *);
int main(int argc, char *argv[])
{
FILE *fp1, *fp2;
if (argc < 3)
{
printf("\nInsufficient Arguments: \n");
printf("\nHelp:./executable <filename1> <filename2>\n");
return;
}
54
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
else
{
fp1 = fopen(argv[1], "r");
if (fp1 == NULL)
{
printf("\nError in opening file %s", argv[1]);
return;
}
if (fp2 == NULL)
{
printf("\nError in opening file %s", argv[2]);
return;
}
/*
* compare two binary files character by character
*/
void compare_two_binary_files(FILE *fp1, FILE *fp2)
{
char ch1, ch2;
int flag = 0;
break;
}
}
if (flag == 0)
{
printf("\n Two files are not equal : byte poistion at which two files differ is
%d\n", ftell(fp1)+1);
}
else
{
printf("\n Two files are Equal\n ", ftell(fp1)+1);
}
}
OUTPUT:
welcome to shadan
welcome to jntuh
14- A) Write a C program to change the nth character (byte) in a text file. Use fseek
function
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
FILE *fp;
char ch;
int n;
fp = fopen("random.txt","r+");
printf("Enter n value\n");
scanf("%d",&n);
printf("Enter charcter value\n");
scanf(" %c",&ch);
fseek(fp,n-1,0);
fputc(ch,fp);
fclose(fp);
}
Before excution
Random.txt
abcdefghijklmnopqrstuvwxyz
OUTPUT:
Enter the n value
4
Enter the character
a
after execution
abca abcdefghijklmnopqrstuvwxyz
56
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
14-B) Write a C program to reverse the first n characters in a file. The file name and n
are specified on the command line. Use fseek function.
Algorithm:
Step 1: Start
Step 2: read the command line arguments
Step 3: check if arguments = 3 or not If not print invalid no of arguments
Step 4: open source file in read mode
Step 5: if NULL pointer, then print file can not be open
Step 6: Store no of chars to reverse in k.K = *argv[2] - 48
Step 7: read the item from file stream using fread
Step 8: Store chars from last position to initial position in another string(temp)
Step 9: print the temp string
Step 10: Stop
Program:
#include<stdio.h >
#include<conio.h >
#include<string.h >
#include<process.h >
void main(int argc, char *argv[])
{
FILE *fs, *fd;
char s[20], d[20];
int c = 0, count = 0, n;
clrscr();
strcpy(s, argv[1]);
n = atoi(argv[2]);
fs = fopen(s, "r");
if(s == NULL)
printf("\n FILE ERROR");
printf("\n SOURCE FILE :\n");
while(!feof(fs))
{
printf("%c", fgetc(fs));
c++;
}
fclose(fs);
fs = fopen(s, "r+");
count = 0;
while(count < n)
{
d[count] = fgetc(fs);
count++;
}
57
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
d[count] = '\0';
fseek(fs, 0L, 0);
fputs(strrev(d), fs);
fclose(fs);
fs = fopen(s,"r");
while(!feof(fs))
{
printf(“\n REVERSE FILE: %c”, fgetc(fs));
c++;
}
fclose(fs);
getch();
}
OUTPUT
REVERSE FILE:balpc
15-A) Write a C program to merge two files into a third file (i.e., the contents of the
firs t file followed by those of the second are put in the third file).
#include<stdio.h>
#include<stdlib.h>
void main()
{
fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");
exit(EXIT_FAILURE);
}
ft = fopen(file3,"w");
if( ft == NULL )
{
perror("Error ");
exit(EXIT_FAILURE);
}
fclose(fs1);
fclose(fs2);
fclose(ft);
getch();
}
OUTPUT:
15- B) Define a macro that finds the maximum of two numbers. Write a C program
that uses the macro and prints the maximum of two numbers.
59
SWCET DEPT. OF CSE COMPUTER PROGRAMMING THROUGH C
#include<stdio.h>
void main()
{
int a,b;
clrscr();
printf("\n ENTER NUMBERS TO FIND MAXIMUM:\n");
printf("\nENTER FIRST NUMBER : ");
scanf("%d", &a);
printf("\nENTER SECOND NUMBER : ");
scanf("%d", &b);
printf("\nTHE MAXIMUN NUMBER IS: %d", MAX(a,b));
printf("\nThe MININUM NUMBER IS:%d", MIN(a,b));
getch();
}
OUTPUT:
60