You are on page 1of 59

Navin Chandra P Meenu Jayamohan Harsh S Suresh Karthika M R Vaisakh S

INTRODUCTION C is a general purpose programming language, originally designed by Dennis Ritchie in 1972 at Bell laboratories. In 1988, it was standardized by the American National Standards Institute (ANSI) and named as ANSI C. C, a powerful language, is used for many purposes like Writing operating systems, business and scientific applications and even the C compiler itself. It is not tied to any particular hardware and programs written in C are portable across any system. The programs written in C are efficient and fast. It is one of the most popular computer languages today. C FEATURES (1) C constants are numbers, which do not change during execution of a program. These may be of three types

Type Integer Floating point (Real) String

Example 27, 10897 etc. 2.723, 0.123 etc. "Focuz magazine"

The string constants are enclosed in double quotes ( ). (2) C variables can contain different C constants during the execution of the program. These are declared in a C program by first specifying the type int for an integer and float for the floating point value and then the variable names separated by commas. The general format is: Type list of variables For example to declare integer variables the statement is int a, b, c; and to declare a floating point variables it is float a, b, c; Variables can be initialized at the same time as they are declared. For e.g. float a = 1.5; Rules for naming C variables : A variable name may contain only alphabets, digits and the underscore (_). It must begin with a alphabet or an underscore. It can be as long as you wish, but on some C systems only first 31 characters are considered. Note. Lower case and upper case alphabets are treated as different in C. For e.g. Num and num are two entirely different variable names. As a matter of convention, lower case alphabets are used. (3) Arrays : An array is an aggregate of variables of the same type. These variables are called elements of the array. The following statements declare arrays in C: int b[10]; float c[2][2]; declares a as a float variable having a value 1.5.

The first statement creates a 1-dimensional array named b having 10 elements, each element being referred by an appropriate subscript in rectangle brackets i.e. b[1], b[2],.b [9]. The second statement creates a 2-dimensional array named c having 4 elements c [0][0], c[0][1], c[1][0], c[1][1]. Rules for naming of arrays are same as those for variable names. Note. Subscripts always start from zero in C. (4) User defined types : Apart from the built in types int and float C allows users to define an identifier that can represent an existing data type. The syntax is : typedef type identifier For e.g. typedef int number ; typedef float matrix [2][2]; The first statement defines number to mean the same as int. The second defines matrix to be mean same as 2 x 2 array of float. The above two statements enable declarations of the form number a, b, c; which declares 3 integers a, b and c, and matrix x; which declares a two dimensional array x having 4 elements x[0][0], x[0][1], x[1][0] and x[1][1]. Initialization of Arrays at the time of declaration The syntax is: type array-name [size] = {list of values} for e.g. int a[2] = {2, 1}; initializes a[0] to 2 and a[1] to 1. int a[2][2] = {{0, 1}, {3, 5}} initializes a[0][0] to 0, a[0][1] to 1, a[1][0] to 3 and a[1] [1] to 5. (5) Arithmetic operators : These are as follows Symbol

Symbol + * /

Use Addition Subtraction Multiplication Division

while using the operators, the following order of precedence is adopted (i) * , / (ii) +, In case, the order of operators is to be changed, circular brackets are used. There is no exponentiation operator in C, but there are various library functions available for the same. For e.g. to calculate the square root sqrt function is used.

(6) Mathematical expressions consist of a sequence of arithmetic operators and variable names. For e.g. i. ii. iii. iv. v. vi. a + b is written as a + b. + c is written as a/b + c. is written as a/(b + c). 4 is written as sqrt (b*b - 4*a*c). (+)is written as alpha * (beta + gamma). is written as exp (b*ln (a))

Note. The multiplication operator has to be written explicitly(ie no expression as ab, only a*b). In C, its presence is never assumed. exp and In are library functions. (7) Arithmetic statements are of the form var = exp ; where var is an integer or a floating point variable. exp is a mathematical expression written in C format. The = sign has a special meaning. It tells C to calculate the value of exp and assign it to var. For e.g. n=i*i A C statement is always terminated by a semi colon ( ; ). C also permits statements of the type k=n=i*i; This is equivalent to the following statements n=i*i; k=n; Note. To test the equality of two expressions C uses = = (8) Shorthand assignment operators : Apart from the assignment operator =, C also support certain short hand assignment operators (+ +, + =, - =, * =, / =). Their use is illustrated by the following examples. calculates the value of i * i and assigns the result to the variable n. If i = 10, then n gets the value 100.

Statement using the assignment operator a=a+1 a=a1 a=a+4 a=a4 a=a*4 a=a/4

Statement using the shorthand operator a + + or + + a a or a a+=4 a=4 a*=4 a/=4

Note. The use of shorthand assignment operators not only results in concise programs but more efficient programs also. (9) Comments in C start with "/ *" and end with "* /". For e.g. /* Euler's Method * /.

(10) Input statement is scanf. Syntax scanf ("control string", & variable 1, & variable 2, ) ; %d for an integer %f for a floating point %c for character %s for string The ampersand (&) symbol is necessary before the integer or floating point type variable. Its significance is discussed under functions. An example of the scanf statement : Assuming the declarations int c,float a [3][3]; the statement scanf ("%d %f , & c, & a[1][2]) takes input from the user and stores it in the corresponding variables %d corresponds to c, %f corresponds to a[1][2] (11) Output statement is printf. syntax printf ("control string, argument 1, argument 2, ) ; The arguments can be C constants or variables. The control string can consist of The characters that will be printed as such. Format specifications for variables. Escape sequences. Format specifications o for integers % w d for floating point % w.p f where w specifies the minimum width (i.e., no. of digits) for output o where p is no. of digits to be displayed after the decimal point, after rounding off if necessary. In this w includes the decimal point too. If width of the number is less than the specified width, the number is right justified in that width. However if width of the number is greater than the specified width, it will be printed in full. Escape sequences : These are sequence of two characters meant for performing special tasks. The first character is always a back slash ( \ ). The most commonly used escape sequence is \n. It causes the output to start from next line. The control string contains the format of the data being input by the user. It contains

An example of the printf statement : For e.g. Assuming the declarations int i = 1; float a = 27.23; the statement printf ("%3d \ n %8.2f \n", i, a) ;

will output 1 27.23 where is a blank space. (12) Relational operators available in C are :

Mathematical symbol > < =

C symbol > >= < <= == !=

(13) Logical expressions are mathematical expressions connected by relational operators. Their value is either true or false. Examples of logical expressions : Assuming: i = 2, j= 3 i <j is true i = =j is false (i * j) > (i + j) is true. In C the result of a logical expression is an integer. 0 is taken as false, any non-zero integer is taken as true. (14) Logical operators are used to test more than one conditions i.e., to combine more than one logical expressions.

Logical operator AND OR NOT

C symbol && || !

The following table illustrates their use.

AND Logical Logical Result expression expression 1 2 True True False False True False True False True False False False

OR Logical Logical Result expression expression 1 2 True True False False True False True False True True True False

NOT Logical expression True Result

False

False

True

(15) Decision making statementIf Syntax if (Lexp) {Tstatements} else {Fstatements} where Lexp is a logical expression. Tstatements are C statements executed when value of Lexp is true. Fstatements are C statements executed when value of Lexp is false. The else part is optional. (16) Loops (i) While Loop Syntax (a) (b) while (Lexp) {statements} do {statements} while (Lexp); Both these forms of the while loop cause execution of statements while value of Lexp is true. The difference between the two forms is that in the latter, the statements are executed at least once irrespective of the value of Lexp. (ii) For loop syntax for (initialization statement ; Lexp ; increment statement) {statements} (17) Break statement : When a break statement is encountered inside a loop, that loop is exited, irrespective of the value of Lexp, and the program continues with the statement immediately following the loop.

(18) Functions : These are the basic block of a C program Functions contain Statements that specify what is to be done. Every program has to contain a function named main. The program begins executing at the first statement of main. Apart from main the C functions are classified into Library functions User defined functions These functions are called from main to accomplish various tasks. (i) Library functions are already available and we just have to use them. e.g. printf, scanf, sqrt, cos, sin, fabs (used to get the absolute value of a floating point variable) etc. (ii) User defined functions have to be written by the user in the program. Syntax return-type function-name (Argument-list) { statements } Program for understanding the various terms and concepts related with functions : 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. / * Sample program / # include < stdio.h> float add (float a, float x) ; void half (float *x) { *x / = 2 ; return ; } main ( ) { float a = 2, b = 2, c ; c = add (a, b) ; print ("%f % f %f\ n", a, b, c) half (&a) ; half ( &b) ; printf ("&f &f &f\ n", a, b, c) ; } float add (float a, float x) { float sum ; sum = a + x ; a = 20 , x = 20 ; /*changing the formal arguments*/ return sum ; }

