C Language
C Language
************************************* Programming languages can be divided into two categories: a) Problem oriented language or high-level language ******************************************* designed to give a better programming efficiency, i.e. faster program development. Example:- FORTRAN, BASIC, COBOL, etc. b)Machine oriented language or low level language ******************************************* designed to give a better machine efficiency. i.e faster program execution. Example:- Assembly language and Machine language C stands between two categories. it is called a Middle level language, since it was designed to have both a relatively good programming efficiency (as compared to Machine oriented language) and a relatively good machine efficiency (as compared to Problem oriented language) What is C? ********** C is a programming language developed at AT & T`s Bell Laboratories of USA in 1972 by Dennis Ritchie. Historical Development of C ****************************
By 1960 there were computer languages been in existence almost each for a specific purpose. For example,COBOL was being used for Commercial Application, FORTRAN for Engineering and Scientific Application and so on. At this stage people started thinking that instead of learning and using so many languages, each for a different purpose,why not use only one language which can program all possible application. Therefore,an international committee for computer languages came out with a solution and developed a language called ALGOL 60.
YEAR LANGUAGE
1960 ALGOL 60 1963
DEVELOPED REMARKS BY
International Committee of computer languages Cambridge University Not Popularised Since it was Too general and too abstract Has so many features.Hard to learn. Difficult to implement Powerless.could deal with only specific problems
1967
1970
1972 C
Dennis Lost generality Ritchie of BCPL and B At AT & T restored Bell Labs.USA
Translator:
************ Computer can understand only machine codes of binary 0 or 1. It is difficult to write and maintain the program of machine codes. hence the need arises for converting the code of high level and low level language into machine codes. translators are used to achieve this process. Assembler: ********** used for converting the code of low level language (assembly language) into machine codes. Compiler: ********** used for converting the code of high level language program into machine codes. The compiler search all the errors of program and list them.errors has to be rectified ( debug ) by the user. If the program is error free then, compiler converts the program into machine code and then the program is executed by the run command.
Interpreter: *********** It is same as the compiler. converting high level language into machine codes. but it checks the errors of program statement by statement. After checking one statement,it converts that statement into machine code and then executes that statement.
Tokens: ******* The smallest unit in a program is known as token. The following entities are known as tokens. 1. keywords 2. identifiers 3. Constants 4. strings 5. operator Keywords or reserved words: ************************** there are 32 Keywords in C, are the predefined words having specific meaning. these keywords can not be used other than the purpose reserved for it. Identifiers : ************* name of the variables, functions, arrays, classes, structures, unions etc., are called identifiers. rules to be followed for constructing an identifier name are as follows. 1. an identifier cannot be a keyword.
2. alphabets,numbers and underscore are alone permitted. 3. first character must be either alphabets or underscore. 4. both uppercase and lowercase are permitted but they are treated differently. i.e. total is different from Total. Operator: ********* An operator operates on constants and variables. Operators are classified as unary, binary and ternary operator. Unary operator operates on single variable. Binary operator operates on two variables. ternary operator has three terms. Basic Data types in C: ********************** Data Type Value Range String Signed char unsigned char Short signed int Short unsigned int long signed int Long unsigned -128 to +127 0 to 255 -32768 to +32767 0 to 65535 -2147483648 to +2147483647 0 to 4294967295
Bytes 1 1 2 2 4 4
4 8 10
%f %lf %Lf
GETTING INTO C 1. START THE COMPUTER IN MS-DOS MODE 2. TYPE THE FOLLOWING F:\ F:\ F:\ F:\ LOGIN > login student STUDENT > md Vxxxx STUDENT > cd Vxxxx STUDENT \ Vxxxx > tc
2. PRESS ALT + O for OPTIONS menu 3. select DIRECTORIES . 4. Then Press ENTER key 5. TYPE THE FOLLOWING include directories : X: \ SOFTWARE \ TURBO \ INCLUDE library directories : X: \ SOFTWARE \ TURBO \ LIB 6. PRESS ESC KEY TWICE PROGRAM EXECUTION 1. TYPE THE PROGRAM 2. 3. 4. 5. 6. press F2 & SAVE the File
press ALT + F9 to COMPILE the file if the Program has Errors press F6 Then correct the mistakes Press ALT + F9 again to COMPILE the file
7. if there is no error , press CTRL + F9 to RUN the Program note: i. press F3 to OPEN the File ii. press ALT + x for EXIT
/* Sum of
The Integers */
*/ */
printf(\n Enter Two Numbers ); scanf(%d%d,&a,&b); /* READING THE VALUES */ c=a+b; /* PROCESSING */ printf("\n Sum of %d and %d is ...%d", a,b,c); /* PRINTING THE VALUES */ getch(); }
/* Product
#include<stdio.h> main ( ) { float x,y,z; /* DECLARATION clrscr();
of
The Floats */
*/ */
printf ("\n Enter Two Decimal Numbers "); /* PRINTING THE MESSAGE */ scanf("%f%f",&x,&y); /* READING THE VALUES */ z=x*y; /* PROCESSING */
printf("\n Product of %f and %f is ... %f ", x,y,z); /* PRINTING THE VALUES */ getch(); } /* Area of The Triangle */ #include<stdio.h> main( ) { float area,b,h;
clrscr( ); printf("\nEnter The Base & Height of The Triangle"); scanf("%f%f",&b,&h); area=0.5*b*h; printf("\n Area of triangle is ...%f ",area); getch(); } /* Area of The Circle*/ #include<stdio.h> main( ) { float area,rad; clrscr(); printf("\n Enter The radius of circle "); scanf("%f ",&rad); area=3.14*rad*rad; printf("\n Area of circle Is ...%f ",area); getch(); }
CHAPTER -2
Operators in C language ************************ 1. Arithmatic operators --- + , * , - , / , % (modulus) 2. Relational operators --- > , >= , < , <=, = =, !=
3. Logical operators --- && (and), || (or), ! (not) 4. Conditional and Ternary operator --- ? , : 5. Assignment operators a) Simple assignment operator -- = equal to b) Compound assignment operators +=, *=, -=, /=, %= 6) Unary operators a) Increment operator ++ b) Decrement operator - 7) Special operators sizeof() , * dereference , indirection ARITHMATIC OPERATORS #include<stdio.h> main( ) { clrscr( ); printf(\n\t\t Arithmatic Operators \n); puts(\n \t\t ------------------------------------); printf(\n\t\t 10+55-7 = %d , 10+55-7 ); printf(\n\t\t 10.0/3 = %.2f , 10.0/3 ); printf(\n\t\t 8.4*17 - 67.4 / 9.3 = %.3f , 8.4*17 - 67.4 / 9.3 ); getch(); } RELATIONAL OPERATORS #include<stdio.h>
main( ) { int x,y,z; clrscr( ); printf(\n Enter 3 numbers ); scanf(%d%d%d,&x,&y,&z); printf(\n\t x<y = %d , x<y); printf(\n\t z>x = %d , z>x); printf(\n\t y<=z = %d , y<=z); printf(\n\t z>=x = %d , z>=x); printf(\n\t x==y = %d , x==y); printf(\n\t y!=z = %d , y!=z); getch(); } LOGICAL OPERATORS #include<stdio.h> main() { clrscr(); printf(\n\t\t 10>7 and 2<5 = %d , 10>7 && 2<5 ); printf(\n\t\t 23>=19 and 56==28*2 = %d , 23>=19 && 56==28*2 ); printf(\n\t\t 45 != 21/7 and 67<=24 = %d , 45 != 21/7 && 67<=24 ); printf(\n\t\t 6 modulus 4>7 or 45 != 56 = %d , 6%4>7 || 45 != 56 ); printf(\n\t\t 29< 45/2 or 34==17*3 = %d , 29<45/2 || 34 == 17*3 ); getch(); }
/*
unary operators
*/
#include<stdio.h> main() { int j,k; clrscr(); printf("\n Enter Two Numbers ); scanf(%d%d,&j,&k); printf(\n pre-increment of j =%d ,++j); printf(\n post-increment of j =%d ,j++); printf(\n J =%d ,j); printf("\n pre-decrement of k =%d,--k); printf("\n post-decrement of k =%d,k--); printf(\n K =%d ,k); getch(); }
CONDITIONAL AND TERNARY OPERATOR #include<stdio.h> void main() { int k; clrscr(); printf("\n Enter a Number "); scanf("%d",&k); k<0? printf (\n %d is negative,k) : printf (\n %d is positive,k) ;
getch(); } Conditional operator is also called as ternary operator because it has three terms. The terms are Test Condition, True Expression and False Expression.
#include<stdio.h> main() { int a, b, g ; clrscr(); printf("\n Enter Two Numbers "); scanf("%d%d",&a,&b); g = a>b? a : b ; printf (\n %d is the Greatest Number, g) ; getch(); } Greatest out of 3 numbers operator #include<stdio.h> main() { int x, y, z, g; clrscr(); printf("\n Enter Three Numbers "); scanf("%d%d%d",&x,&y,&z); by ternary
g = x>y? x>z? x : z : y>z? y : z ; printf (\n Greatest of the given Nos. is%d , g) ; getch(); }
mathematical functions #include<stdio.h> #include<math.h> main() { int n, base, power; unsigned long int b; clrscr(); printf("\n Enter a Number .."); scanf("%d",&n); printf("\n Square Root of %d is %.2f", n, sqrt(n)); printf("\nEnter the base Number and The Power "); scanf("%d%d",&base,&power); b=pow(base,power); printf("\n %d to The Power of %d is %lu ", base,power,b); getch(); }
CELSIUS TO FAHRENHEIT
clrscr(); printf(\n Enter The Temperature in Celsius ); scanf(%f,&cl); fr=1.8*cl+32; printf(\n %.2f CELSIUS IS = %.2f FAHRENHEITS, cl,fr); getch(); } COLOR TEXT #include<stdio.h> main() { int n; clrscr(); printf(\n Enter a Number ); scanf(%d,&n); textcolor(n); cprintf(\n\t LINKED LIST IS THE COLLECTION OF NODES ); getch(); }
/* leap year */ #include<stdio.h> main() { int year; clrscr(); printf("\n Enter the Year .."); scanf("%d",&year); if ( year % 4 = = 0) printf("\n %d is Leap Year", year); else printf("\n %d is Not Leap Year", year); getch(); } /* NESTED IF */ #include<stdio.h> #include<string.h> main() { int age; char name[25], nation[20]; clrscr(); printf(\n Enter The Name and Age ); scanf(%s %d,name,&age); printf(\n Enter The Nation ); scanf(%s,nation); if (age>=18) if (strcmpi (nation, india) = = 0) printf(\n %s is Eligible to vote, name); else
printf(\n %s is not Eligible to vote, name); else printf(\n %s is Below the prescribed age , name); getch(); } ELECTRICITY BILL - NESTED ELSE #include<stdio.h> main() { int units; float amount; clrscr(); printf(\n\n Enter The No of Units ); scanf(%d,&units); if (units <= 100) amount=units*0.80; else if (units > 100 && units <= 200) amount=80 + (units-100)*1.20; else if (units > 200 && units <= 300) amount=200 + (units-200)*1.60; else if (units > 300 && units <= 400) amount=360 + (units-300)*2.00; printf(\n\n Amount to be paid : %.2f , amount); getch(); }
#include<stdio.h> main() { char v; clrscr(); printf(\n Enter a Number or Character ); v=getchar(); if (v == a || v == e || v == i || v == o || v == u ) printf(\n %c is a Vowel , v); else if (v >= 0 && v <= 9 ) printf (\n %c is a Number , v); else if (v >a && v <= z ) printf(\n %c is a Consonant , v); else printf(\n %c is a Special Character , v); getch();
} greatest number among three values logical operators #include<stdio.h> main() { int x,y,z; clrscr(); printf("\nEnter 3 Numbers "); scanf("%d%d%d",&x,&y,&z); if (x>y && x>z) printf("\n %d is greater", x);
else if (y>z) printf("\n %d is greater",y); else printf("\n %d is greater ",z); getch(); } GOTO **** goto statement to move from one point to another unconditionally. /* goto statement */ #include<stdio.h> main() { int no; float cl,fr,ang,rad; clrscr(); printf("\n Enter a number "); scanf("%d",&no); if (no <= 5) goto angle; else printf("\n Enter the Fahrenheit Temparature ); scanf(%f,&fr); cl=(fr-32)/1.8; printf(\n %.2f Fahrenheits = %.2f Celsius, fr,cl);
goto end; angle: printf(\n Enter the Angle ); scanf(%f,&ang); rad=3.14*ang/180; printf(\n %.2f Degress = %.2f Radians, ang,rad); end: puts(\n Try Again ); getch(); } switch case ************ C has a built -in multiway decision statement known as switch. switch statement tests the value of a given variable against a list of case values and when a match is found, a block of statements associated with that case is executed. break brings the control out of the FOR loop & WHILE loop or SWITCH block continue brings the control to the beginning of the loop
#include<stdio.h> main()
{ int x, y, z=0; char v; clrscr(); printf("\n Enter Two Numbers"); scanf("%d%d",&x,&y); printf("\n + A. Addition"); printf("\n -- S. Subtraction"); printf("\n * 3. Multiplication"); printf("\n / 4. Division "); printf("\nEnter a Number or a Character "); v=getche(); switch (v) { case a: case +: z = x + y; break; case s: case -: z = x - y; break; case 3: case *: z = x * y; break; case 4: case / : z = x / y; break;
printf(\n Enter the Radius of Sphere ); scanf(%d,&radius); volume = 4/3 * pi * pow(radius,3); printf(\n Volume of The Sphere: %.3f , volume); break; case 3: printf(\n Enter the Principle Amount ); scanf(%f,&prince); printf(\nEnter the Instalments & Rate of Intrest); scanf(%d%f,&n,&rate); si = prince*n*rate/100; printf(\n Simple Intrest is : %.2f , si ); break; default: puts(\n Choice not determined ); } getch(); } LOOPINGS ******** for loop executes the set of statements to particular number of times. syntax :
for ( Initialising; Condition; Alteration) { statements ; -----------------; } #include<stdio.h> main() { char p; clrscr(); for (p=a;p<=z;p++) { putchar(p); putchar(p-32); putchar(\t); } getch(); }
int n, i; clrscr(); printf(\n Enter a Number ); scanf("%d",&n); for(i=3;i<=n;i++) fact *= i; /* fact = fact * i */ printf(\n Factorial of %d is %lu,n,fact); getch(); } PRIME NUMBERS #include<stdio.h> main() { int n, i, j=0; clrscr(); printf(\n Enter a Number ); scanf(%d,&n); for (i=2;i<=n/2;i++) { if (n%i == 0) j++; } if (j == 0) printf(\n %d is a Prime Number ,n); else printf(\n %d is a Composite Number ,n); getch(); }
/* fibbonacci series */ #include<stdio.h> main() { int n,i,a,b,c; clrscr(); printf("\nEnter The Limit for Fibbonacci"); scanf("%d",&n); printf("\nEnter Two Numbers ); scanf("%d%d",&a,&b); printf(%d \t %d,a,b); for(i=0;i<n;i++) { c=a+b; printf("\t %d",c); a=b; b=c; } getch(); }
int n,i,a,b,c,d; clrscr(); printf("\nEnter The Limit for Tribbonacci"); scanf("%d",&n); printf(" \n Enter 3 numbers ); scanf("%d%d%d",&a,&b,&c); printf("%d \t %d \t %d",a,b,c); for(i=0;i<n;i++) { d=a+b+c; printf("\t %d",d); a=b; b=c; c=d; } getch(); } multiplication table using the for loop #include<stdio.h> main() { int n, i; clrscr(); printf("\nEnter the Multiplication Table number..."); scanf("%d",&n); for(i=1;i<=25;i++) printf("\n %d * %d = %d ", n, i, n*i);
getch(); } NESTED FOR LOOP #include<stdio.h> main() { int j, k; clrscr(); for ( j=2; j<=5; j++) for ( k=2; k<=5; k++) printf(\n \t %d*%d=%d , j, k, j*k); getch(); } PERFECT NUMBERS #include<stdio.h> main() { int n, i, j, f; clrscr(); printf("\n Enter the Limit for Perfect .."); scanf("%d",&n); for (i=6;i<=n;i++) { f=1; for (j=2;j<=i/2;j++) { if (i%j == 0) f=f*j;
#include<stdio.h> main() { int n,i,j,k,m=0; clrscr(); printf("\nEnter the Number of Lines "); scanf("%d",&n); printf("\n\n\n"); for(i=1;i<=n;i++) { printf("\t\t\t"); for (k=n;k>i;k--) printf( ); for(j=1;j<=i;j++) printf(%d ,++m); printf("\n"); } getch(); }
while loop
#include<stdio.h> main() { int a; char ch='y'; clrscr(); while (ch=='Y'|| ch=='y') { printf("\nEnter The Number "); scanf("%d",&a); if (a%2==0) printf(" \n %d is an Even Number ",a); else printf( \n %d is an Odd Number ",a); printf("\nWant To Continue Yes/No?"); fflush(stdin); /* clears the buffer */ ch=getchar(); } getch(); } do while loop to find the positive or negative #include<stdio.h> main() { int a; char ch='y'; clrscr();
do { printf("\n Enter a Number "); scanf ("%d",&a); if (a>0) printf("\n %d is Positive",a); else printf("\n %d is Negative",a); fflush(stdin); printf("\nWant To Continue Yes/No?"); ch=getchar( ); } while (ch=='Y' || ch=='y'); getch(); } GRADE #include<stdio.h> main() { int tam, eng, mat, sci, his, total,; float avg; char name[30] , grade, k; clrscr(); do { printf("\nEnter The Student Name "); scanf("%s,name); printf("\n Enter The Subject Marks "); scanf("%d%d%d%d%d",&tam,&eng,&mat,&sci,&his); total=tam+eng+mat+sci+his; avg=(float) total/5;
printf(\n Total = %d , total); printf(\nAverage = %.2f, avg); if (tam>49 && eng>49 && mat>49 && sci>49 && his>49 ) { if ( avg >= 90 ) grade=A; else if ( avg>70 && avg < 90) grade=B; else grade=C; printf ( \n %s has passed in grade %c , name , grade); } else printf ( \n %s has failed , name ); printf (\nWant to Continue ? Yes/No ); fflush (stdin); k = getchar (); } while (k = = y || k = = Y); getch(); }
COUNT OF LINES, WORDS & CHARECTERS #include<stdio.h> main() { int line=0, word=0, n=0; char c; clrscr();
puts(\n Type the Sentences press CTRL + Z to Stop ); do { c=getchar(); if (c==\n) ++line; else if (c== ) ++word; else ++n; } while (c != EOF); printf(\n TOTAL NO. OF WORDS = %d , word+line); printf(\n TOTAL NO. OF LINES = %d , line); printf(\n TOTAL NO. OF CHARECTERS = %d, n); getch(); } ARMSTRONG NUMBERS
#include<stdio.h> main() { int n, s, z, i, p, r ; clrscr(); printf(\n Enter The Armstrong Limit ); scanf(%d,&n); for (i = 1; i <= n; i++) { z = p = i; s=0; while (p>0) { r=p%10; p=p/10;
CHAPTER 4
ARRAYS
Array is a data structure , stores the values of similar data_type. Array is a group of related data items that shares a common name. types of array ****************** 1. single dimensional syntax: ******* data_type array_name [size]; 2. Two dimensional or multi dimensional syntax ****** data_type array_name [size1] [size2];
scanf("%d",&n); printf("\n Enter The Numbers "); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) { printf("%d\t",a[i]); total += a[i]; } printf("\n Total is ...%d\n",total); avg= (float) total/n; printf("\n Average is ..%.2f",avg); getch(); } character array #include<stdio.h> main() { int i; char b[ ]={'c','o','m','p','u','t','e','r'}; char k[8][10] = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "\0"}; clrscr(); for(i=0;i<8;i++) printf ("%c",b[i]); printf (" \n The weekdays are ); for (i=0;i<7;i++) printf (\n \t %s ,k[i]); getch(); } sound #include<stdio.h>
main() { int i, a[5]; clrscr(); printf(\n Enter the Numbers ); for(i=0;i<5;i++) scanf(%d,&a[i]); for(i=0;i<5;i++) { sound ( a[i] ); delay ( 10000 ); nosound ( ); } exit ( ); }
DELETE THE WORDS FROM A SENTENCE #include<stdio.h> #include<string.h> main() { char str[100]; int n , j , c=0; clrscr(); printf(\n Enter a Sentence ); gets(str); printf(\n Enter The No. of Words to Delete ); scanf(%d,&n); j=strlen(str)-1; while (j >= 0 && c != n) { if (str[j] != 32 && str[j-1] == 32) { c++;
getch(); } /* to find the minimum and maximum value in the array */ #include<stdio.h> main() { int a[25], i, n, min, max; clrscr(); printf("\n Enter the Limit of Array..."); scanf("%d",&n); printf("\n Enter The Numbers "); for(i=0;i<n;i++) scanf("%d",&a[i]); max=a[0]; min=a[0]; for(i=1;i<n;i++) { if (max<a[i]) max=a[i]; if (min>a[i]) min=a[i]; } printf("\n Maximum Value is %d",max); printf("\n Minimum Value is %d",min); getch(); } /* to sort the array */ #include<stdio.h> main()
{ int a[15], i, j, temp, n; clrscr(); printf (\n Enter the Limit for Array.); scanf(%d,&n); printf("\n Enter The Numbers "); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if ( a[i] > a[j] ) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } printf("\nAscending Order Of Given Numbers"); for(i=0;i<n;i++) printf("\n %d ",a[i]); getch(); } /* avoiding the duplicate values in the array */ #include<stdio.h> main() { int n, i, j, a[20]; clrscr(); printf("\n Enter The Limit of Array "); scanf("%d",&n);
printf("\n Enter The Numbers ); for ( i=0; i<n; i++) { scanf ("%d", &a[i]); for ( j=i-1; j>=0; j--) { if ( a[i] == a[j] ) { printf("\nDuplicate Value! Enter Another Value"); i--; } } } puts("\n The Unique Values Are..."); for (i=0; i<n; i++) printf ("%d\t",a[i]); getch(); }
DECIMAL TO BINARY
#include<stdio.h> main() { int i=0, n, b[20]; clrscr(); printf (\n Enter a Number ); scanf (%d,&n); while (n>1) { b[i]=n%2; n/=2; i++; } b[i]=n;
/* Multidimensional ArrayMatrix Addition */ #include<stdio.h> main() { int s[5][5], a[5][5], b[5][5]; int row, col, i, j; clrscr(); printf(\nEnter Number of Rows & Columns); scanf(%d%d,&row,&col); printf(\n Enter the values for matrix A ); for(i=0;i<row;i++) { for(j=0;j<col;j++) scanf("%d",&a[i][j]); } printf("\n Enter the values for matrix B "); for(i=0;i<row;i++) { for(j=0;j<col;j++) scanf("%d",&b[i][j]); } printf("\n Sum of matrices \n"); for(i=0;i<row;i++) { for(j=0;j<col;j++) { s[i][j]=a[i][j]+b[i][j];
MATRIX MULTIPLICATION #include<stdio.h> main() { int a[2][3],b[3][2],d[2][2],i,j,k; clrscr(); printf("\nENTER THE VALUES FOR MATRIX A ( 2 X 3 )"); for (i=0; i<2; i++) { for (j=0; j<3; j++) scanf("%d",&a[i][j]); } printf("\nENTER THE VALUES FOR MATRIX B ( 3 X 2 )"); for(i=0;i<3;i++) { for(j=0;j<2;j++) scanf("%d",&b[i][j]); } printf("\nTHE RESULTANT MATRIX \n "); for(i=0;i<2;i++) { for(j=0;j<2;j++) { d[i][j]=0; for(k=0;k<3;k++) d[i][j] += a[i][k]*b[k][j];
printf("\t %d",d[i][j]); } printf("\n"); } getch(); } STRING HANDLING FUNCTIONS *************************** 1.strlen() to find the length(number of characters) of string. 2.strrev() reverses the given string 3.strcmp() to compare the two strings 4.strcat() to join or concatenate the multiple strings 5.strcpy() to copy one string into another 6.strstr() to find the substring #include<stdio.h> #include<string.h> main() { char word[70], rev[50], str[45]; clrscr(); printf("\n Enter a Word "); gets(word); printf(\n LENGTH OF THE STRING = %d , strlen(word)); strcpy(rev,word); if (strcmp(strrev(word),rev)==0) printf("\n %s is Palindrome",word); else printf("\n %s is Not Palindrome", word); printf("\n Enter another Word "); gets(str);
printf(\n JOINED WORDS ARE = %s , strcat(word,str)); getch(); } Palindrome without string handling functions #include<stdio.h> main() { char word[20], rev[20]; int i, j=0, k=0; clrscr(); printf("\n Enter the word "); scanf("%s",word); for(i=0;word[i]!='\0';i++) k++; printf(\n Length of String is%d,k); for(i=0;i<k;i++) { rev[i]=word[k-1-i]; if (rev[i] != word[i]) j++; } rev[i]='\0'; printf("\n Reversed word..%s", rev); if (j==0) printf("\n %s is Palindrome", word); else printf("\n %s is Not Palindrome", word); getch(); }
CHAPTER-5
********
FUNCTIONS
A function is a sub-program, groups a number of statements into a single unit and given a name (identifier). Function unit can be called from the other part of the program . The purpose of using function is to reduce the length of the program. The repeated set of statements can be defined as a function and the user can call the function any number of times,anywhere from the program . CLASSIFICATION OF FUNCTIONS *************************** 1.LIBRARY FUNCTION or BUILT-IN FUNCTION Example : printf( ), scanf ( ), clrscr (), strlen ( ), puts ( ) etc.etc. 2. USER DEFINED FUNCTION (UDF) Example: add( ), csc ( ), sub ( ) , madhurai ( ) TYPES OF USER DEFINED FUNCTION ****************************** 1.FUNCTION BOTH WITHOUT ARGUMENT AND RETURNTYPE 2.FUNCTION WITHOUT ARGUMENT AND WITH RETURNTYPE 3.FUNCTION WITH ARGUMENT AND WITHOUT RETURNTYPE 4.FUNCTION BOTH WITH ARGUMENT AND RETURNTYPE STEPS OF FUNCTION ***************** 1. FUNCTION DECLARATION or PROTOTYPE 2. FUNCTION CALL 3. FUNCTION DEFINITION or CALLED FUNCTION note:1. FUNCTION DECLARATION IS OPTIONAL IN C LANGUAGE 2. BY DEFAULT RETURNTYPE FOR C LANGUAGE IS INTEGER
3. VOID INDICATES THAT , NO VALUE IS GOING TO BE RETURNED FROM THE FUNCTION function both without argument and returntype #include<stdio.h> void add ( ); /* FUNCTION DECLARATION */ main ( ) { clrscr( ); add( ); /* FUNCTION CALL */ printf("\n I Am In Main"); add( ); /* FUNCTION CALLED AGAIN */ getch(); } void add( ) /* FUNCTION DEFINITION */ { int a,b,c; printf("\nEnter Two Numbers "); scanf("%d%d",&a,&b); c=a+b; printf("\n Sum of the Numbers = %d",c); } function with returntype and without argument #include<stdio.h> float add ( ); /*FUNCTION DECLARATION*/ main ( ) { float s; clrscr( ); s=add( ); /* FUNCTION CALL */
printf("\n Sum is...%.2f",s); getch( ); } float add ( ) /* FUNCTION DEFINITION */ { float a, b, c; printf("\nEnter Two Decimal Numbers "); scanf("%f%f",&a,&b); c=a+b; return c; }
Function without returntype and with argument #include<stdio.h> void add (float, float); /* PROTO-TYPE */ main ( ) { float a,b; clrscr(); printf("\n Enter Two Decimal Numbers "); scanf("%f%f",&a,&b); add(a,b); /*FUNCTION CALL*/ getch(); } void add(float c, float d) /* FUNCTION DEFINITION */ { float e = c + d; printf("\nSum of the Numbers..%.2f", e); }
/*FUNCTION BOTH WITH ARGUMENT AND RETURNTYPE */ #include<stdio.h> int add(int,int); main() { int a,b,c; clrscr(); printf("\n Enter Two Numbers "); scanf("%d%d",&a,&b); c=add(a,b); printf("\n The Sum is...%d",c); getch(); } int add(int c,int d) { int e = c + d; return e; } TO FIND THE MAXIMUM VALUE OUT OF 3 NUMBERS
#include<stdio.h> main() { int maxi (int, int); int m,n,s,t; clrscr(); printf(\nEnter 3 Numbers ); scanf(%d%d%d,&m,&n,&s); t=maxi(m,n); printf(\nMaximum of given=%d, maxi(s,t)); getch(); } int maxi (int q,int r) {
Function both with argument and returntype using array #include<stdio.h> int add(int[ ],int); main() { int n[70], i , m; clrscr ( ); printf("\nEnter The Limit of Array "); scanf("%d",&m); printf("\nEnter The Numbers ); for(i=0;i<m;i++) scanf("%d",&n[i]); printf("\n Sum of the Numbers is...%d", add(n,m)); getch(); } int add(int n[ ], int len) { int i, sum=0; for(i=0;i<len;i++) sum+=n[i]; return (sum); }
Recursion
The process of calling the function inside the same function is called recursion
i.e. function calls itself repeatedly, until some specified condition has been satisfied.
Recursive function
A kind of function which uses the concept of recursion is called recursive function factorial by the recursion #include<stdio.h> unsigned long int fact(int); main() { int n; unsigned long int c; clrscr(); printf("\nEnter the Number To Find Factorial "); scanf("%d",&n); c=fact(n); printf("\n Factorial of %d is...%lu", n,c); getch(); } unsigned long int fact (int k) { unsigned long int f = 1; if (k>0) f=k*fact(k-1); return f; } Two types of variables ********************** 1. local variable (with in a function block) 2. global variable (outside the function block)
STORAGE CLASSES
1.AUTO 2.EXTERN 3.STATIC 4.REGISTER /* automatic variables */ #include<stdio.h> main() { auto int m=1000; clrscr(); func2(); printf("%d\n",m); getch(); } func1() { auto int m=10; printf("%d\n",m); } func2() { auto int m=100; func1(); printf("%d\n",m); } /* STATIC */ #include<stdio.h> main() { int i; clrscr(); for(i=0;i<9;i++)
/* REGISTER */ #include<stdio.h> main() { register int i; clrscr(); for(i=1;i<=100;i++) printf("%d\n",i); getch(); } /* EXTERN */ #include<stdio.h> int x=27; /* GLOBAL VARIABLE */ main() { int x=15; /* LOCAL VARIABLE */ clrscr(); printf("\n x= %d ",x); printf("\n x= %d ",func1()); printf("\n x= %d ",func2()); printf("\n x= %d ",func3()); getch();
} func1() { extern int x; x=x+10; /* global variable added with 10 */ return x; /* value of x = 37 stored in global */ } func2() { int x=64; /* LOCAL VARIABLE */ return x; } func3() { x=x+12; /* global variable added with 12 */ return x; }
global variable
#include<stdio.h> int g; main() { int a; printf(\n Enter a Number ); scanf(%d,&g); a = func(g); printf(\n LOCAL = %d , a); printf(\n GLOBAL = %d , g); getch(); } func(int m) { int v = m; printf(\n Enter a Number ); scanf(%d,&g);
return v; }
CHAPTER 6
POINTERS
********
pointer is a variable, stores the Memory Address or Byte Position of another variable Memory Address ranging between 0 and 65535
syntax:<data_type>
*<Pointer_variables_Name>
example:- char str, *ptc; ptc=&str; in the line above ptc is the pointer variable points to a variable str which holds a character datatype value. *operator preceeds the pointer variable *is termed dereference operator
example:- int f, *y; y=&f; here the pointer variable y points to the location where f is stored, since y stores the address of f
%u is the format code for printing the address & Address of Variable. * dereference operator returns the Value at the address.
/* program without pointer variable */ #include<stdio.h> main() { int a=17; clrscr(); printf("\n Address of A is %u",&a); printf("\n Value of A is %d",a); printf("\n Value of A is %d",*(&a)); *(&a)=96; /* this means a=96 */ printf("\n Value of A is %d",a); getch(); }
/* program with pointer variable */ #include<stdio.h> main() { int a,*p; clrscr(); p=&a; printf("\n Enter Value for A ); scanf(%d",&a); printf("\n Value of A = %d ",a); printf("\n Address of A = %u ", p); printf("\n Value of A = %d ", *p); /* *p=a */ getch(); }
DECLARATION OF POINTER
#include<stdio.h> main() { char a='p', *a1=&a; int b=29, *b1=&b; float c=534.67, *c1=&c; clrscr();
printf("\n Value of A =%c ", *(&a)); printf("\n Value of A =%c ", *a1); printf("\n Value of B =%d ", *(&b)); printf("\n Value of B =%d ", *b1); printf("\n Value of C =%.2f ", *(&c)); printf("\n Value of C =%.2f ", *c1); printf("\n Address of A = value of A1 = %u ", a1); printf("\n Address of B = value of B1 = %u ", b1); printf("\n Address of C = value of C1 = %u ", c1); getch(); }
pointer to pointer is a variable , stores the memory address of another pointer variable. #include<stdio.h> main()
{ int b=5,*b1=&b,**b2=&b1; clrscr(); printf("\n Value of B =%d ", *b1); printf(\n Value of B =%d ", **b2); printf("\n Address of B =%u ", b1); printf("\n Address of B =%u ", *b2); printf("\n Address of B1=%u ", b2); printf("\n Address of B2=%u ", &b2); getch(); } ARITHMATIC OF POINTERS #include<stdio.h> main() { char a , *a1=&a; int b , *b1=&b; float c , *c1=&c; double d, *d1=&d; clrscr(); printf("\n\n Address of A=%u ", a1); printf("\n Address of A + 5 =%u ", a1+5); printf("\n\n\n Address of B=%u ", b1); printf("\n Address of B - 7 =%u ", b1-7); printf("\n\n\n Address of C=%u ", c1); printf("\n Address of C + 9 =%u ", c1+9); printf("\n\n\n Address of D=%u ", d1); printf("\n Address of D - 11 =%u ", d1-11); getch();
/* Function (call by value) */ #include<stdio.h> void value(int,int); main() { int a=52,b=94; clrscr(); printf("\n Before Call A=%d B=%d ", a, b); value(a,b); printf("\n After Call A=%d B=%d ", a, b); getch(); } void value (int c, int d) { ++ c; - - d; printf("\nWithin Function The Values are..A=%d B=%d",c,d); }
printf("\n After Call A=%d B=%d ", a, b); getch(); } ref (int *c, int *d) { ++ (*c); - - (*d); printf("\nWithin Function The Values are...A=%d B=%d",*c,*d); }
swapping - by value
#include<stdio.h> void swap(int,int); main() { int a=22,b=64; clrscr(); printf("\n Before Swapping A=%d B=%d ", a, b); swap(a,b); printf("\n After Swapping A=%d B=%d ", a, b); getch(); } void swap (int c, int d) { int temp; temp=c; c=d; d=temp; printf("\nWithin Function The Values are...A=%d B=%d",c,d); } /* swapping by reference */
#include<stdio.h>
swap(int *,int *); main() { int a=238,b=946; clrscr(); printf("\n Before Swapping A=%d B=%d ", a, b); swap(&a,&b); printf("\n After Swapping A=%d B=%d ", a, b); getch(); } swap(int *c, int *d) { int temp; temp = *c; *c = *d; *d = temp; printf("\nWithin Function Swapped Values are...A=%d B = %d ", *c, *d) ; }
/* Array Index Pointer */ #include<stdio.h> main() { int k[5], i, *b; clrscr(); b=k; /* b=&k[0] */ printf(\n Enter the Numbers ); for(i=0;i<5;i++) scanf(%d,b+i); for(i=0;i<5;i++) { printf("\n Address %u",b+i);
#include<stdio.h> main() { char v[50],*a; printf(\n Enter the Sentence ); gets(v); a=v; /* a= &v[0] */ while (*a != \0 ) { printf(\n Address = %u ,a); printf(\n Character = %c ,*a); a++; } getch(); } /* two dimension using pointer */ #include<stdio.h> main() { int pen[3][2],i,j; clrscr(); printf("\n Enter Six Numbers."); for(i=0;i<3;i++) { for(j=0;j<2;j++)
scanf("%d",(*(pen+i)+j)); } for(i=0;i<3;i++) { for(j=0;j<2;j++) printf("%d ",*(*(pen+i)+j)); printf("\n"); } getch(); } /* pointer array */ #include<stdio.h> main() { int *pen[3],a=832,b=657,c=279,i; clrscr(); pen[0]=&a; pen[1]=&b; pen[2]=&c; for(i=0;i<3;i++) { printf("\n Address is...%u",pen[i]); printf("\n Value is...%d",*pen[i]); } getch(); }
PROCESS OF ALLOCATING THE MEMORY BYTES DURING THE RUN TIME IS CALLED DYNAMIC MEMORY ALLOCATION. 1) MALLOC MEMORY ALLOCATION 2) REALLOC RE ALLOCATION 3) CALLOC CANCELLING ALLOCATION 4) FREE DESTROY OR FREE THE MEMORY BYTES WHICH ARE ALLOCATED DURING THE MALLOC OR REALLOC. SYNTAX FOR MALLOC ***************** POINTER_VARIABLE = (DATA_TYPE *) MALLOC (LIMIT * SIZEOF (DATA_TYPE)); SYNTAX FOR REALLOC ****************** POINTER_VARIABLE = (DATA_TYPE *) REALLOC (POINTER_VARIABLE , LIMIT); SYNTAX FOR FREE *************** FREE (POINTER_VARIABLE);
malloc
#include<stdio.h> #include<alloc.h> main() { int *a, n, i, total=0; clrscr ( ); printf ("\n Enter The Limit
");
scanf ("%d",&n); a=(int *) malloc (n*sizeof (int)); printf ("\n Enter The Numbers "); for (i=0; i<n; i++) { scanf ("%d", a+i); total += *(a+i); } for (i=0; i<n; i++) printf (" %d" , *(a+i)); printf ("\n Total is..%d", total); printf("\n Average %.2f ", (float) total / n); free (a); getch ( ); } realloc #include<stdio.h> #include<alloc.h> main ( ) { char *ptr; clrscr ( ); ptr = (char *) malloc (8); ptr = "MADHURAI"; printf ("%s ", ptr); ptr=(char *) realloc (ptr , 5); printf ("\n%s ", ptr); free (ptr); getch( ); }
calloc
#include <stdio.h> #include <alloc.h> main() { long *p, n, m, i, sum=0; char v = y; printf (\n\tHow Many Blocks to be given ? ); scanf (%ld, &n); p = (long *) calloc (n, sizeof (long)); printf (\n \t ENTER THE NUMBERS ); for (i=0; i<n; i++) scanf(%ld, p+i); while ( v == y || v == Y )
{ printf (\n \t \t No. of Blocks Want to Increase ? ); scanf(%ld, &m); n += m; p= (long *) realloc (p, n*4); printf (\n \t ENTER THE NUMBERS ); for ( ;i<n; i++ ) scanf (%ld, p+i); printf(\n \t \t Want To Modify the Block Size ? (Yes/No) ) fflush (stdin); v=getchar ( ); } for (i=0; i<n; i++) { printf (\t %ld , *p+i); sum += *(p+i);
} printf (\n SUM OF THE NUMBERS %ld , sum); printf (\n AVERAGE %.2f , (float) sum / n); getch ( ); }
GARBAGE VALUES
#include <stdio.h> #include <alloc.h> main ( ) { int *p, *table; clrscr ( ); table = (int *) malloc (84); for ( p = table; p <= table; p - -) printf("\n %d is stored at address %u ", *p, p); getch ( ); }
realloc and free function #include <stdio.h> #include <stdlib.h> main ( ) { char *buffer; clrscr ( ); buffer = (char *) malloc (10); strcpy (buffer, "MADHURAI"); printf("\n buffer contains:%s ", buffer); buffer = (char *) realloc (buffer,15); printf ("\n Buffer size modified "); printf ("\n Buffer still contains : %s ", buffer);
strcpy (buffer, "THIRUNELVELI"); printf ("\n Buffer now contains : %s ", buffer); free (buffer); getch ( ); }
CHAPTER 8
STRUCTURES
********** Structure is a one of the data_structures groups the variables of different data_types which are termed as DATA_MEMBERS. Structure is a user defined data_type. /* structure */ #include<stdio.h> struct book { int no; float price; char name[20]; }; main ( ) { struct book b; clrscr ( ); printf("\n Enter The No and Book Name "); scanf ("%d %s", &b.no, b.name); printf("\n Enter The Book Price"); scanf("%f", &b.price ) ; printf("\n Book Name ..%s", b.name ); printf("\n Book Number ...%d", b.no ); printf("\n Book Price ..%.2f", b.price ); printf("\n Size Of Structure...%d", sizeof(b));
getch ( ); }
/* structural array */ #include<stdio.h> struct student { char name[20]; int mark[5], total; float avg; }; main( ) { struct student s[3]; int i, j; clrscr(); for ( i=0; i<3; i++) { printf ("\n Enter The Name "); scanf ("%s", s[i].name); printf ("\n Enter The Marks "); s[i].total = 0; for ( j=0; j<5; j++) { scanf ("%d", &s[i].mark[j]); s[i].total += s[i].mark[j]; } s[i].avg=s[i].total/5; } for (i=0; i<3; i++) { printf ("\nName ...%s", s[i].name); printf ("Marks Are \n"); for (j=0; j<5; j++)
/* nested structure #include<stdio.h> struct student { int date , year; char month [15]; }; struct detail { int no; char name[25]; struct student s; };
*/
main ( ) { struct detail d; clrscr ( ); printf ("\n Enter the No and Name: "); scanf ("%d%s", &d.no, d.name); printf("\n Enter the Date of Birth :"); scanf ("%d %s %d" , &d.s.date, d.s.month, &d.s.year);
printf("\n No:%d Name:%s", d.no, d.name); printf("\n date of birth \n %d / %s / %d , d.s.date, d.s.month, d.s.year); printf("\n Size of Structures %d", sizeof(d)); getch ( ); } /* Structure Using Pointer */ #include<stdio.h> struct rec { char name[10]; int age; float sal; } v, *p ; main ( ) { clrscr ( ); p = &v; printf ("\n Enter The Name "); gets (pname); /* scanf("%s",(*p).name); *p=v */ printf ("\n Enter The Age and Salary "); scanf ("%d%f" , &page, &psal); printf ("\n Name...%s" , pname); printf ("\n Age...%d" , page); printf ("\n Salary...%.2f" , psal); getch ( ); }
#include <string.h> struct name { char n[20]; } v[20], *p ; main ( ) { char temp[20]; int i, j, k=0, no; clrscr(); printf ("\n Enter the Limit of Array "); scanf ("%d", &no); fflush (stdin); for ( i=0; i<no; i++) { p = &v[i]; printf ("\n Enter The Name "); gets (pn); } for ( i=0; i<no; i++) { for ( j=i+1; j<no; j++) { if (strcmp (v[i].n, v[j].n ) > 0) { strcpy (temp, v[i].n); strcpy (v[i].n, v[j].n); strcpy (v[j].n, temp); } } } puts("\n Sorted Names are..."); for ( i=0; i<no; i++) { p = &v[i];
STRUCTURE STRUCTURE
GROUPS THE DATA MEMBERS OF VARIOUS DATATYPES EVERY DATA MEMBER HAS ITS OWN AND INDIVIDUAL MEMORY LOCATION. VALUES ARE ASSIGNED TO ALL DATA MEMBERS AT TIME . COMPILER ALLOCATES THE MEMORY BYTES FOR ALL THE DATA_MEMBERS
vs
UNION UNION
GROUPS THE DATA MEMBERS OF VARIOUS DATATYPES ALL THE DATA MEMBERS SHARE A SINGLE MEMORY LOCATION. VALUE CAN BE ASSIGNED TO ONLY ONE DATA MEMBER AT TIME . COMPILER ALLOCATES A MEMORY LOCATION TO HOLD THE LARGEST DATATYPE OF THE DATA_MEMBERS
clrscr(); printf("\n Size Of Union : %d ", sizeof(m)); m.weight=375.2689; m.height=19; printf("\n Weight:%.2f",m.weight); printf("\n Height:%d ",m.height); getch(); }
READS A SINGLE CHARACTER FROM THE SPECIFIED FILE. #include<stdio.h> main() { FILE *fp; char v, name[20]; clrscr ( ); printf ("\n Enter the filename from your directory : "); gets (name); fp = fopen (name , "r"); if (fp == NULL) { printf ("\n file not existing"); exit ( ); /* returns to the program */ } while ((v=fgetc (fp)) != EOF) printf ("%c" , v); fclose (fp); getch ( ); } FPRINTF and FSCANF FPRINTF() WRITES THE OUTPUT DATA TO ANOTHER FILE THE FILE POINTER HAS TO BE SPECIFIED FSCANF() READS THE INPUT DATA FROM ANOTHER FILE THE FILE POINTER HAS TO BE SPECIFIED #include<stdio.h> main() { FILE *fp; char name[20],ans='y';
int age; float bs; clrscr(); fp = fopen ("sample.c", "w"); while ( ans=='y' || ans=='Y' ) { printf("\n Enter The Name, Age and Salary"); scanf("%s%d%f" , name, &age, &bs); fprintf(fp,"\n %s %d %.2f ", name, age, bs); fflush (stdin); printf("\n Want to Continue ? (Yes/No)"); ans=getchar(); } fclose (fp); fp = fopen ("sample.c", "r"); clrscr ( ); while (fscanf(fp,%s%d%f , name, &age, &bs) != EOF) printf (\n %s %d %.2f, name, age, bs); fclose(fp); getch(); } GETW and PUTW GETW() READS AN INTEGER FROM THE SPECIFIED FILE AND INCREAMENTS THE FILE POINTER POSITION TO THE NEXT INTEGER PUTW() WRITES AN INTEGER TO THE SPECIFIED FILE REWIND() SETS THE FILE POINTER AT THE BEGINNING OF THE FILE Rewind (file_pointer); #include<stdio.h> main() { FILE *fp;
int n=1, a, m; clrscr( ); printf(\n How Many Numbers be Given? ); scanf(%d, &m); fp = fopen ("sample.c","w+"); printf("\n Enter the numbers ); while (n <= m) { scanf("%d", &a); putw (a, fp); n++; } rewind (fp); while (( a=getw (fp)) != EOF) printf("\n %d", a); fclose (fp); getch ( ); }
FGETS ( ) READS THE STRING FROM THE SPECIFIED FILE #include<stdio.h> main() { FILE *fp; char str[100], name[50]; clrscr( ); printf (\n Enter the File Name to open ); gets (name); fp = fopen (name,"r"); while (fgets ( str, 80, fp) != NULL) printf ("%s", str);
fclose (fp); getch ( ); } FPUTS ( ) WRITES THE STRING TO THE SPECIFIED FILE #include<stdio.h> main() { FILE *fp; char v[50]; clrscr ( ); fp = fopen ("sample.c","w"); puts (\n Type Few Lines of Text Press Z to stop ); while (strcmp (gets (v),"z") != 0) { fputs (v, fp); fputs ("\n", fp); } fclose (fp); getch ( ); } COPYING CONTENTS OF ONE FILE INTO ANOTHER FILE USING FGETC AND FPUTC #include <stdio.h> main() { FILE *fp,*ft; char name[25], v; clrscr ( ); printf(\n Enter The File Name to Open ); gets (name);
fp = fopen (name, "r"); if (fp == NULL) { printf ("\n File Not Existing "); exit ( ); } ft = fopen ("sample.c","w"); while ((v = fgetc (fp)) != EOF) { fputc (v, ft); printf ("%c",v); } fclose (ft); fclose (fp); getch(); } TO DELETE THE FILE USING UNLINK #include<stdio.h> main() { FILE *fp; char name[100]; clrscr(); printf("\n Enter The Filename To Delete "); scanf("%s", name); fp = fopen (name,"r"); if (fp == NULL) { printf("\n File not Existing "); exit( ); } else unlink (name);
printf("\n File %s Deleted ",name); getch(); } FSEEK AND FTELL FSEEK() SETS THE FILE POINTER POSITION TO THE
2.
3. 4.
5.
from Compile menu select item Make EXE file (or) press F9 from FILE menu select item OS Shell type the active file name and argument file(s) name(s) ( i.e. files to be opened) type EXIT for returning to the program
/* to read the file contents using command line arguments */ #include<stdio.h> main( int argc, char *argv[ ]) { char v; FILE *fp; clrscr(); fp = fopen ( argv[1], "r"); /* argv[1] is the argument file name typed after OS Shell */ if ( fp == NULL) printf(" File not Existing "); printf("\n total arguments %d", argc); while ( (v = fgetc (fp) ) != EOF) printf ("%c", v); fclose (fp); getch(); } /* to copy one file into another using command line argument */ #include<stdio.h> main (int argc, char *argv[ ]) {
char v; FILE *fs, *fd; clrscr ( ); fs = fopen (argv[1],"r"); if (fs == NULL) printf("\n File not Existing "); fd = fopen (argv[2],"w"); while ( (v = fgetc (fs) ) != EOF) fputc ( v, fd ); printf("\n File %s copied into %s ", argv[1], argv[2]); printf ("\n total arguments %d ", argc); fclose (fd); fclose (fs); getch ( ); } to delete the file using command line argument #include<stdio.h> main (int argc, char *argv[ ] ) { FILE *fp; clrscr ( ); fp = fopen (argv[1],"r"); if (fp == NULL) printf ("\n File not Existing "); else unlink (argv[1]); printf ("\n File %s Deleted ", argv[1]); printf ("\n Total Arguments %d", argc); getch ( ); }
QUEUE
FIFO FIRST IN FIRST OUT #include <stdio.h> #include <stdlib.h> #define MAX 5 int v, j, k, rear = -1, queue[MAX]; void insert ( ); void delete ( ); void display ( ); void main ( ) { clrscr( ); while (1) { printf(\n 1. INSERT 2. DELETE 3.DISPLAY); printf (\n Enter The Choice No ); scanf (%d, &v ); if (v == 1) insert ( ); else if (v == 2) delete ( ); else if (v == 3) display ( ); else break; } } void insert ( ) { if (rear < MAX 1) { ++rear; printf (\n Enter a Number ); scanf (%d, &queue [rear]); }
else printf (\n\t\t QUEUE IS FULL \n ); } void delete ( ) { if ( rear >= 0) { printf(\n %d is Deleted , queue[0]); for ( k=0; k<rear; k++) { queue [k] = queue [k+1]; } rear--; } else printf (\n\t\t QUEUE IS EMPTY \n); } void display ( ) { for (k = 0; k <= rear; k++) printf (\t %d, queue [k] ); }
STACK
LIFO LAST IN FIRST OUT #include <stdio.h> #include <stdlib.h> #define MAX 5
int v, i, top = 0, stack[MAX]; void push ( ); void pop ( ); void display ( ); void main ( ) { clrscr( ); while (1) { printf(\n 1. PUSH 2. POP 3.DISPLAY); printf(\n Enter The Choice No ); scanf (%d, &v); if ( v == 1 ) push ( ); else if ( v == 2) pop ( ); else if (v==3) display ( ); else break; } } void push ( ) { if (top < =MAX 1) { ++top; printf (\n Enter a Number ); scanf (%d, &stack [top]); } else printf (\n\t\t\t STACK IS FULL \n); } void pop ( ) {
if ( top >= 0) { printf(\n %d is Deleted , stack[top]); top--; } else printf (\n \t \t STACK IS EMPTY \n ); } void display ( ) { for (i = top; i >= 0; i--) printf (\t %d, stack [i] ); }
BINARY TREE
#include <stdio.h> void insert( ); void inorder (struct node*); void preorder (struct node*); void postorder (struct node*); struct node { int i; struct node *l,*r; } *root=NULL,*t,*t1,*t2; void main( ) { int n; clrscr( );
while (1) { printf (\n 1.INSERT 2.IN-ORDER 3. PRE-ORDER 4.POSTORDER ); printf (\n Enter a Choice Number ); scanf (%d,&n); if ( n == 1) insert( ); else if ( n == 2) inorder (root); else if ( n == 3) preorder (root); else if ( n == 4) postorder (root); else break; } } void insert( ) { t=(struct node *) malloc (sizeof (struct node)); tl=tr=NULL; printf (\n Enter a Number ); scanf (%d,&ti); if (root == NULL) root = t; else { t1=root; while (t1!=NULL) { t2=t1; if (t1i > ti) t1=t1l; else t1=tr; } if (t2i > ti)
t2l=t; else t2r=t; } } void inorder(struct node *root ) { if (root !=NULL) { inorder (rootl); printf (%d\t,rooti); inorder (rootr); } } void preorder(struct node *root ) { if (root !=NULL) { printf (%d\t,rooti); preorder (rootl); preorder (rootr); } } void postorder(struct node *root ) { if (root !=NULL) { postorder (rootl); postorder (rootr);
printf (%d\t,rooti); } }
CHAPTER 11
***********
LINKED LIST
linked list is collection of nodes. Node contains address part and data part Types of linked list ******************** 1. Linear Linked List a. single - linear linked list b. double - linear linked list 2. Circular Linked List a. single - circular linked list b. double - circular linked list
main() { int n; clrscr(); while (1) { printf("\n 1.ADD 2.DISPLAY 3.MODIFY 4.INSERT 5.DELETE "); printf("\n Enter The Choice No "); scanf("%d",&n); if ( n == 1 ) add( ); else if ( n == 2 ) display( ); else if ( n == 3 ) modify( ); else if ( n == 4 ) insert( ); else if ( n == 5 ) delete( ); else break; } } /* ##################### */ add( ) { char c; do { cur=(struct tag *)malloc(sizeof(struct tag)); printf("\n Enter No and Name "); scanf("%d %s", &curno, curname); if ( start == NULL) start = cur;
else lastnext=cur; curnext=NULL; last=cur; printf("\n Want to Continue? Yes/No "); fflush (stdin); c=getchar(); } while (c == 'y' || c == 'Y'); } /* ############################ */ display( ) { for(cur=start;cur;cur=curnext) printf("\n No= %d Name=%s ", curno, curname); } /* ####################### */ modify( ) { int n; printf("\n Enter The No For modification "); scanf("%d",&n); for(cur=start;cur;cur=curnext) { if(curno==n) { printf("\n Enter the New No and Name "); scanf("%d %s", &curno, curname); break; } } } /* ##################### */
insert( ) { int n; printf("\n Enter no to Insert (after) "); scanf("%d",&n); for(cur=start;cur;cur=curnext) { if(curno==n) { prev=(struct tag *)malloc(sizeof(struct tag)); printf("\n Enter No and Name "); scanf("%d %s", &prevno, prevname); prevnext=curnext; curnext=prev; break; } } } /* ############################# */ delete( ) { int n; printf("\n Enter The No to Delete "); scanf("%d",&n); for(cur=start;cur;prev=cur,cur=curnext) { if (curno==n) { if ( cur == start) start = curnext; else if (curnext==NULL) { prevnext=NULL;
#include<stdio.h> struct tag { int no; char name[20]; struct tag *next , *prev; }*start=NULL,*last,*cur; main() { int n; clrscr(); while (1) { printf("\n 1.ADD 2.DIS_FORWARD 3.DIS_REVERSE"); printf("\n Enter The Choice No "); scanf("%d",&n); if ( n == 1 ) add( ); else if ( n == 2 ) forward( ); else if ( n == 3 ) reverse( ); else break;
} } add( ) { char c; do { cur=(struct tag *)malloc(sizeof(struct tag)); printf("\n Enter No and Name "); scanf("%d %s", &curno, curname); if ( start == NULL) { start = cur; curprev=NULL; } else { lastnext=cur; curprev=last; } curnext=NULL; last=cur; printf("\n Want to Continue? Yes/No "); fflush(stdin); c=getchar(); } while ( c == 'y' || c == Y); } forward() { for(cur=start;cur;cur=curnext) printf("\n no=%d name=%s ", curno, curname); } reverse() {
CIRCULAR LINKED LIST (SINGLE) #include<stdio.h> struct tag { int no; char name[30]; struct tag *next; }*start=NULL,*last,*cur; main() { int n; while (1) { printf("\n 1.ADD 2.DISPLAY "); printf("\n Enter The Choice No "); scanf("%d",&n); if ( n == 1 ) add( ); else if ( n == 2 ) display ( ); else break; } }
add( ) { char c; do { cur=(struct tag *)malloc(sizeof(struct tag)); printf("\n Enter The No and Name "); scanf("%d %s", &curno, curname); if ( start == NULL ) start=cur; else lastnext=cur; curnext=start; last=cur; printf("\n Want to Continue? Yes/No "); fflush(stdin); c=getchar(); } while(c == 'y' || c == 'Y'); } display() { char c; for(cur=start;cur;cur=curnext) { printf("\n no=%d name=%s ", curno, curname); printf(\n Want to continue ?Yes/No); fflush(stdin); c=getchar(); if (c ==n || c==N) break; } }
INSERTION SORT
#include<stdio.h> main() { int s[20],i=0,q=1,r,n; printf(Enter No. of Elements :); scanf(%d,&n); printf(Enter the Numbers ); while(i<n) scanf(%d,&s[i++]); while(q<n) { r=s[q]; for(i=q-1;i>=0 && r<s[i];i--) s[i+1]=s[i]; s[i+1]=r; q++; } printf(Sorted elements are : ); for(i=0;i<n;i++) printf(\n %d,s[i]); }
#include <stdio.h> #include <conio.h> #include <dos.h> void main ( ) { clrscr ( ); int j=0 , k=0; for (int i=0; i<10; i++) {
delay(1000); gotoxy(j+=3, k+=2); textcolor ( j); textbackground (k); cprintf ( "\n Computer Software College "); } getch ( ); } Number for basic colors *********************** 0 BLACK 1 BLUE 2 GREEN 3 CYAN 4 RED 5 MAGENTA 6 ORANGE 7 WHITE (REPEATING ....) 8 BLACK 9 BLUE #include<stdio.h> #include<conio.h> #include<dos.h> void main( ) { for (int j=0; j < 25; j++) { for(int k=0; k < 25; k++) { clrscr(); delay (100); gotoxy ( j, k ); textcolor ( j ); textbackground( k ); cprintf ( "\n computer software college"); delay(100); } } getch(); }
Graphics *********
Graphical Functions require the GRAPHICS.H header file INITGRAPH( ) syntax ********** initgraph (&graphic_driver, &graphic_mode, "path" ); This library function initialises the graphic system. loads the specific graphic driver and video mode used for graphical functions. Graphics driver DETECT and Graphical Video Modes such as CGA, EGA, SVGA, MCGA etc, etc are given as an integer. path specifies the Directory of Graphic_Drivers A null string (" ") for path indicates driver of the current directory. The driver files have the extension BGI. Each type of hardware requires a different graphic driver. GETMAXX( ) AND GETMAXY( ) ************************ These functions return the X and Y co-ordinates of the Bottom Right Corner of the Screen GETX( ) AND GETY( ) ***************** These functions return the x and y coordinates of Active point SETLINESTYLE( ) ************** sets the width and style for drawing subsequent lines and shapes syntax: ******* setlinestyle (linestyle, pattern, thickness); SETTEXTSTYLE( ) ************** specifies the font , direction and character size to be used. syntax: ******* settextstyle ( Font , Direction , Character_Size ); valid fonts are.. ***************** DEFAULT_FONT TRIPLEX_FONT SMALL_FONT SANS_SERIF_FONT GOTHIC_FONT
0 1 2 3 4
HORIZANTAL_DIRECTION VERTICAL_DIRECTION
0 1
SETTEXTJUSTIFY( ) ****************** Sets the horizontal and vertical alignment of the text syntax: ******* settextjustify ( horizontal , vertical ); valid horizontals ****************** LEFT_TEXT CENTER_TEXT RIGHT_TEXT are.. 0 1 2
valid verticals are... ******************* BOTTOM_TEXT 0 CENTER_TEXT 1 TOP_TEXT 2 CLEARDEVICE ( ) ************** clears the graphics screen and positions the cursor at 0,0 pixels CLOSEGRAPH( ) ************ releases the memory reserved by graphics system and restores the screen to the video mode that was existing before initgraph ( )
MULTIPLE
FILL , TEXT
STYLE
#include<stdio.h> #include<graphics.h> #include<conio.h> void main( ) { int gdr=DETECT,gmode, x, y; clrscr(); initgraph(&gdr , &gmode, " "); x = getmaxx( ) / 2; y = getmaxy( ) / 2; setcolor (YELLOW); setlinestyle (SOLID_LINE,0,7); circle (x, y, 50); rectangle (0, 0, 650, 150); setfillstyle (HATCH_FILL, BLUE);
floodfill (70, 50, YELLOW); setfillstyle (WIDE_DOT_FILL, 4); floodfill (x, y, YELLOW); settextstyle (TRIPLEX_FONT, HORIZ_DIR, 6); outtextxy(250,50,"MADHURAI "); settextstyle (GOTHIC_FONT, 0, 15); outtext (" COUTRALAM "); getch( ); cleardevice( ); settextstyle (DEFAULT_FONT, VERT_DIR, 1); moveto (x, y); settextjustify (LEFT_TEXT, BOTTOM_TEXT); setcolor(2); outtext (" COMPUTER SOFTWARE COLLEGE "); getch( ); printf ("\n Maximum color is .. %d " , getmaxcolor( ) ); printf (" \n Color at the center is %d " , getpixel (x, y) ); putpixel (300, 300, YELLOW); getch( ); closegraph( ); }
FLOODFILL( ) fills a bounded region with color syntax: ******** floodfill (column , row , border); where column , row is point inside the area to be filled border is the bordering colour of the area to be filled CIRCLE AND LINE #include<stdio.h> #include<graphics.h> #include<conio.h> #include<dos.h> void main( ) { int a = DETECT , b; clrscr ( ); initgraph ( &a, &b, ); setcolor (RED); setlinestyle (SOLID_LINE , 0, 3 ); line (180, 180, 320, 320 ); line (320, 180, 180, 320 ); circle (250, 250, 100 ); setfillstyle (SOLID_FILL , GREEN ); floodfill (250, 180, RED ); delay (1000); setfillstyle (SOLID_FILL , BLUE ); floodfill (300, 240, RED ); delay (1000); setfillstyle (SOLID_FILL , CYAN ); floodfill (260, 300, RED ); delay (1000); setfillstyle (SOLID_FILL , YELLOW ); floodfill (200, 250, RED );
delay (1000); getch( ); cleardevice ( ); closegraph ( ); } ARC( ) ***** To draw a circular arc syntax: ******* arc (Column , Row , Start_Angle , End_Angle , Radius) ELLIPSE( ) ********* To draw an ellipse or elliptical arc syntax: ******* ellipse (Column, Row, Start_Angle, End_Angle, Horizantal_Radius, Vertical_Radius ) ARC and ELLIPSE #include <stdio.h> #include <graphics.h> #include <conio.h> void main ( ) { int a = DETECT , b; clrscr ( ); initgraph (&a, &b, ); setlinestyle (SOLID_LINE , 1 , 7); setcolor(RED); arc (400, 300, 25, 315, 75); ellipse ( 180, 250, 0, 360, 70, 150); getch ( ); cleardevice ( ); closegraph ( ); } SETFILLSTYLE( ) *************** sets the fill pattern and color syntax: ******* setfillstyle ( pattern , color) EMPTY_FILL SOLID_FILL LINE_FILL LTSLASH_FILL SLASH_FILL BKSLASH_FILL LTSLASH_FILL HATCH_FILL XHATCH_FILL INTERLEAVE_FILL WIDE_DOT_FILL CLOSE_DOT_FILL 0 1 2 3 4 5 6 7 8 9 10 11
USER_FILL
12
BAR - 3D -- MIDX, MIDY #include <stdio.h> #include <graphics.h> #include <stdlib.h> #include <conio.h> int main ( ) { int k,v=0,driver =DETECT, mode, x, y ; initgraph ( &driver, &mode, ); x = getmaxx ( ) / 2; y = getmaxy ( ) / 2; for ( k=EMPTY_FILL;k<=USER_FILL; k++) { setfillstyle (k, v++); bar3d (x 200, y 200, x + 200, y + 200, 25, 1); getch( ); } closegraph ( ); return 0; } PLANE #include<graphics.h> #include<stdlib.h> #include<dos.h> void plane ( int x , int y) { line (x, y, x+11, y-3); line ( x+11, y-3, x+26,y-2); line ( x+26,y-2, x+30, y-7); line ( x+30, y-7 , x+27, y); line ( x+27, y ,x, y); line ( x+11, y-1, x+15,y-1); } void main ( ) { int gm, gd, k; detectgraph ( &gd, &gm ); initgraph ( &gd, &gm, ); setviewport ( 600, 100, 500, 200, 0 ); setbkcolor (YELLOW); for (k=100; k+250 > 0; k=k-5) { delay (9000); setfillstyle (SOLID_FILL, RED); bar (0, 0, 500, 600); setfillstyle (1, BLUE); fillellipse (88, 3, 12, 9); plane (k, 50); plane (k+50, 30); plane (k+50, 65); plane (k+70, 80); plane (k+100, 100); outtextxy (k, 150, VICTORY AT THE COST OF LIFE ); } exit (1);
clearviewport ( ) ; closegraph ( ); }
SHIFTING
>> is RIGHT SHIFT OPERATOR << is LEFT SHIFT OPERATOR #include<stdio.h> void main ( ) { int a, b, j ; clrscr ( ); printf (\n ENTER 2 NUMBERS ) ; scanf (%d%d , &a ,&b); printf( \n HOW MANY PLACES TO SHIFT ? ) ; scanf (%d, &j ); printf ( \n %d RIGHT SHIFTED TO %d PLACES IS %d , a , j , a >> j ) ; printf ( \n %d LEFT SHIFTED TO %d PLACES IS %d , b , j , b << j ) ; getch ( ); }
EXAMPLE
RIGHT SHIFT Binary of
56 is
1 1 1 0 0 0
32 16 8 4 2 1
56 >> 2
0 0 1 1 1 0
32 16 8 4 2 1
i. e. 14
0 0 1 0 0 1 0
64 32 16 8 4 2 1
18 << 2
1 0 0 1 0 0 0
64 32 16 8 4 2 1
i. e. 72