OpenGurukul : Language : C Programming


Published on

C Language Programming By OpenGurukul

Published in: Technology
1 Comment
  • its amazing really clear all doubts about it
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

OpenGurukul : Language : C Programming

  1. 1. C Programming By OpenGurukul
  2. 2. C Programming Introduction 2
  3. 3. Introduction : History1960 ALGOL In te rn a tion a l G rou p1967 BCPL Ma rtin R ic h a rd s1970 B Ke n T h om p s on1972 Traditional C D e n n is R itc h e 3
  4. 4. Introduction : FeaturesExtensive use of function callsStructured languagePointer implementation - extensive use of pointers for memory,array, structures and functions.C has now become a widely used professional language forvarious reasons.General purpose programming language.Helps in development of both system as well as applicationsoftware.C is a highly portable language.This means it can be run on different machines . 4
  5. 5. Introduction : Program StructureDocumentationPreprocessor directives / header filesType definitionsFunction prototypes -- declare function types and variables passed to function.The main() functionOther Functions 5
  6. 6. Introduction : C program : ExampleProgram : Compilation of C Program$ cat hello.c $ gcc hello.c -o hello#include <stdio.h> $main() Execution of Program{ $ ./hello Hello World printf("Hello Worldn"); $} 6
  7. 7. Introduction : Input and outputThe printf(“control string”, arg_list) is a function to print formatted output.Control string contains format specifier(%) and string of characters to be printed.Each % indicates the argument to be substituted in what form it has to be printed. e.g. %d is used for integer argument.e.g, printf(“the value of x is %d”,x);The scanf(“control string”, &variable) is just like printf(). It reads input instead of writing output.e.g. scanf(“%d”, &x);Note:&-- address of operator.We can also specify width while displaying data. e.g. %6d will print a decimal integer at least 6 characters wide. 7For floating point, to point 2 characters after decimal point, use %.2f
  8. 8. Introduction : I/O : ExampleProgram :#include <stdio.h> OUTPUT : Enter a number : 10main() number = 10{ int x; printf("Enter a number : "); scanf("%d", &x); printf("number = %dn", x); return 0;} 8
  9. 9. CommentsSingle line comment can be specified using //// single line commentMulti line comment can be specified using /* *//** Multi line comment 1* Multi line comment 2*/ 9
  10. 10. C programming Data Types & Variables 10
  11. 11. IdentifiersIdentifiers are names given to the elements such as variables,arrays and functions that are used in a programBasically, these identifiers are sequence of alphabets and digitsThere are certain rules that govern the formation of identifiers,based on those rules the following are the VALID and INVALIDidentifiers :Valid identifiers: Marks, TOTAL_MARKS , gross_salary_1998, Area_of_circle(), Num[20]Invalid identifiers: 8ab, TOTAL MARK, Gross-salary-1997, Area_ _ of _ _ circle 11
  12. 12. Data Types & SizesData types Qualifiers - unsigned & signedchar - single byte - can store one applies to char and integer character default may be signed or unsigned (itint - integer - generally natural size depends on the platform).float - for single precision floating point Rangedouble - for double precision floating point unsigned char : 0, 255 (2^8-1)Qualifiers - short & long signed char : -128 (-2^7), +127 (2^7-1)short and long provides different length of integers.short int - 2 byteslong int - 4 bytes (32-bit systems), 8 bytes(64-bit systems) 12
  13. 13. Data Types & SizesTy p e S iz e Rang e fo rmchar 1 b y te -1 2 8 to 127 %c ‘a ’ ‘A ’ ‘# ’ ‘n ’u n s ig n e d 1 b y te 0 to 255charin t 2 b y te -3 2 7 6 8 to % d -2 5 5 0 -5 32767u n s ig n e d in t 2 b y te 0 to 6 5 5 3 5 % u 25u 32768ulon g in t 4 b y te -2 1 4 7 4 8 3 6 4 8 to % ld 4 5 l -5 l 40000l + 2147483647u n s ig n e d 4 b y te 0 to % lu 1 0 0 lu 5 1 lulon g 4294967295floa t 4 b y te ± 3 .4 * 1 0 ^ ± 3 8 %f -3 .5 f 7 .5 fd ou b le 8 b y te ± 1 .7 * 1 0 ^ ± 3 0 8 % lf -3 .5 7 .5lon g d ou b le 1 0 b y te ± 3 .4 * % L f -3 .5 L 7 .5 L 10^ ± 4932 13
  14. 14. Data types: Example#include <stdio.h> Output:int main(void) { sizeof char = 1printf("sizeof char = %dn", sizeof(char)); sizeof short = 2printf("sizeof short = %dn", sizeof(short)); sizeof int = 4printf("sizeof int = %dn", sizeof(int)); sizeof long = 4printf("sizeof long = %dn", sizeof(long)); sizeof float = 4printf("sizeof float = %dn", sizeof(float)); sizeof double = 8printf("sizeof double = %dn", sizeof(double));return 0;} 14
  15. 15. VariablesIt is a data name that is used to store a data value.Variables can take different values at different times duringexecution.All the variables must be declared before they are used.Example: Declaration: int x; float y; Initialization: x=10; y=10.5; 15
  16. 16. Variable NamesThere are certain conditions to be followed before the declaration of avariable : . They must begin with a letter . Uppercase and lowercase are significant . It should not be a keyword . White space is not allowedExamples of valid variable names: John value x1 T_cutExamples of Invalid variable names: 123 % 21th (area)The underscore "_" counts as a letter. It is very useful for readability of long variable names.Dont begin your variable name with "_" as system library routines uses16 such names.
  17. 17. Variable NamesNames are made up of letters and digits.First character must be letter.The underscore "_" counts as a letter. It is very useful for readability of long variable names.Dont begin your variable name with "_" as system library routines uses such names.Traditional practice - use lower case for variable names, use upper case for symbolic constants.Keywords such as if, else, int are reserved. These cannot be used as variable names.Use shorter names for local variables. Use longer names for global/external variables. 17
  18. 18. Variable DeclarationsAll variables must be declared before use. A declaration announces property (data type) of the variable.The declaration is usually done at the beginning of the block(function)The declaration must be done before any executable statements in a block (function).A declaration specifies a type and contains a list of one or more variables of that type, as inint lower, upper, step;A variable may also be initialized in its declaration. If the name is followed by an equal signs and an expression, the expression serves as an initializer, as inint i = 0; 18
  19. 19. ConstantsThe term constant means that it does not change during the execution of programThere are four basic types of constants in C1.Integer constants2.Floating-point constants3.Character constants4.String constantsComma and blank spaces cannot be included within the constants.Constants can be preceded by a – or + sign, if desired. If either sign does not precede the constant it is assumed to be positive.The value of a constant cannot exceed specified minimum and maximum bounds. 19
  20. 20. Constants : Integer : Example#include <stdio.h> Output :#include <stdlib.h> x = 10int main() y = 255{int x = 012;int y = 0xFF;printf("x = %dn", x);printf("y = %dn", y);return 0;} 20
  21. 21. Constant : Character : Example#include<stdio.h> Outputint main() c=x{const char c = x;printf(“c = %cn”, c);return 0;} 21
  22. 22. Constant : String : Example#include<stdio.h> OutputInt main() s = Open Gurukul{const char *s = ”Open Gurukul”;printf(“s = %sn”, s);return 0;} 22
  23. 23. C Programming Operators 23
  24. 24. OperatorsAn operator is a symbol that tells the compiler to perform specificoperation.Operator are classified into 3 types based upon no. of operands.Unary operator: Required only one operandBinary operator: Required only two operandTernary: Required only three operand 24
  25. 25. OPERATORSUnary operator Binary operator Ternary operator Pre Increment/ Decrement Arithmetic Operator Ternary Operator Post Increment/ Decrement Logical Operator Size Estimating Operator Relational Operator Address of(&) Assignment Operator Pointer operator(*) Conditional Operator Special Operator Bit wise Operator 25
  26. 26. Priority parenthesis ( ) u n a ry !, + , -, + + , -- (p re in c re m e n t/d e c re m e n t) a rith m e tic *, /, % Airthmetic a rith m e tic +,- re la tion a l <,>,<=,>= Relational re la tion a l = = , != log ic a l a n d && Logical log ic a l or || c on d ition a l ?: Ternary a s s ig n m e n t = Pos t 26in c re m e n t/d e c + + , -- re m e n t
  27. 27. Operators : Arithmetic : ExamplePROGRAM:#include<stdio.h>#include<stdlib.h>main() { int num1, num2, sum, sub, mul, div; scanf("%d %d", &num1, &num2); sum = num1 + num2; printf("nsum = %d, ", sum); sub = num1 – num2; printf("diff = %d, ", sub); mul = num1*num2; printf(" product = %d, ", mul); div = num1 / num2; printf("division = %dn", div);}OUTPUT : 4 5 sum = 9, diff = -1, product = 20, division = 0 27
  28. 28. BITWISE OPERATOR The operator which act on the internal bits of respective bytes, are known asbitwise operator. C provides 6 bit wise operators for bit manipulation. & Bitwise and | Bitwise or ^ Bitwise exclusive or << Left shift >> Right shift ~ one’s complement 28
  29. 29. & Bitwise-AND operatorThe & operator performs a bitwise AND on two integers. a b a&b 0 0 0 0 1 0 1 0 0 1 1 1Example: 2&3 2 0000000000000010 3 0000000000000011 2&3 0000000000000010 2 29
  30. 30. | Bitwise-OR operator The | (vertical bar) operator performs a bitwise AND on two integers. a b a|b 0 0 0 0 1 1 1 0 1 1 1 1Example: 2|3 2 0000000000000010 3 0000000000000011 2|3 0000000000000011 3 30
  31. 31. ^ Bitwise exclusive-OR operator The ^(caret) operator performs a bitwise AND on two integers. a b a^b 0 0 0 0 1 1 1 0 1 1 1 0Example: 2^3 2 0000000000000010 3 0000000000000011 2^3 0000000000000001 1 31
  32. 32. Operators : Bit-wise : ExamplePROGRAM : OUTPUT : 231#include<stdio.h>#include<stdlib.h>int main(){ printf(“%d %d %d”, 2&3, 2|3, 2^3); return 0;} 32
  33. 33. Left ShiftThe shift-left operator (<<, or double left) is used to shift the bit pattern of a number by a certain number of bits to the left.Here is an example of shift-left operator:13<<3=10413 (00001101)104 (01101000) 33
  34. 34. Right ShiftThe shift-right operator (>>, or double right) is used to shift this bit pattern to the opposite direction (right).Here is another example for the shift-right operator:52>>4=352 (00110100)3 (00000011) 34
  35. 35. INCREMENT and DECREMENT OPERATORincrement operator ++ adds 1 to its operand.decrement operator -- subtracts 1 from its operand.It are two types 1. Pre increment/ Decrement 2. Post increment/ Decrement 35
  36. 36. Operators : Pre/Post Inc/Dec : ExamplePROGRAM:#include <stdio.h> Output:#include <stdlib.h> x = 11, y = 10 x = 10, y = 10int main() { x = 9, y = 10 int x = 10, y; x = 10, y = 10 y = x++; /* y should have 10, x will be 11 post */ printf("x = %d, y = %dn", x, y); y = --x; /* x will become 10, y will also be 10 */ printf("x = %d, y = %dn", x, y); y = x--; /* y should have 10, x will be 9 post decrement */ printf("x = %d, y = %dn", x, y); y = ++x; /* x will become 10, y will also be 10 */ printf("x = %d, y = %dn", x, y);} 36
  37. 37. Operators : AssignmentIt is used to assign the specific value to the variable or constant. Note: The left hand operand must and should be a variable. Example: int x=10; 37
  38. 38. Operators : Compound Operators C om pound O p e r a t io n P e r f o r m e d O p e ra tor *= Mu ltip lic a tion a s s ig n m e n t /= D iv is ion a s s ig n m e n t %= R e m a in d e r a s s ig n m e n t += Ad d ition a s s ig n m e n t -= S u b tra c tion a s s ig n m e n t <<= L e ft-S h ift a s s ig n m e n t >>= R ig h t s h ift a s s ig n m e n t &= B itw is e -A ND a s s ig n m e n t ^= B itw is e -ex c lu s iv e -O R a s s ig n m e n t |= B itw is e -in c lu s iv e -O R a s s ig n m e n t 38
  39. 39. Operators : RelationalThese operators compare the relation between the specified operands.If it is true, it will return 1. else returns 0.Operators Meaning> Greater than>= Greater than Equal to< Lesser than<= Lesser than Equal to== Equals!= Not Equals 39
  40. 40. Operators : LogicalThe operators, generally used in conditional statements.These operators are used to check between two or more conditions.Operator Meaning && Logical AND || Logical OR ! Logical NOT 40
  41. 41. && Logical-AND operatorIt perform conditional-AND on two boolean expression. a b a&&b falsefalse false falsetrue false true false false true true trueExample: 2&&3 2 true 3 true 2&&3 true 1 41
  42. 42. || Logical-OR operatorIt perform conditional-OR on two boolean expression. a b a||b false false false false true true true false true true true trueExample: 2&&0 2 true 0 false 2||0 true 1 42
  43. 43. ! Logical-NOT operatorIt performs logical not operation. a !a false true true falseExample: 2(true) !2->false->0 43
  44. 44. Operators : Logical : ExamplePROGRAM: OUTPUT :#include<stdio.h> ONE#include<stdlib.h>main(){ if (!1) printf("NOT ONEn"); else printf("ONEn");} 44
  45. 45. Operators : CommaThe comma operator is a binary operator that evaluates its firstoperand and discards the result, it then evaluates the second operand andreturns this value (and type).int a=1, b=2, c=3, i; // not an operator herei = (a, b); // stores b into ii = a, b; // stores a into ii = (a += 2, a + b); // increases a by 2, then stores a+b = 3+2 into ii = a += 2, a + b; // increases a by 2, then stores a = 3 into i 45
  46. 46. Operators : Comma : ExamplePROGRAM: OUTPUT :#include <stdio.h> i = 2, b =2#include <stdlib.h> i = 1, a =1 int main(){ int a = 1, b = 2; int i; i = (a, b); // stores b into i printf("i = %d, b =%dn", i, b); i = a, b; // stores a into i printf("i = %d, a =%dn", i, a); return 0;} 46
  47. 47. TERNARY OPERATORDefines a conditional expression. In the expression expr1 ? expr2 : expr3 the expression expr1 is evaluated first. If it is non-zero(true), then the expression expr2 is evaluated, and that is the value of conditional expression. Otherwise, expr3 is evaluated, and that is the value. Only one of expr2 and expr3 is evaluated. 47
  48. 48. Operators : Ternary : ExamplePROGRAM: OUTPUT :#include <stdio.h> Enter first value : 3#include <stdlib.h> Enter second value : 4main() { Max is : 4 int a, b, max; printf("Enter first value : "); scanf("%d", &a); printf("Enter second value : "); scanf("%d", &b); max = (a > b ? a : b); printf("Max is : %dn", max);} 48
  49. 49. Operators : sizeof()The sizeof() operator can be used PROGRAM :to figure out size of data type. #include <stdio.h>The sizeof() is not a functionwhose value determined at run #include <stdlib.h>time but rather an operator whose int main() {value is determined by compiler, int i; So it can be known as compile printf("sizeof i = %d," time unary operator. "sizeof(int) = %dn" , sizeof (i), sizeof (int)); } OUTPUT : sizeof i = 4, sizeof(int) = 4 49
  50. 50. C Programming Control Flow 50
  51. 51. Control structure : DecisionsIf-statementIf-else-statementswitch-statement 51
  52. 52. Control Flow : If StatementThe if statement used to control the flow of execution ofstatement.The general from of a simple if statement is if ( test expression ) { statement-block; } 52
  53. 53. Control Flow: if Statement : ExamplePROGRAM: OUTPUT :main() { Congratulations! int grade = 68; You passed! if (grade > 60) { printf(“congratulations!”); printf(“You passed!”); }} 53
  54. 54. Control flow : if else StatementsThe if…else statement is an extension of the simple if statement.The general from is if(test expression) { true-block statement(s) } else { false-block statement(s) } 54
  55. 55. Control flow: if else : ExamplePROGRAM : OUTPUT :main() Sorry you failed{ int grade = 58; if (grade > 60) { printf(“congratulations!”); printf(“You passed!”); } else { printf(“Sorry you failed”); }} 55
  56. 56. Control flow : Switch StatementSwitch allows branching on multiple outcomes.The general form of the switch statement is switch (expression) { case value-1: block-1 break; case value-2: block-2 break; …… default: default-block 56 break;
  57. 57. Control flow : Switch : ExamplePROGRAM:main() { OUTPUT: int option = 2; B switch(option) { case 1: printf(“A”); break; case 2: printf(“B”); break; default : printf(“def”); break; } 57}
  58. 58. Looping control structurewhile loopdo-while loopfor loop 58
  59. 59. Control flow : while StatementThe basic format of the while statement is while (test condition) { body of the loop } 59
  60. 60. Control flow : while : ExamplePROGRAM: OUTPUT :main() { 01234 int X = 0; while ( X < 5 ) { printf(“ %d ”, X); X++; }} 60
  61. 61. Control flow : do while StatementThe do while loop takes the following form : do { body of the loop } while ( test-condition) ; 61
  62. 62. Control flow : do while : ExamplePROGRAM: OUTPUT :main() 01234{ int X = 0; do { printf(“ %d ”, X); X++; } while ( X < 5 );} 62
  63. 63. Control Flow : For StatementThe general form of the for loop is for (initialization; test condition; increment / decrement) { body of the loop } 63
  64. 64. Control flow : For Loop : ExamplePROGRAM: OUTPUT:main() 01234{ int i ; for (i = 0; i < 5; i++) { printf(“ %d “,i); }} 64
  65. 65. C Programming Functions 65
  66. 66. Functions : IntroductionA block of statements can be grouped together in curly braces { } and given a name.It may take parameters as input and can return a value if needed.The functions are basic building blocks of modular programming language such as c.Syntax :return_type function_name(data_type_1 param1, data_type_2 param2, ...){ statement1; statement2; return <value>;} 66If the return type is "void", the function doesnt return any value.
  67. 67. Program: Functions : Example#include <stdio.h> sum = add(num1, num2);int sum(int first, int second) printf("sum is %dn", sum);{ } int total; Output : total = first + second ; sum is 30 return total;}void main(){ int num1 = 10; int num2 = 20; int sum; 67
  68. 68. RecursionRecursion is a programming technique in which function calls itself.It repeats the same code, and in some ways it is similar to looping. 68
  69. 69. Recursion ExamplePROGRAM: int fact(int n) {#include <stdio.h> int k;#include <stdlib.h> if (n == 1) return (1);int main() { else k = n * fact(n - 1); int n, fact; return (k); int fact(int); } printf("nenter the number for which you Output : want to find the factorialn"); enter the number for which you want to scanf("%d", &n); find the factorial fact = fact(n); 5 printf("nthe factorial of the number %d the factorial of the number 5 is 120 is %d", n, fact); return 0; 69}
  70. 70. Function : Calling a functionWhile calling a parametrized function, we have to pass some values.There are two ways to call a function,1. Call by Value2. call by Reference.The difference between these two is:In case of Call by value the original data will remain unchanged.But in case of Call by Reference the address is passed to the function as the parameters, So the original data will changed. 70
  71. 71. Functions : Call by Value : ExampleProgram: Output:void modify(int,int); modify: x=100, y=200void main() { main: x=10, y=20int x=10, y=20;modify(x,y);printf(“main: x= %d, y= %dn”,x,y);}void modify(int x,int y){ x=100; y=200;printf(“modify: x= %d, y= %dn”,x,y);} 71
  72. 72. Functions : Call by Reference : ExampleProgram: Output:void modify(int *,int *); modify: x=100, y=200void main() { main: x=100, y=200int x=10, y=20;modify(&x,&y);printf(“main: x= %d, y= %dn”,x,y);}void modify(int *x,int *y){ *x=100; *y=200;printf(“modify: x= %d, y= %dn”,*x,*y); 72}
  73. 73. C Programming Arrays 73
  74. 74. Arrays : introduction1. It is a collection of data of similar data types in a contiguous memory location.2. An array can be declared using : data_type variable_name[size];3.data_type can be: int, float, char etc4. An array elements index or subscript begins with number zero. 74
  75. 75. Arrays : ExampleProgram: Output:#include<stdio.h>void main() s = hi{ char s[5]; // declaration of an character Array s[0]=h; //initialization of 1st index of the array s[1]=i; s[2]=0; printf(“s = %s”,s); //to print the string} 75
  76. 76. Arrays : Array ElementsThe syntax for an element of an array called a is a[i]where i = index of the array element.In memory, one can picture the array id as in the following diagram: 76
  77. 77. Arrays : InitializationThe elements of array can be initialized at the time of declaration Syntax: data_type array_name[array size] = {list of values};Example : initialize array with size int number[3] = {40, 30, 20}; Will declare an array of size 3.Will assign 40, 30, 20 to first, second and third element like below.number[0]=40,number[1]=30,number[2]=20 77
  78. 78. Arrays : Initialization without SizeExample : initialize array without size (compute automatically) int counter[] = {101, 102, 103, 104}; Will declare the array to contain four elements with initial values 101, 102, 103 and 104. 78
  79. 79. Arrays : ExampleProgram:#include<stdio.h> Output:#define MAX_CLASS 5 students in class 1 : 30Int main() students in class 2 : 35{ students in class 3 : 40 /* initialize while declaring */ students in class 4 : 45 int students[MAX_CLASS] = {30, 35, 40, 45, 50}; students in class 5 : 50 int class; for (class = 0; class < MAX_CLASS; class++) { printf("students in class %d : %dn", class+1, students[class]); 79 }
  80. 80. Arrays : Multidimensional ArrayOften there is a need to store and manipulate two dimensional data structure such as matrices & tables.Syntax: data_type array_name[num_rows][num_columns]; Example: int holiday[12][31];Syntax for multidimensional array declaration: data_type array_name[s1][s2][s3]…..[sn]; Example : int holiday[100][12][31]; 80
  81. 81. Arrays : Multidimensional Array : ExampleProgram: for(int i=0;i<2;i++)#include<stdio.h> for(int j=0;j<3;j++)Void main() Printf(“ x[%d][%d]= %dn“,i,j x[i][j]);{ }Int x[2][3] Output:Int k=1; x[0][0] = 1;for(int i=0;i<2;i++) X[0][1] = 2; for(int j=0;j<3;j++) X[0][2] = 3; { x[1][0] = 4; x[i][j]=k; X[1][1] = 5; k++; X[1][2] = 6; } for printing all the values of the array 81
  82. 82. Arrays : Array as Parameters1.An array can also be passed to a function as a parameter by using array name itself.2.The base address of an array is passed to the function.3.The function can use (1) same name or (2) any other name to receive the base address of an array.4.The function can operate on the array passed as a parameter.5.The changes made to the array in a function will be visible in other places as it is accessed through pointer. 82
  83. 83. Arrays : Array as Parameter : ExamplePROGRAM: Output:#include <stdio.h>void print_students(int students[], int numstuds) 0:10{ 1:20 int i; 2:30 for (i = 0; i < numstuds; i++) 3:432 { printf("%d : %d n", i, students[i]); } }#define NUM_TOPPERS 4int main(){ int toppers_roll_no[NUM_TOPPERS] = {10, 20, 30,432}; print_students(toppers_roll_no, NUM_TOPPERS); return 0;} 83
  84. 84. C ProgrammingModule : Structure 84
  85. 85. Basics of StructuresA structure is a collection of one or more variables that are grouped together under a single name. The data type of variables can be same or different.The structure is used for convenient handling of related data that can be grouped together.The variables that are part of structure are called structure members or structure fields.Syntax :typedef struct emp { int emp_id; char emp_name[256];} emp_t ; 85The keyword "struct" is followed by a structure name.
  86. 86. Structures : Access Members/Fieldsemp_t e; defines a variable e which is a structure of the type struct emp.The structure members / fields are referred using dot operator . between structure variable and structure field/member. structure_name.memberExample e.emp_name 86
  87. 87. Structures : Example/* Example : struct.c */ Output :#include <stdio.h>#include <string.h> $ gcc -o struct struct.ctypedef struct emp { int emp_id; $ ./struct char emp_name[256]; id = 432, name = s k} emp_t ; $main() { emp_t e; e.emp_id = 432; strcpy(e.emp_name, "S K"); printf("id = %d, name = %sn", e.emp_id, e.emp_name); 87}
  88. 88. Pointers to StructureThe pointer to a structure is declared by preceding the variable name with an asterisk in the declaration.Access struct members using pointers: An arrow sign is used to access structure member while access the data through a pointer to a structure. pointer_to_structure_variable->structure_member_nameExample: emp_t *e_p; /* pointer to struct */ e_p->emp_id e_p->emp_name 88
  89. 89. Pointers to Structure : Example/* Example : struct_pointer.c */ main() {#include <stdio.h> emp_t e;#include <string.h> emp_t *e_p; /*ptr to struct */ e.emp_id = 432;typedef struct emp { strcpy(e.emp_name, "sk"); int emp_id; e_p = &e; char emp_name[256]; printf("id = %d, name = %sn",} emp_t ; e_p->emp_id, e_p->emp_name); } 89
  90. 90. Self-referential StructureA structure may have a member whose is same as that of a structure itself. Such structures are called self-referential.Self-Referential Structure are one of the most useful features.They allow you to create data structures that contains references to data of the same type as themselves.Self-referential Structure is used in data structure such as binary tree, linked list, stack, Queue etc.Example : Single linked list is implemented using following data structuresstruct node {int value;struct node *next;}; 90
  91. 91. C Programming Pointers 91
  92. 92. Pointers : IntroductionDefinition-A pointer is a variable that can hold address of other variables, structures and functions.Syntax :<variable_type> *<name>;*(de-referencing operator) symbol is used to indicate the pointers.Example: int x=10; ptr x int *ptr; // pointer to an integer 1000 10 ptr=&x; // ptr contains the address of x 2000 1000 printf(“the value of x is %d“, *ptr); // 10 92
  93. 93. Pointers : Need of PointersThese are very efficient to handle the arrays.Pointers allow C to support dynamic memory allocation.Pointers provide support to create dynamic data structures like linked list, stack, queue, etc....They increase the execution speed, so helps to reduce the execution time.Pointers reduce the length and complexity of the programs.They help to return multiple values in functions. 93
  94. 94. Pointers : Declaration & Initialization : ExampleProgram:#include <stdio.h> Output:int main() x=5{ int x=5; *p = 5 int *p; &x = 500 p = &x; p = 500 printf(" x= %dn",x); // the value of x &p = 600 printf("*p = %dn",*p); //the value of x printf("&x = %un",&x); // the address of xprintf(“ p = %un”,p); // the address of xprintf(“&p = %un”, &p); // the address of the pointer} 94
  95. 95. Pointers : Arithmetic OperationPointer variable can be used in arithmetic expressions.For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid.y = *p1 * *p2;sum = sum + *p1;z = 5* - *p2/p1;*p2 = *p2 + 10;C language allows us to add integers to, subtract integers from pointers as well as to subtract one pointer from the other,short hand operators with the pointers p1+=; sum+=*p2; etc.,Comparison of pointers such as p1 > p2 , p1==p2 and p1!=p2 are allowed. 95
  96. 96. Address Arithmetic ExampleProgram:#include <stdio.h> Output:void main() a = 30, b = 6{ x = 30int ptr1,ptr2;int a,b,x;a=30;b=6;ptr1=&a;ptr2=&b;x=*ptr1+ *ptr2 –6;printf("na = %d, b = %dn",a,b);printf("nx = %d”,x); 96}
  97. 97. Pointers : Character pointers in CIn C, string means array of characters. i.e., char a[]=”matsya”;C does not provide any operators for manipulation of an entire string.Strings can be manipulated via pointers.Like 1D arrays, we can use a pointer to access the indivisual characters in a string.Generally when we create a string, compiler automatically inserts a null character(0) at the end.Example :char *cp; m a t s y a 0cp = “matsya”; cp 97
  98. 98. Pointers : Char pointer : ExampleProgram: Output:#include<stdio.h> Matayavoid main(){ char *cptr; cptr=“Matsya”; printf(“%s”,cptr); while(*cptr!=‘0’) { if(*cptr==‘s’) *cptr=‘a’; printf(“%c”,*cptr); cptr++; }} 98
  99. 99. Pointers : Pointers to ArraysPointer means address in memory.Array means group of similar elements in a contiguous memory location.If we can keep the track of index element of an array, then by incrementing the pointer we can obtain the other elements of the array. a[0] a[1] a[2] 1 23 45 p 99
  100. 100. Pointers : Pointers to Array : ExampleProgram : Output:# include<stdio.h> a[0] = 1void main() p+0 = 1{ a[1] = 23int a[]={1,23,45}; p+1 = 23int *p, i;p=&a[0]; a[2] = 45for(i=0;i<3;i++) p+2 = 45{ printf("a[%d] = %dn",i,a[i]); printf("p+%d=%dn",i,*(p+i));}} 100
  101. 101. Pointers : Command line argumentsmain() function has two arguments.The first is number of command line arguments i.e., int argcThe second is a pointer to an array of character strings that contain the arguments one per string i.e., char *argv[] 101
  102. 102. Command line Argument : ExampleProgram: cmd.c bin>tcc cmd.c#include<stdio.h> bin>cmd.exe this is a programmain(int argc, char *argv[]) Output:{ this is a program int i; for(i=1;i<argc;i++) { printf(“%8s”,argv[i]); }} 102
  103. 103. C ProgrammingInput & Output 103
  104. 104. IO : File input & outputThe I/O functionality of C is fairly low-level by modern standards; C abstracts all file operations into operations on streams of bytes, which may be "input streams" or "output streams".stdio.hThe standard library functions for file input and output are included in the c standard library header <stdio.h>TypeWe need a file pointer to read from file and write to a file e.g.:FILE *fp;The FILE is an abstract data structure. It includes file descriptor.FunctionsReading from or writing to a file in C requires 3 basic steps:Open the file.Do reading/writing. 104Close the file.
  105. 105. Opening a file using fopenA filepointer is used to open a file present using the format,FILE* fp;FILE* fopen(char *name, char *mode);For opening a filefp = fopen(name of file, mode);Mode Normal Accessr Open existing file for "r"eadingw Open file for "w"riting, destroying the contents; create if necessarya "A"ppend at end of file; create if necessary Update Access (for fixed-length records)r+ Open existing file for "r"eading & writingw+ Open file for reading & "w"riting, destroying the contents; create if necessarya+ Open file for reading & writing -- all writing is "a"ppended to the end of the file; create if necessary 105
  106. 106. Opening a file using fopenFor checking whether a file exists givefopen(filename)=NULL;To read and to write a file, getc and putc are used.getc returns the next character from a file; it needs the file pointer to tell it which fileint getc(FILE *fp)getc returns the next character from the stream referred to by fp; it returns EOF for end of file or error.putc is an output function :int putc(int c, FILE *fp)putc write the character c to the file fp and returns the character written, or EOF if an error occurs. getc and putc may be macros instead of functions. 106
  107. 107. Opening a file using fopengetchar and putchar can be defined in terms of getc, putc, stdin, and stdout as follows:# define getchar() getc(stdin)# define putchar(c) putc((c), stdout)For formatted input or output of files, the functions fscanf and fprints may be fscanf(FILE *fp, char *format, ....)int fprintf(FILE *fp, char *format, ...)An example program to read characters from console and write that to file and display that onto console console. 107
  108. 108. Opening a file using fopen Example#include <stdio.h> fp = fopen("INPUT", "r");#include <stdlib.h> while ((c = getc(fp)) != EOF)int main() { printf("%c", c); file* fp; fclose(fp); printf("Data inputn"); return 0; fp = fopen("INPUT", "w"); } while ((c = getchar()) != EOF) putc(c, fp); fclose(fp); printf("Data outputn"); 108
  109. 109. Line I/Ofgetschar *fgets(char *line, int maxline, FILE *fp)The standard library provides an input routine fgets to read a line.fgets reads the next input line from the file fp into the character array line; at most maxline-1 characters will be read.The resulting line is terminated with 0. Normally fgets returns line; on end of file or error is returns NULL.fputsint fputs(char *line, FILE *fp)The function fputs writes a string to a file.It returns EOF if an error occurs, and zero otherwise.The library functions gets and puts are similar to fgets and fputs, but operate on stdin and stdout.gets deletes the terminal n, and puts adds it. 109
  110. 110. Formatted Output using printfThe output function printf translates internal values to characters.For exampleint printf(char *format, arg1, arg2, ......)printf converts, formats, and prints its arguments on the standard output under the control of the format.It returns the number of character printed.Basic Printf Conversions--------------------------------------------------------------------------------------------Character Argument type; Printed as--------------------------------------------------------------------------------------------d, i int; decimal number.o int; unsigned octal number(without leading zero)x, X int; unsigned hexadecial number without the leading ox or OX. 110
  111. 111. Formatted Output using printfu int; unsigned decimal number.c int; single character.s char *; print character from the string until a 0 or the number of characters given by the precision.f double; [-]m.dddddd, where the number of ds is given by the recisione,E double; print a double in exponential format, rounded, with one digit before the decimal point, precision after it. A precision of zero suppresses the decimal point.There will be at least two digits in the exponent, which is printed as 1.23e15 in e format, or 1.23E15 in E format.g, G double; use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f.p void *; pointer no argument is converted; print a % 111
  112. 112. Formatted Output using printfA width or precision may be specified as *, in which case the value is computed by the converting the next argument. For example, to print at most max characters from a string s,printf("%.*s", max, s);Example: printf with various effectsThe following table shows the effect of a variety of specifications in printing "hello, world".:%s: :hello, world::%10s: :hello, world::%.10s :hello, wor::%-10s: :hello, world::%.15s: :hello, world::%-15s: :hello, world ::%15.10s: : hello, wor: 112:%-15.10s: :hello,wor :
  113. 113. Formatted Input using scanfscanf syntax:scanf(datatype *format, ....);There is also a function sscanf that reads from a string instead of the standard input:int sscanf(char *string, char *format, arg1, arg2, ....)It scans the string according to the format in format, and stores the resulting values through arg1, arg2, etc.These arguments must be a pointers.Basic Scanf ConversionsCharacter | Input Data | Argument Typed | decimal integer | int *u | unsigned decimal integer | unsigned int * 113c | character | char *
  114. 114. Formatted Input using scanfs | character string | char * (pointing to an array of characters large enough for the string and a terminating 0 that will be added)e, f, g | floating point number with optional sign, optional decimal point and optional exponent | float *.o | octal integer | int *x | hexadecimal integer | int *% | literal % | no assignment is made 114
  115. 115. Error HandlingstderrThe second output stream, called stderr, is assigned to a program in the same way that stdin and stdout are.Output written on stderr normally appears on the screen even if the standard output is redirected.fprintf(stderr, format, arguments);The output produced by fprintf goes onto stderr.It finds it way to the screen instead of disappearing into an output file.exitThe program uses the standard library function exit, which terminates program execution when it is called.The argument of exit is available to whatever process called this one, so the success or failure of the program can be tested by another program that uses this one as a sub process. 115
  116. 116. Char I/Ofgetc()int fgetc(FILE *fp);The fgetc function is used to read a character from a streamIf successful, fgetc returns the next byte or character from the streamIf unsuccessful, fgetc returns EOF.getc()macrobehaves similar to fgetc()it may evaluate its arguments more than once.getchar()int getchar(void);functiontakes no argument. 116equivalent to getc(stdin).
  117. 117. Char I/Ofputc()int fputc(int c, FILE *stream);The fputc function is used to write a character from a stream to the fileIf successful, fputc writes the next byte or character from the streamIf unsuccessful, fgetc returns EOF. 117
  118. 118. C ProgrammingModule : Strings 118
  119. 119. StringsStrings are defined as an array of characters.We can used following statement to define a string of 5 characterschar string1[5];char string2[] = {A, B, C, D, 0};char *string3_p = "ABCD"; /* string literals */char *string4_p = string2; /* string2 is same as &string2[0] */ 119
  120. 120. String LiteralsA string that has been enclosed in double-quotes is called a string literal.It can be used in place of string variables in the code.Example :#include <string.h>main(){ char *s_p = "hello"; /* "hello" is a string literal */ printf("%s %sn", s_p, "world"); /* "world" is a string literal */}Output: hello world 120
  121. 121. String TerminatorA special character 0 is used to indicate the end of the string.This should be stored as a last character of the string.It is also called as a string null character.Example :#include <stdio.h>int main(void){printf("The character 0 is used to terminate a string.");return 0;}Output: The character 121
  122. 122. String format specifierWe must use %s to read & print Output: strings. Enter your country name :Example : india#include <stdio.h> You belong to india#include <string.h>main(){char str[128];printf("Enter your country name : n");scanf("%s", str);printf("You belong to ");printf("%sn", str); 122}
  123. 123. string length : strlen functionThe function strlen() can be used to Example: Calculate lengh of string calculate the length of the string. literals "Hello World"It doesnt take into account null- #include <string.h> terminator 0 at the end of the string. #include <stdio.h>Example: main()length = strlen("hello"); /* should set length to 5 */ { int length; char *message_p = "Hello World"; length = strlen(message_p); printf("length of %s = %dn", message_p, length); } Output:length of Hello World = 11 123
  124. 124. string copy : strcpy functionWe can copy the contents of one Example : Copy string literal "Hello string to another using strcpy() World" to a string and display it. function. #include <string.h>Syntax : #include <stdio.h>char *strcpy(char *dest, const char *src); main() { char message[128]; strcpy(message, "Hello World"); printf("%sn", message); } Output: Hello World 124
  125. 125. string concatenation : strcat functionWe can concatenate contents of one Example : string to another using strcat() function. #include <string.h>Syntax : #include <stdio.h>char *strcat(char *dest, const char *src); main() { char message[128]; strcpy(message, "Hello"); strcat(message, " "); strcat(message, "World"); printf("%sn", message); } Output:Hello World 125
  126. 126. string compare : strcmp functionWe can compare contents of two string to find if they are equal.The strcmp() takes "case" of the characters into account.The strcasecmp() ignores case while comparing.The return value is 0 when the string are equal.The return value is non-zero when the string are unequal.Syntax :#include <string.h>int strcmp(const char *s1, const char *s2);int strcasecmp(const char *s1, const char *s2); 126
  127. 127. string compare: Example#include <string.h> printf("match case, %s == %s, %dn", s1, s2, strcmp(s1, s2));#include <stdio.h> s1 = "Hello";main() s2 = "hello";{ printf("ignore case, %s == %s, %dn",char *s1; s1, s2, strcasecmp(s1, s2));char *s2; }s1 = "Hello"; Output:s2 = "Hello"; match case, Hello == Hello, 0 ignore case, Hello == hello, 0 127
  128. 128. search for string in string : strstrThe function strstr() can be used to search a substring in string.It returns the pointer that matches the substring.The NULL pointer is printed as (null) on Linux.Syntax :#include <string.h>char *strstr(const char *haystack, const char *needle); 128
  129. 129. C ProgrammingStorage Classes 129
  130. 130. Scope of VariablesA complete C program need not be compiled all at once; the source text of the program may be kept in several files, and previously compiled routines may be loaded from libraries.If the variable / function has been defined before it use, no declaration is required.Otherwise an implicit (for function) / explicit (for variable) declaration is required before its use.The same rule applies irrespective of the definition of function/variable in same source file or another source file.General rule- declare all global variables as extern (global) in header file.- declare all globale functions in header file.- include the header file in all the source files that needs to access function / variable.- each function / variable be defined in any one source file 130
  131. 131. External VariablesThe program can consists of multiple source files (object files).For such programs, the variables and functions defined in one file can be accessed/used in another file.To ensure that the variables & functions defined in one file are accessible in another file, you must prefix them with a keyword "extern" (set external scope) at the time of declaration.Generally, "extern" is required only for variables.The functions are implicitly assumed to be "extern" by compiler .The "extern" declarations are generally done in a common header file.The extenal (global) variables are initialized to zero by default by compiler. 131
  132. 132. External Variables:ExampleHeader File : common.h Second Source File : second.cextern int ev; /* explicit extern */ #include "common.h"void set_ev(int ); /* implicit extern */ main()First C Source : first.c {#include "common.h" printf("ev = %d, ", ev);int ev; /* definition */ set_ev(5);void set_ev(int value) printf("ev = %dn", ev);{ } ev = value; Compliation & Linking :} $ gcc -o mexec first.c second.c Output : ev = 0, ev = 5 132
  133. 133. Static VariablesStatic storage class is declared with the keyword static as the class specifier when the variable is defined.These variables are automatically initialized to zero upon memory allocation just as external variables are.Static automatic variables continue to exist even after the block in which they are defined terminates.Thus, the value of a static variable in a function is retained between repeated function calls to the same function.Static variables may be initialized in their declarations.Initialization is done only once at compile time when memory is allocated for the static variable. 133
  134. 134. Static Variables : ExamplePROGRAM: OUTPUT :#include <stdio.h> 2#include <stdlib.h> 3void add() { 4 static int x = 1; x++; printf("%dn", x);}main() { add(); // return 2 add(); // return 3 add(); // return 4} 134
  135. 135. Storage Classes : Register VariablesThe register storage class specifier indicates to the compiler that the object should be stored in a machine register.Register storage class are used in the hopes of enhancing performance by minimizing access time and are used when the variables are frequently used.An object having the register storage class specifier must be defined within a block or declared as a parameter to a function.Objects with the register storage class specifier have automatic storage duration.Available when entering the loop and value is gone once exited.A register variable will be declared as follows:register int i; 135
  136. 136. D e f a u lt TYPE S cope L if e t im e V a lu e a u to b od y b od y G a rb a g e v a lu e s ta tic fu n c tion p rog ra m 0 ex te rn p rog ra m p rog ra m 0re g is te r b od y b od y G a rb a g e v a lu e 136
  137. 137. Storage Classes : InitializationThe static and extern variables are initialized to 0 by compilerAn automatic variable remains uninitialized and it will contain garbage.You can initialize a variable while defining it. 137
  138. 138. Storage Classes : Initialization : Exampleextern int i ; /* declaration */extern int j; /* declaration */int i = 5; /* definition & initialization */int j; /* definition * initilization to zero */main(){ static int s = 5 ; /* deinition and initializtion to 5 */ static int t ; /* definition and initialization to 0 */ int a; /* definition and uninitizlied - automatic variable */ printf("i = %d, j = %d, s = %d, t = %d, a = %dn", i, j, s,t,a);} 138
  139. 139. C Programming Module Miscellaneous 139
  140. 140. The typedefThe typedef statement is used to create a new data type from existing data types.We should not use "#define" to refer to data types.Syntax :typedef existing_data_type new_data_type;Example :typedef unsigned int u_int;NOTES :We can use u_int and s_t to declare variables.u_int i; /* i is a variable of type unsigned int */ 140
  141. 141. UnionA union is a collection of variables that share the same storage.The union is allocated large enough to hold the value of the largest variable contained in it.A union may only be initialized with a value of the type of its first member.The base address of all the fields of a union is same as they all share the common storage.Syntax :union union_name {data_type member;data_type_1 member1;data_type_2 member2;}; 141
  142. 142. Union:Accessunion-name.member : access union fields using union variableunion-pointer->member : access union fields using pointer tounion variableExample: 142
  143. 143. Bit-fieldsWhen Storage space is at premium, it may be necessary to pack several objects into a single machine word; one common use is a set of single-bit flags in applications like compiler symbol tables.Imagine a fragment of a compiler that manipulates a symbol table.The most compact way to encode such information is a set of one-bit flags in a single char or int.The usual way this is done to define a set of "masks" corresponding to the relevant bit position, as in #define KEYWORD 01 #define EXTERNAL 02 #define STATIC 04or enum { KEYWORD = 01 , EXTERNAL = 02 , STATIC = 04 };The numbers must be powers of two. Then accessing the bits become a matter of "bit- fiddling" with the shifting, masking, and complementing operators. 143
  144. 144. Bit-fieldsCertain idioms appear frequently: flags | = EXTERNAL | STATIC;turns on the EXTERNAL and STATIC bits in flags, while flags &= -(EXTERNAL | STATIC);turns them off, and if((flags & (EXTERNAL | STATIC))==0) true if both bits are off.A bit-field or field for short, is a set of adjacent bits within a single implementation-defined storage unit that we will call a "word". struct { unsigned int is_keyword : 1; unsigned int is_extern : 1; unsigned int is_static : 1;This defines a variable called flags that contains three 1-bit fields. The number following the colon represents the field width in bits. The field are declared unsigned int to ensure that they are unsigned quantities. 144