[Line nos. have been added for reference purpose and are not part of the program.]

Notes :
(a) Declaration and Definition : Line no. 3 is the declaration of the function named add. It indicates that there is a function add which takes two arguments a and b both of type float and returns a float. i.e., the Argument list is float a, float b and return-type is float (which can be void if function doesn't return anythingsee line 4. It also indicates that the function is defined later in the program).

Lines 17-23 are the definition of the function add i.e., they define how the function will make use of the arguments it received and return the required sum. Lines 4-8 constitute both the declaration and definition of the function half . (b) Calling a function : Line no. 12 calls the function add with a and b as arguments and stores the value returned by it into the variable c. (c) Actual and Formal arguments: The variables a and x in the declaration of function add are called the formal arguments variables a and b in the call to the function (Line 12) are the actual arguments. (d) Call by value/Call by reference : In C language the values of actual arguments are always copied to the formal arguments when a function is called. This way of passing arguments is called call by value. In this any change made to the formal arguments in the function does not affect the value of actual arguments. But in other languages, notably FORTRAN any change made to the formal arguments is reflected in the actual arguments. This is called call by reference, as the formal argument is treated as just another name for the actual argument. Both of them refer to the same location in the computer's memory. (e) Simulating a call by reference in C : The following thumb rule can be followed to make the formal argument refer to the actual argument (and not just receive a copy of it) "Precede the actual argument with an ampersand & (Line 14) and precede the formal argu-ment with an asterisk * (Line 4)". The actual working of this involves the concepts of pointers, which are another data type in C. (f) Return statement in a function passes the control back to the calling function along with the calculated value (Line 22) syntax return expression ; The expression can be omitted, in this case the return statement causes the function to just terminate then and there and pass control back to the calling function (Line 7). In case no return statement is present in a function, an implicit return takes place on encountering the right curly brace } (For e.g. in the function main, the control passes back to the caller, i.e., the operating system in this case, after line 16). (19) Preprocessor directives The lines in a C program that begin with a hash (#) sign are called preprocessor directives. The two most commonly used are # define and # include. Note. There is NO semi colon ( ; ) after the directive. (i) # define syntax # define name replacement It instructs the computer to replace all occurences of name with the replacement even before the program is processed i.e., checked for syntax. For e.g., consider the following statements # define N 2 int a [N] ; Before the program is processed by the compiler, the second line i.e., int a[N] ; is changed to int a[2] ; and the first line is removed. The resulting statement that is processed is int a[2]. (Line 3). The

(ii) # include syntax # include < header-file-name > This instructs the computer to insert the contents of the mentioned header file at the place where the directive appeared. Note. The header file contains declarations of various functions and many preprocessor directives. (20) Dynamic memory allocations : In today's world utilization of memory resources is needed for efficient programming. We may come across situations where we may have to deal with data, which is dynamic in nature. The number of data items may change during the executions of a program. The number of customers change during the proces at any time. When the list grows we need to allocate more memory space to accommodate additional data items. Such situations can be handled more easily by using dynamic allocation. Dynamic data items at run times, thus optimizing file usage of memory space. The process of allocating memory at run time is known as dynamic memory allocation. Although 'C' does not inherently have this facility there are four library routines which allow this function. Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But 'C' inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in 'C' for purpose of memory management. Function malloc Task Allocate memory requests size of bytesand returns a pointer to the allocated space. calloc Allocates space for a group of elements , initializes them To zero and returns a pointer to the memory. free realloc Deallocates previously allocated space. Modifiyes the size of previously allocated memory.

(21) Memory allocations process : According to the conceptual view the memory is partitioned in four different parts: in first part program instructions are stored, second global variables, third is used for function calls return address, arguments and local variables which are stored in stacks and last is called heap and is used for dynamic allocation during the execution of the program. (22) Allocating a block of memory : A block of memory may be allocated using the function malloc. The malloc function allocates a block of memory of specified size and returns a pointer of type void. ptr= (type*) malloc (size) ; ptr is a pointer of type the malloc returns a pointer (of type) to an area of memory with size. The general form malloc is: Example: x= (int*) malloc (2* sizeof (int) ) ; On successful execution of this statement a memory equivalent to 2 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int. (23) Allocating multiple blocks of memory : Calloc is function that is normally used to allocate multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is: ptr= (type*) calloc (n, elem-size) ;

The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned. (24) Freeing the used space : Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is responsibility of programmer to free the allocated space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function. free (ptr); ptr is a pointer that has been created by using malloc or calloc. (25) Data structure In computer science, a data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently. Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to specific tasks. For example, B-trees are particularly well-suited for implementation of databases, while compiler implementations usually use hash tables to look up identifiers. Data structures are used in almost every program or software system. Specific data structures are essential ingredients of many efficient algorithms, and make possible the management of huge amounts of data, such as large databases and internet indexing services. Some formal design methods and programming languages emphasize data structures, rather than algorithms, as the key organizing factor in software design. Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types.
structure definition struct tag_name { data type memberl; data type member2; ................. . }; Example: struct books { char title [30]; char author [25]; int page; float price; }; general format:

The keyword struct declares a structure to hold the details of four fields namely title, author, pages and price. These are members of the structures. Each member may belong to different or same data type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure. We can declare structure variables using the tag name anywhere in the program. For example the statement,

struct lib_books book1,book2,book3; declares bookl,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books. The complete structure declaration might look like this:
struct lib_books { char title [20]; char author [15]; int pages ; float price; }; struct lib_books, book1, book2, book3;

Structures do not occupy any memory until it is associated with the structure variable such as book1 the template is terminated with a semicolon. While the entire declaration is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template. The tag name such as lib_books can be used to declare structure variables of its data type later in the program. We can also combine both template declaration and variables declaration in one statement, the declaration
struct lib_books { char title [20]; char author [15]; int pages; float price; } bookl, book2,book3;

is valid. The use of tag name is optional for example


struct { ......... } bookl, book2, book3 ;

declares bookl,book2,book3 as structure variables representing 3 books but does not include a tag name for use in the declaration. A structure is usually defines before main along with macro definitions. In such cases the structure assumes global status and all the functions can access the structure. (26) Union : Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory whereas each member within a structure is assigned its own unique storage area. Thus unions are used to conserve memory. They are useful for application, involving multiple members, where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows: union item { int m; float p ; char c; } code;

C PROGRAMS
Simple Input/output Statements
1. Write a C program to nd area and perimeter of rectangle using scanf and printf #include<stdio.h> #include<conio.h> void main() { float l,b,p,a; clrscr(); printf("Enter the length and breadth of a rectangle\n"); scanf("%f%f",&l,&b); p=2*(l+b); a=l*b; printf("Perimeter of the rectangle is %4.2f",p); printf("Area of the rectangle is %4.2f",a); getch(); } RESULT Enter the length and breadth of a rectangle 4 5 Perimeter of the rectangle is 18.00 Area of the rectangle is 20.00 2. Write a C program to nd area and perimeter of circle using scanf and printf #include<stdio.h> #include<conio.h> void main() { float r,p,a; clrscr(); printf("Enter the radius of the circle\n"); scanf("%f",&r); p=2*3.14*r; a=3.14*r*r; printf("Perimeter of the circle is %5.3f\n",p); printf("Area of the circle is %5.3f\n",a); getch(); } RESULT Enter the radius of the circle 3 Perimeter of the circle is 18.840 Area of the circle is 28.260 3. Write a C program to nd area and perimeter of a triangle #include<stdio.h> #include<conio.h> #include<math.h>

void main() { float a,b,c,s,per,area; clrscr(); printf("Enter the sides of the triangle\n"); scanf("%f%f%f",&a,&b,&c); per=a+b+c; s=per/2; area=sqrt(s*(s-a)*(s-b)*(s-c)); printf("Perimeter of the triangle is %6.3f\n",per); printf("Area of the triangle is %6.3f\n",area); getch(); } RESULT Enter the sides of the triangle 3 4 5 Perimeter of the triangle is 12.0000 Area of the triangle is 6.000 4. Write a C program to nd the roots of the quadratic equation #include<stdio.h> #include<conio.h> #include<math.h> void main() { float a,b,c,p,q; clrscr(); printf("Enter the coefficients of quadratic equation a, b & c\n"); scanf("%f%f%f",&a,&b,&c); p=(-b+sqrt(b*b-4*a*c))/(2*a); q=(-b-sqrt(b*b-4*a*c))/(2*a); printf("First root is %6.3f\n",p); printf("Second root is %6.3f\n",q); getch(); } RESULT Enter the coefficients of quadratic equation a, b & c 1 10 24 First root is -4.000 Second root is -6.000

Control Statements
1. Write a C program to find maximum of the given set of numbers #include<stdio.h> #include<conio.h> void main( ) { int a[100],n,l,i; clrscr();

printf("Enter the number of elements\n"); scanf("%d",&n); printf("Enter the elements of the array\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); l=a[0]; for(i=0;i<n;i++) { if(l<a[i]) l=a[i]; } printf("The largest element is %d\n",l); getch( ); } RESULT Enter the number of elements 6 Enter the elements of the array 32 54 12 76 45 66 The largest element is 76 2. Given marks of 10 students in a subject. Write a C program to nd how many students have passed, have got distinction #include<stdio.h> #include<conio.h> void main() { float i,d,p,d1,p1,m[20]; clrscr(); printf("Enter the marks obtained by 10 students (out of 100)\n"); for(i=0;i<10;i++) scanf("%f",&m[i]); printf("Enter the marks required for passing the examination and that required for acquiring distincton\n"); scanf("%f%f",&p,&d); for(i=0;i<10;i++) { if(m[i]>=p) p1++; if(m[i]>=d) d1++; } printf("%.0f students have passed the examination and of these %.0f acquired distinction",p1,d1); getch(); } RESULT Enter the marks obtained by 10 students (out of 100) 19 24 49 45 63 67 38 79 95 88 Enter the marks required for passing the examination and that required for acquiring distincton 45 70 7 students have passed the examination and of these 3 acquired distinction 3. Write a C program to nd whether the given number is prime or not #include<stdio.h> #include<conio.h> void main() { int n,i,f=0; clrscr();

printf("Enter the number to be checked\n"); scanf("%d",&n); for(i=2;i<=(n/2);i++) { if ((n%i)==0) { f=1; break; } } if (f==1) printf("%d is not a prime number",n); else printf("%d is a prime number",n); getch(); } RESULT Enter the number to be checked 31 31 is a prime number

4.

Write a C program to display the prime numbers less than n #include<stdio.h> #include<conio.h> void main() { int i,j,n,f; clrscr(); printf("Enter the number upto which prime numbers are to be displayed\n"); scanf("%d",&n); for(i=2;i<=n;i++) { f=0; for(j=2;j<=(i/2);j++) { if (i%j==0) { f=1; } } if (f==0) printf("%d ",i); } getch(); } RESULT Enter the number upto which prime numbers are to be displayed 25 2 3 5 7 11 13 17 19 23

5.

Write a C program to nd the factorial of a given number

#include<stdio.h> #include<conio.h>

void main( ) { int n,i,f=1; clrscr(); printf("Enter the number\n"); scanf("%d",&n); for(i=1;i<=n;i++) f=f*i; printf("The factorial of %d is %d\n",n,f); getch( ); } RESULT Enter the number 6 The factorial of 4 is 720
6. Write a C program to generate the multiplication table in the format given below: 1 2 3 .........n 2 4 6 .........2n 3 6 9 .........3n ................... 10 ............10n

#include<stdio.h> #include<conio.h> void main( ) { int i, j, p, n; clrscr(); printf("Enter the value of n\n"); scanf("%d",&n); printf("Multiplication table:\n"); for(i=1;i<=10;i++) { for(j=1;j<=n;j++) { p=i*j; printf("%d\t",p); } printf("\n"); } getch( ); } RESULT Enter the value of n 5 Multiplication table: 1 2 3 2 4 6 3 6 9 4 8 12 5 10 15

4 8 12 16 20

5 10 15 20 25

6 7 8 9 10
7.

12 14 16 18 20

18 21 24 27 30

24 28 32 36 40

30 35 40 45 50

Write a C program to display the first n Fibonacci numbers #include<stdio.h> #include<conio.h> void main( ) { int a, b, c, i, n; clrscr(); a=0; b=1; printf("Enter the value of n\n"); scanf("%d",&n); printf("Fibonacci series is as follows\n"); for(i=1;i<=n;i++) { c=a+b; printf("%d\t",a); a=b; b=c; } getch( ); } RESULT Enter the value of n 10 Fibonacci series is as follows 0 1 1 2

13

21

34

8.

Write a program to print the n rows of numbers in the given format 1 1 2 1 2 3 1 2 3 4

#include<stdio.h> #include<conio.h> void main( ) { int i, j, n; clrscr(); printf("Enter the value of n\n"); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) printf("%d\t",j); printf("\n"); } getch( ); }

RESULT Enter the value of n 4 1 1 2 1 2 3 1 2 3


9.

Write a C program to generate the following pattern * * * * * * * * * *

#include<conio.h> #include<stdio.h> void main() { int i, j, n; clrscr(); printf("Enter the number of rows\n"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<n-i;j++) printf("* "); printf("\n"); //new line } getch(); } RESULT Enter the number of rows 4 * * * * * * * * * * 10. Write a program to convert the given binary number into its equivalent decimal number Refer additional qn no 11 11. Write a C program to calculate binomial coefcient nCr = n!/(r! * (n-r)!) #include<stdio.h> #include<conio.h> int factorial(int x); void main() { int n,r,nCr; clrscr(); printf("Enter the value of n and r in nCr\n"); scanf("%d%d",&n,&r); nCr=factorial(n)/(factorial(r)*factorial(n-r)); //nCr= n!/[(n-r)!*r!]

printf("%dC%d = %d\n",n,r,nCr); getch(); }

