=======0======================================Year 1972 at Bell telephone laboratories (AT&T) by DENNIS RITCHIE.Features o...
program statements;}Ex:#include<stdio.h>main(){printf(“god is great”);}Keywords:Keywords are words belongs to C language. ...
Datatype:TYPE                SIZE(bits)   RANGEchar                8            -128 to 127unsigned char       8          ...
Variables:      C variable refers to the name given to the memory location tostore data. A particular memory location is g...
Ex:      int a=10;      float b=43.3;comment statement:      comment statements are non-executable statements.  1. single ...
(ii)       unary operatorsBinary operator:     BO need two operands for operations.Operator                operation      ...
<                     less than            a<b>=                    greater than equal to a<=b<=                    less t...
Ex:Operator                operation              Ex+=                 value of LHS variable                   will be add...
Scanf () is used to give data to the variables using keyboard.The general form isScanf (“control string”, &variable1, ….&v...
H             short-integerS             stringCONTROL STATEMENTS:    1. Unconditional statements    2. Conditional (or) D...
CO are used to skip or to execute a group of statements basedon the result of some condition.   1. if statement   2. if….e...
#include<stdio.h>void main(){int mark;char grade;scanf(“%d %c”, &mark, &grade);if(grade = =’a’){mark=mark+10;}printf(“%d”,...
}else       {            statement block-2;       }next statement;Ex:#include<stdio.h>void main(){int mark;scanf(“%d”, &ma...
else….if ladder statement is used to take multiway decision. Thisstatement is formed by joining if….else statement in whic...
next statement;Ex:#include<stdio.h>void main(){int day;printf(“give a number between 1 to 7n”);scanf(“%d”, &day);if(day= =...
elseprintf(“enter the currect value”n);}Nested if….else statement:       This statement is formed by joining if….else stat...
}next statement;when this statement is executed, the computer first evaluates thevalue of test condition-1. if it is false...
printf(“B is big=%d”,c);       }else       {              if(b>c)              printf(“B is big=%d”,b);       else        ...
statement block-2;           break;…………………………..…………………………..      case label-n:           statement block-n;           brea...
case 1:printf(“Sunday n”);break;case 2:printf(“Monday n”);break;case 3:printf(“Tuesday n”);break;case 4:printf(“Wednesday ...
printf(“Enter the currect no:n”);break;}}LOOPING STATEMENTS:      Looping statements are used to execute a group of statem...
body of the loop;}next statement;Ex:#include<stdio.h>main(){int I;I=1;While(I<5){printf(“god is love”);I++;}}Do…While stat...
condition becomes false. When the test condition becomes falsethe control is transferred to the next statement.The general...
}while(I<5)}For Statement:      For statement is used to execute a statement or a group ofstatements repeatedly for a know...
for(I=1; I<=50; I++){sum=sum+I;}printf(“sum=%d”,sum);}Arrays:     An array is defined as a group of related data items tha...
Ex:      A [10], name [30], …Declaration of one dimensional array:      Arrays must be declared before it is used like oth...
3. static float mark[]={65,87,78, 65,87,78};Ex: smallest no:#include<stdio.h>main(){int I,n,a[10],small;printf(“Give the 1...
An one dimensional array may be horizontal or vertical. Insome applications it is necessary to represent data in horizonta...
Ex:       Int mark[5][2]Array initialization:       Like one dimensional arrays we can assign initial values to2-D arrays ...
for(j=0;j<2;j++)scanf(“%d”, &a[I][j]);printf(“Enter the B matrix no:”);for(I=0;I<2;I++)for(j=0;j<2;j++)scanf(“%d”, &b[I][j...
Any group of characters enclosed in double quotes is a stringconstant. A string is an array of characters terminated by a ...
1. By using scanf () function:  2. By using getchar () function:  3. By using gets () function:  3. By using loopsBy using...
The gets () function with the array name can also be used toread a string from the user. The gets () function overcomes th...
The strlen () function:      The strlen() function returns the count of number ofcharacters stored in a string.Syntax: x=s...
#include<stdio.h>#include<string.h>void main(){char str[10],cpy[10];printf(“Enter a string:”);gets(str);strcpy(cpy,str);pr...
#include<string.h>void main(){char str [10],cat [10];printf(“Enter a string:”);gets(str);printf(“Enter another string:”);g...
{char x[10];printf(“Enter the string:”);gets(x);printf(“The reversed string is :%s”,strrev(x));}The strcmp() function:    ...
printf(“Enter another string:”);gets(cmp);x=strcmp(str,cmp);if(x = = 0)puts(“Strings are equal”);else if (x>0)printf(“Stri...
1. user-defined functions2. library functionThe main () function that we have seen so far in the programs is anexample of ...
A function definition consists of two parts.    1. argument declaration    2. body of the functionSyntax:Return-type funct...
1. Function with no arguments and no return values.      2. Function with no arguments and return values      3. Function ...
return;}Function With No Arguments And Return Values:      In this type of function no value is passed from the callerfunc...
return(area);}Function With Arguments And No Return Values:      In this type of function, some values are passed from the...
area=x*y;printf(“n area of rectangle is %f”, area);return;}Function With Arguments And Return Values:      In this type of...
float area;area=b*h;return(area);}Example for Type of Function’s:/* FUNCTION WITH NO ARGUMENTS AND NO RETURNVALUES#include...
}FUNCTION WITH RETURN VALUES AND NO ARGUMENTS#include<stdio.h>#include<conio.h>int sum();void main(){clrscr();printf("is %...
}FUNCTION WITH ARGUMENTS AND NO RETURNVALUES#include<stdio.h>#include<conio.h>void simple(float,float,int);float principal...
FUNCTION WITH ARGUMENTS AND RETURN VALUES#include<stdio.h>#include<conio.h>int sum(int x);void main(){int n;clrscr();print...
condition has been satisfied. A function is called recursive if astatement within the body of a function calls the same fu...
NESTED OF FUNCTION:      We have seen programs using functions called only from themain() function. But there are situatio...
printf(“n inside function 2”);}STORAGE CLASSES:       The variables are associated with certain properties such asscope an...
/*void main(){auto int x=5;{auto int x=4;{auto int x=3;clrscr();printf("%d t",x);}printf("%d t",x);}printf("%d t",x);getch...
int value;void main(){value = 100;clrscr();test1();test2();test3();printf("%dn", value);getch();}test1(){value += 100;prin...
value += 100;printf("%dn", value);}STATIC STORAGE CLASS:      The world static in general refers to anything that is inser...
printf("%d", x);x=x+1;}*/REGISTER STORAGE CLASS:      The register storage class is similar to the auto storage classsince...
structure, unlike those in an array, can be of different variabletypes. A structure can contain any of C’s data types, inc...
int no;int age;char sex;};Structure declaration:       Structure declaration means defining variables to the alreadydefine...
int no;int age;char sex;}s1,s2,s3;The second general form is:Struct structure-name{data-type member-1;data-type member-2;…...
student s1, s2, s3;Giving values to structure members:       Dot operator or member operator ‘.’ Is used to give data toth...
scanf(“%d”, &s1.no);       scnaf(“%d”, &s1.age);       scanf(“%c”,&s1.sex);(ii) using assignment statement:       s1.no = ...
printf("Give the number....");scanf("%d", &d1.no);printf("Give the salary....");scanf("%f", &d1.salary);printf("n");printf...
{int no;int age;char sex;};struct student s1[2];int i;clrscr();for(i=0;i<2;i++){printf("Enter number,age,sexn");scanf("%d ...
Ex:#include<stdio.h>#include<conio.h>void main(){struct hostel_detail{int hostel_room_no;char food;int deposit_amount;};st...
getch();}Passing Entire Structure To Function:      In this method, the entire structure is passed as an argumentto the fu...
printf("Enter employee no and name:");scanf("%d %s", &emp1.empno, emp1.empname);employ(emp1);}void employ(struct employee ...
A file is defined as FILE in the header file stdio.h thereforeall files should be declared as type FILE before they are us...
The general form is:fclose (pointer variable);Ex:……………….……………….FILE *a, *b;a= fopen(“exam.txt”, “r”);b= fopen(“exam.txt”,”...
Writing to a file:      fprintf function is used to write data into a fileThe general form is:fprintf (pointer variable, “...
ptr=fopen("exam.dat","r");fscanf(ptr, "%s %d %s", &empname, &empno, &deptname);printf("n Employee Name:%s", empname);print...
fptr=fopen("example.txt","r");do{c=fgetc(fptr);putchar(c);}while (c!= EOF);fclose(fptr);getch();}Random Access Function:  ...
The random access functions used in a file are   1. the fseek() function   2. the ftell() function   3. the rewind() funct...
The ftell() Function:      The ftell() function returns the current position of the filepointer in the file.The general fo...
f1=fopen("student.txt","w");printf("Enter the content of file1n");gets(a);fputs(a,f1);fclose(f1);f2=fopen("student1.txt","...
while(fgets(a,strlen(a)+1,f2)!=NULL){fputs(a,f3);printf("%s",a);}fclose(f2);fclose(f3);f3=fopen("student2.txt","r");printf...
Pointer declaration:         All pointer variables must be declared before it is used in theprogram like other variable.Th...
int a=5,b=10, *ptr;clrscr();ptr=&a;printf("n initial values a=%d &b=%d",a,b);b=*ptr;printf("n changed values a=%d &b=%d",a...
scanf("%d", &n);printf("Enter the array elements:");for(i=0;i<n;i++)scanf("%d",&a[i]);*ptr=a[0];for(i=0;i<n;i++)if(a[i]>*p...
void main(){int num;clrscr();printf("Enter any integer:");scanf("%d", &num);printf("The sum of squares of first %d numbers...
C fundamental
Upcoming SlideShare
Loading in …5
×

C fundamental

3,326 views

Published on

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,326
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
203
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

C fundamental

  1. 1. =======0======================================Year 1972 at Bell telephone laboratories (AT&T) by DENNIS RITCHIE.Features of ‘C’ language: 1. it is a flexible high level structured program language 2. it includes the features of low level language like assembly language. 3. it is much faster and efficient. 4. it has a number of built-in functions, which makes the programming task simpleThe ‘C’ language is used for developing: 1. database system. 2. graphics packages. 3. scientific and engineering applications.Format of C program:Headerfile includeMain(){variable declaration;
  2. 2. program statements;}Ex:#include<stdio.h>main(){printf(“god is great”);}Keywords:Keywords are words belongs to C language. The users have noright to change its meaning.Ex:auto, goto, if, int, while, do, switch, case, char, else…..
  3. 3. Datatype:TYPE SIZE(bits) RANGEchar 8 -128 to 127unsigned char 8 0 to 255int 16 -32,768 to 32,767unsigned int 16 0 to 65,535long int 32 -2,147,483,648 to 2,147,483,647unsigned long int 32 0 to 4,294,967,295float 32 3,4E-38 to 3,4E+38double 64 1.7E-308 to 1.7E+308long double 80 3.4E-4932 to 1.1E+4932
  4. 4. Variables: C variable refers to the name given to the memory location tostore data. A particular memory location is given only one name.Yet this name is called a variable because this memory locationcan store sequence of different values during the execution of thesame program.Rules: 1. a variable name is formed with alphabets, digits and a special character underscore( _ ) 2. the first character must be an alphabet. 3. no special characters are used other than underscore 4. both upper case and lower case letters are used.Declaration variables:Syntax: Data-type list of variables;Ex: int x,y,z;initializing variables:syntax: data-type variable=initial value;
  5. 5. Ex: int a=10; float b=43.3;comment statement: comment statements are non-executable statements. 1. single line statement // 2. paragraph statement /* */OPERATORS: An operator is a symbol which represents some operation thatcan be performed on data. There are eight operators available in Cto carry out the operations. They are 1. arithmetic operators 2. relational operators 3. logical operators 4. short hand assignment operators 5. conditional operatorsArithmetic operators: Arithmetic operators are used to do arithmetic calculations.There are 2 types (i) binary operators
  6. 6. (ii) unary operatorsBinary operator: BO need two operands for operations.Operator operation Ex+ addition x=5+6- subtraction x=10-5* multiplication x=5*4/ division x=5/3 =1% modulo operator x=5%3 =2Unary operators:UO need only one operands for operation.Operator operation Ex++ increment i++-- decrement i—Relational operators: RO are used to find out the relationship between twooperands. They areOperator operation Ex> greater than a>b
  7. 7. < less than a<b>= greater than equal to a<=b<= less than equal to a>=b== equal to a= =b!= not equal to a!=bLogical operators: LO are used to find out the relationship between two or morerelational expressions. They areOperator operation Ex&& AND (a>b)&&(a>c)|| OR (a>b)||(a>c)Short-hand assignment operators: SHAO are operators which are used to simplify the codingof certain type of assignment statement.The general form is Variable operator = expressionVariable = user define nameOperator = +,-,*,/,%
  8. 8. Ex:Operator operation Ex+= value of LHS variable will be added to the x = x +10can be RHS value and is written as x+=10 Assigned to LHS variableConditional Operators: The CO ? and : are used to build simple conditionalexpression. It has three operands. So it is called ternary operator.The general form isExpression1 ? expression2: expression3;Expression1 is evaluated first. If it is true expression2 isevaluated.if expression1 if false expression3 is evaluated.Ex:Sum = a>b ? a: b;Input statement:Scanf () function:
  9. 9. Scanf () is used to give data to the variables using keyboard.The general form isScanf (“control string”, &variable1, ….&variable n);Ex:Scanf(“%d”,&a);This statement reads a integer data and assigns to variable aOutput statement:Printf () function:Printf () is used to output the results of the program to the userthrough VDU.The general form isPrintf(“control string”, list);Conversion character table:C single characterD decimal integerF floating point value
  10. 10. H short-integerS stringCONTROL STATEMENTS: 1. Unconditional statements 2. Conditional (or) Decision making statements 3. Looping StatementUnconditional Statement: 1. goto statementgoto statement is used to transfer the program controlunconditionally from one point to another.The general form is: goto label;The label is the name given to the point where the control has to betransferredThe general form is Label:statement;Conditional Statement:
  11. 11. CO are used to skip or to execute a group of statements basedon the result of some condition. 1. if statement 2. if….else statement 3. else….if ladder 4. nested if statement 5. switch statement(i) Simple if statement:Simple if statement is used to execute or skip one statement orgroup of statements for a particular condition.The general form isIf(test condition) { statement block; }next statement;Ex:
  12. 12. #include<stdio.h>void main(){int mark;char grade;scanf(“%d %c”, &mark, &grade);if(grade = =’a’){mark=mark+10;}printf(“%d”,mark);}(ii) if….else statement:if…else statement is used to execute one group of statements if thetest condition is true or other group if the test condition is false.The general form isIf(test condition) { statement block-1;
  13. 13. }else { statement block-2; }next statement;Ex:#include<stdio.h>void main(){int mark;scanf(“%d”, &mark);if(mark=>35)printf(“pass”);elseprintf(“fail”);}(iii) else…..if ladder:
  14. 14. else….if ladder statement is used to take multiway decision. Thisstatement is formed by joining if….else statement in which eachelse conditions another if….elseThe general form isIf(test condition-1) { statement block-1; }else if(test condition-2) { statement block-2; }……………………………………………………………….else if(test condition-n) { statement block-n; }else default statement;
  15. 15. next statement;Ex:#include<stdio.h>void main(){int day;printf(“give a number between 1 to 7n”);scanf(“%d”, &day);if(day= =1)printf(“sundayn”);if(day= =2)printf(“Mondayn”);if(day= =3)printf(“tuesdayn”);if(day= =4)printf(“wednesdayn”);if(day= =5)printf(“thursdayn”);if(day= =6)printf(“fridayn”);if(day= =7)printf(“saturdayn”);
  16. 16. elseprintf(“enter the currect value”n);}Nested if….else statement: This statement is formed by joining if….else statementseither in the if block or in the else block or bothThe general form is:If(test condition-1) { if(test condition-2) { statement block-1; } else { statement block-2; }else { statement block-3;
  17. 17. }next statement;when this statement is executed, the computer first evaluates thevalue of test condition-1. if it is false control will be transferred tostatement block-3. if it is true test condition-2 is evaluated. If it istrue statement block-1 is executed and control is transferred to nextstatement else statement block-2 is executed and control istransferred to next statement.Ex:#include<stdio.h>main(){int a,b,c;printf(“enter 3 no”);scanf(“%d %d%d”, &a,&b,&c);if(a>b) { if(a>c) printf(“A is big=%d”,a); else
  18. 18. printf(“B is big=%d”,c); }else { if(b>c) printf(“B is big=%d”,b); else printf(“C is big=%d”,c); }}Switch Statement: Switch statement is an extension of if…..else statement. Thispermits any number of branches.The general forms:Switch (expression){ case label-1: statement block-1; break; case label-2:
  19. 19. statement block-2; break;…………………………..………………………….. case label-n: statement block-n; break; default: default statement; break;}next statementEx:#include<stdio.h>main(){int day;printf(“Enter the no 1 to 7n”);scanf(“%d”, &day);switch(day){
  20. 20. case 1:printf(“Sunday n”);break;case 2:printf(“Monday n”);break;case 3:printf(“Tuesday n”);break;case 4:printf(“Wednesday n”);break;case 5:printf(“Thursday n”);break;case 6:printf(“Friday n”);break;case 7:printf(“Saturday n”);break;default:
  21. 21. printf(“Enter the currect no:n”);break;}}LOOPING STATEMENTS: Looping statements are used to execute a group of statementsrepeatedly until some condition is satisfied. The loopingstatements are 1. while statement 2. do…while statement 3. for statementWhile statement: First evaluates the test condition. If the value is false, thecontrol is transferred to next statement. If the value is true, then thebody of the loop is executed repetedly until the test conditionbecomes false. When the test condition becomes false the controlis transferred to next statement.The general form is:While(test condition) {
  22. 22. body of the loop;}next statement;Ex:#include<stdio.h>main(){int I;I=1;While(I<5){printf(“god is love”);I++;}}Do…While statement When this statement is executed the body of the loop isexecuted first. Then the test condition is evaluated. If the value isfalse, the control is transferred to the next statement. If the value istrue the body of the loop is executed repeatedly until the test
  23. 23. condition becomes false. When the test condition becomes falsethe control is transferred to the next statement.The general form is:Do { body of the loop; }while(test condition);next statement;Ex:#include<stdio.h>main(){int I;I=1;Do{printf(“god is love”);I++;
  24. 24. }while(I<5)}For Statement: For statement is used to execute a statement or a group ofstatements repeatedly for a known number of times.The general form is:For(initial condition; test condition; increment or decrement){body of the loop;}next statement;Ex:#include<stdio.h>main(){int I, sum;sum=0;
  25. 25. for(I=1; I<=50; I++){sum=sum+I;}printf(“sum=%d”,sum);}Arrays: An array is defined as a group of related data items that sharea common name. In computers we store information in thememory by giving names to them. These names are calledvariables.Subscripted Variables: The variables which are used to represent the individual datain the memory are called subscripted variablesThe general form is: Array-name[subscript]One dimensional arrays: An array name with only one subscript is known as onedimensional array.
  26. 26. Ex: A [10], name [30], …Declaration of one dimensional array: Arrays must be declared before it is used like other variables.The general form is Data-type array-name [size];Ex: Int mark[100]Array initialization: We can assign initial values to the array just like we assignvalues to variables when they are declared.The general form is: Static data-type array-name [size] = { list of values};Ex: 1. Static int mark[3] ={65,87,78}; 2. static int mark[5] ={65,87,78};
  27. 27. 3. static float mark[]={65,87,78, 65,87,78};Ex: smallest no:#include<stdio.h>main(){int I,n,a[10],small;printf(“Give the 10 value”);scanf(“%d”, &n);for(I=0; I<n; I++)scanf(“%d”, &a[I]);small=a[0];for(I=1; I<n;I++){if(a[I] < small)small=a[I];printf(“The small value is:%d”,small);}}Table handling:
  28. 28. An one dimensional array may be horizontal or vertical. Insome applications it is necessary to represent data in horizontal(rows) as well as in vertical (columns). This type of representationis said to be in tabular form. A two dimensional array is needed torepresent a table in memory.Two dimensional array An array with two subscripts is known as two dimensionalarray.The general form is Array-name[subscript1][subscript2]Ex: A[2][2]Declaration of 2-D array: Like one dimentional arrays two dimentional arrays must bedeclared before it is used like other variables.The general form is: Data-type array-name[row size][column size];
  29. 29. Ex: Int mark[5][2]Array initialization: Like one dimensional arrays we can assign initial values to2-D arrays when they are declared.The genearal form is: Static data-type array-name [row size] [column size]={list ofvalues};Ex: 1. Static int mark[3][2]={1,2,3,4,5,6}; 2. Static int mark[3][2]={{1,2}, {3,4}, {5,6}};Ex:#include<stdio.h>void main(){int i,j;int a[2][2], b[2][2], c[2][2];printf(“Enter the A matrix no:”);for(I=0;I<2;I++)
  30. 30. for(j=0;j<2;j++)scanf(“%d”, &a[I][j]);printf(“Enter the B matrix no:”);for(I=0;I<2;I++)for(j=0;j<2;j++)scanf(“%d”, &b[I][j]);for(I=0;I<2;I++)for(j=0;j<2;j++)c[I][j]=a[I][j]-b[I][j];printf(“n result of matrix isn”);for(I=0;I<2;I++){for(j=0;j<2;j++)printf(“%d”,c[I][j]);printf(“n”);}}STRING:
  31. 31. Any group of characters enclosed in double quotes is a stringconstant. A string is an array of characters terminated by a nullcharacter.Declaring String: The string that can hold an array of characters can bedeclared as Char variable_name [size];Ex: Char name [10], book [10];Initializing String: A character array can be initialized by a string constant,resulting in the first element of the array being set to first characterin the string, the second element to the second character and so on.The array also receives the terminating ‘o’ in the string constantEx: Char name [9]=”computer”; Char name [9]={‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’,’o’}Reading String:
  32. 32. 1. By using scanf () function: 2. By using getchar () function: 3. By using gets () function: 3. By using loopsBy using scanf () function: The scanf () function with format string %s can be used toread a string from the user.Ex: Main() { char name[10]; scanf(“%s”, name); } The disadvantage of scanf () function is that there is no wayto read a multi-word string into a single character array variable.The scanf () function terminates its input when it encounters ablank spaceBy using gets () function:
  33. 33. The gets () function with the array name can also be used toread a string from the user. The gets () function overcomes thedisadvantage of the scanf () function, since it can read a string ofany length with any number of blank spaces and tabs.Ex: Main() { char name [10]; gets (name); }By using loops: We know that a string is an array of characters, hence a stringcan also be read, character by character from the user by usingloops.STRING LIBRARY FUNCTION: 1. strcpy() - copies a string into another string 2. strcat() - appends one string at the end of another string 4. strcmp()- compares two string 5. strlen() - finds length of a string 6. strrev() - reverse a string
  34. 34. The strlen () function: The strlen() function returns the count of number ofcharacters stored in a string.Syntax: x=strlen(str);#include<stdio.h>#include<string.h>void main(){char str[10];printf(“Enter a string:”);gets(str);printf(“The length of the string is %d”, strlen(str));}The strcpy() function: The strcpy() function is used to copy the contents of onestring to another. The general form is Strcpy(string1,string2);Ex:
  35. 35. #include<stdio.h>#include<string.h>void main(){char str[10],cpy[10];printf(“Enter a string:”);gets(str);strcpy(cpy,str);printf(“The source string is %s”,str);printf(“The copied string is %s”,cpy);}The strcat() function: The strcat() function concatenates the source string at the endof the target string. The strcat() function takes two arguments forconcatenating.The general form is: Strcat(string1, string2);Ex:#include<stdio.h>
  36. 36. #include<string.h>void main(){char str [10],cat [10];printf(“Enter a string:”);gets(str);printf(“Enter another string:”);gets(cat);strcat(str,cat);printf(“The concatenated string is :%s”,str);}The strrev() function: The strrev() function is used to reverse a string. This functiontakes only one argument.The general form is: X=strrev(string);Ex:#include<stdio.h>#include<string.h>void main()
  37. 37. {char x[10];printf(“Enter the string:”);gets(x);printf(“The reversed string is :%s”,strrev(x));}The strcmp() function: The strcmp() function compares two strings to find whetherthe strings are equal or not.The general form is: Strcmp(string1,string2);Ex:#include<stdio.h>#include<string.h>void main(){char str[10],cmp[10];int x;printf(“Enter a string:”);gets(str);
  38. 38. printf(“Enter another string:”);gets(cmp);x=strcmp(str,cmp);if(x = = 0)puts(“Strings are equal”);else if (x>0)printf(“String %s is greater than string %s”, str, cmp);elseprintf(“String %s is greater than string %s”, cmp, str);}FUNCTION: A function is a self-contained program segment that performssome specific well-defined task when called. Function break largecomputing tasks in to smaller ones. C programs generally consistof many small functions rather than few big ones. Every c programconsists of one or more functions, but there should be at least onefunction which must be main (). C functions may be classified into two categories namely
  39. 39. 1. user-defined functions2. library functionThe main () function that we have seen so far in the programs is anexample of an user-defined function.Printf (), scanf (), etc.. are the examples of library functions.Ex:#include<stdio.h>void func();void main(){printf(“n Inside main function”);func();printf(“n again inside main function”);}void func(){printf(“n inside func function”);}Defining a Function:
  40. 40. A function definition consists of two parts. 1. argument declaration 2. body of the functionSyntax:Return-type function-name (argument list) ->argument decla { declarations; statements; ->body fun return(expression); }Ex:Int add (int x, int y){Int z;Z=x+y;Return (z);}TYPE OF FUNCTION: A function depending upon the arguments present or not andwhether a value is returned or not. There are 4 types of classified
  41. 41. 1. Function with no arguments and no return values. 2. Function with no arguments and return values 3. Function with arguments and no return values. 4. Function with arguments and return values.Function With No Arguments And No Return Values: In this type of function no value is passed from the callerfunction to the called function and no value is returned to thecaller function from called function.Ex:#include<stdio.h>void main(){void message ();printf(“n I am in main function);message();printf(“n I am back in main function”);getch();}void message(){printf(“nn I am in user defined function”);
  42. 42. return;}Function With No Arguments And Return Values: In this type of function no value is passed from the callerfunction to the called function (user defined function) but somevalue is returned to the caller function from the called function.Ex:#include<stdio.h>main(){float f;clrscr();f=area();printf(“n the area is %f”,f);getch();}float area(){float a,b,area;printf(“n enter the length and breadth of a rectangle:”);scanf(“%f %f ”, &a, &b);area = a*b;
  43. 43. return(area);}Function With Arguments And No Return Values: In this type of function, some values are passed from thecaller function and no values are returned to the caller functionfrom the called function.Ex:#include<stdio.h>main(){float a,b;void area_rectangle (float, float);clrscr();printf(“n enter the length & breadth:”);scanf(“%f %f”, &a, &b);area_rectangle (a,b);getch();}void area_rectangle(x,y)float x,y;{float area;
  44. 44. area=x*y;printf(“n area of rectangle is %f”, area);return;}Function With Arguments And Return Values: In this type of functions some values are passed to the calledfunction from the caller function and some values are passed backto the caller function from the called function.Ex:#include <stdio.h>main (){float area(float, float), f,b,h;clrscr();printf(“n enter the breadth and height of a triangle:”);scanf(“%f %f”, &b, &h);f=area(b,h);printf(“n the area is %f”,f);getch();}float area(float b, float h){
  45. 45. float area;area=b*h;return(area);}Example for Type of Function’s:/* FUNCTION WITH NO ARGUMENTS AND NO RETURNVALUES#include<stdio.h>#include<conio.h>void name();void main(){clrscr();name();getch();}void name(){char empname[25];printf("Enter the employee name:");scanf("%s", empname);printf("The employee name is %s", empname);
  46. 46. }FUNCTION WITH RETURN VALUES AND NO ARGUMENTS#include<stdio.h>#include<conio.h>int sum();void main(){clrscr();printf("is %d", sum());getch();}int sum(){int i,n,result=0;printf("Enter the limit:");scanf("%d", &n);printf("Sum of even numbers within %d", n);for(i=2;i<=n;i+=2){result +=i;}return(result);
  47. 47. }FUNCTION WITH ARGUMENTS AND NO RETURNVALUES#include<stdio.h>#include<conio.h>void simple(float,float,int);float principal,rate;int year;void main(){clrscr();printf("Enter principal, rate of interest & no. of years n");scanf("%f %f %d", &principal, &rate, &year);simple(principal,rate,year);getch();}void simple(float principal, float rate, int year){float simple_interest=0.0;simple_interest = (principal * rate * year)/100;printf("The simple interest is %.2f", simple_interest);}
  48. 48. FUNCTION WITH ARGUMENTS AND RETURN VALUES#include<stdio.h>#include<conio.h>int sum(int x);void main(){int n;clrscr();printf("Enter the limit:");scanf("%d", &n);printf("Sum of first %d natural numbers is %d", n, sum(n));getch();}int sum(int x){int i, result=0;for(i=1; i<=x;i++)result +=i;return(result);}RECURSION: In c it is possible to call a function. Recursion is a process bywhich a function calls itself repeatedly until some specified
  49. 49. condition has been satisfied. A function is called recursive if astatement within the body of a function calls the same function.Recursion is a process of defining something in terms of itself.Ex:#include<stdio.h>Long fact (long);void main(){long num, fac;printf(“Enter a number:”);scanf(“%ld”, &num);fac=fact(num);printf(“The factorial of %ld is %ld”, num, fac);}long fact (long x){if(x<=1)return (1);elsereturn(x * fact(x-1));}
  50. 50. NESTED OF FUNCTION: We have seen programs using functions called only from themain() function. But there are situations, where functions otherthan main() can call any other function(s) used in the program.This process is referred as nested of functions.Ex:#include<stdio.h>void func_1 ();void func_2 ();void main (){printf(“n inside main function”);func_1 ();printf(“n again inside main function”);}void func_1 (){printf(“n inside function 1”);func_2 ();printf(“n again inside function 1”);}void func_2 (){
  51. 51. printf(“n inside function 2”);}STORAGE CLASSES: The variables are associated with certain properties such asscope and lifetime in a program. By scope of a variable means thatthe portions of the program in which it can be used. The lifetime ofa variable is the period of time during which the value is availablein memory. The four different storage class 1. automatic storage class 2. external storage class 3. static storage class 4. register storage classAUTOMATIC STORAGE CLASS Variables defined inside a block and are local to the block inwhich they are declared, are refered as automatic variables as localvariables. Automatic variables can only be accessed by the blockin which they are declared. Any another block cannot access itsvalue.Ex:#include<stdio.h>#include<conio.h>
  52. 52. /*void main(){auto int x=5;{auto int x=4;{auto int x=3;clrscr();printf("%d t",x);}printf("%d t",x);}printf("%d t",x);getch();}EXTERNAL STORAGE CLASS: Variables that are both alive and active throughout the entireprogram are called as external variables also refered as globalvariables. Global variables can be accessed by any function in theprogram. Global variables are also stored in the memory. When anexternal variable is not initialized it takes a value of zero.Ex:
  53. 53. int value;void main(){value = 100;clrscr();test1();test2();test3();printf("%dn", value);getch();}test1(){value += 100;printf("%dn", value);}test2(){value = 1000;printf("%dn", value);}test3(){
  54. 54. value += 100;printf("%dn", value);}STATIC STORAGE CLASS: The world static in general refers to anything that is insert tochange. In a program if static variables are declared withinindividual blocks they are local to the block in which they aredeclared. The static variables retain their values throughout the lifeof the program.Ex:void main(){clrscr();sum();sum();sum();sum();getch();}sum(){static int x=1;
  55. 55. printf("%d", x);x=x+1;}*/REGISTER STORAGE CLASS: The register storage class is similar to the auto storage classsince the variables defined inside a block are local to the block inwhich it is specified. Register variable can only be accessed by theblock in which it is declared. Its value cannot be accessed by anyother functionEx:void main(){register int x;clrscr();for (x=1; x<=10; x++)printf("%d",x);getch();}STRUCTURES: A structure is a collection of one or more variables groupedunder a single name for easy manipulation. The variables in a
  56. 56. structure, unlike those in an array, can be of different variabletypes. A structure can contain any of C’s data types, includingarrays and other structures. Each variable within a structure iscalled a member of the structure.Defining a structure: A structure definition contains keyword struct and a userdefined structure-name followed by the members of the structurewith in braces.The general form is:Struct structure-name{data-type member-1;data-type member-2;……………..…………….data-type member-n;};Ex:Struct student{
  57. 57. int no;int age;char sex;};Structure declaration: Structure declaration means defining variables to the alreadydefined structure. We can define variables in two ways. 1. variable definition along with the structure definition 2. variable definition using structure-name any where in the programThe first general form is:Struct structure-name{data-type member-1;data-type member-2;……………..…………….data-type member-n;} variable-1, variable-2,…….variable-n;Ex:Struct student{
  58. 58. int no;int age;char sex;}s1,s2,s3;The second general form is:Struct structure-name{data-type member-1;data-type member-2;……………..…………….data-type member-n;};structure-name variable-1, variable-2,…….variable-n;Ex:Struct student{int no;int age;char sex;};
  59. 59. student s1, s2, s3;Giving values to structure members: Dot operator or member operator ‘.’ Is used to give data tothe structure variables individual members.The general form is;Structure variable . member-name The variable name with a period and the member name isused like any ordinary variableEx:Struct student{int no;int age;char sex;}s1; the above declaration has a variable s1 having threemembers. The values or data to the members of the variable canbe given by any one of the following method.(i) using keyword;
  60. 60. scanf(“%d”, &s1.no); scnaf(“%d”, &s1.age); scanf(“%c”,&s1.sex);(ii) using assignment statement: s1.no = 100; s1.age = 18; s1.sex = ‘m’;Example:#include<stdio.h>#include<conio.h>void main(){struct emp{char sex;int no;float salary;}d1;clrscr();printf("Give the values to the membersn");printf("Give the sex.......");scanf("%c", &d1.sex);
  61. 61. printf("Give the number....");scanf("%d", &d1.no);printf("Give the salary....");scanf("%f", &d1.salary);printf("n");printf("Employee - details n");printf("Sex: %cn", d1.sex);printf("Number: %dn", d1.no);printf("Salary: %fn", d1.salary);getch();}Array of Structures: Array of structures are defined as a group of data of differentdata types stored in a consecutive memory location with a commonvariable name called an array of structures.Ex:#include<stdio.h>#include<conio.h>void main(){struct student
  62. 62. {int no;int age;char sex;};struct student s1[2];int i;clrscr();for(i=0;i<2;i++){printf("Enter number,age,sexn");scanf("%d %d %c", &s1[i].no, &s1[i].age, &s1[i].sex);}for(i=0;i<2;i++)printf("%d %d %cn", s1[i].no, s1[i].age, s1[i].sex);getch();}Structures with structures [Nested Structure]: When a structure is declared as a member of anotherstructure then it is called structure within structure or nestedstructure.
  63. 63. Ex:#include<stdio.h>#include<conio.h>void main(){struct hostel_detail{int hostel_room_no;char food;int deposit_amount;};struct student{char name[10];int no;char branch[5];struct hostel_detail h1;};static struct student s1={"Raja", 100, "Ct", 10, v, 2000};clrscr();printf("%s %d %s %d %c %d", s1.name, s1.no, s1.branch,s1.h1.hostel_room_no,s1.h1.food, s1.h1.deposit_amount);
  64. 64. getch();}Passing Entire Structure To Function: In this method, the entire structure is passed as an argumentto the function. Note that when using a structure as a parameter,remember that the type of the argument in the function callstatement must match the type of a parameter (list if any), in thefunction prototype. Since the function is working on a copy of thestructure, any changes made to the structure members within thefunction are not reflected in the orginal structure.Ex:#include<stdio.h>#include<conio.h>void employ(struct employee emp);struct employee{int empno;char empname[10];}emp1;void main(){
  65. 65. printf("Enter employee no and name:");scanf("%d %s", &emp1.empno, emp1.empname);employ(emp1);}void employ(struct employee emp){printf("n the employee no is :%d", emp.empno);printf("n the employee name is:%s", emp.empname);}FILES Files are used for permanent storage of large amount of data.A file can be used to write and/or read data from a disk. Filehandling in C is very simple, since it essentially treats a file as justa stream of characters and allows input and output in a file.So far we used scanf and printf function to read and write data toand from the computers through the console. If computers dealwith large amount of data as input and output (read, write) thenboth methods are not efficient. The best way is to use files to givedata to the computers and get data from the computers.Defining a File:
  66. 66. A file is defined as FILE in the header file stdio.h thereforeall files should be declared as type FILE before they are used.The general form is: FILE *pointer variable;Opening a File: Before we read from a file or write to a file, we must openthe file. Opening establishes a link between the program and theoperating system.The general form is:FILE *pointer variable;Pointer variable = fopen (“file name”, “mode”);Ex:FILE *a;a = fopen (“exam.txt”, “r”);Closing the file: An opened file must be closed after all operations on it havebeen completed.
  67. 67. The general form is:fclose (pointer variable);Ex:……………….……………….FILE *a, *b;a= fopen(“exam.txt”, “r”);b= fopen(“exam.txt”,”w”);…………………..………………….fclose(a);fclose(b);Reading a file: fscanf function is used to read data from a file.The general form is:fscanf(pointer variable, “control string”,list);Ex:fscanf(a, “%d%d”, &x,&y);
  68. 68. Writing to a file: fprintf function is used to write data into a fileThe general form is:fprintf (pointer variable, “control string”,list);Ex:fprintf(a,”%d%d”, x,y);Example:#include<stdio.h>#include<conio.h>void main(){int empno;char empname[20],deptname[20];FILE *ptr;clrscr();ptr=fopen("exam.dat","w");printf("Enter ename, eno and edept:");scanf("%s %d %s", &empname, &empno, &deptname);fprintf(ptr, "%s %d %s",empname, empno, deptname);fclose(ptr);
  69. 69. ptr=fopen("exam.dat","r");fscanf(ptr, "%s %d %s", &empname, &empno, &deptname);printf("n Employee Name:%s", empname);printf("n Employee Number:%d", empno);printf("n Department Name:%s", deptname);fclose(ptr);getch();}Example:#include<stdio.h>#include<conio.h>void main(){int c;FILE *fptr;clrscr();printf("Enter the text to store in the filen");fptr=fopen("example.txt","w");while((c=getc(stdin))!=EOF)fputc(c,fptr);fclose(fptr);printf("n the contents of the file is n");
  70. 70. fptr=fopen("example.txt","r");do{c=fgetc(fptr);putchar(c);}while (c!= EOF);fclose(fptr);getch();}Random Access Function: Reading and writing operations on any file are normallysequential. This is achieved by a system-controlled pointer, whichpoints the position immediately, after the last character is read orwritten. Which points the position immediately, after the lastcharacter is read or written. However, with the help of randomaccess functions a C programmer can move the file pointer to anydesired position in the file One advantage of a random access file over other files is that,a character can be written or read from the file by specifying theexact location where the operation is to take place.
  71. 71. The random access functions used in a file are 1. the fseek() function 2. the ftell() function 3. the rewind() functionThe fseek() Function: The fseek() function is used to move the file pointer to anydesired location within a file. It can be used to increment ordecrement the file pointer by any number of positions in the file.The general form is:fseek (fptr, long int offset, int position);Ex:fseek (fptr, 5L, 0);The Position: Value Meaning 0 Beginning of the file 1 Current position of the file 2 End of the file
  72. 72. The ftell() Function: The ftell() function returns the current position of the filepointer in the file.The general form is:ftell(fptr);The rewind () function: The rewind () function resets the file pointer to the beginningof the file.The general form is:rewind (fptr);Merging Two Files:Ex:#include<stdio.h>#include<conio.h>void main(){char *a;FILE *f1, *f2, *f3;clrscr();
  73. 73. f1=fopen("student.txt","w");printf("Enter the content of file1n");gets(a);fputs(a,f1);fclose(f1);f2=fopen("student1.txt","w");printf("Enter the content of file2n");gets(a);fputs(a,f2);fclose(f2);f1=fopen("student.txt","r");f3=fopen("student2.txt","w");printf("n the content of file1 is n");while (fgets(a, strlen(a)+1,f1)!=NULL){fputs(a,f3);printf("%s",a);}fclose(f1);fclose(f3);f2=fopen("student1.txt","r");f3=fopen("student2.txt","a");printf("n The content of file2 is n");
  74. 74. while(fgets(a,strlen(a)+1,f2)!=NULL){fputs(a,f3);printf("%s",a);}fclose(f2);fclose(f3);f3=fopen("student2.txt","r");printf("n the content of file3 is n");while (fgets (a, strlen(a) + 1,f3)!=NULL)printf("%s",a);getch();}POINTERS: A pointer is a variable, which represents the location (not thevalue) of a data item, such as a variable or an array element.Advantages: 1. pointers increase the execution speed of the program. 2. pointers reduce the length and complexity of a program. 3. pointers enable us to access a variable that is defined outside the pointers are used to pass information back and forth between a function and its reference point.
  75. 75. Pointer declaration: All pointer variables must be declared before it is used in theprogram like other variable.The general form is:Data-type * variable;Assigning the address of the variable to pointer variable: The address of the variables can be got with the help of theaddress operator &. The operator & immediately preceding avariable returns the address of the variable associated with it.Ex:int *a;int x;a = &x;Example:#include<stdio.h>#include<conio.h>void main(){
  76. 76. int a=5,b=10, *ptr;clrscr();ptr=&a;printf("n initial values a=%d &b=%d",a,b);b=*ptr;printf("n changed values a=%d &b=%d",a,b);printf("n value of ptr is %d", ptr);getch();}Pointers and Array: An array is actually a pointer to its 0th element. Dereferencingthe array name will give the value stored in the 0th element of thearray.Ex:#include<stdio.h>#include<conio.h>void main(){int i,j,n,a[25],*ptr;clrscr();printf("Enter the number of elements:");
  77. 77. scanf("%d", &n);printf("Enter the array elements:");for(i=0;i<n;i++)scanf("%d",&a[i]);*ptr=a[0];for(i=0;i<n;i++)if(a[i]>*ptr)*ptr=a[i];printf("The biggest element in the array is %d",*ptr);getch();}Pointer to Function: A pointer to a function contains the address of the funcntionin memory. A function, like a variable has an address location inthe memory, therefore it is possible to declare a pointer to afunction,Ex:#include<stdio.h>#include<conio.h>int sum(int (*) (int),int);int square(int);
  78. 78. void main(){int num;clrscr();printf("Enter any integer:");scanf("%d", &num);printf("The sum of squares of first %d numbers is %d", num,sum(square, num));}int sum(int (*fptr)(), int n){int add, i;for(i=1;i<=n;i++)add += (*fptr) (i);return 0;}int square (int i){getch();return(i*i);}

×