C Notes
C Notes
Programming In C ____________________________________________________
Introduction To C Programming
Program: A set of instructions used by computer to perform a
particular task in a predefined manner.
A language is used to write instructions that can be translated into machine understandable form and then executed by computer are called language.
First generation language(1GL) Second generation language(2GL) Third generation language(3GL) Fourth generation language(4GL) Fifth generation language(5GL)
_________________________________________________________
Programming In C ____________________________________________________
First generation language (1GL): It is a machine level language or low level language. It consists of binary code i.e. 0s & 1s.
Second generation language (2GL): It is assemble level language which uses mnemonics instead of 0s & 1s. It can be read easy and fairly by a human. It can convert to machine level in order to run on a computer. E.g.: Add 12, 8 This instruction means add 12 and 8.
_________________________________________________________
Programming In C ____________________________________________________
Third generation language (3GL): It is a high level programming language designed to be easier for human to understand and write code. A program developed using 3Gl is highly procedural in that each and every step constituting a program has to be specified clearly by the programmer using constructs of language and conforming to the syntax of language For example b=c+2*d E.g. c, c++, java It is important to understand that a computer language defines the nature of a program and not the way that the program will be executed. To generate methods by which a program can be executed by 2 methods It can be compiled It can be interpreted Before that we should know about source code and object code.
_________________________________________________________
Programming In C ____________________________________________________
Compiler:A compiler reads the entire program and converts it to the object code. It provides errors not of one line but errors of the entire program. Only error-free programs are executed. It consumes little time for converting a source program to an object program.
Interpreter:An Interpreter reads only one line of a source program at a time and converts it to the object codes. In case there are errors, the same will be indicated instantly. The disadvantage is that it consumes more time for converting a source program to an object program.
_________________________________________________________
Programming In C ____________________________________________________
e.g. Select * from EMP; SQL(Structured query Language) Query and manipulate a relational database in a good example of 4GL. Fifth generation language (5GL): Solving problems using constraints given to the program. Constraint based and logic programming languages. Some declarative languages These are used mainly artificial intelligence research such as o Prolog o Ops5 o Mercury These are built upon LISP o ICAD o From languages such as KL-One.
_________________________________________________________
Programming In C ____________________________________________________
Evolution of C:
Dennis Ritchie develops C in 1970s at AT&T Bell labs; Murrey Hill, New Jersey USA.It is developed from older language BCPL. BCPL is developed by Martin Richards. Ken Thomson develops B. Cs place among the generations of programming language Powerful low-level features of second generation languages like pointers, bit manipulations etc High-level languages belonging to the category of 3GLs.The language become available on a very wide range of platforms, from embedded microcontrollers to super computers. C exhibits all the features of 3GL such as Block structured code A unit code in written as a function block A function in turn comprises various constructs such as conditional constraints iterative constructs etc which in turn are written as a block of code. High Level Language: - A high level programming language that is more users friendly and memory access in platform independent.
Why Use C:
C is success based on purely practically considerations Practicality Operation system,compiler,embedded software application software(financial accounting, inventory control) It is a industry standard _________________________________________________________
Programming In C ____________________________________________________ Programming constructs that is provides to the programmer (such as pointer) are essential to know
Features of C:
C is a portable study software. C is case sensitive language. C is function oriented structured language. C supports recursion. C has rich set of operator. C facilitator to create new user defined data types. C supports preprocessing. C supports Dynamic memory allocation. We can perform low-level operations very easy. Very easy to handle pointers.
General Structure of a C programming: /* Documentation: Describe about Programming */. Preprocessing directives. Global variable declarations. Main function. Local variable declaration. Valid C instructions. User defined function definition.
_________________________________________________________
Programming In C ____________________________________________________ main () {Begin -------------------------Statements End} Every C program contains a number of building blocks known as functions. Each function of it performs a task independently. 1. Include header file section:A C program depends upon some header files for function definition that are used in the program. Each header file by default has an extension .h. This file should be using #include directive. #include <stdio.h) or #include stdio.h 2. Global Declaration:This section declares some variables that are used in more than one function. These variables are known as Global Variables. This section must be used outside of all the functions.
3. Function Main:Every program written in C language must contain the main( ) function. The Execution of the program always begins with the function main( ). The program execution starts from the opening brace( { ) and closing brace ( } ). Between these two braces, the programmer should declare declaration and executable parts. 4. Declaration Part:This part declares all variables that are used in the executable part .Initialization means providing initial value to the variables. 5. Executable Part:This part contains the statements following the declaration of the variables. 6. User defined Functions:The functions defined by the user.
_________________________________________________________
Programming In C ____________________________________________________ 7. Comments:Comments are not necessary in the program. To understand the flow of the program. The compiler does not execute comments. Identifiers: -The name given to the program element is called identifier (I). Variable: -A variable is an identifier whose value alters during program execution. Constant: - A variable is an identifier whose value does not alter during program execution. Keyword: - These are reserve words, which are predefined meaning in C language. There are 32 keywords in C.
int long
extern return
continue for
Rules for naming a variable: It should be a combination of alphabets & digits. The first letter should be an alphabet. The compiler recognizes only eight characters for a variable even though we can specify up to 40 characters. No special characters except _ are allowed. Keywords cannot be used as variable name.
_________________________________________________________
10 Programming In C ____________________________________________________
Data type: -Data type specifies the data that the variable can
hold. It specifies the size of memory of that variable.
Sno
Data type
size in bytes
Range
1 2 3 4
2 1 4 8
_________________________________________________________
11 Programming In C ____________________________________________________
Note:
All the variables must be declared before processing. Variable declaration must be placed at the beginning of the function.
_________________________________________________________
12 Programming In C ____________________________________________________
Format specifier
%d %f %c %s %i %I %o %X %u %D or %ld %e, %E %X %O %p % [...] %lf %Lf
Excepted Input
integers (which has no fractional part) float (which has fractional part) characters string a decimal integer A long decimal integer An octal integer a hexa decimal integer an unsigned integer long integer floating point exponential long hexa decimal integer Long octal integer pointer Scan set format specifier double long double
2Formatted console output function :-( printf ()) These are used to perform output operation to console output device VDU. This function is defined in the header file stdio.h General form: -printf (console string, list of variables)
Purpose
the cursor jumps to its new line. the cursor lefts 6/8 spaces in the same line
_________________________________________________________
13 Programming In C ____________________________________________________ \v \a \f \\ \ \r \ \b vertical tab alarm or beep form feed Prints a Prints a carriage return Prints a backspace
_________________________________________________________
14 Programming In C ____________________________________________________ ++ -Increment operator Decrement operator unary operator Increments the Operand by 1 unary operator Decrements the operand by 1
General form:
Bitwise operators: These are used to perform bit manipulations & | ~ (Tilda) ^ (Circumflex) operator >> Bitwise and Bitwise or Ones compliment Bitwise xor << Shift right binary operator binary operator unary operator binary operator Shift left binary binary operator
Special Operators: Sizeof () Operator: - It returns the number of bytes required for a specified a data type or variable.
_________________________________________________________
15 Programming In C ____________________________________________________
Data Typecasting: - It is used to convert one type of data type into another specified data type element.
Description
Associativity
Structure operator left to right Pointer to structure operator Function call operator Array operator Unary operator Unary operator Increment operator Decrement operator Not Ones complement operator Memory reference operator Address operator Comma operator sizeof operator right to left type casting Multiplication Division modulo division Addition left to right
_________________________________________________________
16 Programming In C ____________________________________________________ << >> < > <= >= = ! & | ^ && || ?: += -= /= %= *= <<= >>= &= |= Subtraction Shift left Shift right --------------------------------------------------------Equivalence to Not equal to Bitwise And Bitwise Or Circumflex Logical And Logical or Conditional operator Shorthand operator Shorthand operator right to left right to left
Exercise
1) Write a sample C Program #include<stdio.h> main() { clrscr();/*clears the screen*/ printf("This is my sample 'C' program"); getch(); } 2) Write a program for addition of 2 nos #include<stdio.h> main() _________________________________________________________
17 Programming In C ____________________________________________________ { int a,b,c; clrscr(); printf("enter a & b values"); scanf("%d%d",&a,&b); c=a+b; printf("\n The value of A:%d",a); printf("\n The value of B:%d",b); printf("\n The Sum Of %d+%d=%d",a,b,c); getch(); } 3) Write a program for the demonstration of constant variables #include<stdio.h> main() { int m,h; float pe; const float g=9.8; clrscr(); printf("Enter mass & height"); scanf("%d%d",&m,&h); pe=g*m*h; printf("\n Potential Energy=%.2f",pe); getch(); } 4) Write a program to demonstrate global variable declaration const float pi=3.14; float peri(int); main() { int r; float area,per; clrscr(); printf("Enter the radius:"); scanf("%d",&r); area=pi*r*r; per=peri(r); printf("\n Area of circle=%.2f",area); _________________________________________________________
18 Programming In C ____________________________________________________ printf("\n Perimeter of circle=%.2f",per); getch(); } float peri(int x) { return 2*x*pi; } 5) Write a program to demonstrate swapping of 2 Nos #include<stdio.h> #include<conio.h> main() { int a,b,c; clrscr(); printf("Enter a & b values"); scanf("%d%d",&a,&b); printf("\n Before Swapping"); printf("\n A=%d \t B=%d",a,b); c=a; a=b; b=c; printf("\n After Swapping"); printf("\n A=%d \t B=%d",a,b); getch(); } (Or) #include<stdio.h> #include<conio.h> main() { int a,b; clrscr(); printf("Enter a & b values"); scanf("%d%d",&a,&b); printf("\n Before Swapping"); printf("\n A=%d \t B=%d",a,b); a=a+b; b=a-b; a=a-b; printf("\n After Swapping"); _________________________________________________________
19 Programming In C ____________________________________________________ printf("\n A=%d \t B=%d",a,b); getch(); } 6) Write a program to demonstrate Increment & Decrement operators main() { int i=1; clrscr(); printf("\n++I=%d",++i); printf("\nI++=%d",i++); printf("\n--I=%d",--i); printf("\nI--=%d",i--); printf("\nI=%d",i); getch(); } 7) Write a program to demonstrate Conditional operator main() { int a,b; clrscr(); printf("Enter A & B values"); scanf("%d%d",&a,&b); (a>b)?printf("A(%d) is big",a):printf("B(%d) is big",b); getch(); }
_________________________________________________________
20 Programming In C ____________________________________________________
Control Instructions
These are used to maintain the flow of control of a program. These are categorized into 3 types. They are 1Decision Control Statements: - These are the statements depend upon conditions.
_________________________________________________________
21 Programming In C ____________________________________________________ { if (expression) Statements; Else Statements; } } 2Repetitive (or) Loop Control statements:-Many programs require a group of statements have to be executed until a condition is satisfied. This is called looping.
The loop control statements are classified into: 1. While statements: General form:
While (exp) { statement/compound statement; } The statement under while executed repeatedly until the expression returns non-zero (true). Once the expression is zero (true) the next statement of while. This is also called Entry controlled loop statement. 2. Do-While statement: -
General form:
Do { Statement; } While (exp); The statements under do are executed first, later it checks for the validity of the expression. If the expression is non-zero, again the statements under do are executed. This process is continued till the expression remains true. Once it becomes falls the control goes to the next statement of the while statement. This is exit controlled loop structure.
_________________________________________________________
22 Programming In C ____________________________________________________
3. For statement: -
_________________________________________________________
23 Programming In C ____________________________________________________ Continue statement steps the current iteration and process with next iteration of a loop statement. General form: - Continue; D Case control structure or statement: If we want to take one decision among several decisions, we may use Switch case statement.
General form: Switch (integral expression) { Case case constant 1: statement/compound statement; Break; Case case constant 2: statement/compound statement; Break; Case case constant 3: statement/compound statement; Break; . . . . . . Case case constant n: statement/compound statement; Break; Default: statement/compound statement; } Hence, the integral expression must return either int or char. The result of integral expression is matched for equality with the case constant if match is found; the statement block corresponding to the case constant is executed. There should not be more than one case constant with in a single switch statement. Once the match is found, the statements will be executed till it reaches either break or end of the switch statement. If match is not found then the statement under Default are executed. C allows totally 257(256+1 default) case constant. _________________________________________________________
24 Programming In C ____________________________________________________
Exercise
1. write a sample simple if program #include<stdio.h> #include<conio.h> main() { int a,b,big; clrscr(); printf("ENTER 2 NO : "); scanf("%d%d",&a,&b); big = a; if(b>big) { big = b; } printf("BIG = %d",big); getch(); } 2. write a program to demonstrate Even No or not #include<stdio.h> #include<conio.h> main() { int n; clrscr(); printf("ENTER A NO : "); scanf("%d",&n); if(n%2==0) printf("%d IS EVEN",n); else printf("%d IS ODD",n); getch(); } 3. write a program to demonstrate nested if-else statement _________________________________________________________
25 Programming In C ____________________________________________________ #include<stdio.h> #include<conio.h> main() { int x,y; clrscr(); printf("ENTER 2 NO : "); scanf("%d%d",&x,&y); if(x==y) { printf("BOTH ARE EQUAL "); } else if(x>y) { printf("BIG NO = %d",x); } else { printf("BIG NO = %d",y); } getch(); } 4. write a program to demonstrate if-else ladder #include<stdio.h> #include<conio.h> main() { char gender; int age; clrscr(); printf("ENTER GENDER [M/F] : "); scanf("%c",&gender); gender = tolower(gender); printf("ENTER AGE : "); scanf("%d",&age); if(gender == 'f') if(age>=21) printf("SEARCH FOR BRIDE GROOM"); else printf("Miss wait for %d years",21-age); _________________________________________________________
26 Programming In C ____________________________________________________ else if(gender == 'm') if(age>=23) printf("SEARCH FOR BRIDE"); else printf("Mr wait for %d years",23-age); else printf("CHECK GENDER ONCE"); getch(); } 5. write a program to demonstrate biggest of 3 Nos #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("ENTER 3 NO : "); scanf("%d%d%d",&a,&b,&c); if(a>b) if(a>c) printf("%d is big",a); else printf("%d is big",c); else if(b>c) printf("%d is big",b); else printf("%d is big",c); getch(); } 6. write a program to demonstrate if statements using logical operators #include<stdio.h> #include<conio.h> main() { int m1,m2,m3,t; float avg; _________________________________________________________
27 Programming In C ____________________________________________________ clrscr(); printf("ENTER 3 SUBJECTS MARKS : "); scanf("%d%d%d",&m1,&m2,&m3); t = m1+m2+m3; avg = (float)t/3; printf("\n SUBJECT 1 : %d",m1); printf("\n SUBJECT 2 : %d",m2); printf("\n SUBJECT 3 : %d",m3); printf("\n TOTAL : %d",t); printf("\n AVERAGE : %.2f",avg); if(m1>=35 && m2>=35 && m3>=35) { printf("\n CLASS : "); if(avg>=60) printf("FIRST CLASS"); else if(avg>=50) printf("SECOND CLASS"); else if(avg>=35) printf("THIRD CLASS"); } else printf("\n FAIL"); getch(); } 7. write a program to calculate power bill #include<stdio.h> #include<conio.h> main() { int o,n,u,r,amt; clrscr(); gotoxy(15,5); printf("ENTER OLD READING : "); gotoxy(15,6); printf("ENTER NEW READING : "); gotoxy(35,5); scanf("%d",&o); gotoxy(35,6); scanf("%d",&n); u = n-o; if(u>=500) r = 7; else if(u>=300) r = 5; else if(u>=100) r = 3; else r = 1; amt = r*u; _________________________________________________________
28 Programming In C ____________________________________________________ gotoxy(20,8); gotoxy(20,9); gotoxy(20,10); gotoxy(20,11); gotoxy(20,12); getch(); } printf(" OLD READING : %d",o); printf(" NEW READING : %d",n); printf(" UNITS : %d",u); printf(" RATE : %d",r); printf(" AMOUNT : %d",amt);
8. write a program for to verify the given character is vowel or consonant #include<stdio.h> #include<conio.h> #include<ctype.h> main() { char ch; clrscr(); printf("Enter a Character : "); scanf("%c",&ch); ch = tolower(ch); if(ch=='a' || ch =='e' || ch=='i' || ch == 'o' ||ch == 'u') printf("%c is VOWEL",ch); else printf("%c is CONSONENT",ch); getch(); } 9. write a program for given year is leap year or not #include<stdio.h> #include<conio.h> main() { int year; clrscr(); printf("ENTER YEAR : "); scanf("%d",&year); if(year%4== 0 && year%100!=0 || year%400 ==0) printf("%d LEAP YEAR",year); else printf("%d NOT LEAP YEAR ",year); getch(); _________________________________________________________
29 Programming In C ____________________________________________________ } 10. write a program to verify the given roots are real or not #include<stdio.h> #include<conio.h> #include<math.h> main() { int a,b,c; float d,r1,r2; clrscr(); printf("ENTER a,b,c Values : "); scanf("%d%d%d",&a,&b,&c); d = b*b - 4*a*c; r1 = (-b + sqrt(d))/ 2*a; r2 = (-b - sqrt(d))/ 2*a; printf("\n ROOT 1 = %f",r1); printf("\n ROOT 2 = %f",r2); printf("\n D = %f",d); if(d==0) printf("\n ROOTS ARE REAL & EQUAL"); else if(d>0) printf("\n ROOTS ARE REAL & IMAGINARY"); else printf("\n ROOTS ARE UNEQUAL & IMAGINARY"); getch(); } 11. write a program to demonstrate while loop
#include<stdio.h> #include<conio.h> main() { int i,n; clrscr(); printf("Enter a No:"); scanf("%d",&n); i=1; while(i<=n) { printf("\t I=%d",i); i++; } getch(); _________________________________________________________
30 Programming In C ____________________________________________________ }
12.
#include<stdio.h> #include<conio.h> main() { int i=1,n,s=0; clrscr(); printf("Enter a No:"); scanf("%d",&n); while(i<=n) { printf("\n I=%d",i); s=s+i; i++; } printf("\n Sum of %d No's=%d",n,s); getch(); } 13. write a program for reverse a No
#include<stdio.h> #include<conio.h> main() { int r,n,s=0; clrscr(); printf("Enter a No:"); scanf("%d",&n); while(n!=0) { r=n%10; s=s*10+r; n=n/10; } printf("\n Reverse No=%d",s); getch(); }
_________________________________________________________
#include<stdio.h> #include<conio.h> main() { int r,n,s=0,m; clrscr(); printf("Enter a No:"); scanf("%d",&n); m=n; while(n!=0) { r=n%10; s=s*10+r; n=n/10; } if(m==s) printf("\n Given No %d is palindrome",m); else printf("\n Given No %d is not a palindrome",m); getch(); } 15. write a program for Armstrong No
#include<stdio.h> #include<conio.h> main() { int r,n,s=0,m; clrscr(); printf("Enter a No:"); scanf("%d",&n); m=n; while(n!=0) { r=n%10; s=s+r*r*r; n=n/10; } if(m==s) printf("\n Given No %d is Armstrong",m); else _________________________________________________________
32 Programming In C ____________________________________________________ printf("\n Given No %d is not a Armstrong",m); getch(); } 16. write a program for strong No
#include<stdio.h> #include<conio.h> main() { int r,n,s=0,m,i,f; clrscr(); printf("Enter a No:"); scanf("%d",&n); m=n; while(n!=0) { r=n%10; f=1; i=1; while(i<=r) { f=f*i; i++; } s=s+f; n=n/10; } if(m==s) printf("\n Given No %d is strong",m); else printf("\n Given No %d is not a strong",m); getch(); } 17. write a program for sum digits of given No
33 Programming In C ____________________________________________________ scanf("%d",&n); while(n!=0) { r=n%10; s=s+r; n=n/10; } printf("\n Sum of digits of given No=%d",s); getch(); } 18. write a program to demonstrate do-while loop
#include<stdio.h> #include<conio.h> main() { int i=10; clrscr(); do { printf("\t I:%d",i); i++; } while(i<=10); getch(); } 19. write a program for sum of given No until users choice is no #include<stdio.h> #include<conio.h> main() { char choice; int n,s=0; clrscr(); do { printf("ENTER A NO : "); scanf("%d",&n); s = s + n; fflush(stdin); printf("DO U WANT 2 CONTINUE[Y/N]?"); _________________________________________________________
34 Programming In C ____________________________________________________ scanf("%c",&choice); choice=tolower(choice); }while(choice=='y'); printf("\n SUM : %d",s); getch(); } 20. write a program for product the given no till the given no is zero #include<stdio.h> #include<conio.h> main() { int n; long int p=1; clrscr(); printf("\n\t\t ENTER 0 TO EXIT \n"); do { printf("ENTER A NO : "); scanf("%d",&n); if(n==0) break; p=p*n; }while(n!=0); printf("\n PRODUCT : %ld",p); getch(); } 21. write a program for the biggest of given no till the given no is zero #include<stdio.h> #include<conio.h> main() { int n,big=0; clrscr(); printf("\n\t\t ENTER 0 TO EXIT \n"); do { printf("ENTER A NO : "); _________________________________________________________
35 Programming In C ____________________________________________________ scanf("%d",&n); if(n>=big) big = n; }while(n!=0); printf("\n BIG : %d",big); getch(); } 22. write a program for smallest of given no till the given no is zero #include<stdio.h> #include<conio.h> main() { int n,small; clrscr(); printf("\n\t\t ENTER 0 TO EXIT \n"); printf("ENTER A NO : "); scanf("%d",&n); small = n; do { printf("ENTER A NO : "); scanf("%d",&n); if(n!=0) if(n<=small) small = n; }while(n!=0); printf("\n SMALL : %d",small); getch(); } 23. write a program for print N-natural Nos #include<stdio.h> #include<conio.h> main() { int i,n; _________________________________________________________
36 Programming In C ____________________________________________________ clrscr(); printf("ENTER NUMBER : "); scanf("%d",&n); for(i=1;i<=n;i++) { printf("\n I:%d",i); } getch(); } 24. write a program for loop to print given string for the sepcified times #include<stdio.h> #include<conio.h> main() { int c,n; char name[25]; clrscr(); printf("ENTER NAME : "); gets(name); fflush(stdin); printf("HOW MANY TIMES ? "); scanf("%d",&n); for(c=1;c<=n;c=c+1) { printf("\n %s",name); } getch(); } 25. write a program for multiplication table #include<stdio.h> main() { int c,n; clrscr(); printf("ENTER NUMBER : "); scanf("%d",&n); for(c=1;c<=10;c=c+1) { printf("\n %3d x %3d = %3d",n,c,c*n); _________________________________________________________
37 Programming In C ____________________________________________________ } getch(); } 26. write a program for factorial of a given No #include<stdio.h> main() { int c,n,f=1; clrscr(); printf("ENTER A NO : "); scanf("%d",&n); for(c=1;c<=n;c=c+1) { f=f*c; } printf("\n FACTORIAL OF %d: %d",n,f); getch(); } 27. write a program for power of a given No #include<stdio.h> #include<conio.h> main() { int c,x,y,p=1; clrscr(); printf("ENTER X,Y VALUES "); scanf("%d%d",&x,&y); for(c=1;c<=y;c=c+1) { p=p*x; } printf("%d POWER % d : %d",x,y,p); getch(); } 28. write a program for power/factorial #include<stdio.h> #include<conio.h> main() _________________________________________________________
38 Programming In C ____________________________________________________ { int c,x,y,p=1,f=1; float r; clrscr(); printf("ENTER X,Y VALUES "); scanf("%d%d",&x,&y); for(c=1;c<=y;c=c+1) { p = p*x; f = f*c; } r = (float)p/f; printf("\n %d POWER % d : %d",x,y,p); printf("\n %d FACTORIAL : %d",y,f); printf("\n RESULT : %.2f",r); getch(); } 29. write a program for squares of a N-natural Nos #include<stdio.h> #include<conio.h> main() { int c,n,s=0; clrscr(); printf("ENTER A NUMBER : "); scanf("%d",&n); for(c=1;c<=n;c=c+1) { s = s + c*c; } printf("\n SUM OF SQARES : %d ",s); getch(); } 30. write a program for factors of given No #include<stdio.h> #include<conio.h> main() { int n,c; clrscr(); _________________________________________________________
39 Programming In C ____________________________________________________ printf("ENTER A NO : "); scanf("%d",&n); printf("FACTORS OF %d",n); for(c=1;c<=n/2;c++) { if(n%c==0) printf("\n %d",c); } printf("\n %d",n); getch(); } 31. write a program for No.of factors of given No #include<stdio.h> #include<conio.h> main() { int n,c,s=1; clrscr(); printf("ENTER A NO : "); scanf("%d",&n); printf("FACTORS OF %d",n); for(c=1;c<=n/2;c++) { if(n%c==0) { printf("\n %d",c); s = s+1; } } printf("\n %d",n); printf("\n NO OF FACTORS FOR %d IS %d",n,s); getch(); } 32. write a program for given no is prime or not #include<stdio.h> #include<conio.h> main() { int n,i,count=0; clrscr(); _________________________________________________________
40 Programming In C ____________________________________________________ printf("ENTER A NO : "); scanf("%d",&n); printf("FACTORS OF %d",n); for(i=1;i<=n;i++) { if(n%i==0) { printf("\n %d",i); count++; } } if(count==2) printf("\n %d IS PRIME",n); else printf("\n %d IS NOT PRIME",n); getch(); } 33. write a program for perfect No #include<stdio.h> #include<conio.h> main() { int n,s=0,c; clrscr(); printf("ENTER A NO : "); scanf("%d",&n); for(c=1;c<=n/2;c=c+1) { if(n%c==0) printf("\nC:%d",c); s = s+c; } printf("\nSum:%d",s); if(n==s) printf("\n%d is PERFECT NO",n); else printf("\n%d is NOT PERFECT NO",n); getch(); } 34. write a program for find sum of any given "n" no
_________________________________________________________
41 Programming In C ____________________________________________________ #include<stdio.h> #include<conio.h> main() { int no,c,s=0,n; clrscr(); printf("HOW MANY NO? "); scanf("%d",&n); for(c=1;c<=n;c=c+1) { printf("ENTER A NO : "); scanf("%d",&no); s = s + no; } printf("\n SUM : %d",s); getch(); } 35. Program find the biggest and smallest of any given 'n' no main() { int no,c,small,big,n; clrscr(); printf("\n Enter how many no.s:"); scanf("%d",&n); printf("ENTER A NO : "); scanf("%d",&no); big = small = no; for(c=1;c<n;c++) { printf("ENTER A NO : "); scanf("%d",&no); if(no<=small) small = no; if(no>=big) big = no; } printf("\n SMALL : %d",small); printf("\n BIG : %d",big); _________________________________________________________
42 Programming In C ____________________________________________________ getch(); } 36. write a program for FEBINOCCI SERIES (FIRST N)
#include<stdio.h> #include<conio.h> main() { int a,b,c,i,n; clrscr(); printf("\n Enter how many terms:"); scanf("%d",&n); a = 0; b = 1; printf("\n %d",a); printf("\n %d",b); for(i=3;i<=n;i++) { c = a+b; printf("\n %d",c); a = b; b = c; } getch(); } 37. write a program for FEBINOCCI SERIES below given No #include<stdio.h> #include<conio.h> main() { int a,b,c,no; clrscr(); printf("ENTER A NO : "); scanf("%d",&no); a = 0; b = 1; c = 0; for( ;c<=no; ) { printf("\n %d",c); _________________________________________________________
43 Programming In C ____________________________________________________ a = b; b = c; c = a + b; } getch(); } 38. write a program for FEBINOCCI SERIES #include<stdio.h> #include<conio.h> main() { int a,b,c,no,i; clrscr(); printf("HOW MANY NO? "); scanf("%d",&no); a = 0; b = 1; c = 0; for(i=1;i<=no;i++ ) { printf("\n%5d. %5d",i,c); a = b; b = c; c = a + b; } getch(); } 39. write a program for x + x2/2! + x3/3!...xn/n! #include<stdio.h> #include<conio.h> main() { int i,j,f,p; float s=0.0; int x,n; clrscr(); printf("ENTER X,N VALUES : "); scanf("%d%d",&x,&n); for(i=1;i<=n;i++) { f=1; _________________________________________________________
44 Programming In C ____________________________________________________ p=1; for(j=1;j<=i;j++) { p = p * x; f = f * j; } printf("%d/%d +",p,f); s = s + (float)p/f; } printf("\b = %.2f",s); getch(); } 40. write a program for x + x3/3! + x5/5+
#include<stdio.h> #include<conio.h> main() { int i,x,n,f=1,p=1; float s=0.0; clrscr(); printf("ENTER X,N VALUES : "); scanf("%d%d",&x,&n); s = p = x; for(i=3;i<=n;i = i+2) { f = f*i*(i-1); p = p*x*x; printf("%d/%d+",p,f); s = s + (float)p/f; } printf("\b = %.2f",s); getch(); } 41. write a program for
45 Programming In C ____________________________________________________ 1 2 3 4 5 */ #include<stdio.h> #include<conio.h> main() { int i,j,n; clrscr(); printf("\n Enter the value of n :"); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) printf("%d ",j); printf("\n"); } getch(); } 42. /* 54321 4321 321 21 1 21 321 4321 54321 */ #include<stdio.h> #include<conio.h> main() { int i,j,n; clrscr(); printf("Enter a No:"); scanf("%d",&n); for(i=n;i>=1;i--) { for(j=1;j<=n-i;j++) printf(" "); for(j=i;j>=1;j--) _________________________________________________________ write a program for
46 Programming In C ____________________________________________________ printf(" %d",j); printf("\n"); } for(i=2;i<=n;i++) { for(j=1;j<=n-i;j++) printf(" "); for(j=i;j>=1;j--) printf(" %d",j); printf("\n"); } getch(); } 43. write a program for 1 121 12321 1234321 123454321 #include<stdio.h> #include<conio.h> main() { int i,j,n; clrscr(); printf("Enter a No:"); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=n-i;j++) printf(" "); for(j=1;j<=i;j++) printf("%d ",j); for(j=i-1;j>=1;j--) printf("%d ",j); printf("\n"); } getch(); }
_________________________________________________________
47 Programming In C ____________________________________________________
44.
#include<stdio.h> #include<conio.h> main() { int i,j,n; clrscr(); printf("Enter a No:"); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) printf(" %d",j); for(j=1;j<=(n-i)*2;j++) printf(" "); for(j=i;j>=1;j--) printf(" %d",j); printf("\n"); } getch(); } 45. write a program for A A A A A main() _________________________________________________________ BCDEEDCBA BCD DCBA BC CBA B BA A
48 Programming In C ____________________________________________________ { int i,j,n; clrscr(); printf("Enter a No:"); scanf("%d",&n); for(i=n;i>=1;i--) { for(j=1;j<=i;j++) printf(" %c",j+64); for(j=1;j<=(n-i)*2;j++) printf(" "); for(j=i;j>=1;j--) printf(" %c",j+64); printf("\n"); } getch(); }
46.
A A A A A A A A A
#include<stdio.h> #include<conio.h> main() { int i,j,n; clrscr(); printf("Enter a No:"); scanf("%d",&n); for(i=n;i>=1;i--) _________________________________________________________
49 Programming In C ____________________________________________________ { for(j=1;j<=i;j++) printf(" %c",j+64); for(j=1;j<=(n-i)*2;j++) printf(" "); for(j=i;j>=1;j--) printf(" %c",j+64); printf("\n"); } for(i=2;i<=n;i++) { for(j=1;j<=i;j++) printf(" %c",j+64); for(j=1;j<=(n-i)*2;j++) printf(" "); for(j=i;j>=1;j--) printf(" %c",j+64); printf("\n"); } getch(); } 47. write a program to demonstrate goto statements
#include<stdio.h> #include<conio.h> main() { int c=1; clrscr(); z: if(c<=5) { printf("\n Hello "); c = c+1; goto z; } getch(); } 48. write a program to demonstrate break statement
_________________________________________________________
50 Programming In C ____________________________________________________ #include<stdio.h> #include<conio.h> main() { int i; clrscr(); for(i=1;i<=10;i++) { printf("\n I:%d",i); if(i==5) break; } getch(); } 49. write a program to demonstrate continue statement
#include<stdio.h> #include<conio.h> main() { int i; clrscr(); for(i=1;i<=10;i++) { if(i==5) continue; printf("\n I:%d",i); } getch(); }
50.
#include<stdio.h> #include<conio.h> main() { int ch; clrscr(); printf("Enter ur choice"); scanf("%d",&ch); _________________________________________________________
51 Programming In C ____________________________________________________ switch(ch) { case 1:printf("\n Sunday"); break; case 2:printf("\n Monday"); break; case 3:printf("\n Tuesday"); break; case 4:printf("\n Wednesday"); break; case 5:printf("\n Thursday"); break; case 6:printf("\n Friday"); break; case 7:printf("\n Saturday"); break; default:printf("\n wrong choice"); } getch(); } 51. write a program for arithmetic calculator using switch statement #include<stdio.h> #include<conio.h> main() { int ch,a,b,res; do { clrscr(); printf("\n\t\t 1. ADDITION "); printf("\n\t\t 2. SUBSTRACTION "); printf("\n\t\t 3. MULTIPLICATION "); printf("\n\t\t 4. DIVISION "); printf("\n\t\t 5. EXIT "); printf("\n\n\t\t ENTER UR CHOICE [1,2,3,4,5] : "); scanf("%d",&ch); if(ch==5) exit(0);
_________________________________________________________
52 Programming In C ____________________________________________________ if(ch>5) printf("\n \t\t\t WRONG CHOICE "); else { printf("Enter 2 no : "); scanf("%d%d",&a,&b); switch(ch) { case 1: res = a + b; break; case 2: res = a - b; break; case 3: res = a * b; break; case 4: res = a / b; break; default: res = 0; printf("\n \t\t\tUR CHOICE IS WRONG"); } printf("\n \t\t\t RESULT = %d",res); } printf("\n\n\n \t\t\tPRESS ANY KEY 2 CONT.."); getch(); }while(ch!=5); }
_________________________________________________________
53 Programming In C ____________________________________________________
_________________________________________________________
54 Programming In C ____________________________________________________
ARRAYS
An array is a collection of data items or variables. Which are of homogeneous data type, referred with a common name and stored sequentially in the memory.
Usage of array:
To store more than one value in a single variable. To decrease the completing of a program. To increase the readability of a program. Easy to searching and sorting.
General function:
data type array name [size] = {item1, item2 item n}; Size can be omitted.
_________________________________________________________
55 Programming In C ____________________________________________________
General function:
data type array name [row size][column size]; The row size and column size must be positive integers.
General function:
Data type array name [row size][column size]; Int Tlist [3] [2] = {1, 2, 3, 4, 5, 6}; The row size can be omitted but column size is must be specified. (Not optional).
Exercise
1) write a program to demonstrate array #include<stdio.h> #include<conio.h> main() { int a[5]={10,20,30,40,50}; clrscr(); printf("\n Array is:"); printf("\n a[0]:%d",a[0]); printf("\n a[1]:%d",a[1]); printf("\n a[2]:%d",a[2]); printf("\n a[3]:%d",a[3]); printf("\n a[4]:%d",a[4]); getch(); } 2) write a program for reading values for an array main() { int a[5],i; clrscr(); for(i=0;i<5;i++) { printf("ENTER A NO : ");
_________________________________________________________
56 Programming In C ____________________________________________________ scanf("%d",&a[i]); } printf("\n ARRAY ELEMENTS :\n "); for(i=0;i<5;i++) { printf("\na[%d]= %d",i,a[i]); } getch(); } 3) write a program for sum of elements in an array main() { int a[20],i,n,s=0; clrscr(); printf("\n Enter no. of elements:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("ENTER A NO : "); scanf("%d",&a[i]); s = s + a[i]; } printf("\n ARRAY ELEMENTS :\n "); for(i=0;i<n;i++) { printf("\n a[%d]:%d",i,a[i]); } printf("\n SUM = %d",s); getch(); } 4) write a program to find the biggest and least elements in an array of n elements main() { int a[20],i,n,big,small; clrscr(); printf("\n Enter no. of elements:"); scanf("%d",&n); for(i=1;i<=n;i++) { _________________________________________________________
57 Programming In C ____________________________________________________ printf("ENTER A NO : "); scanf("%d",&a[i]); } big = small = a[1]; for(i=2;i<=n;i++) { if(a[i]>=big) big = a[i]; if(a[i]<=small) small = a[i]; } printf("\n Given Elements : "); for(i=1;i<=n;i++) { printf("\na[%d]: %d",i,a[i]); } printf("\n BIG = %d",big); printf("\n SMALL = %d",small); getch(); } 5) write a program to find an element in an array main() { int a[15],no,i,n,found = 0; clrscr(); printf("Enter no.of elements"); scanf("%d",&no); for(i=0;i<no;i++) { printf("ENTER A NO : "); scanf("%d",&a[i]); } printf("ENTER NO TO SEARCH : "); scanf("%d",&n); for(i=0;i<no;i++) { if(a[i]==n) { found = 1; break; _________________________________________________________
58 Programming In C ____________________________________________________ } } if(found==1) { printf("\n SUCCESSFUL SEARCH"); printf("\n %d FOUND at position : %d",n,i); } else printf("\n UNSUCCESSFUL SEARCH",n); getch(); } 6) write a program insert an element in an array at specified position main() { int a[30],no,p,i,n; clrscr(); printf("\n Enter no. of elements:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("ENTER A NO : "); scanf("%d",&a[i]); } printf("\nENTER NO AND POSITION TO INSERT "); scanf("%d%d",&no,&p); if(p>=0 && p<=n) { for(i=n-1;i>=p;i--) { a[i+1]= a[i]; } a[p] = no; n++; } else printf("\n Invalid position"); printf("\n ARRAY AFTER INSERT \n"); for(i=0;i<n;i++) printf(" %d",a[i]); _________________________________________________________
59 Programming In C ____________________________________________________ getch(); } 7) write a program deleting an element from an array main() { int a[30],i,n,p; clrscr(); printf("\n Enter no. of elements:"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("\n ENTER ELEMENT :"); scanf("%d",&a[i]); } printf("\n Enter position to delete the element in that position:"); scanf("%d",&p); if(p>=1 && p<=n) { for(i=p;i<=n;i++) { a[i]=a[i+1]; } n--; } else printf("\n Invalid position"); printf("\n ARRAY AFTER DELETION:"); for(i=1;i<=n;i++) printf("%d ",a[i]); getch(); } 8) write a program for sort the array in ascending order main() { int a[5],i,j,temp; clrscr(); for(i=0;i<5;i++) { printf("ENTER A NO : "); scanf("%d",&a[i]); } _________________________________________________________
60 Programming In C ____________________________________________________ for(i=0;i<5;i++) { for(j=i+1;j<5;j++) { if(a[i]>=a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } printf("ARRAY IN ASCENDING ORDER :\n"); for(i=0;i<5;i++) printf("\n a[%d]:%d",i,a[i]); getch(); } 9) write a program to demonstrate 2D array main() { int a[3][2]={1,6,3,4,2,5}; int i,j; clrscr(); printf("\n The Given Matrix is:"); for(i=0;i<3;i++) { printf("\n"); for(j=0;j<2;j++) printf("\t %d",a[i][j]); } getch(); } 10) write a program for sum of 2 given matrices
main() { int a[5][5],b[5][5],c[5][5],i,j,m,n,p,q; clrscr(); printf("\n Enter order of first matrix:"); scanf("%d%d",&m,&n); printf("\n Enter order of second matrix:"); _________________________________________________________
61 Programming In C ____________________________________________________ scanf("%d%d",&p,&q); if(m==p && n==q) { printf("\n ENTER VALUES FOR MATRIX A : \n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); printf("\n ENTER VALUES FOR MATRIX B : \n"); for(i=0;i<p;i++) for(j=0;j<q;j++) scanf("%d",&b[i][j]); printf("\n THE VALUES FOR MATRIX A : \n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) printf("\t %d",a[i][j]); printf("\n"); } printf("\n THE VALUES FOR MATRIX B : \n"); for(i=0;i<p;i++) { for(j=0;j<q;j++) printf("\t %d",b[i][j]); printf("\n"); } for(i=0;i<m;i++) for(j=0;j<n;j++) c[i][j] = a[i][j] + b[i][j]; printf("RESULTANT MATRIX : \n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) printf("\t%d",c[i][j]); printf("\n"); } } else printf("\n MATRIX ADDITION IS NOT POSSIBLE"); getch(); } _________________________________________________________
62 Programming In C ____________________________________________________ 11) write a program to find the sum of diagnol of a square matrix(trace matrix) main() { int a[10][10],r,c,s=0,i,j; clrscr(); printf("\n How many Rows? "); scanf("%d",&r); printf("\n How many Cols? "); scanf("%d",&c); if(r!=c) printf("\n NOT A SQUARE MATRIX "); else { printf("Enter %d Values \n ",r*c); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("Enter a no : "); scanf("%d",&a[i][j]); if(i==j) s+=a[i][j]; } } printf("\n GIVEN MATRIX \n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf(" %d",a[i][j]); printf("\n"); } } printf("TRACE : %d",s); getch(); } 12) write a program to find transpose matrix for a given matrix
_________________________________________________________
63 Programming In C ____________________________________________________ main() { int a[10][10],r,c,i,j; clrscr(); printf("How many Rows? "); scanf("%d",&r); printf("How many Cols? "); scanf("%d",&c); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("Enter a No : "); scanf("%d",&a[i][j]); } } printf("Given Matrix \n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf("%3d",a[i][j]); printf("\n"); } printf("Transpose Matrix : \n"); for(i=0;i<c;i++) { for(j=0;j<r;j++) printf("%3d",a[j][i]); printf("\n"); } getch(); } 13) write a program to find given matrix is symetric or not main() { int a[10][10],b[10][10],r,c,i,j,sym = 1; clrscr(); printf("How many Rows? "); scanf("%d",&r); printf("How many Cols? "); _________________________________________________________
64 Programming In C ____________________________________________________ scanf("%d",&c); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("Enter a No : "); scanf("%d",&a[i][j]); } } for(i=0;i<c;i++) for(j=0;j<r;j++) b[i][j]=a[j][i]; printf("Given Matrix \n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf("%3d",a[i][j]); printf("\n"); } printf("Transpose Matrix : \n"); for(i=0;i<c;i++) { for(j=0;j<r;j++) printf("%3d",b[i][j]); printf("\n"); } if(r==c) { for(i=0;i<r;i++) for(j=0;j<c;j++) { if(a[i][j]!=b[i][j]) { sym = 0; break; } } } else sym = 0; _________________________________________________________
65 Programming In C ____________________________________________________ if(sym==1) printf("\n GIVEN MATRIX IS SYMETRIC"); else printf("\n GIVEN MATRIX IS NOT SYMETRIC"); getch(); } 14) write a program for matrix multiplication main() { int a[10][10],b[10][10],c[10][10]; int r1,r2,c1,c2,i,j,k; clrscr(); printf("Enter Rows & Cols for Matrix 1 : "); scanf("%d%d",&r1,&c1); printf("Enter Rows & Cols for Matrix 2 : "); scanf("%d%d",&r2,&c2); if(c1 != r2) printf("MULTIPLICATION IS NOT POSSIBLE "); else { printf("Enter Values for Matrix 1 \n "); for(i=0;i<r1;i++) for(j=0;j<c1;j++) scanf("%d",&a[i][j]); printf("The Values for Matrix 1 \n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) printf("%3d",a[i][j]); printf("\n"); } printf("Enter Values for Matrix 2 \n "); for(i=0;i<r2;i++) for(j=0;j<c2;j++) scanf("%d",&b[i][j]); printf("Enter Values for Matrix 2 \n"); for(i=0;i<r2;i++) { for(j=0;j<c2;j++) _________________________________________________________
66 Programming In C ____________________________________________________ printf("%3d",b[i][j]); printf("\n"); } for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { c[i][j] = 0; for(k=0;k<r2;k++) c[i][j] = c[i][j] + a[i][k]*b[k][j]; } } printf("\n Resultant matrix is : \n"); for(i=0;i<r1;i++) { for(j=0;j<c2;j++) printf("%3d",c[i][j]); printf("\n"); } } getch(); }
_________________________________________________________
67 Programming In C ____________________________________________________
STRINGS
A string is a character may terminate with a null character`\0.
_________________________________________________________
68 Programming In C ____________________________________________________
Unformatted IO Function For Strings: 1gets () Function: It is defined in <stdio.h>. It is an unformatted Input function to accept a string.
_________________________________________________________
69 Programming In C ____________________________________________________
_________________________________________________________
70 Programming In C ____________________________________________________ Strlwr (): - The task of this function is to convert the given string into lower case. Strlwr (string name); Strdup (): - The task of this function to make a duplicate string for the given string Strdup (string name);
Exercise
1. write a program read a string #include<stdio.h> #include<conio.h> main() { char name[20]; int i; clrscr(); printf("ENTER UR NAME : "); gets(name); for(i=0; name[i]!='\0'; i++) printf("\n %c",name[i]); getch(); } _________________________________________________________
71 Programming In C ____________________________________________________ 2. write a program to read a string using gets() function & print that strin using puts() function main() { char str[20]; clrscr(); printf("\n Enter a string:"); gets(str); printf("\n The string is :"); puts(str); getch(); } 3. write a program to print a string character wise #include<stdio.h> #include<conio.h> main() { char name[20]; int i,j; clrscr(); printf("ENTER UR NAME : "); gets(name); for(i=0; name[i]!='\0'; i++) { for(j=0;j<=i;j++) printf("%2c",name[j]); printf("\n"); } getch(); } 4. write a program to print the before characters of a given string #include<stdio.h> #include<conio.h> #include<string.h> main() { _________________________________________________________
72 Programming In C ____________________________________________________ char name[20]; int i,j; clrscr(); printf("ENTER UR NAME : "); gets(name); strupr(name); puts(name); for(i=0; name[i]!='\0'; i++) { printf("%c - ",name[i]); for(j='A';j<= name[i];j++) printf("%2c",j); printf("\n"); } getch(); } 5. write a program to print specified No. of strings #include<stdio.h> #include<conio.h> main() { char name[5][20]; int i,n; clrscr(); printf("Enter a No:"); scanf("%d",&n); fflush(stdin); for(i=1;i<=n;i++) { printf("Enter Name : "); gets(name[i]); } printf("\n Given Name : \n"); for(i=1;i<=n;i++) puts(name[i]); getch(); }
_________________________________________________________
73 Programming In C ____________________________________________________ 6. write a program for String Handling Function strcpy() #include<stdio.h> #include<conio.h> #include<string.h> main() { char a[20],b[20]; clrscr(); printf(" Enter String A: "); gets(a); strcpy(b,a); printf(" String Copied \n B = %s",b); getch(); } 7. write a program for String Handling Function strcat() #include<stdio.h> #include<conio.h> #include<string.h> main() { char a[20],b[20]; clrscr(); printf(" Enter a String : "); gets(a); printf(" Enter a String : "); gets(b); strcat(a,b); printf(" String concatinated \n a = %s",a); getch(); } 8. write a program for String Handling Function strlen(). main() { char a[20]; int len; clrscr(); printf(" Enter a String : "); gets(a); _________________________________________________________
74 Programming In C ____________________________________________________ len = strlen(a); printf(" String Length = %d",len); getch(); } 9. write a program for String Handling Function strcmp() #include<stdio.h> #include<conio.h> #include<string.h> main() { char a[20],b[20]; int i; clrscr(); printf("Enter A String : "); gets(a); printf("Enter A String : "); gets(b); i = strcmp(a,b); if(i==0) printf("BOTH ARE EQUAL"); else if(i>0) printf("BIG = %s (FIRST STRING)",a); else printf("BIG = %s (SECOND STRING)",b); getch(); } 10. write a program for String Handling Function strcmpi() #include<string.h> main() { char a[20],b[20]; int i; clrscr(); printf("Enter A String : "); gets(a); printf("Enter A String : "); gets(b); i = strcmpi(a,b); _________________________________________________________
75 Programming In C ____________________________________________________ if(i==0) printf("BOTH ARE EQUAL"); else if(i>0) printf("BIG = %s (FIRST STRING)",a); else printf("BIG = %s (SECOND STRING)",b); getch(); } 11. write a program for String Handling Function strlwr(),strupr #include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[20]; clrscr(); printf("Enter a String : "); gets(a); printf("\n Given String in Upper Case : %s",strupr(a)); printf("\n Given String in Lower Case : %s",strlwr(a)); getch(); } 12. write a program for String Handling Function strrev() main() { char a[25]; clrscr(); printf("Enter A string : "); gets(a); printf("Reverse String : %s",strrev(a)); getch(); }
76 Programming In C ____________________________________________________ #include<stdio.h> #include<conio.h> #include<string.h> void main() { char ch,str[25]; int x; clrscr(); printf("Enter a String : "); gets(str); printf("Enter a Character to search : "); scanf("%c",&ch); x = strchr(str,ch); if(x!=0) printf("%c Existing in %s",ch,str); else printf("%c NOT EXISTING",ch); getch(); } 14. write a program for String Handling Function strstr
#include<stdio.h> #include<conio.h> #include<string.h> main() { char ch[25],str[25]; int x; clrscr(); printf("Enter a String : "); gets(str); printf("Enter a String to search : "); gets(ch); x = strstr(str,ch); if(x!=0) printf("%s Existing in %s",ch,str); else printf("%s NOT EXISTING",ch); getch(); }
_________________________________________________________
77 Programming In C ____________________________________________________ 15. write a program for String Handling Function strdup
#include<stdio.h> #include<conio.h> #include<string.h> main() { char s1[20]; char *s2; clrscr(); printf("\n Enter a string :"); gets(s1); s2=strdup(s1); printf("\n The duplicate copy is : %s",s2); getch(); } 16. write a program for Given string is palandrome or not #include<stdio.h> #include<conio.h> #include<string.h> main() { char a[25],b[25]; int x; clrscr(); printf("Enter a String : "); gets(a); printf("\n String in A:%s",a); strcpy(b,a); printf("\n String in B:%s",b); strrev(b); printf("\nAfter reversing the string B is:%s",b); x = strcmpi(a,b); if(x==0) printf("\n%s is PALANDROME",a); else printf("\n%s is NOT PALNDROME",a); getch(); } 17. write a program to arrange the given strings in alphabetical order _________________________________________________________
78 Programming In C ____________________________________________________ #include<stdio.h> #include<conio.h> #include<string.h> main() { char s[10][15],t[15]; int i,j,n; clrscr(); printf("\n Enter no. of strings:"); scanf("%d",&n); fflush(stdin); printf("\n Enter strings:"); for(i=0;i<n;i++) { scanf("%s",s[i]); } for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) { if(strcmpi(s[i],s[j])>0) { strcpy(t,s[i]); strcpy(s[i],s[j]); strcpy(s[j],t); } } printf("\n Strings in Alphabetical order"); for(i=0;i<n;i++) { printf("\n %s",s[i]); } getch(); }
Functions
_________________________________________________________
79 Programming In C ____________________________________________________
Function is a self-contained block of statements to achieve a specific task. A C program is a collection of functions along with the main () function.
Uses of Functions: To achieve modularity (Replication vs Repetition). To achieve readability. Errors can be easily identified (logically). Code can be reduced whenever there is replication.
Function Declaration or Prototype: It can be used to verify whether the function call made by the user is valid or not. It tells information about the function, like Number of arguments about the function along with data.Also tells the return type.
_________________________________________________________
80 Programming In C ____________________________________________________
81 Programming In C ____________________________________________________ is called, the control transferred along with the values of actual arguments, performs execution and will not return any value to the calling function. Function with arguments & with return values: -In this case there will be a two-way data transfer between the calling function and called function. Calling function may send any number of arguments where as the called function will return only one value.
General form:
_________________________________________________________
82 Programming In C ____________________________________________________
Library function:
Function prototype
Clrscr void clrscr ();
description
clear the screen, moves cursor to top left Corner.
Gotoxy () Kbhit ()
moves the cursor to the desired position. verified that any key is pressed or not, if The key is pressed returns its ASCII code Else 0
<ctype.h>
isdigit () int isdigit (char) non zero (if digit) Zero (if non digit) isspace () int isspace (char) non zero (if white space) Zero (else) isctrl () int isctrl (char) non-zero if control char. (ASCII value 0 to 32 char) isalpha () int isalpha (char)
_________________________________________________________
83 Programming In C ____________________________________________________
isupper () islower () toupper () tolower () int isupper (char) int islower(char) char toupper (char) char tolower (char)
<Math.h>
abs () ceil () floor () Pow () Log () log10 () exp () sqr() sqrt() cos acos() int abs (int); int ceil (double); int floor (double); int pow (int, int); double log (double); double log10(double); double exp(double) double sqr(double) double sqrt(int) double cos(double) double acos(double) returns cosine value for the given radians returns inverse of cosine of given radians with base e with base e exponential value absolute value nearest integer>value nearest integer<value
<stdlib.h>
atol() int atoi(char[]) returns integer equivalent of given string. it returns zero if the string contains non numeric. Atof() float atof(char[]) converts the given string into float Equivalent. Atol() Exit() Abort() System () long int atol(char[]); void exit(int); void abort(void) void system (char []) returns long int equivalent of given string. normal termination of the program abnormal termination. executes the dos command.
1) write a program to demonstrate Functions int add(int a,int b) /* function definition */ _________________________________________________________
Exercise
main() { int x,y,sum; clrscr(); printf("\n ENTER 2 NO : "); scanf("%d%d",&x,&y); sum = add(x,y); /* function call x,y are actual arguments */ printf("\n SUM = %d",sum); getch(); } 2) write a program to calculate ncr value using functions float fact(float n) { int i; float f=1.0; for(i=1;i<=n;i++) f = f*i; return f; } main() { float n,r,fn,fr,fnr,f; clrscr(); printf("ENTER N,R VALUES : "); scanf("%f%f",&n,&r); fn = fact(n); fr = fact(r); fnr = fact(n-r); f = fn/(fr*fnr); printf("\n RESULT : %.0f",f); getch(); }
_________________________________________________________
85 Programming In C ____________________________________________________ 3) write a program for reverse No int reverse(int x) { int r,s=0; while(x!=0) { r = x % 10; s = s*10+r; x = x/10; } return s; } main() { int n,r; clrscr(); printf("ENTER A NO : "); scanf("%d",&n); r = reverse(n); if(r==n) printf("%d PALANDROME",n); else printf("%d NOT PALANDROME",n); getch(); } 4) write a program for call by value void change(int x) { x = x*10; printf("\n VALUE IN FUNCTION : %d",x); } main() { int a=10; clrscr(); printf("\n A = %d",a); change(a); printf("\n A = %d",a); getch(); } _________________________________________________________
86 Programming In C ____________________________________________________
5) write a program for call by reference void change(int *x) { *x=*x * 10; printf("\n value in function=%d",*x); } main() { int y=10; clrscr(); printf("\n Y = %d",y); change(&y); printf("\n Y = %d",y); getch(); } 6) write a program funtion to find given no is prime or not int isPrime(int n) { int i,k=0; for(i=1;i<=n;i++) { if(n%i==0) k++; } if(k==2) return 1; else return 0; } main() { int n; clrscr(); printf("Enter a no : "); scanf("%d",&n); if(isPrime(n)) printf("%d IS PRIME",n); else printf("%d NOT PRIME",n); getch(); _________________________________________________________
87 Programming In C ____________________________________________________ } 7) write a program to pass array as arguments to a function printarray(int ar[]) { int i; printf("Enter an array values"); for(i=0;i<10;i++) scanf("%d",&ar[i]); printf("\n The Array elements are:"); for (i=0;i<10;i++) printf("%5d",ar[i]); } main() { int a[10]; clrscr(); printarray(a); getch(); } 8) write a program for recursive function long int fact(int n); main() { int n; long int f; clrscr(); printf("ENTER N : "); scanf("%d",&n); f=fact(n); printf("Factorial is :%ld",f); getch(); } long int fact(int n) { int i; long int f=1; for(i=n;i>=1;i--) f = f*i; _________________________________________________________
Storage classes
We can specify the storage class along with the data type, at the time of variable declaration. The storage class tells the following: _________________________________________________________
89 Programming In C ____________________________________________________ where the variable is stored(ram/cpu registers) where is the scope of the variable what is the life of variable. In c the storage classes are classified into
Storage: Main memory (RAM) Initial default value: Unpredictable (garbage) Scope: Local to the block/function in which the variable is
declared.
Eg: main()
Auto int a=0; { auto int a=1; { auto int a=2; printf(%d,a) } printf(%d,a); } printf(a) }
_________________________________________________________
90 Programming In C ____________________________________________________
Storage: Cpu register Initial default value: Unpredictable (garbage) Scope: Local to the block /function, in which the variable is
declared.
Initial default value: 0 Scope: Global to the block/function/entire program. Life: Through-out the program.
Static storage class variables are very use full in recursive functions.
91 Programming In C ____________________________________________________
Storage: Main memory. Initial default value: 0 Scope : Through out the program Life: Till the program comes to end
The extern storage class variables cannot be initialized at the time of definition.
Exercise
1. write a program for automatic storage class void display() { auto int a; printf("\n a = %d",a); } main() { clrscr(); display(); getch(); } 2. write a program for static variable void increment() { static int a; a++; printf("\n a= %d",a); } main() { clrscr(); increment(); increment(); increment(); getch(); _________________________________________________________
92 Programming In C ____________________________________________________ } 3. write a program for register storage class void put() { register int i; for(i=1;i<=100;i++) { printf("\n INDIA IS GREAT"); } } main() { clrscr(); put(); getch(); } 4. write a program for global variables int a,b=20; void demo() { a++; printf("\n a = %d",a); } main() { clrscr(); demo(); b++; printf("\n b = %d",b); getch(); }
_________________________________________________________
93 Programming In C ____________________________________________________ C supports a constructed user defined data type structure which is a method of packing data of different data types. Structure is useful to combine logically related information. The purpose of using the structures is to increase the readability of a program.
_________________________________________________________
94 Programming In C ____________________________________________________ The numbers of a structure variables can be accessed by means of a structure operator (.). The structure operator is used to superate the structure variable and its member.
Initialization structures:
We can initialize the structure , variables at the time of declaration .
Syntax: Struct structure name1 { data type member 1; data type member 2; : : data type member n; }; Struct structure name2 { data type member 1; data type member 2; : : data type member n; Struct structure name1 variable1,variable2;
_________________________________________________________
95 Programming In C ____________________________________________________ };
POINTERS TO STRUCTURES:
We can create pointers to a structure variable. The general form of defining pointer variable is Struct structure name * pointer variable; Here the pointer variable ,holds the address of the structure variable. The folder of the structure can be accessed indirectly by means of a pointer variable using pointer to structure operator. ()
_________________________________________________________
96 Programming In C ____________________________________________________ call by reference. sending the values of structure variable: when we are sending structure variable to a function, a dummy structure variable will be created in the called function and the content of actual argument is copy to it.
Syntax: Struct structure name { data type member 1; data type member 2; : : data type member n; }; Return type functionname(struct structure name variable_name) { ---------------------------------------}
_________________________________________________________
whenever we want to update a structure variable, we have to past the structure variable by reference to that function.
Syntax: Function name(&structure variable); Returntype variable) { ------------------------------} function name(struct structure name *pointer
Eg:
Increment (&e); Void increment (struct employee *pe) { pe e basic = pi e basic + 4000-00; return; } whenever the member of a structure is a pointer is referencing to a variable of same structure type then that structure is called self referencing structure. Synatax: Struct structure name { Datatype member1; Datatype member2; _________________________________________________________
Eg:
Struct node { int info; struct mode * next; };
UNIONS:
It is a method of packing data of different data types and all the union members will share the same storage area with in the main member. Unions are used to define user de find datatypes. Unions are use full for applications involving multiple members at a given time. The union variable may be defined as the variable that is shared by fields of that union be assigned to all the members at a given time. The union variable must be defined as the variable that is shared by fields of that union, which are generally of different data type at different times.
General form:
Union unionname { data type member1; data type member2; : : data type member n; };
_________________________________________________________
99 Programming In C ____________________________________________________ Once the union is defined, we can declare the union variables. The size of union variable is the size of its largest member.
General form:
Union union name variabled1,variable2,----variablen ; To access the members of the union we have to use the union operator (.). We can use pointer to union operator ()when we are accessing the members through a union pointer.
Type definition:
The new data type name can be created using typedef statement the typedef statement will create a new name for an existing data type other than creating a new datatype.
General form: typedef existing data type new name; Eg: Typedef int number;
Here number is an additional data type name, but not the replacement data type name int. It can be used to achieve machine independency is portability. It is for self documentation .
Enumerations:
An enumeration is a set of named integers constants. the fields of enumeration called as enumerators. The key word enum used to define new user defined data type along with renaming the integer constants. The enumeration values are treated as integer variables.
_________________________________________________________
General form:
enum [enum name] {enumerators separated by [variables]};
Eg3: enum{ten=10,twenty=20,thirty=30}; Note: The enumerators can not be used a long with console IO
functions; for (inputting)making IO through enumerators. Enumerations can be used to increase readability of the code. 1) write a program to demonstrate structure struct employee { int no; char name[20]; float sal; }; main() { struct employee e; clrscr(); printf("\n Enter employee no,name,sal:"); scanf("%d%s%f",&e.no,e.name,&e.sal); printf("EMPLOYEE DETAILS : \n"); printf("\n NO : %d",e.no); printf("\n NAME : %s",e.name); printf("\n SALARY : %f",e.sal); getch(); } 2) write a program to demonstrate array of structures
Exercise
_________________________________________________________
101Programming In C ____________________________________________________ #include<stdio.h> struct Employee { int no,sal; char name[20],job[20]; }; void line() { int i; for(i=1;i<=80;i++) printf("-"); } main() { struct Employee e[20]; /* array of structures */ int i,n; clrscr(); printf("\n Enter no. of employee:"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("\n"); printf("Enter no : "); scanf("%d",&e[i].no); printf("Enter Name : "); fflush(stdin); gets(e[i].name); printf("Enter Job : "); gets(e[i].job); printf("Enter Salary : "); scanf("%d",&e[i].sal); } for(i=1;i<=n;i++) { clrscr(); printf("\n \t\t\t EMPLOYEE DETAILS \n"); line(); printf("\n No : %d",e[i].no); printf("\n Name : %s",e[i].name); printf("\n Job : %s",e[i].job); printf("\n Salary : %d",e[i].sal); printf("\n Press key to next record.."); getch(); } getch(); _________________________________________________________
102 Programming In C ____________________________________________________ } 3) write a program to demonstrate Pointer to Array of structure variables #include<stdio.h> struct student { int no; char name[25],qual[25]; }; void main() { struct student s[50],*p,*t; int i,n; p=s; t=p; clrscr(); printf("How many Students? "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter No : "); scanf("%d",&p->no); fflush(stdin); printf("Enter Name : "); gets(p->name); printf("Enter Qualification :"); gets(p->qual); fflush(stdin); p++; } printf("\n\t\t Student Details "); printf("\n No Name \t\t Qual"); for(i=0;i<n;i++) { printf("\n %d %-25s %-25s",t->no,t->name,t->qual); t++; } getch(); } _________________________________________________________
103Programming In C ____________________________________________________ 4) write a program to demonstrate initialize a structure struct Item { char name[20]; int price; }; void main() { struct Item i ={"Soap",10}; struct Item *p; p=&i; clrscr(); printf(" ITEM : %s",p->name); printf("\n PRICE : %d",p->price); getch(); } 5) write a program to demonstrate structure with functions struct student { int rno; char name[10]; float per; }; void display(int n,char *s,float p) { printf("\n Roll no: %d",n); printf("\n Name : %s",s); printf("\n Percentage : %f",p); } main() { struct student s={10,"ravi",70.33}; clrscr(); display(s.rno,s.name,s.per); getch(); } _________________________________________________________
104 Programming In C ____________________________________________________ 6) write a program to demonstrate structure with pointers struct point { int x; int y; }; void increment(struct point *m) { m->x++; m->y++; } main() { struct point p; clrscr(); printf("\n Enter x,y coordinates:"); scanf("%d%d",&p.x,&p.y); printf("\n Before call: (%d,%d)",p.x,p.y); increment(&p); printf("\n After call: (%d,%d)",p.x,p.y); getch(); } 7) write a program to demonstrate structure with in a structure struct date { int dd; int mm; int yy; }; struct student { char name[15]; char class[10]; struct date d; }; _________________________________________________________
105Programming In C ____________________________________________________ main() { struct student s; clrscr(); printf("\n Enter name:"); gets(s.name); printf("\n Enter class:"); gets(s.class); printf("\n Enter joining date(d-m-y) :"); scanf("%d%d%d",&s.d.dd,&s.d.mm,&s.d.yy); printf("\n\n STUDENT DETAILS"); printf("\n Name : %s", s.name); printf("\n Class : %s",s.class); printf("\n DOJ : %d-%d%d",s.d.dd,s.d.mm,s.d.yy); getch(); } 8) write a program to demonstrate union union item { int code; char name[10]; }; main() { union item i; clrscr(); printf("\n Enter item code:"); scanf("%d",&i.code); printf("\n Item code : %d",i.code); printf("\n Enter item name:"); scanf("%s",i.name); printf("\n Item name : %s",i.name); printf("\n Size of union = %d bytes",sizeof(i)); getch(); } 9) write a program to demonstrate typedef typedef struct _________________________________________________________
106 Programming In C ____________________________________________________ { char name[25]; int age; }person; main() { person p; clrscr(); printf("Enter Name : "); gets(p.name); printf("Enter Age : "); scanf("%d",&p.age); printf("\n Person Details \n"); printf("\n Name : %s",p.name); printf("\n Age : %d",p.age); getch(); }
PREPROCESSORS
_________________________________________________________
INCLUDE
. OBJ .exe
Source code
The macro expansion directives: # define,# undefined is used to define macros and undefined macros.
_________________________________________________________
108 Programming In C ____________________________________________________ #define end } #define and && #define can be used to define a statement as normally . #define found printf(item is found) #define can be used to define macro with arguments. #define max (a,b)(a>b) a:b main(){ t=max(2,3);..}
_________________________________________________________
109Programming In C ____________________________________________________
General function:
# ifdef macro Sequence of statement(s); #else sequence of statement(s); #endif.
Eg:
#define INDIA main() _________________________________________________________
110 Programming In C ____________________________________________________ { #ifndef INDIA printf(India is my country); #else printf(India is not my country); #endif { 3. #ifndef #else #endif
General form:
#ifndef macro sequence of statement(s); #else sequence of statement(s); #endif
eg:
#define INDIA main() { #ifndef INDIA printf(India is not my country); #else printf(India is my country); #endif.
4.Miscellenenus directives:
_________________________________________________________
111Programming In C ____________________________________________________
General form:
#error message
eg:
main() { int I,n; printf(%d,n); #error after two statements . . }
Pointers
Pointer is a variables which holds the address of another variable. The uses of pointers are: _________________________________________________________
112 Programming In C ____________________________________________________ it provides the mechanism of to access a variables out side function in which it is defined. Pointers increase the execution speed. Pointers reduce the length and complexity of program. Pointers provide mechanism to maintain data tables more effectively. A pointer helps to support dynamic memory allocation.
Declaration of pointers:
General form: data type *ptr variablename;
_________________________________________________________
113Programming In C ____________________________________________________
Eg: scanf(%d,&list[i]);
Printf(%d,list[i]);
Homogeneous-arrays
Non homogeneous-structures Linear-arrays Non linear-pointers
_________________________________________________________
1. malloc (): <alloc.h> and <stdlib.h> Used to allocate a block of memory. The malloc () function returns the base address of allocated memory block as one.
General form:
Ptrvariable=(cast type*) malloc (size); Ptr=(int*)malloc(100*sizeof (int);
Note:
1. We cannot give names to the memory that are allocated dynamically.
_________________________________________________________
115Programming In C ____________________________________________________ 2. These functions returns null, if these failed to allocate sufficient amount of storage specified in malloc(). 3. #define NULL (void*) 0;
General function:
ptrvariable=(casttype x) calloc(no. of items, size of items);
General form:
ptrvariable=(casttype*)realloc(prevptr,newsize);
Exercise
1. write a program to demonstrate pointers main() { _________________________________________________________
116 Programming In C ____________________________________________________ int a = 10 int *ptr = &a; clrscr(); printf("\n a = %d",a); printf("\n *ptr = %d",*ptr); printf("\n &a = %u",&a); printf("\n ptr = %u",ptr); getch(); } 2. write a program to demonstrate pointers main() { int a,b,*ptr; clrscr(); a = 10; b = 20; ptr = &a; printf("\n *ptr = %d",*ptr); *ptr = 100; printf("\n a = %d",a); ptr = &b; printf("\n *ptr = %d",*ptr); *ptr = *ptr * 10; printf("\n b = %d",b); getch(); } 3. write a program to demonstrate pointers to arrays main() { int a[5]={5,4,6,2,1}; int *ptr,i; clrscr(); ptr = &a; printf("\n Array is:"); for(i=0;i<5;i++) { printf("\n %d",*ptr); ptr++; } getch(); _________________________________________________________
117Programming In C ____________________________________________________ } 4. write a program to demonstrate pointers with array variable main() { int a[5]={5,4,6,2,1}; int *ptr; clrscr(); ptr = a+3; printf("\n Element in position 3is:%d",*ptr); getch(); } 5. write a program to demonstrate pointers with functions void swap(int *,int *); main() { int x,y; clrscr(); printf("Enter 2 no : "); scanf("%d%d",&x,&y); printf("\nBefore Swaping: x = %d , y = %d",x,y); swap(&x,&y); printf("\nAfter Swaping : x = %d , y = %d",x,y); getch(); } void swap(int *a,int *b) { int c; c=*a; *a=*b; *b=c; } 6. write a program to demonstrate function with pointers void square(int s,int *a,int *p) _________________________________________________________
118 Programming In C ____________________________________________________ { *a = s*s; *p = 4*s; } main() { int s,area,peri; clrscr(); printf("ENTER SIDE : "); scanf("%d",&s); square(s,&area,&peri); printf("\n AREA = %d",area); printf("\n PERI = %d",peri); getch(); } 7. write a program to demonstrate pointer to pointer main() { int a=10,*p,**q; clrscr(); printf("\n a = %d",a); p=&a; printf("\n *p = %d",*p); printf("\n p(address of a) = %u",p); q=&p; printf("\n **q = %d",**q); printf("\n q(address of p) = %u",q); printf("\n *q(address of a) = %u",*q); printf("\n address of q = %u",&q); getch(); } 8. write a program function with pointers to demonstrate strings int slen(char *p) { int len=0; while(*p!='\0') { len++; _________________________________________________________
119Programming In C ____________________________________________________ p++; } return(len); } main() { char a[10]; int l; clrscr(); printf("\nEnter string:"); gets(a); l=slen(a); printf("\n Length of %s is: %d",a,l); getch(); } 9. write a program to demonstrate calling max() function through pointer int max(int a,int b) { if(a>b) return(a); else return(b); } main() { int x,y,big; int (*p)(int a,int b); p=&max; clrscr(); printf("\n Enter two no.s:"); scanf("%d%d",&x,&y); big=(*p)(x,y); printf("\n Biggest = %d",big); getch(); } 10. write a program to demonstrate factors
120 Programming In C ____________________________________________________ for(i=1;i<=n/2;i++) { if(n%i==0) printf("%d ",i); } printf(" %d",n); } main() { int n; void (*p)(int n); p=&factors; clrscr(); printf("\n Enter a no:"); scanf("%d",&n); printf("\n Factors of %d :",n); (*p)(n); getch(); } 11. write a program to demonstrate largest number int largest(int n) { int i,no,big=0; for(i=1;i<=n;i++) { printf("\n Enter a no:"); scanf("%d",&no); if(no>=big) big=no; } return(big); } main() { int n,res; int (*p)(int n); clrscr(); p=&largest; printf("\n Enter how many no.s:"); scanf("%d",&n); _________________________________________________________
121Programming In C ____________________________________________________ res=(*p)(n); printf("\n Biggest = %d",res); getch(); } 12. write a program to demonstrate void pointers
main() { int a=100; char b='s'; float c=45.4; void *p; clrscr(); p=&a; printf("\n *p = %d",*(int *)p); p=&b; printf("\n *p = %c",*(char *)p); p=&c; printf("\n *p = %f",*(float *)p); getch(); } 13. write a program to demonstrate sum of elements of array through pointer main() { int a[10],i,n,*p,s=0; clrscr(); printf("\n Enter no. of elements:"); scanf("%d",&n); printf("\n Enter elements:"); for(i=0;i<n;i++) scanf("%d",&a[i]); p=a; for(i=0;i<n;i++) { s=s+(*p); p++; } printf("\n Sum = %d",s); getch(); }
_________________________________________________________
main() { char a[10]={"aptech"}; char *s; clrscr(); s=a; printf("\n The string is:"); while(*s!='\0') { printf("%c",*s); s++; } getch(); } 15. write a program to demonstrate matrix multiplication using pointers #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int **a,**b,**c,r1,r2,c1,c2,i,j,k; clrscr(); printf(Enter the No.Of Rows & Coloumns of 1st matrix); scanf(%d%d,&r1,&c1); printf(Enter the No.Of Rows & Coloumns of 2nd matrix); scanf(%d%d,&r2,&c2); if(r2!=c1) printf(\n Multiplication is not possible); else { printf(Enter the elements of 1st matrix); a=(int **)malloc(r1 * sizeof(int *)); for(i=0;i<r1;i++) { *(a+i)=(int *)malloc(c1 * sizeof(int)); for(j=0;j<c1;j++) _________________________________________________________
123Programming In C ____________________________________________________ scanf(%d,*(a+i)+j); } printf(Enter the elements of 2nd matrix); b=(int **)malloc(r2 * sizeof(int *)); for(i=0;i<r2;i++) { *(b+i)=(int *)malloc(c2 * sizeof(int)); for(j=0;j<c2;j++) scanf(%d,*(b+i)+j); } c=(int **)malloc(r1 * sizeof(int *)); for(i=0;i<r1;i++) { *(c+i)=(int *)malloc(c2 * sizeof(int)); for(j=0;j<c2;j++) *(*(c+i)+j)=0; } for(i=0;i<r1;i++) for(j=0;j<c2;j++) for(k=0;k<c1;k++) *(*(c+i)+j)+=(*(*(a+i)+k))*(*(*(b+k)+j)); printf(\n Resultant Matrix is:); for(i=0;i<r1;i++) { printf(\n); for(j=0;j<c2;j++) printf(%3d,*(*(c+i)+j)); } } getch(); }
Files
A file is a place on the disk, where a group of related data is stored permanently ->c supports a no. of functions that have the ability to perform basic file operations
_________________________________________________________
Eg: file *fp; General form opening a file :File pointer=fopen(filename, mode); The file pointer contains the information about the file and i.e. subsequently used as a communication link. Between the hard disk and the program Opening the file specifies the purpose of opening the file, which is known as mode of operation
_________________________________________________________
125Programming In C ____________________________________________________ w+-same as w both reading and writing r+ -same as r both reading and writing a+ -same as a both reading and writing
General function:
fclose(file pointer); Ex: fclose(fp);
INPUT/OUTPUT FILES: 1.getc() & putc() functions: Putc (): the task of this function to write a character into a file
that is opened for writing. General function: Putc(char,fileptr); Eg: file*fp; fp=fopen(file name,w); putch(a,fp) fclose(fp);
_________________________________________________________
_________________________________________________________
127Programming In C ____________________________________________________
fscanf(),fprintf():
These functions are used to perform IO on files with mixed data. These are called as mixedIO functions
general function:
fscanf(fp,controlstring,address of variables); ->The fscanf() function will return EOF at the end of the file
General function:
write (address of data, size of data, number of items file pointer);
_________________________________________________________
General function:
read(address,size,no of items ,file pointer);
fseek:
fseek(fp,offset,origin) 0-seek-set 1-seek-cur 2-seek-end ->fseek() can be used to move the file pointer to the desired location in the file ->The origin tell base for the reference ->The offset tells no of bytes that the file pointer is shifted from the specified origin eg:seek (fp,50*il,seek-set); seek (fp,50*il,seek-end);
ferror() functions :
ferror is used to identify any kind of errors during file operations
_________________________________________________________
129Programming In C ____________________________________________________
Execise
1) write a program to demonstrate inputting and outputting a file #include<stdio.h> #include<conio.h> main() { FILE *fp; char c; clrscr(); fp = fopen("Dev.dat","w"); printf("\n Enter data into the file( Ctrl + z to stop): "); while((c=getchar())!=EOF) { putc(c,fp); } fclose(fp); fp=fopen("Dev.dat","r"); printf("DATA IS : "); while((c=getc(fp))!=EOF) { printf("%c",c); } getch(); } 2) write a program to demonstrate to make one file data to another #include<stdio.h> #include<conio.h> main() { FILE *sfp,*dfp; char sfile[20],dfile[20],ch; clrscr(); printf("Source File Name With Extension: "); gets(sfile); printf("Destination File Name With Extension:"); gets(dfile); _________________________________________________________
130 Programming In C ____________________________________________________ sfp = fopen(sfile,"w"); printf("\n Enter data into Source File:"); while((ch=getchar())!=EOF) { putc(ch,sfp); } fclose(sfp); sfp=fopen(sfile,"r"); dfp=fopen(dfile,"w"); while((ch=getc(sfp))!=EOF) { putc(ch,dfp); } fclose(sfp); fclose(dfp); printf("\n DATA TRANSFERED"); dfp=fopen(dfile,"r"); printf("\n Data in Destination File:"); while((ch = getc(dfp))!=EOF) { printf("%c",ch); } fclose(dfp); getch(); } 3) write a program to demonstrate to find even & odd files #include<stdio.h> #include<conio.h> void main() { int i,n,num; FILE *f1,*f2,*f3; clrscr(); printf("\n Enter how many no.s:"); scanf("%d",&n); f1=fopen("main.dat","w"); for(i=1;i<=n;i++) { printf("\n Enter a no:"); scanf("%d",&num);
_________________________________________________________
131Programming In C ____________________________________________________ if(num==-1) break; else putw(num,f1); } fclose(f1); f1=fopen("main.dat","r"); f2=fopen("even.dat","w"); f3=fopen("odd.dat","w"); while((num=getw(f1))!=EOF) { if(num%2==0) putw(num,f2); else putw(num,f3); } fclose(f1); fclose(f2); fclose(f3); printf("\n Even file: "); f2=fopen("even.dat","r"); while((num=getw(f2))!=EOF) { printf("%d ",num); } fclose(f2); printf("\n Odd file :"); f3=fopen("odd.dat","r"); while((num=getw(f3))!=EOF) { printf("%d ",num); } fclose(f3); getch(); } 4) write a program to demonstrate files using structures #include<stdio.h> #include<conio.h> struct address { char name[10],dno[10],street[10]; }; void main() { struct address a; _________________________________________________________
132 Programming In C ____________________________________________________ FILE *fp; clrscr(); fp=fopen("address.dat","w"); printf("\n Enter name:"); scanf("%s",a.name); printf("\n Enter door no:"); scanf("%s",a.dno); printf("\n Enter street:"); scanf("%s",a.street); fprintf(fp,"%s\n%s\n %s",a.name,a.dno,a.street); fclose(fp); fp=fopen("address.dat","r"); printf("\n Data in the file is :"); while(!feof(fp)) { fscanf(fp,"%s%s%s",a.name,a.dno,a.street); printf("%s \n %s \n %s",a.name,a.dno,a.street); } fclose(fp); getch(); }
133Programming In C ____________________________________________________ Eg: main (int argc, char *argr []) { int I; for(I=;I<=args;++) printf(%s,args[i]; note:args is that the possible argument vector used to store the argument values
_________________________________________________________