int factorial(int x) //function that returns factorial { int i,fact=1; for(i=1;i<=x;i++) fact*=i; return(fact); } RESULT Enter the value of n and r in nCr 7 2 7C2 =21 12. Write a program to print the Pascals triangle #include<stdio.h> #include<conio.h> int fact(int x); //function declaration void main() { int i,j,n,nCr=0; clrscr(); printf("Enter the number of lines :"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<=n-i;j++) printf(" "); for(j=0;j<=i;j++) { nCr=(fact(i)/(fact(i-j)*fact(j))); printf("%d ",nCr); } printf("\n"); } getch(); } int fact(int x) //function to find factorial { int i,factorial=1; for(i=1;i<=x;i++) { factorial*=i; } return(factorial); } RESULT Enter the number of lines : 7 1 1 1 2 1 1

1 1 1 1 6 5 15 4

3 6 10 20

3 4 10 15

1 1 5 6 1 1

13. Write a C program to print the third largest element from an array #include<conio.h> #include<stdio.h> void main() { int a[50],n,i,j,temp; clrscr(); printf("Enter the number of elements\n"); scanf("%d",&n); printf("Enter the elements\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } //sorting of array (Selection sort) for(i=0;i<n;i++) for(j=0;j<n;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } printf("Third largest element is %d",a[2]); getch(); } RESULT Enter the number of elements 7 Enter the elements 23 64 53 75 24 54 85 Thirs largest element is 64 14. Write a C program to check whether the given number is palindrome or not #include<stdio.h> #include<conio.h> void main() { int n,nbck,remainder,nreverse=0; clrscr(); printf("Enter the number to be checked for palindrome/not\n"); scanf("%d",&n); nbck=n; while(n>0) { remainder=n%10; nreverse=nreverse*10+remainder; n/=10; } if(nbck==nreverse)

printf("The entered number is palindrome"); else printf("The entered number is not palindrome"); getch(); } RESULT Enter the number to be checked for palindrome/not 32123 The entered number is palindrome 15. Given the factorial of a number. Write a C program to nd the number. Refer additional qn no 5 16. Write a C program to sort names of N students in alphabetical order #include<stdio.h> #include<conio.h> #include<string.h> void main() { char name[20][20],temp[20]; int i,n,j; clrscr(); //Entering array printf("Enter the number of students\n"); scanf("%d",&n); printf("Enter the names of students\n"); for(i=0;i<n;i++) scanf("%s",name[i]); //name sorting 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); } } //printing array printf("Sorted array \n"); for(i=0;i<n;i++) printf("%s\n",name[i]); getch(); } RESULT Enter the number of students 5 Enter the names of students: Rakesh Anish Kesav Dhanya Anjaly

Sorted array Anish Anjaly Dhanya Kesav Rakesh 17. Write a C program to check whether the given string is palindrome or not #include<stdio.h> #include<conio.h> void main() { char ch,s[100]; int i=0,l,f=0; clrscr(); printf("Enter the string\n"); do { ch=getchar(); s[i]=ch; i++; }while(ch!='\n'); s[i-1]='\0'; l=i-1; for(i=0;i<=l/2;i++) { if(s[i]!=s[l-i-1]) { f=1; break; } } if(f==0) printf("The string \"%s\" is a palindrome\n",s); else printf("The string \"%s\" is not a palindrome\n",s); getch(); } RESULT Enter the string

malayalam
The string " malayalam " is a palindrome 18. Write a program to print the following pattern c co com . . computer . . com co c

#include<stdio.h> #include<conio.h> void main() { char ch,word[100]; int i=0,j,l; clrscr(); printf("Enter the word\n"); do { ch=getchar(); word[i]=ch; i++; }while(ch!='\n'); word[i-1]='\0'; l=i-1; //equivalent to l=strlen(l); for(i=0;i<l;i++) { for(j=0;j<=i;j++) printf("%c",word[j]); printf("\n"); } i-=2; for(;i>=0;i--) { for(j=0;j<=i;j++) printf("%c",word[j]); printf("\n"); } getch(); } RESULT Enter the word computer c co com comp compu comput compute computer compute comput compu comp com co c

Functions
1. Write a function power (x,n) that will compute x^n, where x is a oating point number and n is an integer. Write a C program to compute x^8+7x^4-9x^3 using the function power (x,n) #include<stdio.h> #include<conio.h>

void main( ) { float power(float x,int n); float var, r; clrscr(); printf("Enter the variable\n"); scanf("%f",&var); r= power(var,8)+(7*power(var,4))-(9*power(var,3)); printf("The result is %f\n",r); getch( ); } float power(float x,int n) { int i; float p=1; for(i=1;i<=n;i++) p=p*x; return(p); } RESULT Enter the variable 2 The result is 296.000000 2. Write a non-recursive function to nd factorial of n. Use this function to find factorial of all numbers less than n #include<stdio.h> #include<conio.h> void main( ) { int fact(int x); int i, n; clrscr(); printf("Enter the number upto which factorial is to be obtained\n"); scanf("%d",&n); for(i=0;i<=n;i++) printf("Factorial of %d = %d\n",i,fact(i)); getch( ); } int fact(int x) { int i, f=1; for(i=1;i<=x;i++) f=f*i; return(f); } RESULT Enter the number upto which factorial is to be obtained 4 Factorial of 0 = 1 Factorial of 1 = 1 Factorial of 2 = 2 Factorial of 3 = 6 Factorial of 4 = 24 3. Write a recursive function recursive_ fact ( ) to find factorial of n. Using recursive__ fact ( ) write a program to nd nCr #include<stdio.h>

#include<conio.h> void main( ) { long int fact(int x); long int n,r,comb; clrscr(); printf("Enter the value of n & r\n"); scanf("%ld%ld",&n,&r); comb=fact(n)/(fact(r)*fact(n-r)); printf("The result is %ld",comb); getch( ); } long int fact(int x) { long int i; if(x==1) i=1; else i=x*fact(x-1); return(i); } RESULT Enter the value of n and r 64 The result is 15 4. Write a C program to nd sin(x)using the functions power(x, n) and factorial(n) #include<stdio.h> #include<conio.h> #include<math.h> float power(float x,int n) { int i; float p=1; for(i=1;i<=n;i++) p=p*x; return(p); } int factorial(int n) { int i,f=1; for(i=1;i<=n;i++) f=f*i; return(f); } void main( ) { float power(float x,int n); int factorial(int n); int i, j, m; float var,s,y; clrscr(); printf("Enter the value of variable in degrees\n"); scanf("%f",&var); y=var; var=(var*3.1416)/180; j=1; s=var;

printf("Enter the limit(no of terms in sinx expansion)\n"); scanf("%d",&m); for(i=3;i<=m;i=i+2) //For in terms of accuracy a loop for comparing s & accuracy is needed { s=s+(pow(-1,j)*power(var,i))/factorial(i); j++; } printf("Sin %6.2f = %6.4f",y,s); getch( ); } RESULT Enter the value of variable in degrees 30 Enter the limit(no of terms in sinx expansion) 6 Sin 30.00 = 0.5000 5. Write an efficient C program to nd sin(x) to specied accuracy #include<stdio.h> #include<conio.h> void main() { float x,acc,sinx(float,float); clrscr(); printf("Enter the value of x and accuracy\n"); scanf("%f%f",&x,&acc); printf("sin %.4f for an accuracy of %f is %f",x,acc,sinx(x,acc)); getch(); } float sinx(float a,float b) { float temp,sinx,n=1; temp=a; sinx=a; while(temp>b) { temp=temp*(-1)*(a*a)/((2*n)*(2*n+1)); sinx+=temp; n++; } return(sinx); } RESULT Enter the value of x and accuracy .523583 .0001 Sin .5236 for an accuracy of .000100 is .499661

Functions : Pass by referance


1. Write a function which can be used to find area and perimeter of a rectangle. Write a c program which calls function to do the same #include<stdio.h>

#include<conio.h> void rect(int l, int b, int *AREA, int *PERIMETER); void rect(int l, int b, int *AREA, int *PERIMETER) { *AREA=l*b; *PERIMETER=2*(l+b); } void main() { int l,b,area,perimeter; clrscr(); printf("Enter the value of length and breadth\n"); scanf("%d%d",&l,&b); rect(l,b,&area,&perimeter); printf("Area = %d\nPerimeter = %d",area,perimeter); getch(); } RESULT Enter the value of length and breadth: 3 4 Area = 12 Perimeter = 14 2. Write functions to swap values of two integer variables. a) Using pass by reference b) Using pointers #include<conio.h> #include<stdio.h> void swap_ref(int *x,int *y) { int t; t=*y; *y=*x; *x=t; printf("a = %d \nb = %d",*x,*y); } void swap_ptr(int *PA,int *PB) { int x; x=*PA; *PA=*PB; *PB=x; } void main() { int a,b,A,B,*pa,*pb; clrscr(); printf("Enter the two numbers\n"); scanf("%d%d",&a,&b); A=a; B=b; pa=&A; pb=&B; //swap by reference printf("Swap by pass by reference\n");

swap_ref(&a,&b); //swap by pointer printf("Swap by pointer\n"); swap_ptr(pa,pb); printf("a = %d\nb = %d",A,B); getch(); } RESULT Enter the two numbers 4 5 Swap by pass by reference a=5 b=4 Swap by pointer a=5 b=4 3. Write a C program which arranges the given set of 10 numbers in the ascending order .Use swap_ref. #include<stdio.h> #include<conio.h> void swap_ref(int *x,int *y); void main() { int n[10],i,j; clrscr(); printf("Enter 10 numbers\n"); for(i=0;i<10;i++) scanf("%d",&n[i]); //sorting with use of swap_ref() for(i=0;i<9;i++) for(j=i+1;j<10;j++) if(n[i]>n[j]) swap_ref(&n[i],&n[j]); printf("Sorted elements in ascending order\n"); for(i=0;i<10;i++) printf("%d\t",n[i]); getch(); } void swap_ref(int *x,int *y) { int t; t=*y; *y=*x; *x=t; } RESULT Enter 10 numbers 13 24 76 44 98 25 75 11 35 80 Sorted elements in ascendin order 11 13 24 25 35 44 75 76 80 4.

98

Write a C program to write the given set of 10 names in the alphabetical order.Write and use a function with prototype. void swap_ref(string & stl, string & st2) #include<stdio.h>

#include<conio.h> #include<string.h> void swap_ref(char *s1,char *s2) { char temp[20]; strcpy(temp,s1); strcpy(s1,s2); strcpy(s2,temp); } void main() { int i,j; char name[10][20]; clrscr(); printf("Enter 10 names\n"); for(i=0;i<10;i++) gets(name[i]); for(i=0;i<9;i++) for(j=i+1;j<10;j++) if(strcmp(name[i],name[j])>0) swap_ref(&name[i],&name[j]); printf("Sorted Array is as follows \n"); for(i=0;i<10;i++) printf("%s\n",name[i]); getch(); } RESULT Enter 10 names Hridya Anjaly Anish Sushama Mahalakshmi Neetha Rakesh Ishan Priyansh Mrigaank Sorted Array is as follows Anish Anjaly Hridya Ishan Mahalakshmi Mrigaank Neetha Priyansh Rakesh Sushama

File Handling
1. Write a C program to copy 5 names in in.txt to out.txt #include<stdio.h> #include<conio.h> void main() {

FILE *f0,*f1,*f2; char a[100][100],b[100][100]; int n,i; clrscr(); /* to create file in.txt */ printf("Enter the no: of names\n"); scanf("%d",&n); printf("Enter the names\n"); f0=fopen("in.txt","w"); for(i=0;i<=n;i++) { gets(a[i]); fputs(a[i],f0); fputs("\n",f0); } fclose(f0); /* to copy to file out.txt */ f1=fopen("in.txt","r"); for(i=0;i<n;i++) fscanf(f1,"%s",&b[i]); f2=fopen("out.txt","w"); printf("The text in out.txt is\n"); for(i=0;i<n;i++) { puts(b[i]); fputs(b[i],f2); fputs("\n",f2); } fclose(f1); fclose(f2); getch(); } RESULT Enter the no: of names 5 Enter the names n1 n2 n3 n4 n5 The text in out.txt is n1 n2 n3 n4 n5 2. Write a C program to copy the content of file fi.txt to fi.bak #include<stdio.h> #include<conio.h> void main() { FILE *f0,*f1,*f2; char text[100],ch; clrscr(); /* to create file fi.txt */ f0=fopen("fi.txt","w");

printf("Enter a text\n"); gets(text); fputs(text,f0); fclose(f0); /* to copy to file fi.bak */ printf("\n"); f1=fopen("fi.txt","r"); f2=fopen("fi.bak","w"); printf(Output in fi.bak is\n); while(ch!=EOF) { ch=getc(f1); putc(ch,f2); printf("%c",ch); } fclose(f1); fclose(f2); getch(); } RESULT Enter a text This is Focuz 2012! Output in fi.bak is This is Focuz 2012! 3. Write a C program to sort the names stores in f_orginal.txt. Store the sorted list in f_sort.txt #include<stdio.h> #include<conio.h> #include<string.h> void main() { FILE *f0,*f1,*f2; char names[50][50],temp[50]; int n,i,j; clrscr(); /*To create file f_original.txt*/ printf("Enter the number of names\n"); scanf("%d",&n); printf("Enter the names\n"); f0=fopen("f_original.txt","w"); for(i=0;i<=n;i++) { gets(names[i]); fputs(names[i],f0); fputs("\n",f0); } fclose(f0); /* To sort the array names*/ f1=fopen("f_original.txt","r"); i=0; while(i<n) { fscanf(f1,"%s",&names[i]); i++; } for(i=0;i<n-1;i++) for(j=i+1;j<n;j++)

if(strcmp(names[i],names[j])>0) { strcpy(temp,names[i]); strcpy(names[i],names[j]); strcpy(names[j],temp); } printf("\nSORTED NAMES \n"); f2=fopen("f_sort","w"); for(i=0;i<n;i++) { puts(names[i]); fputs(names[i],f2); fputs("\n",f2); } fclose(f1); fclose(f2); getch(); } RESULT Enter the number of names 6 Enter the names Robin Kevin Milan Vilas Anandhu Shambhu Sorted Anandhu Kevin Milan Robin Shambhu Vilas

Matrix manipulation
1. Write a program to read two arrays of length 5 and find its sum #include<stdio.h> #include<conio.h> void main() { int a[50],b[50],n,c,i,j,e; clrscr(); printf("Enter array 1 \n"); for(i=0;i<5;i++) scanf("%d",&a[i]); printf("Enter array 2 \n"); for(i=0;i<5;i++) scanf("%d",&b[i]); printf("The array after summation is\n"); for(i=0;i<5;i++) printf("%d\t",a[i]+b[i]); getch();

} RESULT Enter array 1 2 4 6 8 10 Enter array 2 3 5 7 9 11 The array after summation is 5 9 13 17 21 2. Write a program to read two matrices A and B and to find C=A*B. Display A, B and C .Given A IS 3 X 4 ,B is 4 X 2 #include<stdio.h> #include<conio.h> void main() { int i,j,k,n,m,p,q; float a[50][50],b[50][50],c[50][50]; clrscr(); printf("Enter the order of matrix 1\n"); scanf("%d%d",&m,&n); printf("Enter the order of matrix 2\n"); scanf("%d%d",&p,&q); printf("Enter the elements matrix 1\n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%f",&a[i][j]); printf("Enter the elements of matrix 2\n"); for(i=0;i<p;i++) for(j=0;j<q;j++) scanf("%f",&b[i][j]); printf("The first matrix is\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) printf("%.2f\t",a[i][j]); printf("\n"); } printf("The second matrix is\n"); for(i=0;i<p;i++) { for(j=0;j<q;j++) printf("%.2f\t",b[i][j]); printf("\n"); } if(n==p) { for(k=0;k<m;k++) for(i=0;i<n;i++) { c[k][i]=0; for(j=0;j<n;j++) c[k][i]+=a[k][j]*b[j][i]; } printf("The product matrix is\n"); for(i=0;i<m;i++) { for(j=0;j<q;j++) printf("%.2f\t",c[i][j]); printf("\n");

} } else printf("Given matrices cannot be multiplied\n"); getch(); } RESULT Enter the order of matrix 1 3 4 Enter the order of matrix 2 4 2 Enter the elements of matrix 1 1 2 3 4 5 6 7 8 1 2 3 4 Enter the elements of matrix 2 1 2 3 4 5 6 7 8 The first matrix is 1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 1.00 2.00 3.00 4.00 The second matrix is 1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 The product matrix is 50.00 60.00 114.00 140.00 50.00 60.00 3. Write a program to remove an element from a sorted array and to print the modified array Refer additional qn no 6 4. Write a program to insert an element at the exact position in a sorted array .(For example when 5 is inserted in the sorted array 1 7 8 9 50 ,5 should exactly place as shown :1 5 7 8 9 50) Refer additional qn no 7 5. Write a program to merge two given single dimensional arrays Refer additional qn no 8 6. Write a program to search for an item in an array using binary search

#include<stdio.h> #include<conio.h> #include<math.h> void main() { int arr[100],i,n,j,e,temp,beg,ends,mid,pos; clrscr(); printf("Enter the no of array elements\n");

scanf("%d",&n); printf("Enter array elements\n"); for(i=0;i<n;i++) scanf("%d",&arr[i]); for(i=0;i<n;i++) //Bubble sorting for(j=0;j<n-1;j++) if(arr[j]>arr[j+1]) { temp=arr[j+1]; arr[j+1]=arr[j]; arr[j]=temp; } printf("Sorted array : \n"); for(i=0;i<n;i++) printf("%-5d",arr[i]); printf("Enter element to be found\n"); scanf("%d",&e); beg=0; ends=n-1; pos=-1; while(beg<ends&&e>=arr[beg]&&e<=arr[ends])/* giving a condition to avoid infinite loop if e<1st or e> last element*/ { mid=(beg+ends)/2; if(arr[mid]==e) { pos = mid+1; break; } else if(arr[mid]<e) beg=mid; else ends=mid; } if(pos==-1) printf("Element %d not present in array.\n",e); else printf("Element %d found at position %d.\n",e,pos); getch(); } RESULT Enter the no of array elements 8 Enter array elements 2 6 4 12 10 8 14 16 Sorted array : 2 4 6 8 10 12 14 Enter element to be found 10 Element 10 found at position 5 7.

16

Write a program to check whether the given matrix is a magic square #include<stdio.h> #include<conio.h> void main() { int i,j,n; float a[50][50],r[10],c[10],f=0; clrscr();

printf("Enter the order of square matrix\n"); scanf("%d",&n); printf("Enter the elements matrix\n"); for(i=0;i<n;i++) { r[i]=0; c[i]=0; for(j=0;j<n;j++) { scanf("%f",&a[i][j]); } } for(i=0;i<n;i++) for(j=0;j<n;j++) { r[i]+=a[i][j]; c[i]+=a[j][i]; } for(i=0;i<n;i++) { if(r[i]!=r[0]||c[i]!=r[0]) { f=1; break; } } if(f==1) printf("The given matrix is not a magic square\n"); else printf("The given matrix is a magic square\n"); getch(); } RESULT Enter the order of square matrix 3 Enter the elements matrix 4 9 2 3 5 7 8 1 6 The given matrix is a magic square 8. Write a program to read a matrix and to display the sum of each row #include<stdio.h> #include<conio.h> void main() { int i,j,m,n; float a[50][50],s[10]; clrscr(); printf("Enter the order (row x column)\n"); scanf("%d%d",&m,&n); printf("Enter the elements of the matrix\n"); for(i=0;i<m;i++) { s[i]=0; for(j=0;j<n;j++) { scanf("%f",&a[i][j]);

s[i]+=a[i][j]; } } printf("The sum of rows are\n"); for(i=0;i<m;i++) printf("Row %d is %0.2f\n",i+1,s[i]); getch(); } RESULT Enter the order (row x column) 3 4 Enter the elements of the matrix 1 2 3 4 5 6 7 8 2 4 6 8 The sum of rows are Row 1 is 10.00 Row 2 is 26.00 Row 3 is 20.00 9. Write a program to read a matrix and display the sum of the diagonal elements #include<stdio.h> #include<conio.h> void main() { int i,j,m,n; float a[50][50],s=0; clrscr(); printf("Enter the order\n"); scanf("%d",&n); printf("Enter the elements of the matrix \n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { scanf("%f",&a[i][j]); if(i==j) s+=a[i][j]; } } printf("The sum of diagonal elements is %0.2f",s); getch(); } RESULT Enter the order 3 Enter the elements of the matrix 1 2 3 4 5 6 7 8 9 The sum of diagonal elements is 15.00 10. Write a program to read a matrix and to print the average of the elements of each row and total average #include<stdio.h> #include<conio.h>

void main() { float i,j,m,n,a[50][50],r[100],avg,avgr[100]; clrscr(); printf("Enter the order row x coloumn\n"); scanf("%f%f",&m,&n); printf("Enter the elements of the matrix \n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { scanf("%f",&a[i][j]); avg+=a[i][j]; r[i]+=a[i][j]; } } avg/=(m*n); printf("The average of all elements in the matrix is %0.2f\n",avg); for(i=0;i<n;i++) { avgr[i]=r[i]/n; printf("The average of row - %.0f is %.2f\n",i+1,avgr[i]); } getch(); } RESULT Enter the order row x coloumn 3 3 Enter the elements of the matrix 1 2 3 4 5 6 7 8 9 The average of all elements in the matrix is 5.00 The average of row 1 is 2.00 The average of row 2 is 5.00 The average of row 3 is 8.00 11. Write a program to read a matrix and to print its upper triangular matrix #include<stdio.h> #include<conio.h> void main() { int i,j,k,n,a[50][50]; clrscr(); printf("Enter the order of matrix\n"); scanf("%d",&n); printf("Enter the elements of the matrix\n"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); printf("The upper triangular matrix is\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i<=j) printf("%d\t",a[i][j]); else

printf("%d\t",0); } printf("\n"); } getch(); } RESULT Enter the order of matrix 3 Enter the elements of the matrix 1 2 3 4 5 6 7 8 9 The upper triangular matrix is 1 2 3 0 5 6 0 0 9 12. Write a program to read a matrix and to print its lower triangular matrix #include<stdio.h> #include<conio.h> void main() { int i,j,k,n,a[50][50]; clrscr(); printf("Enter the order of matrix\n"); scanf("%d",&n); printf("Enter the elements of the matrix\n"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); printf("The upper triangular matrix is\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i>=j) printf("%d\t",a[i][j]); else printf("%d\t",0); } printf("\n"); } getch(); } RESULT Enter the order of matrix 3 Enter the elements of the matrix 1 2 3 4 5 6 7 8 9 The upper triangular matrix is 1 0 0 4 5 0 7 8 9

13. Write a program to find the determinant of the given square matrix #include<math.h> #include<stdio.h> #include<conio.h> int b[5][5]; int determinant(int b[5][5],int m) { int i,j,p,sum = 0,c[5][5],a; if(m==2) { sum = b[0][0]*b[1][1] - b[0][1]*b[1][0]; return(sum); } else { for(p=0;p<m;p++) { int h = 0,k = 0; for(i=1;i<m;i++) { for( j=0;j<m;j++) { if(j==p) continue; c[h][k] = b[i][j]; k++; } k=0; h++; } a=pow(-1,p); sum = sum + b[0][p]*a*determinant(c,m-1); } return(sum); } } void main() { int i,j,k,n; clrscr(); printf("Enter the order of matrix\n"); scanf("%d",&n); printf("Enter the elements of the matrix\n"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&b[i][j]); printf("The determinant of the given matrix is %d ",determinant(b,n)); getch(); } RESULT Enter the order of the matrix 3 Enter the elements of the matrix 2 3 4 1 5 6 9 7 8

The determinant of the given matrix is -18

Solution of linear equations


1. Write a program to read a square matrix of order 3, and display the matrix after the following row operation R0=R0/10 #include<stdio.h> #include<conio.h> void main() { int i,j,a[100][100]; clrscr(); printf("Enter the elements of square matrix of order 3\n"); for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%d",&a[i][j]); for(j=0;j<3;j++) a[0][j]/=10; printf("The modified matrix after operation R0=R0/10 is\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) printf("%d\t",a[i][j]); printf("\n"); } getch(); } RESULT Enter the elements of square matrix of order 3 10 20 30 4 5 6 7 8 9 The modified matrix after operation R0=R0/10 is 1 2 3 4 5 6 7 8 9 2. Write a program to read a square matrix of order 3 and display it after the following row operation R2 = R2 5R1 #include<stdio.h> #include<conio.h> void main() { int i,j,a[100][100]; clrscr(); printf("Enter the elements of square matrix of order 3\n"); for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%d",&a[i][j]); for(j=0;j<3;j++) a[2][j]-=5*a[1][j]; printf("The modified matrix after operation R2=R2-5*R1 is\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) printf("%d\t",a[i][j]); printf("\n"); } getch();

} RESULT Enter the elements of square matrix of order 3 1 2 3 4 5 6 27 33 39 The modified matrix after operation R2=R2-5*R1 is 1 2 3 4 5 6 7 8 9 3. Write a program to solve three linear equations in the three unknowns using Gauss elimination method .Display the matrix after triangularisation step #include<stdio.h> #include<conio.h> void main() { float ratio,x[100],a[100][100]; int i,j,k,l; clrscr(); printf("Enter the augmented matrix\n"); for(i=0;i<3;i++) for(j=0;j<4;j++) scanf("%f",&a[i][j]); for(i=0;i<2;i++) for(j=i+1;j<3;j++) { ratio=a[j][i]/a[i][i]; for(k=i;k<4;k++) a[j][k]-=ratio*a[i][k]; } printf("The triangularised matrix is \n"); for(i=0;i<3;i++) { for(j=0;j<4;j++) printf("%f\t",a[i][j]); printf("\n"); } x[2]=a[2][3]/a[2][2]; for(i=1;i>=0;i--) { x[i]=a[i][3]; for(j=i+1;j<3;j++) x[i]-=a[i][j]*x[j]; x[i]/=a[i][i]; } printf("The solutions are\n"); for(l=120,i=0;i<3;i++,l++) /* l used for priting in format */ printf("%c = %f\t",l,x[i]); /* x=_ , y=_ etc.Not necessary */ getch(); } RESULT Enter the augmented matrix 1 1 -1 2 2 3 5 -3 3 2 -4 6

The triangularised marix is 1.000000 1.000000 0.000000 1.000000 0.000000 0.000000 The solutions are x = -0.333333 y = 1.166666 4.

-1.000000 7.000000 6.000000 z = -1.1666667

2.000000. -7.000000 -7.000000

Write a program to solve n linear equations in n unknowns using Gauss elimination .Use function to display the transformed matrix #include<stdio.h> #include<conio.h> #include<math.h> void main() { int i,j,k,l=120,n; float a[50][50],ratio,x[50]; clrscr(); printf("Enter the no: of variables\n"); scanf("%d",&n); printf("Enter the augmented matrix\n"); for(i=0;i<n;i++) for(j=0;j<=n;j++) scanf("%f",&a[i][j]); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) { ratio=a[j][i]/a[i][i]; for(k=0;k<=n;k++) a[j][k]-=ratio*a[i][k]; } printf("The tranformed upper triangular matrix with RHS is\n"); for(i=0;i<n;i++) { for(j=0;j<(n+1);j++) printf("%f\t",a[i][j]); printf("\n"); } x[n-1]=a[n-1][n]/a[n-1][n-1]; for(i=n-2;i>=0;i--) { x[i]=a[i][n]; for(j=i+1;j<n;j++) x[i]-=a[i][j]*x[j]; x[i]/=a[i][i]; } printf("The solutions are\n"); for(i=0;i<n;i++,l++) printf("%c = %f\t",l,x[i]); getch(); } RESULT Enter the number of variables 3 Enter the augmented matrix 2 1 1 10 3 2 3 18 1 4 9 16

The transformed upper triangular matrix with RHS is 2.000000 1.000000 1.000000 0.000000 0.500000 1.500000 0.000000 0.000000 -2.000000 The solutions are x = 7.000000 y=-9.000000 z=5.000000

10.000000 3.000000 -10.000000

5.

Write a program to solve a set of linear equation by Gauss Jordan method x+2y+3z=9 4x-6y+8z=13 3x+4y+5z=40 Refer additional qn no 14

Solution of differential equations


1. Write a C program to solve the D.E dy/dx=1/2(1+x)y , y(0)=1 by Eulers method. Calculate y(2) with step size 2 and 0.2. #include<stdio.h> #include<conio.h> #include<math.h> void main() { float fn(float x,float y); int i=1; float xo,xn,yo,x,y,h,d; clrscr(); printf("Enter the values of xo,yo,xn and h\n"); scanf("%f%f%f%f",&xo,&yo,&xn,&h); x=xo; y=yo; printf("Step \t x \t y "); while(x<xn) { d=fn(x,y); y=y+h*d; x=x+h; printf("\n%d \t %5.3f \t %5.3f",i,x,y); i++; } getch(); } float fn(float x,float y) { float value; value=0.5/((1+x)*y*y); return(value); } RESULT Enter the values of xo,yo,xn and h 0 1 2 0.2 Step x y 1 0.200 1.100
2

2 3 4 5 6 7 8 9 10 2.

0.400 0.600 0.800 1.000 1.200 1.400 1.600 1.800 2.000

1.169 1.221 1.263 1.298 1.328 1.353 1.376 1.396 1.415


2 nd

Write a C program to solve the D.E dy/dx=1/2(1+x)y : y(0)=1 by Range Kutta 2 order method . Display y(x) for 0<x<5. Choose h=0.5 #include<stdio.h> #include<conio.h> #include<math.h> void main() { float fn(float x,float y); int i=1; float xo,xn,yo,x,y,h,k1,k2; clrscr(); printf("Enter the values of xo,yo,xn and h\n"); scanf("%f%f%f%f",&xo,&yo,&xn,&h); x=xo; y=yo; printf("Step \t x \t y "); while(x<=xn) { k1=h*fn(x,y); k2=h*fn(x+h/2,y+k1/2); x=x+h; y=y+k2; printf("\n%d \t %5.3f \t %5.3f",i,x,y); i++; } getch(); } float fn(float x,float y) { float value; value=0.5/((1+x)*y*y); return value; } RESULT Enter the values of xo,yo,xn and h 0 1 5 0.5 Step x y 1 0.000 1.000 2 0.500 1.158 3 1.000 1.254 4 1.500 1.320 5 2.000 1.370 6 2.500 1.410 7 3.000 1.443 8 3.500 1.470 9 4.000 1.494

10 11 3.

4.500 5.000

1.515 1.534

Given dy/dt=t; y(0)=1. Find y(t) for 0<t<10 using (a) Eulers method (b) Range Kutta IV order method (c) Analytical formula (d) Tabulate the answers obtained in (a),(b) and (c).Choose h=1. #include<stdio.h> #include<conio.h> #include<math.h> void main() { float fn(float t,float y); float f(float t); int i=1; float to,tn,yo,t,y,h,d,k1,k2,k3,k4,k,a[25],b[25],c[25]; clrscr(); printf("Enter the values of to,yo,tn and h\n"); scanf("%f%f%f%f",&to,&yo,&tn,&h); t=to; y=yo; printf("\nEULER\n"); printf("-----\n"); printf("\nStep \t t \t\t y "); while(t<tn) { d=fn(t,y); y=y+h*d; t=t+h; a[i]=y; printf("\n%d \t %5.3f \t %5.3f",i,t,y); i++; } getch(); t=to; y=yo; i=1; printf("\n\nRUNGA_KUTTA \n"); printf("-----------\n"); printf("\nStep \t t \t\t y "); while(t<tn) { k1=h*fn(t,y); k2=h*fn(t+h/2,y+k1/2); k3=h*fn(t+h/2,y+k2/2); k4=h*fn(t+h,y+k3); k=(k1+2*(k2+k3)+k4)/6.0; t=t+h; y=y+k; b[i]=y; printf("\n%d \t %5.3f \t %5.3f",i,t,y); i++; } getch(); printf("\n\nANALYTICAL METHOD \n"); printf("-----------------\n"); printf("y= t^2/2+const \nApplying initial condition, t=0,y=1.... \n"); printf("\t\t\t const=1\nHence \t y=(t^2/2)+1\n"); printf("\nStep\t t\t y\t"); t=to; y=yo;

i=1; while(t<tn) { t=t+h; y=f(t); c[i]=y; printf("\n%d \t %5.3f\t %5.3f",i,t,y); i++; } getch(); printf("\n\nFOR COMPARISON\n"); printf("--------------\n"); printf("step \t t \t Euler \t RK \t Analytical \n"); t=to; for(i=1;i<=((tn-to)/h);i++) { t=t+h; printf("%d \t %5.3f\t %5.3f \t%5.3f\t %5.3f\n",i,t,a[i],b[i],c[i]); } getch(); } float fn(float t,float y) { float value; value=t; return(value); } float f(float t) { float value; value=(pow(t,2)/2)+1.0; return(value); } RESULT Enter the values of to,yo,tn and h 0 1 10 1 EULER -------Step 1 2 3 4 5 6 7 8 9 10 t 1.000 2.000 3.000 4.000 5.000 6.000 7.000 8.000 9.000 10.000 y 1.000 2.000 4.000 7.000 11.000 16.000 22.000 29.000 37.000 46.000

RUNGE KUTTA

------------------Step 1 2 3 4 5 6 7 8 9 10 t 1.000 2.000 3.000 4.000 5.000 6.000 7.000 8.000 9.000 10.000 y 1.500 3.000 5.500 9.000 13.500 19.000 25.500 33.000 41.500 51.000

ANALYTICAL METHOD ---------------------------y= t^2/2+const Applying initial condition, t=0,y=1.... const=1 Hence y=(t^2/2)+1 Step 1 2 3 4 5 6 7 8 9 10 t 1.000 2.000 3.000 4.000 5.000 6.000 7.000 8.000 9.000 10.000 y 1.500 3.000 5.500 9.000 13.500 19.000 25.500 33.000 41.500 51.000

FOR COMPARISON -----------------------Step 1 2 3 4 5 6 7 8 9 10 t 1.000 2.000 3.000 4.000 5.000 6.000 7.000 8.000 9.000 10.000 Euler 1.000 2.000 4.000 7.000 11.000 16.000 22.000 29.000 37.000 46.000 RK Analytical 1.500 1.500 3.000 3.000 5.500 5.500 9.000 9.000 13.500 13.500 19.000 19.000 25.500 25.500 33.000 33.000 41.500 41.500 51.000 51.000

Numerical Integration
1. Write a C program to evaluate 0.2. #include<stdio.h> #include<conio.h> #include<math.h> void main() dx using Trapezoidal rule.(Limits 4 to 5.2). Run the program with step size 0.4 and

{ float n,h,sum,x0,xn,i,j,f[100],fn(float); clrscr(); printf("Enter the step size\n"); scanf("%f",&h); printf("Enter x0 and xn\n"); scanf("%f%f",&x0,&xn); n=(xn-x0)/h; i=x0; for(j=0;i<=xn;j++) { f[j]=fn(i); i+=h; } sum=f[0]+f[n]; for(i=1;i<n-1;i++) sum+=f[i]*2; sum=sum*h/2; printf("Answer is %f",sum); getch(); } float fn(float a) //function is used for flexibility of program { float v; v=log(a); return(v); } RESULT Enter the step size 0.4 Enter x0 and xn 4 5.2 Answer is 1.183624 2.
2

Enter the step size 0.2 Enter x0 and xn 4 5.2 Answer is 1.183622

Write a C program to evaluate (x +sin x)dx using simpsons one third rule.(Limits 0 to 0.75) #include<stdio.h> #include<conio.h> #include<math.h> void main() { int n,j; float h,sum,x0,xn,i,f[100],fn(float); clrscr(); printf("Enter the no of steps\n"); scanf("%d",&n); if((n%2)==0) { printf("Enter x0 and xn\n"); scanf("%f%f",&x0,&xn); h=(xn-x0)/n; i=x0; for(j=0;i<=xn;j++) { f[j]=fn(i); i+=h; } sum=f[0]+f[n];

for(j=1;j<n;j++) { if((j%2)==0) sum+=f[j]*2; else sum+=f[j]*4; } sum=sum*h/3; printf("Integrated value is %f",sum); } else printf("The calculation cannot be done\n"); getch(); } float fn(float a) //function is used for flexibility of program { float v; v=a*a+sin(a); return(v); } RESULT Enter the no of steps 6 Enter x0 and xn 0 0.75 Integrated value is 0.408937

Solution of algebraic equation


1. Write a C program to find the root of the equation x -cos(x)=0, using bisection method #include<stdio.h> #include<conio.h> #include<math.h> void main() { float x0,x2,xn,a[100],acc,f2,fn,f(float); int i; clrscr(); printf("Enter the value of x0, xn and accuracy\n"); scanf("%f%f%f",&x0,&xn,&acc); fn=f(xn); repeat : x2=(xn+x0)/2; f2=f(x2); while(fabs(f2)>acc) { if((fn*f2)>0) xn=x2; else x0=x2; goto repeat; } printf("The root is %f",xn); getch(); } float f(float x) {
2

float val; val=x*x-cos(x); return(val); } RESULT Enter the value of x0, xn and accuracy 0 1 0.0001 The root is 0.824219 2. Write a C program to find a root correct to 3 decimal places of the equation logx-x+3=0, using Newton Raphson method #include<stdio.h> #include<conio.h> #include<math.h> void main() { float x[20],f(float),f1(float); int i; clrscr(); printf("Enter the initial value\n"); scanf("%f",&x[0]); printf("Iteration\tx\t\tf(x)\n"); for(i=0;;i++) { printf("\t\t%f\t%f\n",x[i],f(x[i])); x[i+1]=x[i]-f(x[i])/f1(x[i]); if(fabs(x[i+1]-x[i])<0.001) break; } printf("\nThe root is %f",x[i]); getch(); } float f(float x) { float val; val=log(x)-x+3; return(val); } float f1(float x) { float val; val=((1/x)-1); return(val); } RESULT Enter the initial value 5 Iteration x 5.000000 4.511797 4.505243 The root is 4.505243

f(x) -0.390562 -0.005102 -0.000001

Additional programs

1.

Write a C program to print the Pascals triangle Refer control statement qn no:12

2.

Write a C program to print the third largest element from an array #include<stdio.h> #include<conio.h> void main() { float n,i,j,temp,a[100]; clrscr(); printf("Enter the no of numbers\n"); scanf("%f",&n); printf("Enter the numbers\n"); for(i=0;i<n;i++) scanf("%f",&a[i]); for(i=0;i<n-1;i++) for(j=0;j<(n-i-1);j++) if(a[j]<a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } printf("The third largest element in the numbers is %f",a[2]); getch(); } RESULT Enter the no of numbers 6 Enter the numbers 34 85 27 65 86 44 The third largest element in the numbers is 65.000000

3.

Write a C program to check whether the given string is palindrome or not Refer control statement qn no:17

4.

Write a C program to arrange a set of numbers in ascending order using bubble sort #include<stdio.h> #include<conio.h> void main() { float i,j,n,a[100],temp; clrscr(); printf("Enter the number of elements in the array\n"); scanf("%f",&n); printf("Enter the elements\n"); for(i=0;i<n;i++) scanf("%f",&a[i]); for(i=0;i<n-1;i++) for(j=0;j<n-i-1;j++) if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp;

} printf("The array in ascending order is \n"); for(i=0;i<n;i++) printf("%.4f\t",a[i]); getch(); } RESULT Enter the number of elements in the array 8 Enter the elements 78 34 26 75 14 88 56 45 The array in ascending order is 14.0000 26.0000 34.0000 45.0000 56.0000 75.0000 78.0000 88.0000 5. Write a C program to find the number whose Factorial is given #include<stdio.h> #include<conio.h> void main() { float n,i,f=0; clrscr(); printf("Enter the value of factorial\n"); scanf("%f",&n); if(n==1) printf("The number is either 0 or 1\n"); else { for(i=1;n!=1;i++) { n/=i; if(n<1) { f=1; break; } } i--; if(f==0) printf("The number is %.0f\n",i); else printf("The factorial not possible\n"); } getch(); } RESULT Enter the value of factorial 120 The number is 5 6. Write a C program to remove an element from a sorted array and to print the modified array #include<stdio.h> #include<conio.h> void main() { int d,i,n,f=0,a[100];

clrscr(); printf("Enter the no of elements in the array\n"); scanf("%d",&n); printf("Enter the elements in ascending order\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the number to be deleted\n"); scanf("%d",&d); for(i=0;i<n;i++) if(a[i]==d) { f=1; break; } for(;i<n-1;i++) a[i]=a[i+1]; if(f==0) printf("The element not available in the array\n"); else { printf("The array after deletion is \n"); for(i=0;i<n-1;i++) printf("%d\t",a[i]); } getch(); } RESULT Enter the no of elements in the array 6 Enter the elements in ascending order 23 45 51 56 60 90 Enter the number to be deleted 60 The array after deletion is 23 45 51 56 90 7. Write a C program to insert a element at the exact position in a sorted array #include<stdio.h> #include<conio.h> void main() { int a[100],i,n,no,pos; clrscr(); printf("Enter the total number of numbers\n"); scanf("%d",&n); printf("Enter the numbers in ascending order\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the new number to be inserted\n"); scanf("%d",&no); /* For finding the position */ for(pos=0;pos<n;pos++) if(no<a[pos]) break; for(i=n-1;i>=pos;i--) a[i+1]=a[i]; a[pos]=no; printf("Elements of array after insertion\n");

for(i=0;i<n+1;i++) printf("%d\t",a[i]); getch(); } RESULT Enter the total number of numbers 6 Enter the numbers in ascending order 23 45 51 56 60 90 Enter the new number to be inserted 74 Elements of array after insertion 23 45 51 56 60 74 90 8. Write a C program to merge two given single dimensional arrays #include<stdio.h> #include<conio.h> void main() { int a[100],b[100],c[100],i,j,m,n; clrscr(); printf("Enter the number of elements in first and second array\n"); scanf("%d%d",&m,&n); printf("Enter the elements of first array\n"); for(i=0;i<m;i++) scanf("%d",&a[i]); printf("Enter the elements in second array\n"); for(i=0;i<n;i++) scanf("%d",&b[i]); for(i=0;i<m;i++) c[i]=a[i]; for(i=0;i<n;i++) c[i+m]=b[i]; printf("Merged array is "); for(i=0;i<m+n;i++) printf("%d ",c[i]); getch(); } RESULT Enter the number of elements in first and second array 5 6 Enter the elements of first array 1 2 3 4 5 Enter the elements in second array 6 7 8 9 10 11 Merged array is 1 2 3 4 5 6 7 8 9 10 11 9. Write a C program to check whether the given number is prime or not Refer control statement qn no:3 10. Write a C program to print the n Fibonacci number #include<stdio.h> #include<conio.h> void main( )
th

{ int a, b, c, i, n; clrscr(); a=0; b=1; printf("Enter the value of n\n"); scanf("%d",&n); for(i=1;i<n;i++) { c=a+b; a=b; b=c; } printf("The fibonacci number in position %d is %d",n,a); getch( ); } RESULT Enter the value of n 5 The fibonacci number in position 5 is 3 11. Write a C program to convert the given binary number into its equivalent decimal number #include<stdio.h> #include<conio.h> #include<math.h> void main() { long int bin,dec=0,i,bck,rem; clrscr(); printf("Enter the binary number\n"); scanf("%ld",&bin); bck=bin; for(i=0;bin>0;i++) { rem=bin%10; if(rem>1) { printf("The number given is not binary\n"); goto end; } dec+=rem*pow(2,i); bin/=10; } printf("The decimal equivalent of binary %ld is %ld",bck,dec); end: getch(); } RESULT Enter the binary number 11011 The decimal equivalent of binary 11011 is 27 12. Write a C program to convert the given decimal number into its equivalent binary number #include<stdio.h> #include<conio.h>

void main() { long int dec,bin=0,rem,bck,a[100],i=0; clrscr(); printf("Enter the decimal number\n"); scanf("%ld",&dec); bck=dec; while(dec>0) { a[i]=dec%2; dec/=2; i++; } i--; for(;i>=0;i--) bin=bin*10+a[i]; printf("The binary equivalent of decimal %ld is %ld",bck,bin); getch(); } RESULT Enter the decimal number 25 The binary equivalent of decimal 25 is 11001 13. Write a C program to find A*X where A is a nxn matrix and X is a nx1 vector #include<stdio.h> #include<conio.h> void main() { int i,j,k,n,a[100][100],b[100][100],c[100][100]; clrscr(); printf("Enter the order of first square matrix\n"); scanf("%d",&n); printf("Enter first matrix elements\n"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); printf("Enter the second vector\n"); for(i=0;i<n;i++) scanf("%d",&b[i][0]); for(i=0;i<n;i++) { c[i][0]=0; for(k=0;k<n;k++) c[i][0]+=a[i][k]*b[k][0]; } printf("The multiplied vector is\n"); for(i=0;i<n;i++) printf("%d\n",c[i][0]); getch(); } RESULT Enter the order of first square matrix 3 Enter first matrix elements 1 2 3

4 5 6 7 8 9 Enter the second vector 1 2 3 The multiplied vector is 14 32 50 14. Write a C program to solve a set of linear equation by Gauss Jordan method 2x+y+z = 10 3x+2y+3z = 18 X+4y+9z = 16 #include<stdio.h> #include<conio.h> void main() { int i,j,k,l; float n,ratio,x[100],a[100][100]; clrscr(); printf("Enter the number of unknowns\n"); scanf("%f",&n); printf("Enter the augmented matrix\n"); for(i=0;i<n;i++) for(j=0;j<(n+1);j++) scanf("%f",&a[i][j]); for(i=0;i<n;i++) for(j=0;j<n;j++) if(i!=j) { ratio=a[j][i]/a[i][i]; for(k=0;k<(n+1);k++) a[j][k]-=ratio*a[i][k]; } l=120; for(i=0;i<n;i++,l++) { x[i]=a[i][n]/a[i][i]; printf("%c = %f\t",l,x[i]); } getch(); } RESULT Enter the number of unknowns 3 Enter the augmented matrix 2 1 1 10 3 2 3 18 1 4 9 16 x = 7.000000 y= -9.000000

z= 5.000000

You might also like